@cortexkit/pi-openai-auth 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import{createRequire as VX}from"node:module";var UX=VX(import.meta.url);import{createAssistantMessageEventStream as AY}from"@earendil-works/pi-ai";import{streamSimple as RY}from"@earendil-works/pi-ai/compat";var c="all",x3=Object.freeze(["primary"]);function N6($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function u1($,Z){return JSON.stringify([$,Z])}function o0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y0($){return typeof $==="number"&&Number.isFinite($)}function q6($){return typeof $==="string"&&$.length>0}function U0($,Z,X){return $[Z]===void 0||X($[Z])}function jX($){return Y0($)&&$>0}function b3($){return typeof $==="string"}function KX($){if(!o0($)||!q6($.scope)||!q6($.label))return!1;switch($.kind){case"reading":return Y0($.checkedAt)&&Y0($.usedPercent)&&U0($,"resetsAt",b3)&&U0($,"windowMinutes",jX);case"retired":return Y0($.retiredAt);case"absent":return Y0($.checkedAt);default:return!1}}function DX($){if(!o0($)||!Y0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&U0($,"remainingPercent",Y0)&&U0($,"usedPercent",Y0)&&U0($,"resetsAt",b3)&&U0($,"limit",Y0)&&U0($,"used",Y0)&&U0($,"remaining",Y0)&&U0($,"unit",b3)}function F6($){return o0($)&&Y0($.value)&&Number.isInteger($.value)&&$.value>=0&&Y0($.checkedAt)}function k3($){return o0($)&&Object.values($).every(F6)}function qX($){return typeof $==="boolean"}function m0($){return o0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&U0($,"balance",Y0)&&U0($,"overageLimitReached",qX)&&Y0($.checkedAt)}function f3($){if(!o0($))return;let Z=Object.entries($).filter(([,X])=>F6(X));return Z.length===0?void 0:Object.fromEntries(Z)}function C1($){if(X0($))return $;if(!o0($))return;let{counters:Z,credits:X,...J}=$;if(!X0(J))return;let z=f3(Z),G=m0(X)?X:void 0;return{...J,...z===void 0?{}:{counters:z},...G===void 0?{}:{credits:G}}}function X0($){if(!o0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!KX(X))return!1;let J=u1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return U0($,"budget",DX)&&U0($,"counters",k3)&&U0($,"credits",m0)}class W2 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function U2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V2($){return typeof $==="number"&&Number.isFinite($)}function M6($){return $===void 0||typeof $==="string"&&$!==""}function _6($){return typeof $==="string"&&$!==""}function F$($,Z){return $[Z]===void 0||V2($[Z])}function y3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function NX($){return U2($)&&M6($.scope)&&_6($.label)&&V2($.usedPercent)&&y3($,"resetsAt")&&($.windowMinutes===void 0||V2($.windowMinutes)&&$.windowMinutes>0)}function FX($){return U2($)&&M6($.scope)&&_6($.label)}function MX($){if(!U2($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&F$($,"remainingPercent")&&F$($,"usedPercent")&&y3($,"resetsAt")&&F$($,"limit")&&F$($,"used")&&F$($,"remaining")&&y3($,"unit")}function l1($){if(!U2($)||!V2($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let J=new Set;for(let z of Z){if(!NX(z))return!1;let G=u1(z.scope??c,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(FX))return!1;return($.budget===void 0||MX($.budget))&&($.counters===void 0||k3($.counters))&&($.credits===void 0||m0($.credits))}function _X($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function LX($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function OX($,Z){let X=new Map(Object.entries($??{}));for(let[J,z]of Object.entries(Z??{})){let G=X.get(J);if(G===void 0||z.checkedAt>=G.checkedAt)X.set(J,z)}return X.size===0?void 0:Object.fromEntries(X)}function PX($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function w0($,Z){let X=$===void 0?void 0:C1($);if($!==void 0&&X===void 0)throw new W2("stored quota map is malformed");if(!l1(Z))throw new W2("quota observation is malformed");let J=X??{limits:[]},z=Z.checkedAt,G=new Map;for(let D of J.limits)G.set(u1(D.scope,D.label),D);let B=(D)=>{let F=G.get(D);return F===void 0||z>=N6(F)},H=new Set;for(let D of Z.readings??[]){let F=D.scope??c,L=u1(F,D.label);if(H.add(L),!B(L))continue;G.set(L,{scope:F,label:D.label,kind:"reading",checkedAt:z,usedPercent:D.usedPercent,...D.resetsAt===void 0?{}:{resetsAt:D.resetsAt},...D.windowMinutes===void 0?{}:{windowMinutes:D.windowMinutes}})}for(let D of Z.coverage??[]){let F=D.scope??c,L=u1(F,D.label);if(H.has(L)||!B(L))continue;let R=G.get(L);G.set(L,R===void 0||R.kind==="absent"?{scope:F,label:D.label,kind:"absent",checkedAt:z}:{scope:F,label:D.label,kind:"retired",retiredAt:z})}let{limits:Y,budget:Q,counters:W,credits:V,...U}=J,K=LX(J.budget,Z.budget,z),j=OX(J.counters,Z.counters),N=PX(J.credits,Z.credits);return{...U,limits:[...G.values()].sort(_X),...K===void 0?{}:{budget:K},...j===void 0?{}:{counters:j},...N===void 0?{}:{credits:N}}}var g3=Object.freeze({validate:X0,decode:C1,merge:w0});var C6=900000,T6="no quota reading yet",S6="no limits reported";function A6($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let z=Math.floor(Z/60),G=Z%60;return G===0?`${z}h`:`${z}h${G}m`}let X=Math.floor(Z/1440),J=Math.floor(Z%1440/60);return J===0?`${X}d`:`${X}d${J}h`}function R6($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function K2($){if($.scope!==c||$.windowMinutes===void 0)return $.label;return R6($.windowMinutes)}function h3($){return Math.min(100,Math.max(0,$))}function j2($){return Math.round(h3($))}function L6($){return`${j2($)}% left`}function O6($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:A6(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function CX($,Z){let X=$.windowMinutes,J=Z.windowMinutes;if(X!==void 0&&J!==void 0&&X!==J)return X-J;if(X===void 0!==(J===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===c)return-1;if(Z.scope===c)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function E6($,Z){let{windows:X,age:J}=I6($,Z),z=X.map(({part:G})=>G);return J===void 0?{windows:z}:{windows:z,age:J}}function TX($){let Z=b6($.filter(({part:X,scope:J})=>X.kind==="window"&&J!==c).map(({scope:X})=>X));for(let X of $)X.part.short=X.part.kind==="budget"?"cr":X.scope===c?X.part.name:Z.get(X.scope)??X.scope;return $}function I6($,Z){if(!$)return{windows:[]};let{now:X}=Z,z=$.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(CX).map((B)=>{let H=h3(B.remainingPercent??0);return{scope:B.scope,...B.windowMinutes===void 0?{}:{windowMinutes:B.windowMinutes},part:{kind:"window",name:K2(B),short:"",figure:L6(B.remainingPercent??0),remainingPercent:H,checkedAt:B.checkedAt,...O6(B.resetsAt,B.checkedAt,X)}}}),G=$.budget;if(G){let B=G.remainingPercent,H=G.reached?"credits spent":B!==void 0?`credits ${L6(B)}`:"credits available";z.push({scope:c,spent:G.reached,part:{kind:"budget",name:"credits",short:"",figure:H,...B===void 0?{}:{remainingPercent:h3(B)},checkedAt:G.checkedAt,...O6(G.resetsAt,G.checkedAt,X)}})}if(TX(z),z.length>0){let B=X-Math.min(...z.map(({part:H})=>H.checkedAt));if(B>(Z.staleAfterMs??C6))return{windows:z,age:`checked ${A6(B)} ago`}}return{windows:z}}function P6($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function b6($){let Z=[...new Set($.map(P6))],X=new Map(Z.map((z)=>[z,2])),J=(z)=>z.slice(0,X.get(z));for(;;){let z=new Map;for(let B of Z)z.set(J(B),[...z.get(J(B))??[],B]);let G=!1;for(let B of z.values()){if(B.length<2)continue;for(let H of B){let Y=X.get(H)??2;if(Y<H.length)X.set(H,Y+1),G=!0}}if(!G)break}return new Map($.map((z)=>[z,J(P6(z))]))}var SX=2;function AX($){let Z=$.map((J)=>J.label.trim()||J.scope),X=b6(Z);return Z.map((J)=>X.get(J)??J)}function RX($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:H})=>H.kind==="window");if(X.some(({scope:H})=>H===c))return;let J=$.flatMap((H,Y)=>{let W=X.filter(({scope:V})=>V===H.scope).reduce((V,U)=>V===void 0||(U.part.remainingPercent??0)<(V.part.remainingPercent??0)?U:V,void 0);return W?[{group:H,listed:Y,window:W}]:[]});if(J.length===0)return;let z=AX($),G=(H)=>H.window.part.remainingPercent??0,B=[...J].sort((H,Y)=>G(H)-G(Y)||H.listed-Y.listed).slice(0,SX).sort((H,Y)=>H.listed-Y.listed);return B.map((H,Y)=>{let{windowMinutes:Q}=H.window,W=[z[H.listed]??H.group.scope,...Q===void 0?[]:[R6(Q)],`${j2(G(H))}%`].join(" ");return Y===B.length-1?`${W} left`:W})}function EX($,Z){let{windows:X}=I6($,Z),J=RX($?.groups,X);if(J)return J;let z=X.filter(({part:V,scope:U})=>V.kind==="window"&&U===c),G=X.filter(({part:V,scope:U})=>V.kind==="window"&&U!==c),B=X.find(({part:V})=>V.kind==="budget"),H=B?.spent?0:B?.part.remainingPercent,Q=[...G.map(({part:V})=>({label:V.short,remaining:V.remainingPercent??0})),...H===void 0||B===void 0?[]:[{label:B.part.short,remaining:H}]].reduce((V,U)=>V===void 0||U.remaining<V.remaining?U:V,void 0),W=z.map(({part:V})=>`${V.name} ${j2(V.remainingPercent??0)}%`);if(Q)W.push(`${Q.label} ${j2(Q.remaining)}%`);if(W.length===0)return X.map(({part:V})=>V.figure);return W.map((V,U)=>U===W.length-1?`${V} left`:V)}function d1($,Z){if(Z.form==="narrow")return EX($,Z);let X=E6($,Z),J=(Z.form??"full")==="full",z=X.windows.map((G)=>{let B=J&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${B}`});return X.age===void 0?z:[...z,X.age]}function P0($,Z){let X=d1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?S6:T6}function M$($){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 IX($){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 bX($,Z){let X=$.windowMinutes!==void 0,J=Z.windowMinutes!==void 0;if(X!==J)return X?-1:1;if(X&&J&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function xX($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=c){let X=new Map;for(let W of $?.limits??[]){if(W.scope!==Z&&W.scope!==c)continue;let V=X.get(W.label);if(V===void 0){X.set(W.label,W);continue}let U=W.scope===c?V:W,K=W.scope===c?W:V;X.set(W.label,U.kind==="reading"?U:K)}let J=[...X.values()].map(IX).sort(bX),z=J.filter((W)=>W.kind==="reading"),G=z.length>0?z:J,B=G.length>0?Math.min(...G.map((W)=>W.checkedAt)):void 0,H=$?.budget?.kind==="reading"?xX($.budget):void 0,Y=f3($?.counters),Q=m0($?.credits)?$.credits:void 0;return{scope:Z,limits:J,...B===void 0?{}:{checkedAt:B},...H===void 0?{}:{budget:H},...Y===void 0?{}:{counters:Y},...Q===void 0?{}:{credits:Q}}}function T1($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let J=Date.parse(X.resetsAt);if(!Number.isFinite(J)||J<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:J}}function v3($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function D2($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function x6($,Z,X){let J=Z.rateLimitMarks?.get($);if(J!==void 0&&X<J)return{id:$,reason:"rate-limited",until:J};let z=Z.refreshBackoff?.get($);if(z!==void 0&&X<z)return{id:$,reason:"refresh-backoff",until:z};return}function kX($,Z,X,J){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 z=Z.limits.filter(v3);for(let G of z)if(D2(G,J)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of z){let B=D2(G,J);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 b0($){let Z=$.scope??c,X=$.requiredLabels??x3,J=[],z=[],G=[];for(let U of $.rows){let K=x6(U.id,$,$.now);if(K){J.push(K);continue}if(U.kind==="api-key"){G.push({id:U.id,kind:U.kind});continue}let j=s(U.quota,Z),N=kX(U.id,j,X,$.now);if(N){z.push(N);continue}G.push({id:U.id,kind:U.kind,projection:j})}let B=new Map(G.flatMap((U)=>{let K=T1(U.projection,$.now);return K?[[U.id,K]]:[]})),H=B.size>0&&B.size===G.length,Y=[];for(let U of G){let K=B.get(U.id);if(K===void 0)Y.push(U);else if(H)Y.push({...U,lastPath:!0});else z.push({id:U.id,stage:2,reason:"budget-spent",...K})}let Q=new Map($.rows.map((U,K)=>[U.id,K])),W=(U,K)=>(Q.get(U.id)??0)-(Q.get(K.id)??0);z.sort(W);let V=z.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of V)$.requestPull?.(U);return{admitted:Y,refused:z,excluded:J,pulls:V}}var q2="main";function m3($){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 c1($,Z,X=q2){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((z)=>z!==X);return Z==="main-first"?[X,...J]:[...J,X]}function w3($){let Z=b0($),X=new Set(Z.admitted.map((z)=>z.id));return{order:c1($.rows.map((z)=>z.id),$.placement??"roster",$.formerMainId).filter((z)=>X.has(z)&&$.killswitch?.get(z)!==!1),admission:Z}}function p3($,Z,X){let J=Z.at(-1);if(J!==void 0){if(J.status===void 0||!X.includes(J.status))return}let z=new Set(Z.map((G)=>G.id));return $.find((G)=>!z.has(G))}function _$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function u3($,Z,X){let J=new Map;for(let[z,G]of $){if(z===X)continue;if(G.quotaCheckedAt!==Z.get(G.accountId))continue;J.set(G.accountId,(J.get(G.accountId)??0)+(G.inputBytes??0))}return J}var L$=900000,f6=0.016666666666666666,l3=0.000001;function N2($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function y6($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function g6($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,X)=>{let J=Z.windowMinutes!==void 0,z=X.windowMinutes!==void 0;if(J!==z)return J?-1:1;if(J&&z)return(X.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function c3($){let Z=($.classifyStatus??y6)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=N2($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>L$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of g6($.quota)){let G=z.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:z.scope,label:z.label},...typeof z.resetsAt==="string"?{resetsAt:z.resetsAt}:{}}}let J=T1($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function d3($,Z,X){let J=Math.max(0,$.remainingPercent-Z);if(J<=0)return 0;if(!$.resetsAt)return J;let z=Date.parse($.resetsAt);if(!Number.isFinite(z)||z<=X)return J;let G=Math.max((z-X)/3600000,f6);return J/G}function k6($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function fX($,Z){if(!$.quota)return;let X=N2($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>L$)return;let J=g6($.quota).map((B)=>d3({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},$.reservePercent[B.label]??0,Z)),z=$.quota.budget;if(z&&typeof z.remainingPercent==="number"&&Number.isFinite(z.remainingPercent))J.push(d3({remainingPercent:z.remainingPercent,...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}},0,Z));let G=J.length>0?Math.min(...J):0;return G>0?{candidate:$,quotaCheckedAt:X,weight:G}:void 0}function h6($){let Z=$.candidates.filter((z)=>z.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((z)=>fX(z,$.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,B)=>{let H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,l3),Y=(($.pendingBytes.get(B.candidate.accountId)??0)+$.requestBytes)/Math.max(B.weight,l3);return H-Y||G.candidate.configuredOrder-B.candidate.configuredOrder||k6(G.candidate.accountId,B.candidate.accountId)});let z=X[0];if(z)return{accountId:z.candidate.accountId,quotaCheckedAt:z.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let J=[...Z].sort((z,G)=>{let B=(z.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-B||z.configuredOrder-G.configuredOrder||k6(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:N2(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function s3($){let Z=b0($),X=new Map(Z.admitted.map((j)=>[j.id,j])),J=new Map(Z.refused.map((j)=>[j.id,j])),z=new Set(Z.excluded.map((j)=>j.id)),G=new Set($.rows.map((j)=>j.id)),B=$.pin!==void 0&&_$($.pin,G,$.identities?.get($.pin.accountId));if(B&&$.pin){let j=X.get($.pin.accountId);if(j&&$.killswitch?.get(j.id)!==!1)return{outcome:"dispatch",accountId:j.id,source:"pin",...j.projection?.checkedAt===void 0?{}:{quotaCheckedAt:j.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let H=$.pin?J.get($.pin.accountId):void 0,Y=B&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||H?.reason==="exhausted"||H?.reason==="budget-spent"),Q=(j)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(j):$.rowReservePercent?.get(j.id))??$.reservePercent??{}},W=$.scope,V=$.rows.map((j,N)=>({row:j,configuredOrder:N})).filter(({row:j})=>!z.has(j.id)).map(({row:j,configuredOrder:N})=>{let D=$.killswitch?.get(j.id),F=$.resetCreditsApplicable?.get(j.id);return{accountId:j.id,quota:j.kind==="api-key"?void 0:X.get(j.id)?.projection??s(j.quota,W),reservePercent:Q(j),configuredOrder:N,...F===void 0?{}:{resetCreditsApplicable:F},...D===void 0?{}:{killswitchPasses:D}}}),U=[],K=B?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(V.length>0){let j=h6({candidates:V,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!j)break;let N=J.get(j.accountId);if(N){U.push(N),V=V.filter((F)=>F.accountId!==j.accountId);continue}let D=$.identities?.get(j.accountId);return{outcome:"dispatch",accountId:j.accountId,source:j.source,...j.quotaCheckedAt===void 0?{}:{quotaCheckedAt:j.quotaCheckedAt},pin:B&&!Y?{action:"retain"}:{action:"assign",pin:{accountId:j.accountId,inputBytes:$.requestBytes,...D===void 0?{}:{wireIdentity:D},...j.quotaCheckedAt===void 0?{}:{quotaCheckedAt:j.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:K,refusedSelections:U,admission:Z}}import{appendFileSync as sX,chmodSync as aX,existsSync as r3,renameSync as i6,statSync as iX}from"node:fs";import{open as nX}from"node:fs/promises";import{dirname as rX,resolve as oX}from"node:path";import{randomUUID as p6}from"node:crypto";import{lstat as u6,readFile as l6,rename as yX,unlink as v6}from"node:fs/promises";import{tmpdir as gX}from"node:os";import{dirname as t0,join as hX,resolve as M0}from"node:path";var I=process.platform==="win32",m6=new Set;function a3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var w6;var d6="native-addon-unavailable";function c6($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:d6})}function vX($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function mX($){try{await $.verifyPrivatePath(hX(gX(),`.common-auth-private-files-probe-${p6()}`),"file")}catch(Z){if(vX($,Z))throw c6(Z)}}function s1(){return w6??=import("@cortexkit/private-files").then(async($)=>{if(I)await mX($);return $},($)=>{throw I?c6($):$}),w6}class i extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,X){let J=X;super(J?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${d6}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:X});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=a3(J),this.win32Code=J?.win32Code,this.reason=J?.reason}}async function q0($,Z,X){try{return await X()}catch(J){if(J instanceof i)throw J;throw new i($,Z,J)}}var wX;async function p0($,Z){$=M0($),Z??=wX,await q0($,"safe-parent",async()=>{let X=await(await s1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await u6($);throw new i(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function G0($,Z,X=!1){if($=M0($),Z==="directory")return p0($);await q0($,"verify",async()=>{let J=await s1(),z=await J.verifyOwnerOnly($),G=!1;if(!z.ok){let{reason:B}=z.refusal;if(B==="io-error")await J.verifyPrivatePath($,Z);if(X&&[J.EXTRA_ACE,J.NOT_PROTECTED,J.NULL_DACL,J.EMPTY_DACL].includes(B))await p0(t0($)),await J.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:B,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await J.verifyPrivatePath($,Z),G&&!m6.has($))m6.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function N0($,Z=!1,X){$=M0($),await q0($,"directory",async()=>{let J=await s1();try{return await u6($),await p0($,X)}catch(G){if(a3(G)!=="ENOENT")throw G}let z=t0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await N0(z,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(G){if(a3(G)!=="EEXIST")throw G}await p0($,X)})}async function _0($,Z=!1){if(!I)return l6($,"utf8");return(await i3($,Z)).toString("utf8")}async function i3($,Z=!1){if(!I)return l6($);if($=M0($),Z)await p0(t0($)),await G0($,"file",!0);return q0($,"read",async()=>(await s1()).readOwnerOnly($))}async function a1($,Z){await p0(t0(M0($))),await q0($,"create",async()=>{await(await s1()).createPrivateFile(M0($),Z)})}async function s6($){await p0(t0(M0($))),await q0($,"directory-create",async()=>{await(await s1()).createOwnerOnly(M0($),{kind:"dir"})})}async function n3($,Z,X={}){$=M0($),Z=M0(Z);let J=X.now??(()=>performance.now()),z=J(),G=X.deadline??1/0,B,H=[0,10,20,40,80,100],Y,Q=0;for(let V of H){let U=Math.min(B??1/0,G);if(J()>=U)break;if(V)await(X.sleep??((j)=>new Promise((N)=>setTimeout(N,j))))(Math.min(V,Math.max(0,U-J())));if(J()>=U)break;let K=J();if(await X.beforeRename?.(),B!==void 0)B+=J()-K;if(J()>=G)break;Q++;try{return await(X.rename??yX)($,Z),{attempts:Q,elapsedMs:J()-z}}catch(j){Y??=j;let N=j;if(!(N.win32Code!==void 0?N.win32Code===32||N.win32Code===33:["EBUSY","EPERM","EACCES"].includes(N.code??"")&&!N.reason))break;B??=J()+500}}let W=new i(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw W.attempts=Q,W.elapsedMs=J()-z,W}async function i1($,Z,X={}){$=M0($),await N0(t0($));try{await G0($,"file",!0)}catch(Q){if(Q.code!=="ENOENT")throw Q}let J=M0(X.stagePath??`${$}.${p6()}.tmp`);if(t0(J)!==t0($))throw new i($,"stage-directory",{code:"EXDEV"});let z=!1,G=!1,B={attempts:0,elapsedMs:0},H="stage-create",Y=(Q)=>{try{X.onOutcome?.({path:$,stage:Q?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Q?.attempts??B.attempts,elapsedMs:Q?.elapsedMs??B.elapsedMs,...Q&&{code:Q.code,win32Code:Q.win32Code}})}catch{}};try{if(await a1(J,Z),z=!0,H="before-rename",B=await n3(J,$,X),z=!1,G=!0,H="published-callback",X.onRenamed?.(),H="published-verify",await G0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new i($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(Q){let W=Q instanceof i?Q:new i($,H,Q);if(W.published=G,W.fileDurable=G,G)Object.assign(W,B);if(z){try{await v6(J)}catch{W.orphanPath=J}z=!1}throw Y(W),W}finally{if(z)await v6(J).catch(()=>{})}}var pX=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,uX=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function lX($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function x0($={}){let Z=[uX,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function X(G){let B=G.toLowerCase().replace(/[-_]/g,"");return pX.test(G)||B.includes("apikey")||B.endsWith("secret")||B.endsWith("password")||B.endsWith("token")&&!B.endsWith("tokens")||!!$.extraSecretKeys?.(B)}function J(G){let B=G,H=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Q of["code","status","cause"])if(B[Q]!==void 0)H.push([Q,B[Q]]);let Y=new Set(H.map(([Q])=>Q));for(let Q of Object.entries(G))if(!Y.has(Q[0]))H.push(Q);return H}function z(G,B,H,Y=0){if(typeof G==="string")return Z.reduce((Q,W)=>Q.replace(W,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(H.has(G))return"[Circular]";H.add(G);try{if(Array.isArray(G))return G.map((V)=>z(V,B,H,Y));let Q=lX(G);if(Q&&Y>=8)return"[Truncated]";let W=Q?Y+1:Y;return Object.fromEntries((Q?J(G):Object.entries(G)).map(([V,U])=>[V,B&&X(V)?"***REDACTED***":z(U,B,H,W)]))}finally{H.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var a6=x0(),dX=a6.redact,cX=a6.redactStrings;var F2={error:0,warn:1,info:2,debug:3,trace:4},r6=5242880,o6=3;function o3($){try{aX($,384)}catch{}}function tX($){try{if(!(r3($)&&iX($).size>=r6))return;for(let X=o6-1;X>=1;X--)if(r3(`${$}.${X}`)){let J=`${$}.${X+1}`;i6(`${$}.${X}`,J),o3(J)}let Z=`${$}.1`;i6($,Z),o3(Z)}catch{}}async function u0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await q0(Z,"log-close",()=>X.close())}async function n6($,Z){await N0(rX(Z));try{await G0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await a1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await G0(Z,"file",!0)}}return $.handle=await q0(Z,"log-open",()=>nX(Z,"a")),$.file=Z,$.handle}async function eX($,Z,X){Z=oX(Z);try{if($.file!==Z)await u0($);let J=$.handle??await n6($,Z);if((await q0(Z,"log-stat",()=>J.stat())).size>=r6){await u0($);for(let G=o6-1;G>=0;G--){let B=G===0?Z:`${Z}.${G}`,H=`${Z}.${G+1}`;try{await G0(B,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await G0(H,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await n3(B,H),await G0(H,"file")}J=await n6($,Z)}await q0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await u0($).catch(()=>{}),J}}function $J($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function ZJ($){let Z,X,J,z=x0(),G,B=[],H,Y=Promise.resolve(),Q,W={};function V(q){let _=Y.then(q);return Y=_.catch((A)=>{Q=A}),_}function U(q){if(I&&q.file!==Z)V(()=>u0(W)).catch(()=>{});Z=q.file,X=q.level,z=x0(q),G=q.captureSink}function K(q){if(q===void 0||q in F2)J=q}function j(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function N(){if(J)return J;let q=typeof X==="function"?X():X;if(q&&q in F2)return q;return"info"}function D(q=!0){if(H)clearTimeout(H),H=void 0;if(!B.length){if(I)return V(async()=>{if(q)await u0(W);if(Q)throw Q});return}let _;try{_=j()}catch{if(B=[],I&&q)return V(()=>u0(W));return}let A=B.join("");if(B=[],!_){if(I&&q)return V(()=>u0(W));return}if(I)return V(async()=>{try{await eX(W,_,A)}finally{if(q)await u0(W)}});try{if(tX(_),r3(_))o3(_);sX(_,A,{encoding:"utf8",mode:384})}catch{}}function F(){if(!H)H=setTimeout(()=>{H=void 0;let q=D(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function L(q,_,A,T){if(Z===void 0&&G===void 0)return;try{if(F2[_]>F2[N()])return;let b=z.redactStrings(A),w;try{w=z.redact(T)}catch{w="[unserializable]"}let f=`[${new Date().toISOString()}] ${_.toUpperCase()} [${q}] ${b}`+(T===void 0?"":$J(w))+`
2
- `;try{G?.({channel:q,level:_,message:b,data:w})}catch{}if(Z===void 0)return;if(B.push(f),B.length>=50){let y=D(!1);if(y instanceof Promise)y.catch(()=>{})}else F()}catch{}}function R(q){return{error:(_,A)=>L(q,"error",_,A),warn:(_,A)=>L(q,"warn",_,A),info:(_,A)=>L(q,"info",_,A),debug:(_,A)=>L(q,"debug",_,A),trace:(_,A)=>L(q,"trace",_,A)}}function M(){if(I)V(()=>u0(W)).catch(()=>{});if(Q=void 0,B=[],H)clearTimeout(H),H=void 0;Z=void 0,X=void 0,J=void 0,z=x0(),G=void 0}if($)U($);return{configure:U,createLogger:R,setLogLevel:K,flushLogs:D,reset:M}}var XJ=ZJ();function d($){return XJ.createLogger($)}class g extends Error{operation;rowId;phase;retryable;kind;committed;constructor($){super($.message??`${$.operation} failed (${$.kind}, ${$.phase})`,$.cause===void 0?void 0:{cause:$.cause});this.name="PoolOperationError",this.operation=$.operation,this.rowId=$.rowId,this.phase=$.phase,this.retryable=$.retryable,this.kind=$.kind,this.committed=$.committed}}class M2 extends Error{operation;constructor($){super(`${$} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=$}}var n1="identity-contradicted: ",t3="duplicate-identity";function e0($,Z,X){let J=$.rosterRow(Z);if(!J)return;J.enabled=!1;let z=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...z,disabledReason:G?z.disabledReason:X})}function O$($,Z){let X=$.rosterRow(Z);if(!X)return;X.enabled=!0;let J=$.entry(Z);if(J&&"disabledReason"in J){let z={...J};delete z.disabledReason,$.setEntry(Z,z)}}function r1($,Z){let X=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),J=[];for(let z of X.slice(1))e0($,z.id,"duplicate-identity"),J.push(z.id);return J}function S1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,r1($,X)}import{setTimeout as bJ}from"node:timers/promises";import{randomUUID as t6}from"node:crypto";import{mkdir as YJ,open as _2,rename as QJ,rm as WJ}from"node:fs/promises";import{dirname as e3}from"node:path";class P$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function L0($,Z,X={}){await $Z($,Z,X)}async function $Z($,Z,X,J){if(I)return i1($,X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
3
- `,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??t6)()}.tmp`,onRenamed:J,durable:X.durable,durability:X.durability,onOutcome:X.onOutcome});await YJ(e3($),{recursive:!0});let z=`${$}.${(X.stageName??t6)()}.tmp`,G,B=!1;try{if(G=await _2(z,"wx",384),B=!0,await G.writeFile(X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
4
- `,"utf8"),await G.chmod(384),X.durable)try{await G.sync()}catch(H){throw new P$(H)}if(await G.close(),G=void 0,await X.beforeRename?.(),await QJ(z,$),B=!1,J?.(),X.durable){let H=await _2(e3($),"r");try{await H.sync()}catch(Y){throw new P$(Y)}finally{await H.close()}}}finally{if(await G?.close().catch(()=>{}),B)await WJ(z,{force:!0}).catch(()=>{})}}async function ZZ($){if(I){await G0($,"file");let J=new i($,"directory-sync-unsupported",{code:"ENOTSUP"});throw J.published=!0,J}let Z=await _2($,"r");try{await Z.sync()}finally{await Z.close()}let X=await _2(e3($),"r");try{await X.sync()}finally{await X.close()}}import{randomUUID as L2}from"node:crypto";import{mkdir as e6,open as G8,readFile as $8,rename as Z8,rm as O2,stat as X8}from"node:fs/promises";import{dirname as XZ,join as J8}from"node:path";async function z8($,Z){let X=await G8($,"wx",384);try{await X.writeFile(Z,"utf8")}finally{await X.close()}}var VJ=globalThis.setTimeout.bind(globalThis),UJ=globalThis.clearTimeout.bind(globalThis);function JZ($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function J0($){return jJ({...$,now:Date.now})}async function jJ($){let Z=zZ($.path,$.name),X=J8(Z,"owner.json"),J=L2(),z=$.now??Date.now,G=null,B=!1,H=!1,Y,Q,W=new Promise((C)=>{Q=C});function V(C){try{let S=$.onRenewalTimer?.(C);if(S&&(typeof S==="object"||typeof S==="function")&&"then"in S&&typeof S.then==="function")Promise.resolve(S).catch(()=>{})}catch{}}function U(){if(!G)return;UJ(G),G=null,V("cancelled")}function K(C,S){if(Y||B)return;Y=Object.freeze({reason:C,expectedOwnerId:J,...typeof S?.ownerId==="string"?{observedOwnerId:S.ownerId}:{},...typeof S?.expiresAt==="number"?{observedExpiresAt:S.expiresAt}:{}}),U(),Q(Y)}let j,N=null,D=`${Z}.evicting`,F=J8(D,"owner.json"),L=L2(),R=5000,M=8;async function q(){if(I)try{return JSON.parse(await _0(Z,!0))}catch(C){if(C.code!=="EISDIR"&&C.reason!=="wrong-kind")throw C;return await G0(Z,"directory",!0),JSON.parse(await _0(X,!0))}try{return JSON.parse(await $8(Z,"utf8"))}catch(C){if(C.code!=="EISDIR")throw C;return JSON.parse(await $8(X,"utf8"))}}async function _(){if(I){let u=await q(),$0=Number(u?.expiresAt)-z();await i1(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
5
- `,{deadline:performance.now()+Math.max(0,$0),beforeRename:async()=>{let Q2=await q();if(Q2?.ownerId!==J||!(Number(Q2?.expiresAt)>z())||!await h())throw new $1({target:$.path,name:$.name})}});return}let C=`${Z}.${L2()}.tmp`,S,x=!1;try{S=await G8(C,"wx",384),x=!0,await S.writeFile(`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
6
- `,"utf8"),await S.chmod(384),await S.close(),S=void 0;let u=await q();if(u?.ownerId!==J||!(Number(u?.expiresAt)>z())||!await h())throw new $1({target:$.path,name:$.name});await Z8(C,Z),x=!1}finally{if(await S?.close().catch(()=>{}),x)await O2(C,{force:!0}).catch(()=>{})}}async function A(){let C=`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
7
- `;if(I)await a1(Z,C);else await z8(Z,C)}async function T(C){let S=C.code;if(S==="EEXIST"){if(I)await q();return!0}if(S==="EISDIR"){if(I)await G0(Z,"directory",!0),await _0(X,!0);return!0}return!1}async function b(){if(I)await N0(XZ(Z));try{return await A(),!0}catch(C){let S=C.code;if(await T(C))return!1;if(S==="ENOENT"){if(I)await N0(XZ(Z));else await e6(XZ(Z),{recursive:!0});try{return await A(),!0}catch(x){if(await T(x))return!1;throw x}}throw C}}async function w(){await new Promise((C)=>setTimeout(C,Math.floor(Math.random()*4)))}async function f(C=!0){if(C&&$.onStep)await $.onStep("lock-read-ready");let S;try{S=await q()}catch(u){if(I&&u.code!=="ENOENT")throw u}let x=Number(S?.expiresAt);if(Number.isFinite(x)&&x>z())return{status:"live"};if(typeof S?.ownerId==="string"&&Number.isFinite(x))return{status:"stale",identity:{kind:"owner",ownerId:S.ownerId,expiresAt:x}};try{let u=await X8(Z),$0=Number.isFinite(x)?x:u.mtimeMs+$.ttlMs;if($0>z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:u.dev,ino:u.ino,mtimeMs:u.mtimeMs,expiresAt:$0}}}catch(u){if(u.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw u}}function y(C,S){if(S.status!=="stale")return!1;let x=S.identity;if(C.kind==="owner"&&x.kind==="owner")return C.ownerId===x.ownerId&&C.expiresAt===x.expiresAt;return C.kind==="stat"&&x.kind==="stat"&&C.dev===x.dev&&C.ino===x.ino&&C.mtimeMs===x.mtimeMs&&C.expiresAt===x.expiresAt}async function h(){try{return JSON.parse(await _0(F,I))?.ownerId===L}catch(C){if(I&&C.code!=="ENOENT")throw C;return!1}}async function e(C){if(I)await q0(C,"remove",()=>O2(C,{recursive:!0,force:!0}));else await O2(C,{recursive:!0,force:!0}).catch(()=>{})}async function n(){if(await h())await e(D)}async function H2(){if(I)await s6(D);else await e6(D);try{let C=`${JSON.stringify({ownerId:L,createdAt:z()})}
8
- `;if(I)await a1(F,C);else await z8(F,C)}catch(C){if(JZ(C))return!1;throw await n(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function p1(){let C;try{C=await X8(D)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if(I)await G0(D,"directory",!0);if(C.mtimeMs+R>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let S=`${D}.${L2()}`;try{await Z8(D,S)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if($.onStep)await $.onStep("stale-marker-claimed");return await e(S),"recovered"}async function Y2(C){try{if(!await H2())return!1}catch(S){if(S.code==="EEXIST"){if(I){await G0(D,"directory",!0);try{await _0(F,!0)}catch(x){if(x.code!=="ENOENT")throw x}}return!1}throw S}try{await C()}finally{await n()}return!0}async function v(){for(let C=0;C<M;C++){if($.onStep)await $.onStep("relinquish-read");let S;try{S=await q()}catch(x){if(I)throw x;return}if(S?.ownerId!==J)return;try{await O2(Z,{recursive:!0,force:!0});return}catch(x){if(I)throw x;await w()}}}function v0(){if(!$.renew||B||Y)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=VJ(()=>{G=null;let S=(async()=>{let x=!B;try{if(!await Y2(async()=>{let $0=await q(),Q2=z();if(B||Y){x=!1;return}if($0?.ownerId!==J){K("taken-over",$0),x=!1;return}if(!(Number($0?.expiresAt)>Q2)){K("expired",$0),x=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(B||Y){x=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(B||Y){x=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(B||Y){x=!1;return}if(await _(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){K("marker-lost"),x=!1,await v();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(u){if(I&&u instanceof i)j=u,K("renewal-failed"),x=!1;try{let $0=await q();if($0?.ownerId!==J)K("taken-over",$0);else if(!(Number($0?.expiresAt)>z()))K("expired",$0)}catch{K("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(x&&!B&&!Y)v0()}})();N=S,S.finally(()=>{if(N===S)N=null})},C),"unref"in G)G.unref();V("scheduled")}function D6(){try{let C=$.onContended?.();if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")Promise.resolve(C).catch(()=>{})}catch{}return null}let P1=await b();if(!P1)for(let C=0;C<M;C++){if(P1=await b(),P1)break;let S=await f();if(S.status==="live")return D6();if(S.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await H2()){await w();continue}}catch(x){if(x.code!=="EEXIST")throw x;if(await p1()==="fresh")return null;await w();continue}try{let x=await f();if(x.status==="live")return D6();if(!y(S.identity,x))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let u=await f(!1);if(!y(S.identity,u))continue;if(await e(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(P1=await b(),!P1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),P1=!1,null;break}finally{await n()}}if(!P1)return null;return v0(),{ownerId:J,whenLost:()=>W,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(j)throw j;let C;try{let S=await q();if(C=S,!B&&!Y&&S?.ownerId===J&&Number(S?.expiresAt)>z())return;K(S?.ownerId!==J?"taken-over":"expired",S)}catch(S){if(K("unreadable"),I&&S instanceof i)throw S}throw new $1({target:$.path,name:$.name,expectedOwnerId:J,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}})},release:async()=>{if(I&&H)return;B=!0,U(),await N;for(let C=0;C<M;C++){try{let S=!1;if(await Y2(async()=>{let u;try{u=await q()}catch($0){if(I&&$0.code==="ENOENT"){S=!0;return}throw $0}if(u?.ownerId!==J){S=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await e(Z),S=!0})){if(I&&!S)throw new i(Z,"release-not-confirmed",{code:"EIO"});H=S;return}await p1()}catch(S){if(I)throw S;return}await w()}if(I)throw new i(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function zZ($,Z){return`${$}.${Z}.lock`}class l0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class $1 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function GZ($,Z,X){let J=performance.now();for(;;){Z.signal?.throwIfAborted();let z=await J0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(z)try{return Z.signal?.throwIfAborted(),await X(z)}finally{await z.release()}let G=Z.timeoutMs-(performance.now()-J);if(G<=0)throw new l0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((B)=>setTimeout(B,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as KJ}from"node:async_hooks";var B8=new KJ;function B0($){if(B8.getStore()!==void 0)throw new M2($)}function k0($,Z){return B8.run($,async()=>await Z())}async function H8($,Z,X,J,z){if(!Z)return;try{await k0($,()=>Z(X,J))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:X,error:G instanceof Error?G.message:String(G)})}}var BZ=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function DJ($,Z,X){let J=(B)=>{try{let H=X.onLockEvent?.({type:B,name:$.name,path:$.path});if(H&&(typeof H==="object"||typeof H==="function")&&"then"in H&&typeof H.then==="function")Promise.resolve(H).catch(()=>{})}catch{}},z={...Z,...qJ($)},G=performance.now();for(;;){let B=await J0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(Q)=>X.onRenewalTimer?.({name:$.name,path:$.path},Q)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...X.onLockStep?{onStep:(Q)=>X.onLockStep?.({name:$.name,path:$.path},Q)}:{}});if(B){J("acquired");let Q={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),J("released")}};try{await Q.assertOwned()}catch(W){throw await Q.release(),W}return Q}let H=z.timeoutMs-(performance.now()-G);if(H<=0)throw new l0({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Q)=>setTimeout(Q,Math.min(z.retryMs+Y,H)))}}function qJ($){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 Z1{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await DJ($,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)}}function A1($,Z,X){if(X!==void 0)throw new g({operation:$,rowId:Z,kind:"row-staged",phase:$==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${Z} is reserved for roster publication`})}import{createHash as C$}from"node:crypto";var p="commonAuthPool",X1=1,C0="rows",P2="retiredEpochs",T$=1,HZ=300000,m=p;function NJ($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(P(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function R1($){return C$("sha256").update(NJ($)).digest("hex")}function Y8($){if(!P($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function FJ($){if(!P($)||typeof $.reservation!=="string"||!$.reservation||typeof $.disabledReason!=="string")return;if(Object.keys($).some((Z)=>!["reservation","label","disabledReason","providerState"].includes(Z)))return;if("label"in $&&typeof $.label!=="string")return;if("providerState"in $&&(typeof $.providerState!=="string"||!/^[a-f0-9]{64}$/.test($.providerState)))return;return $}var Q0="commonAuthProviderState";function P($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var MJ=new Set(["__proto__","constructor","prototype"]);function o1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(MJ.has($))return"id is a reserved object key";return}function YZ($){let Z=typeof $==="string"?$.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}}function Q8($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function J1($){return C$("sha256").update(Q8($)).digest("hex")}function f0($){return C$("sha256").update(`credential-stamp\x00${Q8($)}`).digest("hex")}function d0($){let Z=$.type==="oauth"?["oauth",typeof $.access==="string"?$.access:null,$.refresh,typeof $.expires==="number"&&Number.isFinite($.expires)?$.expires:null]:["api",$.apiKey,$.baseURL.trim(),$.authHeader??"authorization-bearer"];return C$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function QZ($,Z,X,J={}){return{credentialEpoch:Z,digest:f0($),dispatch:d0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function t1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return C$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function S$($,Z,X,J){if(!Z||X===void 0)return;if(!P($)||!Object.hasOwn($,Q0))return;let z=j0($[m]);if(!z||z.providerState===void 0||z.digest!==f0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function z0($){return Number.isSafeInteger($)&&$>=1}function j0($){if(!P($))return;let Z=$.credentialEpoch;if(!z0(Z))return;if(typeof $.digest!=="string")return;if("dispatch"in $&&typeof $.dispatch!=="string")return;if("replace"in $&&$.replace!==!0)return;if("providerState"in $&&typeof $.providerState!=="string")return;let X="staged"in $?FJ($.staged):void 0;if("staged"in $&&!X)return;let J={...X?{staged:X}:{},...typeof $.dispatch==="string"?{dispatch:$.dispatch}:{},...$.replace===!0?{replace:!0}:{},...typeof $.providerState==="string"?{providerState:$.providerState}:{}};if(!("binding"in $))return"dispatch"in $||"replace"in $||"providerState"in $||"staged"in $?void 0:{credentialEpoch:Z,digest:$.digest};let z=$.binding;if(!P(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!YZ(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...J,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function _J($,Z,X){if($.identity!==X)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function LJ($,Z,X,J){if(!$)return"none";if(!P(J)||!Object.hasOwn(J,m))return"missing";let z=j0(J[m]);if(!z)return"malformed";if(z.digest!==f0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!_J(z.binding,$,X))return"mismatched";if(z.dispatch!==d0($))return"mismatched";return"bound"}function W8($){if(!$.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in $)return{status:"error",reason:"config file is not valid JSON"};let Z=$.value;if(!P(Z))return{status:"error",reason:"config root is not an object"};if("accounts"in Z&&!Array.isArray(Z.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(p in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let X=Z[p];if(!P(X))return{status:"error",reason:`${p} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${p}.schemaVersion is invalid`};if(J>X1)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${X1}`};if(C0 in X&&!P(X[C0]))return{status:"error",reason:`${p}.${C0} is not an object`};return{status:"ready",exists:!0,config:Z}}function V8($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!P($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!P($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function e1($){return Array.isArray($.accounts)?$.accounts:[]}function U8($){let Z=$[p];if(!P(Z))return{};let X=Z[C0];return P(X)?X:{}}function OJ($){return P($.accounts)?$.accounts:{}}function PJ($){if(!P($))return"not an object";let Z=o1($.id);if(Z)return Z;if($.type==="api")return YZ($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function CJ($,Z){if(!P($))return;let X=$.credentialEpoch;if(!z0(X))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let J="quota"in $&&Z.decode?Z.decode($.quota):$.quota;if("quota"in $&&!Z.validate(J))return;if("staged"in $&&!Y8($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function TJ($,Z){if(!P(Z))return;if($.type==="api"){let J=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!J)return;return{type:"api",apiKey:J,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let X=Z.refresh;if(typeof X!=="string"||!X.trim())return;return{type:"oauth",refresh:X,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function C2($,Z){return e1($).find((X)=>P(X)&&X.id===Z)}function j8($){if(!P($[p]))$[p]={};return $[p]}function WZ($){let Z=j8($);if(!P(Z[C0]))Z[C0]={};return Z[C0]}function z1($,Z){let X=U8($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return P(J)?J:void 0}function T2($,Z,X){Object.defineProperty(WZ($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function K8($,Z){let X=$[p];if(!P(X))return;let J=X[P2];if(!P(J)||!Object.hasOwn(J,Z))return;let z=J[Z];return z0(z)?z:void 0}function D8($,Z){let X=z1($,Z)?.credentialEpoch;return z0(X)?X:void 0}function S2($,Z){return Math.max(K8($,Z)??0,D8($,Z)??0)+1}function q8($,Z){let X=[...Z];if(X.length===0)return;let J=j8($),z=P(J[P2])?J[P2]:{},G={},B=(H,Y)=>Object.defineProperty(G,H,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[H,Y]of Object.entries(z))if(z0(Y))B(H,Y);for(let H of X)B(H,Math.max(K8($,H)??0,D8($,H)??1));J[P2]=G}function G1($,Z,X,J){let z=U8($),G=OJ(Z),B=new Set,H=[];for(let Y of e1($)){let Q=PJ(Y),W=P(Y)&&typeof Y.id==="string"?Y.id:void 0,V=W===void 0?void 0:z[W],U=P(V)&&Object.hasOwn(V,"staged"),K=U?Y8(V.staged):void 0;if(Q||!P(Y)||W===void 0||B.has(W)){if(W!==void 0&&!B.has(W))B.add(W);if(W!==void 0)H.push({id:W,type:P(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,W),candidate:!1,invalid:"roster",stamp:"none",...K?{staged:K}:{}});continue}B.add(W);let j=Y.type==="api"?"api":"oauth",N=Object.hasOwn(z,W),D=N?CJ(z[W],X):void 0,F=TJ(Y,G[W]),L=Y.enabled!==!1,R=D?D.credentialEpoch:N?void 0:1,M=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,q={id:W,type:j,enabled:L,needsFirstReading:D?D.needsFirstReading:j==="oauth",hasEntry:N,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...M!==void 0?{identity:M}:{},...F?{credential:F,fingerprint:J1(F)}:{},...D?{credentialEpoch:D.credentialEpoch}:{},...K?{staged:K}:{},...D?.disabledReason!==void 0?{disabledReason:D.disabledReason}:{},...D&&"quota"in D?{quota:D.quota}:{},...SJ(G[W],F,R,M,J),stamp:LJ(F,R,M,G[W])};if(N&&!D)q.invalid="entry";else q.candidate=L&&F!==void 0&&!U;H.push(q)}return H}function SJ($,Z,X,J,z){if(!P($)||!Object.hasOwn($,Q0))return{};let G=S$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let B=$[Q0];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(t1(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function l($){return $.identity??$.id}function A$($,Z){if($===void 0||$>Z+HZ)return Z;return Math.max(Z,$+1)}function VZ($,Z){return A$($,Z)>Z+HZ}function $$($){let{id:Z,credential:X,identity:J,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:X.type,addedAt:G,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function N8($,Z){if($.type==="api")return{apiKey:$.apiKey};return{...$.access!==void 0?{access:$.access}:{},refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{},...Z!==void 0?{lastRefreshedAt:Z}:{}}}function F8($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function M8($,Z={}){if(!P($))return"credential must be an object";if($.type==="oauth"){if(typeof $.refresh!=="string"||!$.refresh.trim())return"oauth credential needs a refresh token";return}if($.type==="api"){if(typeof $.apiKey!=="string"||!$.apiKey.trim())return"api credential needs an api key";if($.apiKey.trim()!==$.apiKey)return"api key must not carry surrounding whitespace";if(!(Z.baseURLOptional&&$.baseURL===void 0)&&!YZ($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var A2="transition",_8="transitionMark";function AJ($){if(!P($))return;let Z=$[A2];if(!P(Z))return;if(typeof Z.mark!=="string"||Z.mark.length===0)return;if(Z.enabled===!0)return{mark:Z.mark,enabled:!0};if(Z.enabled===!1&&typeof Z.reason==="string")return{mark:Z.mark,enabled:!1,reason:Z.reason};return}function R$($,Z,X){if(X.enabled)O$($,Z);else e0($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[_8]:X.mark}),!X.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)r1($,z.identity)}function RJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function EJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function IJ($,Z,X,J={}){let z=P(Z.accounts)?Z.accounts:{},G=new Map;for(let B of G1($,Z,X)){if(B.invalid||B.staged||!B.credential)continue;let H=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!P(H))continue;let Y=j0(H[m]);if(!Y?.binding)continue;if(Y.digest!==f0(B.credential))continue;let Q=B.credentialEpoch??1;if(Y.credentialEpoch>Q){if(!EJ(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==d0(RJ(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===Q&&Y.dispatch!==void 0&&Y.dispatch===d0(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===Q&&Y.binding.identity===B.identity){if(J.requireCredentialStamps&&Y.dispatch!==d0(B.credential))continue;let W=AJ(H[m]);if(W&&z1($,B.id)?.[_8]!==W.mark)G.set(B.id,{kind:"transition",transition:W})}}return G}function UZ($,Z,X,J){let G={...$.entry(Z)??{},credentialEpoch:X,needsFirstReading:!0};if(delete G.quota,J.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(n1))delete G.disabledReason;$.setEntry(Z,G);let B=$.rosterRow(Z);if(!B)return;if(J.identity!==void 0)B.accountId=J.identity;else delete B.accountId;if(J.baseURL!==void 0)B.baseURL=J.baseURL;if(J.authHeader!==void 0)B.authHeader=J.authHeader}function jZ($,Z,X,J={}){let z=IJ($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),B={rows:()=>G1(G,Z,X),rosterRow:(H)=>C2(G,H),entry:(H)=>z1(G,H),setEntry:(H,Y)=>T2(G,H,Y)};for(let[H,Y]of z)if(Y.kind==="replace")UZ(B,H,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[H,Y]of z)if(Y.kind==="identity")S1(B,H,Y.identity);else if(Y.kind==="transition")R$(B,H,Y.transition);else if(Y.stamp.binding.identity!==void 0)r1(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function KZ($,Z,X,J={}){let{config:z,torn:G}=jZ($,Z,X,J),B=G1(z,Z,X,J.providerState);for(let H of B){if(G.includes(H.id))H.torn=!0,H.candidate=!1;if(J.requireCredentialStamps&&H.stamp!=="bound")H.unbound=!0,H.candidate=!1}return B}async function DZ($){try{return await _0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function L8($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function W0($){for(let Z=0;Z<3;Z++){let X=await DZ($.configPath),J=await DZ($.statePath),z=await DZ($.configPath);if(X!==z){if(Z<2)await bJ(2+Math.floor(Math.random()*4));continue}let G=W8(L8(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=V8(L8(J));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:KZ(G.config,B.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function T0($,Z,X,J="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:$.reason});return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,retryable:!1,kind:$.status==="pending-migration"?"pending-migration":"load-error",message:$.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${$.file} file cannot be loaded: ${$.reason}`})}class O8{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,X,J,z){this.ctx=$,this.snapshot=Z,this.locks=X,this.progress=J,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return KZ(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row($){return this.rows().find((Z)=>Z.id===$)}reservation($){if(this.rosterRow($)){let X=this.entry($);return X&&Object.hasOwn(X,"staged")?X.staged:void 0}let Z=this.stateAccount($)?.[m];return P(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){A1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),C2(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(P(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return WZ(this.config)}entry($){return this.entries(),z1(this.config,$)}setEntry($,Z){T2(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=jZ(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(Z.length===0)return;this.config=$,await this.commitConfig({counted:!1})}stateAccount($){let Z=P(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return P(X)?X:void 0}dropStateAccount($){if(P(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!P(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,$,{value:Z,enumerable:!0,writable:!0,configurable:!0})}async commitConfig($={}){let Z=this.roster(),X=new Set;for(let Y of Z)if(P(Y)&&typeof Y.id==="string")X.add(Y.id);let J=new Set;for(let Y of e1(this.snapshot.config))if(P(Y)&&typeof Y.id==="string"&&!X.has(Y.id))J.add(Y.id);for(let Y of Object.keys(this.entries()))if(!X.has(Y))J.add(Y);q8(this.config,J);let z=this.entries(),G={};for(let[Y,Q]of Object.entries(z))if(X.has(Y))Object.defineProperty(G,Y,{value:Q,enumerable:!0,writable:!0,configurable:!0});let B=this.config[p],H={...this.config,version:T$,accounts:Z,[p]:{...B,schemaVersion:X1,[C0]:G}};await this.write(this.ctx.configPath,H,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of J)this.ctx.removedIds.add(Y);this.config=H}),this.config=H}async commitState($,Z={}){let X={...this.state,version:T$,accounts:P(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,X,"state",!0,Z.durable??!1),this.state=X,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await ZZ(this.ctx.statePath)}catch($){throw new g({operation:this.info.operation,rowId:this.info.rowId,phase:"before-first-write",kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await ZZ(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await $Z($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function P8($,Z){let X=new Z1($.lockDefaults,$.lockEnv),J={writes:0};try{for(let H of $.storeLocks)await X.acquire(H);let z=await W0($);if(z.status==="error")throw T0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[H,Y]of Object.entries(z.config))if(!Z.includes(H))G[H]=Y;G.version=T$,G[p]={schemaVersion:X1,[C0]:{}};let B={operation:"initialize",rowId:void 0};return await L0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",B),await X.assertAll()}}),J.writes++,await $.onStep?.("after-config-write",B),"initialized"}catch(z){throw Z$(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function t($,Z,X,J,z,G={}){let B=Z.held.length;try{for(let Q of $.storeLocks)await Z.acquire(Q);let H=await W0($);if(H.status!=="ready")throw T0(H,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let Y=new O8($,H,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))Y.assertNotStaged(J.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await Z.releaseTo(B)}}function Z$($,Z,X,J){let z=Z==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?J.committed:void 0;if(Z==="publishRoster"&&J.publicationDecided)return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:$});if(Z==="publishRoster"&&$ instanceof P$)return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof g){if($.phase===z&&$.rowId===X&&$.operation===Z&&$.committed===G)return $;return new g({operation:Z,...X!==void 0?{rowId:X}:{},phase:$.kind==="after-persist-hook"?$.phase:z,retryable:$.retryable,kind:$.kind,...$.committed??G?{committed:$.committed??G}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let B={operation:Z,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof $1)return new g({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${Z} lost a lease after its first write; the intermediate stays on disk`:`${Z} lost a lease before writing; nothing was written`});if($ instanceof l0)return new g({...B,retryable:!0,kind:"lock-contention",message:$.message});return new g({...B,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function H0($,Z,X,J,z){let G=new Z1($.lockDefaults,$.lockEnv),B={writes:0};try{return await z(G,B)}catch(H){let Y=Z$(H,Z,X,B);if(Y.kind!=="after-persist-hook")await H8(Z,J,X,Y,$.logger);throw Y}finally{await G.releaseAll()}}function F0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(l(Z))}`,path:$.ctx.statePath}}async function c0($,Z,X){let J=await W0($.ctx);if(J.status!=="ready")throw T0(J,Z,X);let z=J.rows.find((Q)=>Q.id===X),G=z1(J.config,X),B=J.state.accounts,H=P(B)&&Object.hasOwn(B,X)?B[X]:void 0,Y=P(H)?H[m]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))A1(Z,X,G.staged);if(!z&&P(Y)&&Object.hasOwn(Y,"staged"))A1(Z,X,Y.staged);if(!z)throw S0(Z,X);return{result:J,row:z}}function S0($,Z){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function V0($,Z){if(Z.unbound)throw O($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function O($,Z,X,J,z=!1){return new g({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:X,message:J})}async function R2($,Z,X,J){let{ctx:z}=$,G=new Z1(z.lockDefaults,z.lockEnv),B={writes:0};try{if(!z0(X?.credentialEpoch))throw O("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await t(z,G,B,{operation:"pull",rowId:Z},async(H)=>{H.assertNotStaged(Z);let Y=H.row(Z);if(!Y)throw S0("pull",Z);if(Y.invalid)throw O("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!Y.credential)throw O("pull",Z,"no-credential",`row ${Z} holds no credential`);V0("pull",Y);let Q=H.entry(Z);if(Y.torn||!Q||Q.credentialEpoch!==X.credentialEpoch||Y.identity!==X.identity)throw new g({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`});let W=z.codec.merge(Q.quota,J);if(!z.codec.validate(W))throw O("pull",Z,"invalid-quota","the quota codec rejected the merged map");H.setEntry(Z,{...Q,quota:W,needsFirstReading:!1}),await H.commitConfig()},{completeTorn:!1})}catch(H){throw Z$(H,"pull",Z,B)}finally{await G.releaseAll()}}function s0($,Z,X,J,z="the provider state"){if(!$)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(J);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw O(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw O(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function E$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:s0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function C8($,Z,X,J,z){let G=$?.onReplace,B=G?G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:X,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...J!==void 0?{identity:J}:{},...z!==void 0?{incoming:structuredClone(z)}:{}}):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:s0($,"replace",Z.id,B,"the provider state onReplace returned")}}function T8($,Z,X,J,z){if(Z.kind==="set")return t1($,Z.value);if(Z.kind==="clear")return;return S$(X,J?.credential,z,J?.identity)}async function S8($,Z,X,J,z={}){B0("updateProviderState");let{ctx:G}=$,B="updateProviderState";return H0(G,B,Z,z.onFailure,async(H,Y)=>{let Q=G.providerState;if(!Q)throw O(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw O(B,Z,"invalid-input","a mutator is required");let W=P(X)?X.credentialEpoch:void 0;if(!z0(W))throw O(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await c0($,B,Z);await H.acquire(F0($,V));for(let U of z.extraLocks??[])await H.acquire(U);return t(G,H,Y,{operation:B,rowId:Z},async(U)=>{let K=U.row(Z);if(!K)throw S0(B,Z);if(l(K)!==l(V))throw O(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(K.invalid)throw O(B,Z,"invalid-row",`row ${Z} failed validation`);if(!K.credential)throw O(B,Z,"no-credential",`row ${Z} holds no credential`);if(V0(B,K),(K.credentialEpoch??1)!==W||K.identity!==X.identity)throw O(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let N=await qZ(U,Q,B,K,J);if(N.kind!=="changed")return{id:Z,outcome:"unchanged",...N.kind==="unchanged"&&N.value!==void 0?{providerState:N.value}:{}};return U.setStateAccount(Z,N.account),await U.commitState(),N.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:N.value}})})}var A8=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function qZ($,Z,X,J,z,G=!1){let{id:B,credential:H}=J;if(!H)throw O(X,B,"no-credential",`row ${B} holds no credential`);let Y=J.credentialEpoch??1,Q=$.stateAccount(B),W=Q?.[m],V=j0(W);if(!P(W)||!V?.binding||V.digest!==f0(H)||V.credentialEpoch!==Y||V.binding.identity!==J.identity)throw O(X,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let U=J.providerState===void 0?void 0:structuredClone(J.providerState),K=await k0(X,()=>z(U,J));if(G&&K===A8)return{kind:"declined"};let j=K===void 0?void 0:s0(Z,X,B,K,"the provider state the mutator returned"),N=Q!==void 0&&Object.hasOwn(Q,Q0);if(j===void 0?!N:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(j))return{kind:"unchanged",...j!==void 0?{value:j}:{}};let D={...Q};if(j===void 0){delete D[Q0];let F={...W};delete F.providerState,D[m]=F}else{D[Q0]=j;let F=t1(Z,j);if(V.providerState!==F)D[m]={...W,providerState:F}}return{kind:"changed",...j!==void 0?{value:j}:{},account:D}}import{randomUUID as R8}from"node:crypto";async function x2($,Z,X){if(!X)return;let J=$.rows().map((G)=>{let{id:B,type:H,label:Y,enabled:Q,disabledReason:W,identity:V,credentialEpoch:U,stamp:K,staged:j,torn:N,invalid:D}=G;return{id:B,type:H,label:Y,enabled:Q,disabledReason:W,identity:V,credentialEpoch:U,stamp:K,staged:j,torn:N,invalid:D}}),z=await k0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw O($.info.operation,Z,"row-protected",z)}var xJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function kJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function fJ($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!P(J)){if(X.baseURL===void 0)throw O($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...X,baseURL:X.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:kJ(J),B=X.baseURL?.trim()??G.baseURL,H=X.authHeader??G.authHeader;if(B!==G.baseURL||H!==G.authHeader)throw O($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:B,authHeader:H}}function E8($,Z,X,J){let z=$.rosterRow(Z),G=$.row(Z),B=J??(G?G.identity:P(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function E2($,Z,X,J,z={}){let G=fJ(Z,X,J),B=Z.stateAccount(X),H=z.providerState??{kind:"keep"},Y=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,Q=typeof Y==="number"?Y:1,W=T8($.ctx.providerState,H,B,B&&Object.hasOwn(B,Q0)?Z.row(X):void 0,Q),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??A$(V,$.ctx.now()):void 0,K={...B??{}};for(let D of xJ)delete K[D];if(z.clearErrors)delete K.lastRefreshError,delete K.lastQuotaRefreshError,delete K.quota;if(H.kind==="clear")delete K[Q0];else if(H.kind==="set")K[Q0]=H.value;let j=F8(G,U),N={...K,...N8(G,U),[m]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[A2]:z.transition}:{},...QZ(j,Q,z.binding??E8(Z,X,j,z.identity),{replace:z.binding!==void 0,...W!==void 0?{providerState:W}:{}})}};return{stored:j,account:N}}async function I2($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function k2($,Z,X,J,z={}){return I2(Z,X,E2($,Z,X,J,z))}async function yJ($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=S$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:QZ(Z.credential,Z.credentialEpoch??1,E8($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function FZ($,Z,X){let J=$==="add"?o1(Z):void 0;if(J)throw O($,Z,"invalid-input",J);let z=M8(X,{baseURLOptional:$==="rotate"});if(z)throw O($,Z,"invalid-input",z)}function f2($,Z,X,J){if(!X)throw S0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw O($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function J$($,Z,X){if(X!==void 0&&!z0(P(X)?X.credentialEpoch:void 0))throw O($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function y2($,Z,X,J){if(!X)throw S0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw O($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function b2($,Z){return O($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function I$($,Z){return O($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function gJ($,Z,X,J){let{id:z,credential:G,identity:B}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!X$(Z.state,z))return;let H=()=>{throw O("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(z),Q=j0(Y?.[m]);if(!Q?.binding||Q.dispatch===void 0||Q.replace)return H();if(G.type==="api"&&(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0))return H();let W=G.type==="api"?{...G,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}:G,[V]=G1({accounts:[$$({id:z,credential:W,identity:Q.binding.identity,addedAt:0})],[p]:{rows:{[z]:{credentialEpoch:S2(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return H();if(B!==void 0&&B!==V.identity)return H();if(f0(G)!==Q.digest)return H();if(G.type==="api"){if(G.baseURL.trim()!==Q.binding.baseURL)return H();if((G.authHeader??"authorization-bearer")!==Q.binding.authHeader)return H()}else if(d0(G)!==Q.dispatch)return H();if(Q.providerState!==void 0&&V.providerState===void 0)return H();if(J!==void 0&&t1($.ctx.providerState,J)!==Q.providerState)return H();return V}function hJ($,Z,X,J){let{id:z,credential:G,identity:B,label:H}=X,Y=Z.rosterRow(z),Q=()=>{throw O("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},W=Z.stateAccount(z),V=j0(W?.[m]),U=V?.staged;if(!V?.binding||!U||V.replace||V.dispatch===void 0)return Q();if(Y&&(Y.type!==G.type||Y.label!==H||Y.accountId!==B))return Q();if(U.reservation!==X.stage?.reservation||U.label!==H||U.disabledReason!==X.disabled?.reason||V.binding.identity!==B)return Q();let K=J===void 0?void 0:R1(J),j=W?.[Q0],N=j===void 0?void 0:R1(j);if(U.providerState!==K||U.providerState!==N)return Q();if(f0(G)!==V.digest||d0(G)!==V.dispatch)return Q();let D=Y?Z.config:{accounts:[{...$$({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[p]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},F=G1(D,Z.state,$.ctx.codec,$.ctx.providerState).find((L)=>L.id===z);if(!F?.credential||F.invalid||F.stamp!=="bound"||F.type!==G.type||F.enabled||F.label!==U.label||F.identity!==V.binding.identity||F.disabledReason!==U.disabledReason||F.staged?.reservation!==U.reservation)return Q();if(Y)return{id:z,outcome:"exists",credential:F.credential,credentialEpoch:V.credentialEpoch};if(S2(Z.config,z)!==V.credentialEpoch)return Q();return Z.roster().push({...$$({id:z,credential:G,identity:B,label:H,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:F.credential,credentialEpoch:V.credentialEpoch}))}async function I8($,Z,X={}){B0("add");let{ctx:J}=$,{id:z,credential:G,identity:B,label:H}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,Q=await H0(J,"add",z,X.onFailure,async(W,V)=>{FZ("add",z,G);let U=X.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw O("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(U)||Z.stage!==void 0&&(H!==void 0&&typeof H!=="string"||B!==void 0&&(typeof B!=="string"||!B))||Z.disabled!==void 0&&(!P(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!P(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||U==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw O("add",z,"invalid-input","staging requires a reservation and a disabled reason");let K=Z.providerState===void 0?void 0:s0(J.providerState,"add",z,Z.providerState);if(await W.acquire(F0($,{id:z,identity:B})),G.type==="oauth")await W.acquire(X.providerLock??$.providerLock);for(let j of X.extraLocks??[])await W.acquire(j);return t(J,W,V,{operation:"add",rowId:z},async(j)=>{await x2(j,z,X.protect);let N=P(j.state.accounts)?j.state.accounts:{},D=Object.entries(N).find(([f,y])=>{if(f===z||j.rosterRow(f)||!P(y))return!1;let h=y[m];if(!P(h)||!Object.hasOwn(h,"staged"))return!1;return G.type==="oauth"?y.refresh===G.refresh:typeof y.apiKey==="string"&&y.apiKey.trim()===G.apiKey.trim()});if(D)throw O("add",D[0],"row-staged",`orphan ${D[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(z))throw O("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&U!=="rotate"&&(j.rosterRow(z)||X$(j.state,z)))return hJ($,j,Z,K);if(U==="rotate"){j.assertNotStaged(z);let f=j.rows().find((y)=>y.fingerprint===J1(G));if(f)j.assertNotStaged(f.id)}if(U==="refuse"){let f=j.rows().find((n)=>n.fingerprint===J1(G)||n.id===z&&n.credential),y=P(j.state.accounts)?j.state.accounts:{},h=Object.entries(y).find(([,n])=>{if(!P(n))return!1;if(G.type==="oauth")return n.refresh===G.refresh;return typeof n.apiKey==="string"&&n.apiKey.trim()===G.apiKey.trim()})?.[0],e=f?.id??h??z;if(f||h!==void 0||X$(j.state,z))throw O("add",e,"credential-exists",`row ${e} already holds this secret or id`)}if(U==="stage-duplicate"&&(j.rosterRow(z)||X$(j.state,z)))throw O("add",z,"id-exists",`row ${z} already exists`);let F=gJ($,j,Z,K),L=j.rows(),R=J1(G),M=U==="rotate"&&!F&&L.find((f)=>f.invalid===void 0&&f.fingerprint===R);if(M){if(j.assertNotStaged(M.id),V0("add",M),B!==void 0&&M.identity!==void 0&&B!==M.identity)throw b2("add",M.id);let f=E2($,j,M.id,G,{...K!==void 0?{providerState:E$(J.providerState,"add",M.id,M.providerState,K)}:{}});await j.completeTorn(),j.assertNotStaged(M.id);let y=await I2(j,M.id,f);return{id:M.id,outcome:"rotated",credential:y,credentialEpoch:M.credentialEpoch??1}}let q=L.find((f)=>f.id===z);if(q){if(q.invalid)throw O("add",z,"invalid-row",`row ${z} is invalid`);if(q.credential)throw O("add",z,"id-exists",`row ${z} already holds a credential`);if(V0("add",q),q.type!==G.type)throw O("add",z,"type-mismatch",`row ${z} is a ${q.type} row`);if(B!==void 0&&q.identity!==void 0&&B!==q.identity)throw b2("add",z);if(!q.hasEntry)j.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let f=E2($,j,z,G,{clearErrors:!0,...K!==void 0?{providerState:{kind:"set",value:K}}:{}});await j.completeTorn();let y=await I2(j,z,f);if(!q.hasEntry)await j.commitConfig();return{id:z,outcome:"completed",credential:y,credentialEpoch:q.credentialEpoch??1}}let _=S2(j.config,z);if(!z0(_))throw O("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=F?.identity??B;j.roster().push($$({id:z,credential:G,...A!==void 0?{identity:A}:{},...H!==void 0?{label:H}:{},addedAt:J.now()})),j.setEntry(z,{credentialEpoch:_,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let T="added";if(Z.disabled)e0(j,z,Z.disabled.reason),T="added-disabled";if(!Z.disabled&&A!==void 0&&G.type==="oauth"){if(L.find((y)=>y.invalid===void 0&&y.type==="oauth"&&y.enabled&&y.identity===A))e0(j,z,t3),T="added-disabled"}if(F?.credential)return await j.commitConfig(),{id:z,outcome:T,credential:F.credential,credentialEpoch:F.credentialEpoch??_};j.dropStateAccount(z);let b=E2($,j,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...H!==void 0?{label:H}:{},...K!==void 0?{providerState:R1(K)}:{}}}:{},...K!==void 0?{providerState:{kind:"set",value:K}}:{}});if(U==="rotate")await j.completeTorn();let w=await I2(j,z,b);return await j.commitConfig(),{id:z,outcome:T,credential:w,credentialEpoch:_}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(Q.outcome==="added"||Q.outcome==="completed"))$.firePull(Q.id,"add");return Q}async function b8($,Z,X,J={},z={}){B0("replace");let{ctx:G}=$,B=await H0(G,"replace",Z,z.onFailure,async(H,Y)=>{FZ("replace",Z,X),J$("replace",Z,z.attribution);let Q=J.providerState===void 0?void 0:s0(G.providerState,"replace",Z,J.providerState),{row:W}=await c0($,"replace",Z);if(await H.acquire(F0($,W)),X.type==="oauth")await H.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await H.acquire(V);return t(G,H,Y,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)y2("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let U=f2("replace",Z,V.row(Z),X);if(l(U)!==l(W))throw I$("replace",Z);let K=V.entry(Z)?.credentialEpoch,j=(typeof K==="number"?K:1)+1;if(!z0(j))throw O("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let N=C8(G.providerState,U,j,J.identity,Q),D={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(UZ(V,Z,j,D),J.identity!==void 0)r1(V,J.identity);let F=await k2($,V,Z,X,{clearErrors:!0,binding:D,providerState:N});return await V.commitConfig(),{id:Z,credential:F,credentialEpoch:j}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return B}async function x8($,Z,X,J={},z={}){B0("rotate");let{ctx:G}=$;return H0(G,"rotate",Z,z.onFailure,async(B,H)=>{FZ("rotate",Z,X),J$("rotate",Z,z.attribution);let Y=J.providerState===void 0?void 0:s0(G.providerState,"rotate",Z,J.providerState),{row:Q}=await c0($,"rotate",Z);if(await B.acquire(F0($,Q)),J.identity!==void 0&&X.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await B.acquire(W);return t(G,B,H,{operation:"rotate",rowId:Z},async(W)=>{if(z.attribution!==void 0)y2("rotate",Z,W.row(Z),z.attribution),await W.completeTorn();let V=f2("rotate",Z,W.row(Z),X);if(l(V)!==l(Q))throw I$("rotate",Z);if(V0("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw b2("rotate",Z);let U=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,K=await k2($,W,Z,X,{identity:U,...Y!==void 0?{providerState:E$(G.providerState,"rotate",Z,V.providerState,Y)}:{}}),j=!1;if(!V.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),j=!0;if(J.identity!==void 0&&V.identity!==J.identity)S1(W,Z,J.identity),j=!0;if(j)await W.commitConfig();return{id:Z,credential:K}},{completeTorn:z.attribution===void 0})})}async function k8($,Z,X,J,z){B0(Z);let{ctx:G}=$,B=G.providerState,H=z.attribution,Y=z.providerState;return H0(G,Z,X,z.onFailure,async(Q,W)=>{if(J$(Z,X,H),Y!==void 0){if(typeof Y!=="function")throw O(Z,X,"invalid-input","the provider-state mutator must be a function");if(H===void 0)throw O(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await c0($,Z,X);await Q.acquire(F0($,V));for(let U of z.extraLocks??[])await Q.acquire(U);return t(G,Q,W,{operation:Z,rowId:X},async(U)=>{await x2(U,X,z.protect),U.assertNotStaged(X);let K=U.row(X),j=J.enabled?f2("enable",X,K):K;if(!j||!U.rosterRow(X))throw S0(Z,X);if(l(j)!==l(V))throw I$(Z,X);if(H!==void 0)y2(Z,X,j,H);if(J.enabled&&j.disabledReason?.startsWith(n1))throw O("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let N=!J.enabled||!j.enabled||j.disabledReason!==void 0;if(J.enabled&&N&&j.type==="oauth"){let M=j.identity===void 0?void 0:U.rows().find((q)=>q.id!==X&&q.invalid===void 0&&q.type==="oauth"&&q.enabled&&q.identity===j.identity);if(M)throw O("enable",X,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${X}`)}if(Y===void 0||B===void 0){if(await U.completeTorn(),!N)return{id:X};if(J.enabled)O$(U,X);else e0(U,X,J.reason);return await U.commitConfig(),{id:X}}if(!j.credential)throw O(Z,X,"no-credential",`row ${X} holds no credential`);V0(Z,j);let D=await qZ(U,B,Z,j,Y,!0);if(D.kind==="declined")return{id:X,declined:!0};await U.completeTorn();let F={id:X,providerStateOutcome:D.kind==="unchanged"?"unchanged":D.value===void 0?"cleared":"updated",...D.value!==void 0?{providerState:D.value}:{}};if(D.kind==="unchanged"){if(N){if(J.enabled)O$(U,X);else e0(U,X,J.reason);await U.commitConfig()}return F}if(!N)return U.setStateAccount(X,D.account),await U.commitState(),F;let L=J.enabled?{mark:R8(),enabled:!0}:{mark:R8(),enabled:!1,reason:J.reason},R=D.account[m];return U.setStateAccount(X,{...D.account,[m]:{...R,[A2]:L}}),await U.commitState(),R$(U,X,L),await U.commitConfig(),F},{completeTorn:!1})})}function f8($,Z,X,J={}){return k8($,"disable",Z,{enabled:!1,reason:X},J)}function y8($,Z,X={}){return k8($,"enable",Z,{enabled:!0},X)}async function g8($,Z,X={}){B0("remove");let{ctx:J}=$;return H0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw O("remove",Z,"invalid-input","id must be non-empty");let B=X.attribution;if(J$("remove",Z,B),X.staged!==void 0&&(!P(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw O("remove",Z,"invalid-input","a staged removal needs a reservation");let H=await W0(J);if(H.status!=="ready")throw T0(H,"remove",Z);let Y=H.rows.find((W)=>W.id===Z);if(!Y&&!X$(H.state,Z))throw S0("remove",Z);let Q=l(Y??{id:Z});await z.acquire(F0($,Y??{id:Z}));for(let W of X.extraLocks??[])await z.acquire(W);return t(J,z,G,{operation:"remove",rowId:Z},async(W)=>{let V=W.reservation(Z);if(V!==void 0){if(!P(V)||!X.staged||V.reservation!==X.staged.reservation)throw O("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw O("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=W.row(Z),K=X$(W.state,Z);if(!U&&!K)throw S0("remove",Z);if(l(U??{id:Z})!==Q)throw I$("remove",Z);if(B!==void 0)if(U)g2(Z,U,B);else vJ($,W,Z,B);let j=X.protect;if(j){let N={row:U,config:W.snapshot.config,state:W.snapshot.state},D=await k0("remove",()=>j(Z,N));if(D!==void 0)throw O("remove",Z,"row-protected",D)}if(U){if(B===void 0)await W.completeTorn();W.dropRosterRows(Z),await W.commitConfig()}if(K)W.dropStateAccount(Z),await W.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function g2($,Z,X,J="remove"){if(y2(J,$,Z,X),Z.torn)throw O(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw O(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function vJ($,Z,X,J){let z=()=>O("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(X),B=j0(G?.[m]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let H;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();H={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")H={type:"oauth",refresh:G.refresh};else throw z();let[Y]=G1({accounts:[$$({id:X,credential:H,identity:B.binding.identity,addedAt:0})],[p]:{rows:{[X]:{credentialEpoch:B.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==J.credentialEpoch||B.binding.identity!==J.identity)throw O("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function X$($,Z){let X=$.accounts;return P(X)&&Object.hasOwn(X,Z)}function NZ($){return P($)&&typeof $.id==="string"?$.id:void 0}function mJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let B=NZ(G);if(B!==void 0)X.add(B)}let J=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(J.has(G))return`id ${G} appears more than once`;if(!X.has(G))return`id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function wJ($,Z){let X=new Map;for(let G of $){let B=NZ(G);if(B===void 0)continue;let H=X.get(B);if(H)H.push(G);else X.set(B,[G])}let J=Z.flatMap((G)=>X.get(G)??[]),z=0;return $.map((G)=>NZ(G)===void 0?G:J[z++])}async function h8($,Z,X={}){B0("reorder");let{ctx:J}=$,z=X.onFailure;return H0(J,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let H of X.extraLocks??[])await G.acquire(H);return t(J,G,B,{operation:"reorder",rowId:void 0},async(H)=>{let Y=H.roster(),Q=mJ(Y,Z);if(Q)throw new g({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Q});let W=[...Z],V=wJ(Y,W);if(V.every((U,K)=>U===Y[K]))return{ids:W,outcome:"unchanged"};return H.config.accounts=V,await H.commitConfig(),{ids:W,outcome:"reordered"}},{completeTorn:!1})})}async function v8($,Z,X,J,z={}){return B0("recordIdentity"),H0($.ctx,"recordIdentity",Z,z.onFailure,async(G,B)=>{if(typeof X!=="string"||X.length===0)throw O("recordIdentity",Z,"invalid-input","identity must be non-empty");let H=P(J)?J.credentialEpoch:void 0;if(!z0(H))throw O("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await c0($,"recordIdentity",Z);await G.acquire(F0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let Q of z.extraLocks??[])await G.acquire(Q);return t($.ctx,G,B,{operation:"recordIdentity",rowId:Z},async(Q)=>{let W=f2("recordIdentity",Z,Q.row(Z));if(l(W)!==l(Y))throw I$("recordIdentity",Z);if(V0("recordIdentity",W),(W.credentialEpoch??1)!==H)throw O("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(W.identity!==void 0&&W.identity!==X)throw b2("recordIdentity",Z);if(W.identity===void 0)await yJ(Q,W,X);let V=S1(Q,Z,X);return await Q.commitConfig(),{id:Z,disabled:V}})})}function w8($){let Z=$[p];return P(Z)&&P(Z.publications)?Z.publications:{}}function p8($,Z){let X=w8($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!P(J)||J.operationId!==Z||typeof J.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(J.planDigest)||!["committed","cleaned"].includes(String(J.phase))||!Array.isArray(J.removed)||!Array.isArray(J.finalized)||J.removed.some((z)=>!P(z)||typeof z.id!=="string"||!z0(z.credentialEpoch))||J.finalized.some((z)=>!P(z)||typeof z.id!=="string"||!z0(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw O("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function u8($,Z){let X=await W0($.ctx);if(X.status!=="ready")throw T0(X,"publishRoster",Z);return p8(X.config,Z)}function pJ($,Z){let X=()=>{throw O("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!P(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))X();let J=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!P(z)||typeof z.id!=="string"||o1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),J$("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))X()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")X();for(let z of Z.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))X();if(Z.order.some((z)=>typeof z!=="string"||o1(z))||new Set(Z.order).size!==Z.order.length)X()}function l8($,Z){$.entries();let X=$.config[p],J={...w8($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function uJ($,Z,X){let J=new Set;for(let B of e1($.config)){if(!P(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw O("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(B.id)}let z=new Set(Z.remove.map((B)=>B.id)),G=X.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==Z.order.length||Z.order.some((B)=>!G.some((H)=>H.id===B))||G.some((B)=>!Z.order.includes(B.id)))throw O("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function m8($,Z){await $.assertAll();for(let J of Z.removed)if(j0($.stateAccount(J.id)?.[m])?.credentialEpoch===J.credentialEpoch&&!$.rosterRow(J.id))$.dropStateAccount(J.id);for(let J of Z.finalized){let z=$.stateAccount(J.id),G=j0(z?.[m]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let B={...z[m]};delete B.staged,$.setStateAccount(J.id,{...z,[m]:B})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return l8($,X),await $.commitConfig({durable:!0}),X}async function d8($,Z,X={}){return B0("publishRoster"),H0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!P(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw O("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=R1(Z),B=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((H)=>P(H)&&typeof H.id==="string");for(let H=0;;H++){let Y=await W0($.ctx);if(Y.status!=="ready")throw T0(Y,"publishRoster",Z.operationId);let Q=new Map(B.map(({id:V})=>[V,l(Y.rows.find((U)=>U.id===V)??{id:V})]));for(let V of[...new Set(Q.values())].sort())await J.acquire(F0($,{id:V}));await J.acquire(X.providerLock??$.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let W=await t($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let U=V.rows();if(B.some(({id:q})=>l(U.find((_)=>_.id===q)??{id:q})!==Q.get(q)))return;let K=p8(V.config,Z.operationId);if(K){if(K.planDigest!==G)throw O("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(K.phase==="cleaned")return{outcome:"already-cleaned",receipt:K};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await m8(V,K)}}pJ($,Z);let j=uJ(V,Z,U),N=[];for(let q of Z.remove){V.assertNotStaged(q.id);let _=U.find((A)=>A.id===q.id);if(!_)throw O("publishRoster",q.id,"attribution","the removed row no longer exists");if(g2(q.id,_,q.attribution,"publishRoster"),!_.credential||q.fingerprint!==void 0&&J1(_.credential)!==q.fingerprint)throw O("publishRoster",q.id,"attribution","the removed secret no longer matches");N.push(_)}let D=[];for(let q of Z.finalize){let _=U.find((y)=>y.id===q.id),A=j0(V.stateAccount(q.id)?.[m]);if(!_||_.staged?.reservation!==q.reservation||A?.staged?.reservation!==q.reservation||_.enabled)throw O("publishRoster",q.id,"row-staged","the finalized row is not disabled under this reservation");let T=V.stateAccount(q.id),b=V.rosterRow(q.id),w=T?.[Q0],f=w===void 0?void 0:R1(w);if(!A?.staged||A.staged.label!==b?.label||A.staged.disabledReason!==_.disabledReason||A.staged.providerState!==f)throw O("publishRoster",q.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");g2(q.id,_,q.attribution,"publishRoster"),D.push(_)}let F=j.find((q)=>q.torn);if(F)throw O("publishRoster",Z.operationId,"attribution",`Row ${F.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let L=new Set;for(let q of j){if(!(Z.finalize.find((A)=>A.id===q.id)?.enabled??q.enabled)||q.type!=="oauth"||q.identity===void 0)continue;if(L.has(q.identity))throw O("publishRoster",q.id,"invalid-input","the final enabled roster repeats a known identity");L.add(q.identity)}for(let q of j)if(q.identity!==void 0&&q.fingerprint!==void 0&&j.some((_)=>_.id!==q.id&&_.identity!==void 0&&_.identity!==q.identity&&_.fingerprint===q.fingerprint))throw O("publishRoster",q.id,"attribution","the resulting pool gives the same secret different known identities");for(let q of D)if(q.identity!==void 0&&N.some((_)=>_.identity!==void 0&&_.identity!==q.identity&&_.fingerprint===q.fingerprint))throw O("publishRoster",q.id,"attribution","the staged secret belonged to a different known identity");await x2(V,Z.operationId,X.protect);let R={operationId:Z.operationId,planDigest:G,phase:"committed",removed:N.map((q)=>({id:q.id,credentialEpoch:q.credentialEpoch??1})),finalized:Z.finalize.map((q,_)=>({id:q.id,credentialEpoch:D[_]?.credentialEpoch??1,reservation:q.reservation,enabled:q.enabled}))};for(let q of Z.remove)V.dropRosterRows(q.id);for(let q of Z.finalize){let _=V.rosterRow(q.id);_.enabled=q.enabled;let A={...V.entry(q.id)};if(delete A.staged,q.enabled)delete A.disabledReason;else A.disabledReason=q.disabledReason;V.setEntry(q.id,A)}let M=V.roster().filter((q)=>!P(q)||typeof q.id!=="string"||U.find((_)=>_.id===q.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((q)=>V.rosterRow(q)),...M],l8(V,R),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await m8(V,R)}},{completeTorn:!1});if(W)return W;if(await J.releaseAll(),H>=1)throw O("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class MZ{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,X,J,z){this.rt=$,this.hook=Z,this.onFailure=X,this.firedAtLoad=J,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let X=this.run($,Z);this.inflight.add(X),X.finally(()=>this.inflight.delete(X))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let X=this.rt(),{ctx:J}=X,z=new Z1(J.lockDefaults,J.lockEnv),G={writes:0};try{let B=await t(J,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let Q=Y.row($);if(Q?.unbound&&Q.enabled&&Q.type==="oauth"&&Q.credential&&!Q.invalid)V0("pull",Q);if(!Q?.candidate||Q.type!=="oauth")return;if(!Q.hasEntry)Y.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Y.commitConfig();let W=Y.row($);if(!W?.credential||W.credentialEpoch===void 0)return;return{id:$,credential:W.credential,credentialEpoch:W.credentialEpoch,...W.identity!==void 0?{identity:W.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let H;try{H=await this.hook?.(B)}catch(Y){throw new g({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await R2(X,$,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},H)}catch(B){this.firedAtLoad.delete($);let H=Z$(B,"pull",$,G);if(this.onFailure)try{await this.onFailure($,H)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:H.kind})}finally{await z.releaseAll()}}}import{randomUUID as lJ}from"node:crypto";function _Z($,Z){if(A1("refresh",$,Z?.staged),!Z)throw O("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw O("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw O("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw O("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function c8($){return O("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function s8($,Z,X,J={}){B0("refresh");let{ctx:z}=$;return H0(z,"refresh",Z,J.onFailure,async(G,B)=>{let{row:H}=await c0($,"refresh",Z);_Z(Z,H);let Y=await J.refuse?.(H);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let Q=l(H),W;for(let j=0;;j++){await G.acquire(F0($,{id:Z,identity:Q===Z?void 0:Q})),await G.acquire(J.providerLock??$.providerLock);for(let F of J.extraLocks??[])await G.acquire(F);let D=await t(z,G,{writes:0},{operation:"refresh",rowId:Z},async(F)=>{let L=_Z(Z,F.row(Z));if(V0("refresh",L),!L.hasEntry)F.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await F.commitConfig(),L=_Z(Z,F.row(Z));if(l(L)!==Q)return{keyNow:l(L)};let R=await J.refuse?.(L);if(R!==void 0)return{refused:R};return{row:L,credential:L.credential,credentialEpoch:L.credentialEpoch,identity:L.identity}});if("refused"in D)return{status:"refused",rowId:Z,reason:D.refused};if("keyNow"in D){if(await G.releaseAll(),j>=1)throw O("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Q=D.keyNow;continue}W=D;break}if(VZ(W.credential.lastRefreshedAt,z.now()))throw c8(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await X(W.credential,W.row)}catch(j){throw new g({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:j})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw O("refresh",Z,"provider","the provider returned no refresh token",!0);let U=V.providerState===void 0?void 0:s0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),K=await t(z,G,B,{operation:"refresh",rowId:Z},async(j)=>{let N=j.row(Z),D=j.entry(Z);if(!N||N.invalid||!D||D.credentialEpoch!==W.credentialEpoch||N.identity!==W.identity)throw new g({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${Z} changed credential while its refresh was in flight; the rotation is discarded`});V0("refresh",N);let F=await J.refuse?.(N);if(F!==void 0)return{refused:F};let L=z.now(),R=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if(VZ(R,L))throw c8(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},q=N.identity!==void 0&&V.identity!==void 0&&N.identity!==V.identity?{expectedIdentity:N.identity,returnedIdentity:V.identity}:void 0,_=q?{mark:lJ(),enabled:!1,reason:`${n1}${JSON.stringify(q)}`}:void 0,A=N.identity===void 0&&V.identity?V.identity:void 0,T=await k2($,j,Z,M,{stamp:A$(R,L),transition:_,identity:A,...U!==void 0?{providerState:E$(z.providerState,"refresh",Z,N.providerState,U)}:{}});if(_!==void 0)R$(j,Z,_),await j.commitConfig();let b=N.identity;if(A!==void 0)S1(j,Z,A),b=A,await j.commitConfig();return{stored:T,identity:b,contradiction:q,refused:void 0}});if(K.refused!==void 0)return{status:"refused",rowId:Z,reason:K.refused};if(K.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...K.contradiction,credential:K.stored};if(J.onPersisted)try{let j=J.onPersisted;await k0("refresh",()=>j(Z,K.stored))}catch(j){throw new g({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:K.stored,message:"the after-persist hook threw; the rotation stays committed",cause:j})}return{status:"rotated",rowId:Z,credential:K.stored,...K.identity!==void 0?{identity:K.identity}:{}}})}import{isDeepStrictEqual as dJ}from"node:util";var v2=Object.freeze(["version","accounts",p]);function LZ($){let Z={};for(let[X,J]of Object.entries($))if(!v2.includes(X))h2(Z,X,J);return Z}function h2($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function cJ($,Z){let X={};for(let[J,z]of Object.entries($))if(v2.includes(J))h2(X,J,z);else if(Object.hasOwn(Z,J))h2(X,J,Z[J]);for(let[J,z]of Object.entries(Z))if(!Object.hasOwn($,J))h2(X,J,z);return X}function a8($){return new g({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function i8($){let Z=await W0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:LZ(Z.config)}}async function n8($,Z,X={}){B0("updateSettings");let{ctx:J}=$,z=X.onFailure;return H0(J,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of X.extraLocks??[])await G.acquire(Y);let H=G.held.length;try{for(let D of J.storeLocks)await G.acquire(D);let Y=await W0(J);if(Y.status!=="ready")throw T0(Y,"updateSettings",void 0);let Q=LZ(Y.config),W=structuredClone(Q),V=await k0("updateSettings",()=>Z(W)),U=V===void 0?W:V;if(!P(U))throw a8("the settings mutator must produce an object");let K=v2.filter((D)=>Object.hasOwn(U,D));if(K.length>0)throw a8(`settings cannot set the pool-owned key(s) ${K.join(", ")}`);if(dJ(U,Q))return{settings:Q,outcome:"unchanged"};let j=cJ(Y.config,U),N={operation:"updateSettings",rowId:void 0};return await L0(J.configPath,j,{beforeRename:async()=>{await J.onStep?.("before-config-write",N),await G.assertAll()}}),B.writes++,await J.onStep?.("after-config-write",N),{settings:LZ(j),outcome:"updated"}}finally{await G.releaseTo(H)}})}var r8=new Map;function sJ($){let Z=r8.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},r8.set($,Z);return Z}function o8($){if($.status==="ready")return{status:"ready",schemaVersion:X1,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function OZ($){let Z=sJ($.configPath),X={...BZ,...$.lockOptions},J={provider:$.provider,configPath:$.configPath,statePath:$.statePath,codec:$.quota,...$.providerState?{providerState:$.providerState}:{},now:$.now??Date.now,storeLocks:$.storeLocks??[{name:"save",path:$.configPath},{name:"save",path:$.statePath}],lockDefaults:X,lockEnv:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new MZ(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(B,H)=>z.fire(B,H)};return{async load(){let B=await W0(J);if(B.status==="ready"){for(let H of B.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return o8(B)},async read(){return o8(await W0(J))},async initialize(B={}){return{status:await P8(J,B.dropKeys??[])}},add:(B,H)=>I8(G,B,H),publishRoster:(B,H)=>d8(G,B,H),publication:(B)=>u8(G,B),replace:(B,H,Y,Q)=>b8(G,B,H,Y,Q),rotate:(B,H,Y,Q)=>x8(G,B,H,Y,Q),updateProviderState:(B,H,Y,Q)=>S8(G,B,H,Y,Q),disable:(B,H,Y)=>f8(G,B,H,Y),enable:(B,H)=>y8(G,B,H),remove:(B,H)=>g8(G,B,H),reorder:(B,H)=>h8(G,B,H),readSettings:()=>i8(G),updateSettings:(B,H)=>n8(G,B,H),recordIdentity:(B,H,Y,Q)=>v8(G,B,H,Y,Q),refresh:(B,H,Y)=>s8(G,B,H,Y),recordQuota:(B,H,Y)=>R2(G,B,H,Y),requestReading:(B)=>z.fire(B,"admission"),pullsSettled:()=>z.settled()}}var aJ=[/\b[\w-]*(?:secret|token|password|passwd|api[_-]?key|authorization|verifier)["']?\s*[:=]\s*["']?(?:(?:Bearer|Basic)\s+)?[^\s"'&,;}]+/gi,/\b[0-9a-fA-F]{32,}\b/g];function TZ($={}){let{redactStrings:Z}=x0({...$,extraValuePatterns:[...aJ,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class r extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var t8=/^[a-z][a-z0-9-]{0,63}$/,PZ={code:"action-failed",text:"That action failed."},iJ=new Set(["unknown-row","invalid-row","invalid-input","id-exists","id-removed","type-mismatch","no-credential","row-disabled","row-protected","duplicate-identity","row-key-changed","invalid-order","pending-migration","provider","pull","attribution"]);function b$($){if($ instanceof r)return{code:t8.test($.code)?$.code:PZ.code,text:$.message};if($ instanceof g)return{code:`pool-${$.kind}`,text:iJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return PZ}var e8="This cannot be undone. Continue?",nJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function rJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return nJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function oJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function CZ($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>CZ(z,`${Z}[${G}]`,X));if(!oJ($))return $;let J={};for(let[z,G]of Object.entries($)){if(rJ(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:CZ(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function $9($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=CZ($,"payload",J);if(J.dropped.length>0)X.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:J.dropped});if(J.redacted.length>0)X.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:J.redacted});return z}function tJ($){return{value:String($.value),label:String($.label)}}function eJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(tJ),...$.value!==void 0?{value:$.value}:{}};case"toggle":return{kind:"toggle",id:$.id,label:$.label,value:$.value===!0};case"number":return{kind:"number",id:$.id,label:$.label,...$.value!==void 0?{value:$.value}:{},...$.min!==void 0?{min:$.min}:{},...$.max!==void 0?{max:$.max}:{},...$.required?{required:!0}:{}};case"text":return{kind:"text",id:$.id,label:$.label,...$.value!==void 0&&!$.masked?{value:$.value}:{},...$.placeholder!==void 0?{placeholder:$.placeholder}:{},...$.masked?{masked:!0}:{},...$.required?{required:!0}:{}}}}function SZ($){if($.irreversible===!0)return{message:$.confirm||e8,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function Z9($){let Z=SZ($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(eJ),...Z?{confirm:Z}:{}}}function $z($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function Zz($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:$z($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(Z9)}}function Xz($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(Zz),actions:(Z.actions??[]).map(Z9),...Z.facts!==void 0?{facts:Z.facts}:{}}}function X9($,Z,X){return{command:$,title:Z,sections:X.map(Xz)}}function J9($,Z,X,J){return $9({command:$,menu:X9($,Z,X)},$,J)}function z9($,Z,X,J,z){return $9({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:t8.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:X9($,Z,X)},$,z)}var H9="disabled from the command menu";function Jz($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function a0($){return Jz($)?{...$}:{}}function zz($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((X)=>{if(Z.has(X.id))return!1;return Z.add(X.id),!0})}function Gz($,Z){return $.label??Z??$.id}function m2($,Z){return X0($.quota)?s($.quota,Z):void 0}function Y9($,Z){return`${$} ${Z}${$===1?"":"s"}`}var x$="Actions";function Bz($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function G9($,Z){switch(Z.outcome){case"added":return`Added ${$}.`;case"added-disabled":return`Added ${$}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${$}.`;case"rotated":return`${$} was already in the pool; its credential was updated.`;case"exists":return`${$} was already in the pool; its credential is unchanged.`}}function B9($){return b$($).text}async function Hz($){let{store:Z}=$,X=await Z.read(),J=await Z.readSettings(),z=await $.routing?.vaultOrder?.();return{load:X,rows:zz(X),settings:J.status==="error"?{}:J.settings,...z?{vault:z}:{}}}function w2($,Z){let X=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...X!==void 0?{identity:X}:{}},name:Gz($,X)}}function Yz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((V)=>V.id),B=Bz(Z.load),H=Z.rows.filter((V)=>V.enabled).length,Y=Z.rows.map((V,U)=>{let{account:K,name:j}=w2(V,$),N=[V.type==="api"?"API key":"OAuth",...K.identity!==void 0?[K.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),D=V.invalid?"invalid":V.enabled?"enabled":"disabled",F=[];if(!V.invalid&&V.enabled)F.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,H9,z),`Disabled ${j}.`}});if(!V.invalid&&!V.enabled)F.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${j}.`}});if(G.length>1)F.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((L,R)=>({value:String(R+1),label:String(R+1)})),value:String(U+1)}],run:async({values:L})=>{let R=Number(L.position),M=G.filter((_)=>_!==V.id);return M.splice(R-1,0,V.id),(await X.reorder(M,z)).outcome==="unchanged"?`${j} is already at position ${R}.`:`Moved ${j} to position ${R}.`}});return F.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${j}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${j}.`}}),{id:V.id,label:j,detail:N,group:"Accounts",status:D,account:K,actions:F}}),Q=$.accounts?.login,W=[];if(Q&&!B)W.push({id:"add",label:Q.label??"Add account",group:x$,knobs:Q.knobs??[],run:async({values:V,invocation:U})=>{let K=await Q.run(V,U);if(K.status==="cancelled")return{ok:!1,text:K.message??"Login cancelled."};if(K.status==="ready"){let j=await X.add(K.account,z);return G9(K.account.label??j.id,j)}return K.completion.then(async(j)=>{if(!j){U.notify("Login cancelled.","warning");return}let N=await X.add(j,z);U.notify(G9(j.label??N.id,N))},(j)=>{U.notify(`Adding the account failed: ${B9(j)}`,"error")}).catch((j)=>{U.notify(`Adding the account failed: ${B9(j)}`,"error")}),K.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${Y9(Z.rows.length,"account")}, ${H} enabled`],items:B?[]:Y,actions:W}}}function Qz($,Z){let X=$.quota?.scope??"all",J=$.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(W,V)=>{if($.quota?.check)await $.quota.check(W,V);else{for(let U of W)$.store.requestReading(U);await $.store.pullsSettled()}},B=Z.rows.filter((W)=>W.candidate),H=B.map((W)=>{let{account:V,name:U}=w2(W,$),K=m2(W,X);return{id:W.id,label:U,group:z,status:P0(K,{now:J,form:"compact"}),detail:P0(K,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:j})=>{return await G([W.id],j),`Checked quota for ${U}.`}}]}}),Y=Z.rows.filter((W)=>!W.candidate).map((W)=>{let{name:V}=w2(W,$),U=W.invalid?"invalid":!W.enabled?"disabled":W.credential===void 0?"no credential":"unavailable",K=P0(m2(W,X),{now:J,form:"compact"});return`${V} (${U}): ${K}`}),Q=[];if(B.length>0)Q.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:x$,run:async({invocation:W})=>{let V=B.map((U)=>U.id);return await G(V,W),`Checked quota for ${Y9(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:H,actions:Q}}}async function Wz($,Z){try{return await $.reorder(Z)}catch(X){if(X instanceof Error&&X.name==="ClaustrumConsumerError"&&X.kind==="invalid-order")throw new r("vault-invalid-order",X.message,{cause:X});throw X}}function AZ($){return new r("vault-invalid-order",$)}function Vz($){let Z=$.rows.map((J)=>({id:J.id,label:J.label.trim()||J.id})),X=(J)=>Z.filter((z)=>z.id===J||z.label===J);return{ids:Z.map((J)=>J.id),nameOf:(J)=>Z.find((z)=>z.id===J)?.label??J,entryOf:(J)=>{let z=Z.find((G)=>G.id===J);return z&&!/[,\n]/.test(z.label)&&X(z.label).length===1?z.label:J},resolve:(J)=>{let z=[];for(let G of J){let B=X(G);if(B.length===0)throw AZ(`"${G}" is not a vault account.`);if(B.length>1)throw AZ(`"${G}" matches more than one vault account; enter those accounts by route id.`);let H=B[0].id;if(z.includes(H))throw AZ(`"${G}" names an account already in the order.`);z.push(H)}return z}}}function Uz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=a0(Z.settings.routing).mode,H=typeof B==="string"&&G.some((D)=>D.value===B)?B:"ordered",Y=m3(H),Q=Z.vault?Vz(Z.vault):void 0,W=Q?Q.ids:Z.rows.map((D)=>D.id),V=(D)=>Q?Q.nameOf(D):D,U=c1(W,Y.placement,$.routing?.formerMainId??q2),j=[`Mode: ${G.find((D)=>D.value===H)?.label??H}`];if(W.length>0)j.push(`${Q?"Vault account order":"Roster order"}: ${W.map(V).join(", ")}`);if(Y.mode==="ordered"&&U.join()!==W.join())j.push(`Tried in order: ${U.map(V).join(", ")}`);let N=[{id:"mode",label:"Change mode",group:x$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:H}],run:async({values:D})=>{let F=String(D.mode);return await X.updateSettings((L)=>{L.routing={...a0(L.routing),mode:F};return},z),`Routing mode set to ${G.find((L)=>L.value===F)?.label??F}.`}}];if(W.length>1)N.push({id:"order",label:"Set order",group:x$,knobs:[{kind:"text",id:"order",label:Q?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:Q?W.map(Q.entryOf).join(", "):W.join(", "),required:!0}],run:async({values:D})=>{let L=String(D.order).split(Q?/[,\n]+/:/[\s,]+/).map((M)=>M.trim()).filter((M)=>M.length>0),R=Z.vault&&Q?await Wz(Z.vault,Q.resolve(L)):await X.reorder(L,z);return R.outcome==="unchanged"?"The order is unchanged.":`Order set to ${R.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:N}}}function jz($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let z of Z.rows)for(let G of m2(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function Kz($,Z){let X=$.quota?.scope??"all",J=new Map;for(let z of Z.rows)for(let G of m2(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,K2(G));return(z)=>J.get(z)??z}function Dz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=a0(Z.settings.killswitch),B=G.enabled===!0,H=a0(G.accounts),Y=jz($,Z),Q=Kz($,Z),W=B?"on":"off",V=Z.rows.map((U)=>{let{account:K,name:j}=w2(U,$),N=a0(H[U.id]),D=Y.filter((F)=>typeof N[F]==="number");return{id:U.id,label:j,group:`Floors · killswitch ${W}`,status:D.length===0?"no floors":D.map((F)=>`${Q(F)} ≥${N[F]}%`).join(" · "),account:K,actions:[{id:"floors",label:"Set floors",knobs:Y.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${Q(F)}`,min:0,max:100,...typeof N[F]==="number"?{value:N[F]}:{}})),run:async({values:F})=>{return await X.updateSettings((L)=>{let R=a0(L.killswitch),M=a0(R.accounts),q=a0(M[U.id]);for(let _ of Y){let A=F[_];if(typeof A==="number")q[_]=A;else if(A===null)delete q[_]}if(Object.keys(q).length>0)M[U.id]=q;else delete M[U.id];if(Object.keys(M).length>0)R.accounts=M;else delete R.accounts;L.killswitch=R;return},z),`Floors updated for ${j}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${W}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:x$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:U})=>{let K=U.enabled===!0;return await X.updateSettings((j)=>{j.killswitch={...a0(j.killswitch),enabled:K};return},z),`Killswitch ${K?"on":"off"}.`}}]}}}async function Q9($){let Z=await Hz($);return[Yz($,Z),Qz($,Z),Uz($,Z),Dz($,Z)]}var qz=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),RZ=["accounts","quota","routing","limits"];function W9($,Z){let{sessionId:X}=$,J=$.notify.bind($);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(z,G)=>G===void 0?J(Z(String(z))):J(Z(String(z)),G)})}function Nz($,Z){switch($.kind){case"choice":{let X=Z??$.value;if(typeof X==="string"&&$.choices.some((J)=>J.value===X))return{value:X};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let X=Z??$.value;return typeof X==="boolean"?{value:X}:{problem:`${$.label} must be on or off.`}}case"number":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let J=typeof X==="number"?X:Number(X);if(typeof X==="boolean"||!Number.isFinite(J))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&J<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&J>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:J}}case"text":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof X==="string"?{value:X}:{problem:`${$.label} must be text.`}}}}function Fz($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=Nz(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function Mz($,Z){let X=$.find((z)=>z.id===Z.sectionId);if(!X)return;return(Z.itemId===void 0?X.content.actions:X.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function E1($){let Z=$.logger??d("commands"),X=TZ($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],B=$.replace??{},H=RZ.filter((U)=>!B[U]);for(let U of RZ)if(B[U]&&$[U]!==void 0)throw Error(`the ${U} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(H.length>0&&!Y)throw Error(`a store is required for the built-in ${H.join(", ")} section${H.length>1?"s":""}`);let Q=new Set;for(let U of G){if(qz.has(U.id)||Q.has(U.id))throw Error(`extra section id ${U.id} is taken`);Q.add(U.id)}async function W(U,K,j,N){try{return{id:U,slot:K,title:j.title,content:await j.build(N)}}catch(D){return Z.warn("command menu section failed to build",{command:$.command,section:U,error:X(D instanceof Error?D.message:String(D))}),{id:U,slot:K,title:j.title,content:{lines:["This section could not be loaded."]}}}}async function V(U){let K=Y&&H.length>0?await Q9({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],j=[];for(let N of RZ){let D=B[N];if(D)j.push(await W(N,N,D,U));else{let F=K.find((L)=>L.slot===N);if(F)j.push(F)}}if($.cache)j.push(await W("cache","cache",$.cache,U));if($.diagnostics)j.push(await W("diagnostics","diagnostics",$.diagnostics,U));for(let N of G)j.push(await W(N.id,"extra",N,U));return j}return{command:$.command,async open(U){let K=W9(U,X);return J9($.command,$.title,await V(K),J)},async apply(U,K){let j=W9(K,X),N=async(M)=>z9($.command,$.title,await V(j),M,J),D=U.command===$.command?Mz(await V(j),U):void 0;if(!D)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let F=SZ(D);if(F&&U.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:F.message,needsConfirmation:!0});let L=Fz(D.knobs??[],U.values);if("problem"in L)return N({ok:!1,code:"invalid-input",text:L.problem});let R;try{let M=await D.run({values:L.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:j});R=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let q=b$(M);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:q.code,error:X(M instanceof Error?M.message:String(M))}),R={ok:!1,...q}}return N(R)}}}async function k$($,Z,X){let J=new Map,z=[];for(let B of X){let H=B.label;for(let Y=2;J.has(H);Y++)H=`${B.label} (${Y})`;J.set(H,B.value),z.push(H)}let G=await $.select(Z,z);return G===void 0?void 0:J.get(G)}function V9($,Z){return Z.length>0?`${$}
1
+ import{createRequire as FX}from"node:module";var MX=FX(import.meta.url);import{createAssistantMessageEventStream as fY}from"@earendil-works/pi-ai";import{streamSimple as yY}from"@earendil-works/pi-ai/compat";var c="all",y6=Object.freeze(["primary"]);function O4($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function u1($,Z){return JSON.stringify([$,Z])}function e0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y0($){return typeof $==="number"&&Number.isFinite($)}function _4($){return typeof $==="string"&&$.length>0}function U0($,Z,X){return $[Z]===void 0||X($[Z])}function LX($){return Y0($)&&$>0}function f6($){return typeof $==="string"}function _X($){if(!e0($)||!_4($.scope)||!_4($.label))return!1;switch($.kind){case"reading":return Y0($.checkedAt)&&Y0($.usedPercent)&&U0($,"resetsAt",f6)&&U0($,"windowMinutes",LX);case"retired":return Y0($.retiredAt);case"absent":return Y0($.checkedAt);default:return!1}}function OX($){if(!e0($)||!Y0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&U0($,"remainingPercent",Y0)&&U0($,"usedPercent",Y0)&&U0($,"resetsAt",f6)&&U0($,"limit",Y0)&&U0($,"used",Y0)&&U0($,"remaining",Y0)&&U0($,"unit",f6)}function P4($){return e0($)&&Y0($.value)&&Number.isInteger($.value)&&$.value>=0&&Y0($.checkedAt)}function g6($){return e0($)&&Object.values($).every(P4)}function PX($){return typeof $==="boolean"}function l0($){return e0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&U0($,"balance",Y0)&&U0($,"overageLimitReached",PX)&&Y0($.checkedAt)}function h6($){if(!e0($))return;let Z=Object.entries($).filter(([,X])=>P4(X));return Z.length===0?void 0:Object.fromEntries(Z)}function T1($){if(X0($))return $;if(!e0($))return;let{counters:Z,credits:X,...J}=$;if(!X0(J))return;let z=h6(Z),G=l0(X)?X:void 0;return{...J,...z===void 0?{}:{counters:z},...G===void 0?{}:{credits:G}}}function X0($){if(!e0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!_X(X))return!1;let J=u1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return U0($,"budget",OX)&&U0($,"counters",g6)&&U0($,"credits",l0)}class U2 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function K2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j2($){return typeof $==="number"&&Number.isFinite($)}function C4($){return $===void 0||typeof $==="string"&&$!==""}function T4($){return typeof $==="string"&&$!==""}function F$($,Z){return $[Z]===void 0||j2($[Z])}function v6($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function CX($){return K2($)&&C4($.scope)&&T4($.label)&&j2($.usedPercent)&&v6($,"resetsAt")&&($.windowMinutes===void 0||j2($.windowMinutes)&&$.windowMinutes>0)}function TX($){return K2($)&&C4($.scope)&&T4($.label)}function AX($){if(!K2($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&F$($,"remainingPercent")&&F$($,"usedPercent")&&v6($,"resetsAt")&&F$($,"limit")&&F$($,"used")&&F$($,"remaining")&&v6($,"unit")}function d1($){if(!K2($)||!j2($.checkedAt))return!1;let Z=$.readings??[],X=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(X))return!1;let J=new Set;for(let z of Z){if(!CX(z))return!1;let G=u1(z.scope??c,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(TX))return!1;return($.budget===void 0||AX($.budget))&&($.counters===void 0||g6($.counters))&&($.credits===void 0||l0($.credits))}function SX($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function RX($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function EX($,Z){let X=new Map(Object.entries($??{}));for(let[J,z]of Object.entries(Z??{})){let G=X.get(J);if(G===void 0||z.checkedAt>=G.checkedAt)X.set(J,z)}return X.size===0?void 0:Object.fromEntries(X)}function IX($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function u0($,Z){let X=$===void 0?void 0:T1($);if($!==void 0&&X===void 0)throw new U2("stored quota map is malformed");if(!d1(Z))throw new U2("quota observation is malformed");let J=X??{limits:[]},z=Z.checkedAt,G=new Map;for(let D of J.limits)G.set(u1(D.scope,D.label),D);let B=(D)=>{let F=G.get(D);return F===void 0||z>=O4(F)},H=new Set;for(let D of Z.readings??[]){let F=D.scope??c,_=u1(F,D.label);if(H.add(_),!B(_))continue;G.set(_,{scope:F,label:D.label,kind:"reading",checkedAt:z,usedPercent:D.usedPercent,...D.resetsAt===void 0?{}:{resetsAt:D.resetsAt},...D.windowMinutes===void 0?{}:{windowMinutes:D.windowMinutes}})}for(let D of Z.coverage??[]){let F=D.scope??c,_=u1(F,D.label);if(H.has(_)||!B(_))continue;let R=G.get(_);G.set(_,R===void 0||R.kind==="absent"?{scope:F,label:D.label,kind:"absent",checkedAt:z}:{scope:F,label:D.label,kind:"retired",retiredAt:z})}let{limits:Y,budget:Q,counters:W,credits:V,...U}=J,K=RX(J.budget,Z.budget,z),j=EX(J.counters,Z.counters),q=IX(J.credits,Z.credits);return{...U,limits:[...G.values()].sort(SX),...K===void 0?{}:{budget:K},...j===void 0?{}:{counters:j},...q===void 0?{}:{credits:q}}}var m6=Object.freeze({validate:X0,decode:T1,merge:u0});var E4=900000,I4="no quota reading yet",b4="no limits reported";function x4($){let Z=Math.max(1,Math.floor($/60000));if(Z<60)return`${Z}m`;if(Z<1440){let z=Math.floor(Z/60),G=Z%60;return G===0?`${z}h`:`${z}h${G}m`}let X=Math.floor(Z/1440),J=Math.floor(Z%1440/60);return J===0?`${X}d`:`${X}d${J}h`}function k4($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function N2($){if($.scope!==c||$.windowMinutes===void 0)return $.label;return k4($.windowMinutes)}function w6($){return Math.min(100,Math.max(0,$))}function D2($){return Math.round(w6($))}function A4($){return`${D2($)}% left`}function S4($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:x4(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function bX($,Z){let X=$.windowMinutes,J=Z.windowMinutes;if(X!==void 0&&J!==void 0&&X!==J)return X-J;if(X===void 0!==(J===void 0))return X===void 0?1:-1;if($.scope!==Z.scope){if($.scope===c)return-1;if(Z.scope===c)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function f4($,Z){let{windows:X,age:J}=y4($,Z),z=X.map(({part:G})=>G);return J===void 0?{windows:z}:{windows:z,age:J}}function xX($){let Z=g4($.filter(({part:X,scope:J})=>X.kind==="window"&&J!==c).map(({scope:X})=>X));for(let X of $)X.part.short=X.part.kind==="budget"?"cr":X.scope===c?X.part.name:Z.get(X.scope)??X.scope;return $}function y4($,Z){if(!$)return{windows:[]};let{now:X}=Z,z=$.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(bX).map((B)=>{let H=w6(B.remainingPercent??0);return{scope:B.scope,...B.windowMinutes===void 0?{}:{windowMinutes:B.windowMinutes},part:{kind:"window",name:N2(B),short:"",figure:A4(B.remainingPercent??0),remainingPercent:H,checkedAt:B.checkedAt,...S4(B.resetsAt,B.checkedAt,X)}}}),G=$.budget;if(G){let B=G.remainingPercent,H=G.reached?"credits spent":B!==void 0?`credits ${A4(B)}`:"credits available";z.push({scope:c,spent:G.reached,part:{kind:"budget",name:"credits",short:"",figure:H,...B===void 0?{}:{remainingPercent:w6(B)},checkedAt:G.checkedAt,...S4(G.resetsAt,G.checkedAt,X)}})}if(xX(z),z.length>0){let B=X-Math.min(...z.map(({part:H})=>H.checkedAt));if(B>(Z.staleAfterMs??E4))return{windows:z,age:`checked ${x4(B)} ago`}}return{windows:z}}function R4($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function g4($){let Z=[...new Set($.map(R4))],X=new Map(Z.map((z)=>[z,2])),J=(z)=>z.slice(0,X.get(z));for(;;){let z=new Map;for(let B of Z)z.set(J(B),[...z.get(J(B))??[],B]);let G=!1;for(let B of z.values()){if(B.length<2)continue;for(let H of B){let Y=X.get(H)??2;if(Y<H.length)X.set(H,Y+1),G=!0}}if(!G)break}return new Map($.map((z)=>[z,J(R4(z))]))}var kX=2;function fX($){let Z=$.map((J)=>J.label.trim()||J.scope),X=g4(Z);return Z.map((J)=>X.get(J)??J)}function yX($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:H})=>H.kind==="window");if(X.some(({scope:H})=>H===c))return;let J=$.flatMap((H,Y)=>{let W=X.filter(({scope:V})=>V===H.scope).reduce((V,U)=>V===void 0||(U.part.remainingPercent??0)<(V.part.remainingPercent??0)?U:V,void 0);return W?[{group:H,listed:Y,window:W}]:[]});if(J.length===0)return;let z=fX($),G=(H)=>H.window.part.remainingPercent??0,B=[...J].sort((H,Y)=>G(H)-G(Y)||H.listed-Y.listed).slice(0,kX).sort((H,Y)=>H.listed-Y.listed);return B.map((H,Y)=>{let{windowMinutes:Q}=H.window,W=[z[H.listed]??H.group.scope,...Q===void 0?[]:[k4(Q)],`${D2(G(H))}%`].join(" ");return Y===B.length-1?`${W} left`:W})}function gX($,Z){let{windows:X}=y4($,Z),J=yX($?.groups,X);if(J)return J;let z=X.filter(({part:V,scope:U})=>V.kind==="window"&&U===c),G=X.filter(({part:V,scope:U})=>V.kind==="window"&&U!==c),B=X.find(({part:V})=>V.kind==="budget"),H=B?.spent?0:B?.part.remainingPercent,Q=[...G.map(({part:V})=>({label:V.short,remaining:V.remainingPercent??0})),...H===void 0||B===void 0?[]:[{label:B.part.short,remaining:H}]].reduce((V,U)=>V===void 0||U.remaining<V.remaining?U:V,void 0),W=z.map(({part:V})=>`${V.name} ${D2(V.remainingPercent??0)}%`);if(Q)W.push(`${Q.label} ${D2(Q.remaining)}%`);if(W.length===0)return X.map(({part:V})=>V.figure);return W.map((V,U)=>U===W.length-1?`${V} left`:V)}function c1($,Z){if(Z.form==="narrow")return gX($,Z);let X=f4($,Z),J=(Z.form??"full")==="full",z=X.windows.map((G)=>{let B=J&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${B}`});return X.age===void 0?z:[...z,X.age]}function C0($,Z){let X=c1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?b4:I4}function M$($){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 hX($){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 vX($,Z){let X=$.windowMinutes!==void 0,J=Z.windowMinutes!==void 0;if(X!==J)return X?-1:1;if(X&&J&&$.windowMinutes!==Z.windowMinutes)return(Z.windowMinutes??0)-($.windowMinutes??0);if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function mX($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function s($,Z=c){let X=new Map;for(let W of $?.limits??[]){if(W.scope!==Z&&W.scope!==c)continue;let V=X.get(W.label);if(V===void 0){X.set(W.label,W);continue}let U=W.scope===c?V:W,K=W.scope===c?W:V;X.set(W.label,U.kind==="reading"?U:K)}let J=[...X.values()].map(hX).sort(vX),z=J.filter((W)=>W.kind==="reading"),G=z.length>0?z:J,B=G.length>0?Math.min(...G.map((W)=>W.checkedAt)):void 0,H=$?.budget?.kind==="reading"?mX($.budget):void 0,Y=h6($?.counters),Q=l0($?.credits)?$.credits:void 0;return{scope:Z,limits:J,...B===void 0?{}:{checkedAt:B},...H===void 0?{}:{budget:H},...Y===void 0?{}:{counters:Y},...Q===void 0?{}:{credits:Q}}}function A1($,Z){let X=$?.budget;if(X?.reached!==!0||typeof X.resetsAt!=="string")return;let J=Date.parse(X.resetsAt);if(!Number.isFinite(J)||J<=Z)return;return{resetsAt:X.resetsAt,resetAtMs:J}}function p6($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function q2($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function h4($,Z,X){let J=Z.rateLimitMarks?.get($);if(J!==void 0&&X<J)return{id:$,reason:"rate-limited",until:J};let z=Z.refreshBackoff?.get($);if(z!==void 0&&X<z)return{id:$,reason:"refresh-backoff",until:z};return}function wX($,Z,X,J){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 z=Z.limits.filter(p6);for(let G of z)if(q2(G,J)===void 0)return{id:$,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of z){let B=q2(G,J);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 x0($){let Z=$.scope??c,X=$.requiredLabels??y6,J=[],z=[],G=[];for(let U of $.rows){let K=h4(U.id,$,$.now);if(K){J.push(K);continue}if(U.kind==="api-key"){G.push({id:U.id,kind:U.kind});continue}let j=s(U.quota,Z),q=wX(U.id,j,X,$.now);if(q){z.push(q);continue}G.push({id:U.id,kind:U.kind,projection:j})}let B=new Map(G.flatMap((U)=>{let K=A1(U.projection,$.now);return K?[[U.id,K]]:[]})),H=B.size>0&&B.size===G.length,Y=[];for(let U of G){let K=B.get(U.id);if(K===void 0)Y.push(U);else if(H)Y.push({...U,lastPath:!0});else z.push({id:U.id,stage:2,reason:"budget-spent",...K})}let Q=new Map($.rows.map((U,K)=>[U.id,K])),W=(U,K)=>(Q.get(U.id)??0)-(Q.get(K.id)??0);z.sort(W);let V=z.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of V)$.requestPull?.(U);return{admitted:Y,refused:z,excluded:J,pulls:V}}var F2="main";function l6($){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 s1($,Z,X=F2){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((z)=>z!==X);return Z==="main-first"?[X,...J]:[...J,X]}function u6($){let Z=x0($),X=new Set(Z.admitted.map((z)=>z.id));return{order:s1($.rows.map((z)=>z.id),$.placement??"roster",$.formerMainId).filter((z)=>X.has(z)&&$.killswitch?.get(z)!==!1),admission:Z}}function d6($,Z,X){let J=Z.at(-1);if(J!==void 0){if(J.status===void 0||!X.includes(J.status))return}let z=new Set(Z.map((G)=>G.id));return $.find((G)=>!z.has(G))}function L$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function c6($,Z,X){let J=new Map;for(let[z,G]of $){if(z===X)continue;if(G.quotaCheckedAt!==Z.get(G.accountId))continue;J.set(G.accountId,(J.get(G.accountId)??0)+(G.inputBytes??0))}return J}var _$=900000,m4=0.016666666666666666,s6=0.000001;function M2($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function w4($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function p4($){return $.limits.filter((Z)=>Z.kind==="reading").sort((Z,X)=>{let J=Z.windowMinutes!==void 0,z=X.windowMinutes!==void 0;if(J!==z)return J?-1:1;if(J&&z)return(X.windowMinutes??0)-(Z.windowMinutes??0);return 0})}function i6($){let Z=($.classifyStatus??w4)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=M2($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>_$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of p4($.quota)){let G=z.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:z.scope,label:z.label},...typeof z.resetsAt==="string"?{resetsAt:z.resetsAt}:{}}}let J=A1($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function a6($,Z,X){let J=Math.max(0,$.remainingPercent-Z);if(J<=0)return 0;if(!$.resetsAt)return J;let z=Date.parse($.resetsAt);if(!Number.isFinite(z)||z<=X)return J;let G=Math.max((z-X)/3600000,m4);return J/G}function v4($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function pX($,Z){if(!$.quota)return;let X=M2($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>_$)return;let J=p4($.quota).map((B)=>a6({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},$.reservePercent[B.label]??0,Z)),z=$.quota.budget;if(z&&typeof z.remainingPercent==="number"&&Number.isFinite(z.remainingPercent))J.push(a6({remainingPercent:z.remainingPercent,...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}},0,Z));let G=J.length>0?Math.min(...J):0;return G>0?{candidate:$,quotaCheckedAt:X,weight:G}:void 0}function l4($){let Z=$.candidates.filter((z)=>z.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((z)=>pX(z,$.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,B)=>{let H=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,s6),Y=(($.pendingBytes.get(B.candidate.accountId)??0)+$.requestBytes)/Math.max(B.weight,s6);return H-Y||G.candidate.configuredOrder-B.candidate.configuredOrder||v4(G.candidate.accountId,B.candidate.accountId)});let z=X[0];if(z)return{accountId:z.candidate.accountId,quotaCheckedAt:z.quotaCheckedAt,source:"weighted"}}$.onEmptyWeightedSet?.();let J=[...Z].sort((z,G)=>{let B=(z.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-B||z.configuredOrder-G.configuredOrder||v4(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:M2(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function n6($){let Z=x0($),X=new Map(Z.admitted.map((j)=>[j.id,j])),J=new Map(Z.refused.map((j)=>[j.id,j])),z=new Set(Z.excluded.map((j)=>j.id)),G=new Set($.rows.map((j)=>j.id)),B=$.pin!==void 0&&L$($.pin,G,$.identities?.get($.pin.accountId));if(B&&$.pin){let j=X.get($.pin.accountId);if(j&&$.killswitch?.get(j.id)!==!1)return{outcome:"dispatch",accountId:j.id,source:"pin",...j.projection?.checkedAt===void 0?{}:{quotaCheckedAt:j.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let H=$.pin?J.get($.pin.accountId):void 0,Y=B&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||H?.reason==="exhausted"||H?.reason==="budget-spent"),Q=(j)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(j):$.rowReservePercent?.get(j.id))??$.reservePercent??{}},W=$.scope,V=$.rows.map((j,q)=>({row:j,configuredOrder:q})).filter(({row:j})=>!z.has(j.id)).map(({row:j,configuredOrder:q})=>{let D=$.killswitch?.get(j.id),F=$.resetCreditsApplicable?.get(j.id);return{accountId:j.id,quota:j.kind==="api-key"?void 0:X.get(j.id)?.projection??s(j.quota,W),reservePercent:Q(j),configuredOrder:q,...F===void 0?{}:{resetCreditsApplicable:F},...D===void 0?{}:{killswitchPasses:D}}}),U=[],K=B?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(V.length>0){let j=l4({candidates:V,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!j)break;let q=J.get(j.accountId);if(q){U.push(q),V=V.filter((F)=>F.accountId!==j.accountId);continue}let D=$.identities?.get(j.accountId);return{outcome:"dispatch",accountId:j.accountId,source:j.source,...j.quotaCheckedAt===void 0?{}:{quotaCheckedAt:j.quotaCheckedAt},pin:B&&!Y?{action:"retain"}:{action:"assign",pin:{accountId:j.accountId,inputBytes:$.requestBytes,...D===void 0?{}:{wireIdentity:D},...j.quotaCheckedAt===void 0?{}:{quotaCheckedAt:j.quotaCheckedAt}}},refusedSelections:U,admission:Z}}return{outcome:"no-admissible-account",pin:K,refusedSelections:U,admission:Z}}import{appendFileSync as eX,chmodSync as $J,existsSync as e6,renameSync as e4,statSync as ZJ}from"node:fs";import{open as XJ}from"node:fs/promises";import{dirname as JJ,resolve as zJ}from"node:path";import{randomUUID as s4}from"node:crypto";import{lstat as a4,readFile as i4,rename as lX,unlink as u4}from"node:fs/promises";import{tmpdir as uX}from"node:os";import{dirname as $1,join as dX,resolve as M0}from"node:path";var I=process.platform==="win32",d4=new Set;function r6($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var c4;var n4="native-addon-unavailable";function r4($){return Object.assign(Error("Windows private-files native addon is unavailable",{cause:$}),{code:"ERR_PRIVATE_FILES_UNAVAILABLE",reason:n4})}function cX($,Z){return Z instanceof $.PrivateFilesUnavailableError||Z?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"}async function sX($){try{await $.verifyPrivatePath(dX(uX(),`.common-auth-private-files-probe-${s4()}`),"file")}catch(Z){if(cX($,Z))throw r4(Z)}}function a1(){return c4??=import("@cortexkit/private-files").then(async($)=>{if(I)await sX($);return $},($)=>{throw I?r4($):$}),c4}class i extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor($,Z,X){let J=X;super(J?.code==="ERR_PRIVATE_FILES_UNAVAILABLE"?`Private file refused at ${Z}: ${$} (${n4}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`:`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`,{cause:X});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=r6(J),this.win32Code=J?.win32Code,this.reason=J?.reason}}async function N0($,Z,X){try{return await X()}catch(J){if(J instanceof i)throw J;throw new i($,Z,J)}}var aX;async function d0($,Z){$=M0($),Z??=aX,await N0($,"safe-parent",async()=>{let X=await(await a1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await a4($);throw new i(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function G0($,Z,X=!1){if($=M0($),Z==="directory")return d0($);await N0($,"verify",async()=>{let J=await a1(),z=await J.verifyOwnerOnly($),G=!1;if(!z.ok){let{reason:B}=z.refusal;if(B==="io-error")await J.verifyPrivatePath($,Z);if(X&&[J.EXTRA_ACE,J.NOT_PROTECTED,J.NULL_DACL,J.EMPTY_DACL].includes(B))await d0($1($)),await J.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:B,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await J.verifyPrivatePath($,Z),G&&!d4.has($))d4.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function q0($,Z=!1,X){$=M0($),await N0($,"directory",async()=>{let J=await a1();try{return await a4($),await d0($,X)}catch(G){if(r6(G)!=="ENOENT")throw G}let z=$1($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await q0(z,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(G){if(r6(G)!=="EEXIST")throw G}await d0($,X)})}async function L0($,Z=!1){if(!I)return i4($,"utf8");return(await o6($,Z)).toString("utf8")}async function o6($,Z=!1){if(!I)return i4($);if($=M0($),Z)await d0($1($)),await G0($,"file",!0);return N0($,"read",async()=>(await a1()).readOwnerOnly($))}async function i1($,Z){await d0($1(M0($))),await N0($,"create",async()=>{await(await a1()).createPrivateFile(M0($),Z)})}async function o4($){await d0($1(M0($))),await N0($,"directory-create",async()=>{await(await a1()).createOwnerOnly(M0($),{kind:"dir"})})}async function t6($,Z,X={}){$=M0($),Z=M0(Z);let J=X.now??(()=>performance.now()),z=J(),G=X.deadline??1/0,B,H=[0,10,20,40,80,100],Y,Q=0;for(let V of H){let U=Math.min(B??1/0,G);if(J()>=U)break;if(V)await(X.sleep??((j)=>new Promise((q)=>setTimeout(q,j))))(Math.min(V,Math.max(0,U-J())));if(J()>=U)break;let K=J();if(await X.beforeRename?.(),B!==void 0)B+=J()-K;if(J()>=G)break;Q++;try{return await(X.rename??lX)($,Z),{attempts:Q,elapsedMs:J()-z}}catch(j){Y??=j;let q=j;if(!(q.win32Code!==void 0?q.win32Code===32||q.win32Code===33:["EBUSY","EPERM","EACCES"].includes(q.code??"")&&!q.reason))break;B??=J()+500}}let W=new i(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw W.attempts=Q,W.elapsedMs=J()-z,W}async function n1($,Z,X={}){$=M0($),await q0($1($));try{await G0($,"file",!0)}catch(Q){if(Q.code!=="ENOENT")throw Q}let J=M0(X.stagePath??`${$}.${s4()}.tmp`);if($1(J)!==$1($))throw new i($,"stage-directory",{code:"EXDEV"});let z=!1,G=!1,B={attempts:0,elapsedMs:0},H="stage-create",Y=(Q)=>{try{X.onOutcome?.({path:$,stage:Q?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Q?.attempts??B.attempts,elapsedMs:Q?.elapsedMs??B.elapsedMs,...Q&&{code:Q.code,win32Code:Q.win32Code}})}catch{}};try{if(await i1(J,Z),z=!0,H="before-rename",B=await t6(J,$,X),z=!1,G=!0,H="published-callback",X.onRenamed?.(),H="published-verify",await G0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new i($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(Q){let W=Q instanceof i?Q:new i($,H,Q);if(W.published=G,W.fileDurable=G,G)Object.assign(W,B);if(z){try{await u4(J)}catch{W.orphanPath=J}z=!1}throw Y(W),W}finally{if(z)await u4(J).catch(()=>{})}}var iX=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,nX=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function rX($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function k0($={}){let Z=[nX,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function X(G){let B=G.toLowerCase().replace(/[-_]/g,"");return iX.test(G)||B.includes("apikey")||B.endsWith("secret")||B.endsWith("password")||B.endsWith("token")&&!B.endsWith("tokens")||!!$.extraSecretKeys?.(B)}function J(G){let B=G,H=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Q of["code","status","cause"])if(B[Q]!==void 0)H.push([Q,B[Q]]);let Y=new Set(H.map(([Q])=>Q));for(let Q of Object.entries(G))if(!Y.has(Q[0]))H.push(Q);return H}function z(G,B,H,Y=0){if(typeof G==="string")return Z.reduce((Q,W)=>Q.replace(W,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(H.has(G))return"[Circular]";H.add(G);try{if(Array.isArray(G))return G.map((V)=>z(V,B,H,Y));let Q=rX(G);if(Q&&Y>=8)return"[Truncated]";let W=Q?Y+1:Y;return Object.fromEntries((Q?J(G):Object.entries(G)).map(([V,U])=>[V,B&&X(V)?"***REDACTED***":z(U,B,H,W)]))}finally{H.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var t4=k0(),oX=t4.redact,tX=t4.redactStrings;var L2={error:0,warn:1,info:2,debug:3,trace:4},Z8=5242880,X8=3;function $3($){try{$J($,384)}catch{}}function GJ($){try{if(!(e6($)&&ZJ($).size>=Z8))return;for(let X=X8-1;X>=1;X--)if(e6(`${$}.${X}`)){let J=`${$}.${X+1}`;e4(`${$}.${X}`,J),$3(J)}let Z=`${$}.1`;e4($,Z),$3(Z)}catch{}}async function c0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await N0(Z,"log-close",()=>X.close())}async function $8($,Z){await q0(JJ(Z));try{await G0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await i1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await G0(Z,"file",!0)}}return $.handle=await N0(Z,"log-open",()=>XJ(Z,"a")),$.file=Z,$.handle}async function BJ($,Z,X){Z=zJ(Z);try{if($.file!==Z)await c0($);let J=$.handle??await $8($,Z);if((await N0(Z,"log-stat",()=>J.stat())).size>=Z8){await c0($);for(let G=X8-1;G>=0;G--){let B=G===0?Z:`${Z}.${G}`,H=`${Z}.${G+1}`;try{await G0(B,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await G0(H,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await t6(B,H),await G0(H,"file")}J=await $8($,Z)}await N0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await c0($).catch(()=>{}),J}}function HJ($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function YJ($){let Z,X,J,z=k0(),G,B=[],H,Y=Promise.resolve(),Q,W={};function V(N){let L=Y.then(N);return Y=L.catch((S)=>{Q=S}),L}function U(N){if(I&&N.file!==Z)V(()=>c0(W)).catch(()=>{});Z=N.file,X=N.level,z=k0(N),G=N.captureSink}function K(N){if(N===void 0||N in L2)J=N}function j(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function q(){if(J)return J;let N=typeof X==="function"?X():X;if(N&&N in L2)return N;return"info"}function D(N=!0){if(H)clearTimeout(H),H=void 0;if(!B.length){if(I)return V(async()=>{if(N)await c0(W);if(Q)throw Q});return}let L;try{L=j()}catch{if(B=[],I&&N)return V(()=>c0(W));return}let S=B.join("");if(B=[],!L){if(I&&N)return V(()=>c0(W));return}if(I)return V(async()=>{try{await BJ(W,L,S)}finally{if(N)await c0(W)}});try{if(GJ(L),e6(L))$3(L);eX(L,S,{encoding:"utf8",mode:384})}catch{}}function F(){if(!H)H=setTimeout(()=>{H=void 0;let N=D(!1);if(N instanceof Promise)N.catch(()=>{})},500)}function _(N,L,S,T){if(Z===void 0&&G===void 0)return;try{if(L2[L]>L2[q()])return;let b=z.redactStrings(S),w;try{w=z.redact(T)}catch{w="[unserializable]"}let f=`[${new Date().toISOString()}] ${L.toUpperCase()} [${N}] ${b}`+(T===void 0?"":HJ(w))+`
2
+ `;try{G?.({channel:N,level:L,message:b,data:w})}catch{}if(Z===void 0)return;if(B.push(f),B.length>=50){let g=D(!1);if(g instanceof Promise)g.catch(()=>{})}else F()}catch{}}function R(N){return{error:(L,S)=>_(N,"error",L,S),warn:(L,S)=>_(N,"warn",L,S),info:(L,S)=>_(N,"info",L,S),debug:(L,S)=>_(N,"debug",L,S),trace:(L,S)=>_(N,"trace",L,S)}}function M(){if(I)V(()=>c0(W)).catch(()=>{});if(Q=void 0,B=[],H)clearTimeout(H),H=void 0;Z=void 0,X=void 0,J=void 0,z=k0(),G=void 0}if($)U($);return{configure:U,createLogger:R,setLogLevel:K,flushLogs:D,reset:M}}var QJ=YJ();function u($){return QJ.createLogger($)}class y extends Error{operation;rowId;phase;retryable;kind;committed;constructor($){super($.message??`${$.operation} failed (${$.kind}, ${$.phase})`,$.cause===void 0?void 0:{cause:$.cause});this.name="PoolOperationError",this.operation=$.operation,this.rowId=$.rowId,this.phase=$.phase,this.retryable=$.retryable,this.kind=$.kind,this.committed=$.committed}}class _2 extends Error{operation;constructor($){super(`${$} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=$}}var r1="identity-contradicted: ",Z3="duplicate-identity";function Z1($,Z,X){let J=$.rosterRow(Z);if(!J)return;J.enabled=!1;let z=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");$.setEntry(Z,{...z,disabledReason:G?z.disabledReason:X})}function O$($,Z){let X=$.rosterRow(Z);if(!X)return;X.enabled=!0;let J=$.entry(Z);if(J&&"disabledReason"in J){let z={...J};delete z.disabledReason,$.setEntry(Z,z)}}function o1($,Z){let X=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),J=[];for(let z of X.slice(1))Z1($,z.id,"duplicate-identity"),J.push(z.id);return J}function S1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,o1($,X)}import{setTimeout as vJ}from"node:timers/promises";import{randomUUID as J8}from"node:crypto";import{mkdir as DJ,open as O2,rename as NJ,rm as qJ}from"node:fs/promises";import{dirname as X3}from"node:path";class P$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function _0($,Z,X={}){await J3($,Z,X)}async function J3($,Z,X,J){if(I)return n1($,X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
3
+ `,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??J8)()}.tmp`,onRenamed:J,durable:X.durable,durability:X.durability,onOutcome:X.onOutcome});await DJ(X3($),{recursive:!0});let z=`${$}.${(X.stageName??J8)()}.tmp`,G,B=!1;try{if(G=await O2(z,"wx",384),B=!0,await G.writeFile(X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
4
+ `,"utf8"),await G.chmod(384),X.durable)try{await G.sync()}catch(H){throw new P$(H)}if(await G.close(),G=void 0,await X.beforeRename?.(),await NJ(z,$),B=!1,J?.(),X.durable){let H=await O2(X3($),"r");try{await H.sync()}catch(Y){throw new P$(Y)}finally{await H.close()}}}finally{if(await G?.close().catch(()=>{}),B)await qJ(z,{force:!0}).catch(()=>{})}}async function z3($){if(I){await G0($,"file");let J=new i($,"directory-sync-unsupported",{code:"ENOTSUP"});throw J.published=!0,J}let Z=await O2($,"r");try{await Z.sync()}finally{await Z.close()}let X=await O2(X3($),"r");try{await X.sync()}finally{await X.close()}}import{randomUUID as P2}from"node:crypto";import{mkdir as z8,open as W8,readFile as G8,rename as B8,rm as C2,stat as H8}from"node:fs/promises";import{dirname as G3,join as Y8}from"node:path";async function Q8($,Z){let X=await W8($,"wx",384);try{await X.writeFile(Z,"utf8")}finally{await X.close()}}var FJ=globalThis.setTimeout.bind(globalThis),MJ=globalThis.clearTimeout.bind(globalThis);function B3($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function J0($){return LJ({...$,now:Date.now})}async function LJ($){let Z=H3($.path,$.name),X=Y8(Z,"owner.json"),J=P2(),z=$.now??Date.now,G=null,B=!1,H=!1,Y,Q,W=new Promise((C)=>{Q=C});function V(C){try{let A=$.onRenewalTimer?.(C);if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")Promise.resolve(A).catch(()=>{})}catch{}}function U(){if(!G)return;MJ(G),G=null,V("cancelled")}function K(C,A){if(Y||B)return;Y=Object.freeze({reason:C,expectedOwnerId:J,...typeof A?.ownerId==="string"?{observedOwnerId:A.ownerId}:{},...typeof A?.expiresAt==="number"?{observedExpiresAt:A.expiresAt}:{}}),U(),Q(Y)}let j,q=null,D=`${Z}.evicting`,F=Y8(D,"owner.json"),_=P2(),R=5000,M=8;async function N(){if(I)try{return JSON.parse(await L0(Z,!0))}catch(C){if(C.code!=="EISDIR"&&C.reason!=="wrong-kind")throw C;return await G0(Z,"directory",!0),JSON.parse(await L0(X,!0))}try{return JSON.parse(await G8(Z,"utf8"))}catch(C){if(C.code!=="EISDIR")throw C;return JSON.parse(await G8(X,"utf8"))}}async function L(){if(I){let l=await N(),$0=Number(l?.expiresAt)-z();await n1(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
5
+ `,{deadline:performance.now()+Math.max(0,$0),beforeRename:async()=>{let V2=await N();if(V2?.ownerId!==J||!(Number(V2?.expiresAt)>z())||!await h())throw new X1({target:$.path,name:$.name})}});return}let C=`${Z}.${P2()}.tmp`,A,x=!1;try{A=await W8(C,"wx",384),x=!0,await A.writeFile(`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
6
+ `,"utf8"),await A.chmod(384),await A.close(),A=void 0;let l=await N();if(l?.ownerId!==J||!(Number(l?.expiresAt)>z())||!await h())throw new X1({target:$.path,name:$.name});await B8(C,Z),x=!1}finally{if(await A?.close().catch(()=>{}),x)await C2(C,{force:!0}).catch(()=>{})}}async function S(){let C=`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
7
+ `;if(I)await i1(Z,C);else await Q8(Z,C)}async function T(C){let A=C.code;if(A==="EEXIST"){if(I)await N();return!0}if(A==="EISDIR"){if(I)await G0(Z,"directory",!0),await L0(X,!0);return!0}return!1}async function b(){if(I)await q0(G3(Z));try{return await S(),!0}catch(C){let A=C.code;if(await T(C))return!1;if(A==="ENOENT"){if(I)await q0(G3(Z));else await z8(G3(Z),{recursive:!0});try{return await S(),!0}catch(x){if(await T(x))return!1;throw x}}throw C}}async function w(){await new Promise((C)=>setTimeout(C,Math.floor(Math.random()*4)))}async function f(C=!0){if(C&&$.onStep)await $.onStep("lock-read-ready");let A;try{A=await N()}catch(l){if(I&&l.code!=="ENOENT")throw l}let x=Number(A?.expiresAt);if(Number.isFinite(x)&&x>z())return{status:"live"};if(typeof A?.ownerId==="string"&&Number.isFinite(x))return{status:"stale",identity:{kind:"owner",ownerId:A.ownerId,expiresAt:x}};try{let l=await H8(Z),$0=Number.isFinite(x)?x:l.mtimeMs+$.ttlMs;if($0>z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:l.dev,ino:l.ino,mtimeMs:l.mtimeMs,expiresAt:$0}}}catch(l){if(l.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw l}}function g(C,A){if(A.status!=="stale")return!1;let x=A.identity;if(C.kind==="owner"&&x.kind==="owner")return C.ownerId===x.ownerId&&C.expiresAt===x.expiresAt;return C.kind==="stat"&&x.kind==="stat"&&C.dev===x.dev&&C.ino===x.ino&&C.mtimeMs===x.mtimeMs&&C.expiresAt===x.expiresAt}async function h(){try{return JSON.parse(await L0(F,I))?.ownerId===_}catch(C){if(I&&C.code!=="ENOENT")throw C;return!1}}async function e(C){if(I)await N0(C,"remove",()=>C2(C,{recursive:!0,force:!0}));else await C2(C,{recursive:!0,force:!0}).catch(()=>{})}async function r(){if(await h())await e(D)}async function Q2(){if(I)await o4(D);else await z8(D);try{let C=`${JSON.stringify({ownerId:_,createdAt:z()})}
8
+ `;if(I)await i1(F,C);else await Q8(F,C)}catch(C){if(B3(C))return!1;throw await r(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function l1(){let C;try{C=await H8(D)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if(I)await G0(D,"directory",!0);if(C.mtimeMs+R>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let A=`${D}.${P2()}`;try{await B8(D,A)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if($.onStep)await $.onStep("stale-marker-claimed");return await e(A),"recovered"}async function W2(C){try{if(!await Q2())return!1}catch(A){if(A.code==="EEXIST"){if(I){await G0(D,"directory",!0);try{await L0(F,!0)}catch(x){if(x.code!=="ENOENT")throw x}}return!1}throw A}try{await C()}finally{await r()}return!0}async function v(){for(let C=0;C<M;C++){if($.onStep)await $.onStep("relinquish-read");let A;try{A=await N()}catch(x){if(I)throw x;return}if(A?.ownerId!==J)return;try{await C2(Z,{recursive:!0,force:!0});return}catch(x){if(I)throw x;await w()}}}function p0(){if(!$.renew||B||Y)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=FJ(()=>{G=null;let A=(async()=>{let x=!B;try{if(!await W2(async()=>{let $0=await N(),V2=z();if(B||Y){x=!1;return}if($0?.ownerId!==J){K("taken-over",$0),x=!1;return}if(!(Number($0?.expiresAt)>V2)){K("expired",$0),x=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(B||Y){x=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(B||Y){x=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(B||Y){x=!1;return}if(await L(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){K("marker-lost"),x=!1,await v();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(l){if(I&&l instanceof i)j=l,K("renewal-failed"),x=!1;try{let $0=await N();if($0?.ownerId!==J)K("taken-over",$0);else if(!(Number($0?.expiresAt)>z()))K("expired",$0)}catch{K("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(x&&!B&&!Y)p0()}})();q=A,A.finally(()=>{if(q===A)q=null})},C),"unref"in G)G.unref();V("scheduled")}function L4(){try{let C=$.onContended?.();if(C&&(typeof C==="object"||typeof C==="function")&&"then"in C&&typeof C.then==="function")Promise.resolve(C).catch(()=>{})}catch{}return null}let C1=await b();if(!C1)for(let C=0;C<M;C++){if(C1=await b(),C1)break;let A=await f();if(A.status==="live")return L4();if(A.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await Q2()){await w();continue}}catch(x){if(x.code!=="EEXIST")throw x;if(await l1()==="fresh")return null;await w();continue}try{let x=await f();if(x.status==="live")return L4();if(!g(A.identity,x))continue;if(!await h())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await h())return null;let l=await f(!1);if(!g(A.identity,l))continue;if(await e(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(C1=await b(),!C1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),C1=!1,null;break}finally{await r()}}if(!C1)return null;return p0(),{ownerId:J,whenLost:()=>W,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(j)throw j;let C;try{let A=await N();if(C=A,!B&&!Y&&A?.ownerId===J&&Number(A?.expiresAt)>z())return;K(A?.ownerId!==J?"taken-over":"expired",A)}catch(A){if(K("unreadable"),I&&A instanceof i)throw A}throw new X1({target:$.path,name:$.name,expectedOwnerId:J,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}})},release:async()=>{if(I&&H)return;B=!0,U(),await q;for(let C=0;C<M;C++){try{let A=!1;if(await W2(async()=>{let l;try{l=await N()}catch($0){if(I&&$0.code==="ENOENT"){A=!0;return}throw $0}if(l?.ownerId!==J){A=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await e(Z),A=!0})){if(I&&!A)throw new i(Z,"release-not-confirmed",{code:"EIO"});H=A;return}await l1()}catch(A){if(I)throw A;return}await w()}if(I)throw new i(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function H3($,Z){return`${$}.${Z}.lock`}class s0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class X1 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function Y3($,Z,X){let J=performance.now();for(;;){Z.signal?.throwIfAborted();let z=await J0({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1,...Z.onStep?{onStep:Z.onStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}});if(z)try{return Z.signal?.throwIfAborted(),await X(z)}finally{await z.release()}let G=Z.timeoutMs-(performance.now()-J);if(G<=0)throw new s0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((B)=>setTimeout(B,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as _J}from"node:async_hooks";var V8=new _J;function B0($){if(V8.getStore()!==void 0)throw new _2($)}function f0($,Z){return V8.run($,async()=>await Z())}async function U8($,Z,X,J,z){if(!Z)return;try{await f0($,()=>Z(X,J))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:X,error:G instanceof Error?G.message:String(G)})}}var Q3=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function OJ($,Z,X){let J=(B)=>{try{let H=X.onLockEvent?.({type:B,name:$.name,path:$.path});if(H&&(typeof H==="object"||typeof H==="function")&&"then"in H&&typeof H.then==="function")Promise.resolve(H).catch(()=>{})}catch{}},z={...Z,...PJ($)},G=performance.now();for(;;){let B=await J0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(Q)=>X.onRenewalTimer?.({name:$.name,path:$.path},Q)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...X.onLockStep?{onStep:(Q)=>X.onLockStep?.({name:$.name,path:$.path},Q)}:{}});if(B){J("acquired");let Q={name:$.name,path:$.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),J("released")}};try{await Q.assertOwned()}catch(W){throw await Q.release(),W}return Q}let H=z.timeoutMs-(performance.now()-G);if(H<=0)throw new s0({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Q)=>setTimeout(Q,Math.min(z.retryMs+Y,H)))}}function PJ($){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 y0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await OJ($,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)}}function R1($,Z,X){if(X!==void 0)throw new y({operation:$,rowId:Z,kind:"row-staged",phase:$==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${Z} is reserved for roster publication`})}import{createHash as C$}from"node:crypto";var p="commonAuthPool",J1=1,T0="rows",T2="retiredEpochs",T$=1,W3=300000,m=p;function CJ($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(P(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function E1($){return C$("sha256").update(CJ($)).digest("hex")}function j8($){if(!P($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function TJ($){if(!P($)||typeof $.reservation!=="string"||!$.reservation||typeof $.disabledReason!=="string")return;if(Object.keys($).some((Z)=>!["reservation","label","disabledReason","providerState"].includes(Z)))return;if("label"in $&&typeof $.label!=="string")return;if("providerState"in $&&(typeof $.providerState!=="string"||!/^[a-f0-9]{64}$/.test($.providerState)))return;return $}var Q0="commonAuthProviderState";function P($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var AJ=new Set(["__proto__","constructor","prototype"]);function t1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(AJ.has($))return"id is a reserved object key";return}function V3($){let Z=typeof $==="string"?$.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}}function K8($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function z1($){return C$("sha256").update(K8($)).digest("hex")}function g0($){return C$("sha256").update(`credential-stamp\x00${K8($)}`).digest("hex")}function a0($){let Z=$.type==="oauth"?["oauth",typeof $.access==="string"?$.access:null,$.refresh,typeof $.expires==="number"&&Number.isFinite($.expires)?$.expires:null]:["api",$.apiKey,$.baseURL.trim(),$.authHeader??"authorization-bearer"];return C$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function U3($,Z,X,J={}){return{credentialEpoch:Z,digest:g0($),dispatch:a0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function e1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return C$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function A$($,Z,X,J){if(!Z||X===void 0)return;if(!P($)||!Object.hasOwn($,Q0))return;let z=j0($[m]);if(!z||z.providerState===void 0||z.digest!==g0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function z0($){return Number.isSafeInteger($)&&$>=1}function j0($){if(!P($))return;let Z=$.credentialEpoch;if(!z0(Z))return;if(typeof $.digest!=="string")return;if("dispatch"in $&&typeof $.dispatch!=="string")return;if("replace"in $&&$.replace!==!0)return;if("providerState"in $&&typeof $.providerState!=="string")return;let X="staged"in $?TJ($.staged):void 0;if("staged"in $&&!X)return;let J={...X?{staged:X}:{},...typeof $.dispatch==="string"?{dispatch:$.dispatch}:{},...$.replace===!0?{replace:!0}:{},...typeof $.providerState==="string"?{providerState:$.providerState}:{}};if(!("binding"in $))return"dispatch"in $||"replace"in $||"providerState"in $||"staged"in $?void 0:{credentialEpoch:Z,digest:$.digest};let z=$.binding;if(!P(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!V3(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...J,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function SJ($,Z,X){if($.identity!==X)return!1;if($.baseURL!==void 0&&(Z.type!=="api"||Z.baseURL!==$.baseURL))return!1;if($.authHeader!==void 0&&(Z.type!=="api"||Z.authHeader!==$.authHeader))return!1;return!0}function RJ($,Z,X,J){if(!$)return"none";if(!P(J)||!Object.hasOwn(J,m))return"missing";let z=j0(J[m]);if(!z)return"malformed";if(z.digest!==g0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!SJ(z.binding,$,X))return"mismatched";if(z.dispatch!==a0($))return"mismatched";return"bound"}function D8($){if(!$.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in $)return{status:"error",reason:"config file is not valid JSON"};let Z=$.value;if(!P(Z))return{status:"error",reason:"config root is not an object"};if("accounts"in Z&&!Array.isArray(Z.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(p in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let X=Z[p];if(!P(X))return{status:"error",reason:`${p} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${p}.schemaVersion is invalid`};if(J>J1)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${J1}`};if(T0 in X&&!P(X[T0]))return{status:"error",reason:`${p}.${T0} is not an object`};return{status:"ready",exists:!0,config:Z}}function N8($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!P($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!P($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function $$($){return Array.isArray($.accounts)?$.accounts:[]}function q8($){let Z=$[p];if(!P(Z))return{};let X=Z[T0];return P(X)?X:{}}function EJ($){return P($.accounts)?$.accounts:{}}function IJ($){if(!P($))return"not an object";let Z=t1($.id);if(Z)return Z;if($.type==="api")return V3($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function bJ($,Z){if(!P($))return;let X=$.credentialEpoch;if(!z0(X))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let J="quota"in $&&Z.decode?Z.decode($.quota):$.quota;if("quota"in $&&!Z.validate(J))return;if("staged"in $&&!j8($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function xJ($,Z){if(!P(Z))return;if($.type==="api"){let J=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!J)return;return{type:"api",apiKey:J,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let X=Z.refresh;if(typeof X!=="string"||!X.trim())return;return{type:"oauth",refresh:X,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function A2($,Z){return $$($).find((X)=>P(X)&&X.id===Z)}function F8($){if(!P($[p]))$[p]={};return $[p]}function j3($){let Z=F8($);if(!P(Z[T0]))Z[T0]={};return Z[T0]}function h0($,Z){let X=q8($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return P(J)?J:void 0}function S2($,Z,X){Object.defineProperty(j3($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function M8($,Z){let X=$[p];if(!P(X))return;let J=X[T2];if(!P(J)||!Object.hasOwn(J,Z))return;let z=J[Z];return z0(z)?z:void 0}function L8($,Z){let X=h0($,Z)?.credentialEpoch;return z0(X)?X:void 0}function R2($,Z){return Math.max(M8($,Z)??0,L8($,Z)??0)+1}function _8($,Z){let X=[...Z];if(X.length===0)return;let J=F8($),z=P(J[T2])?J[T2]:{},G={},B=(H,Y)=>Object.defineProperty(G,H,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[H,Y]of Object.entries(z))if(z0(Y))B(H,Y);for(let H of X)B(H,Math.max(M8($,H)??0,L8($,H)??1));J[T2]=G}function G1($,Z,X,J){let z=q8($),G=EJ(Z),B=new Set,H=[];for(let Y of $$($)){let Q=IJ(Y),W=P(Y)&&typeof Y.id==="string"?Y.id:void 0,V=W===void 0?void 0:z[W],U=P(V)&&Object.hasOwn(V,"staged"),K=U?j8(V.staged):void 0;if(Q||!P(Y)||W===void 0||B.has(W)){if(W!==void 0&&!B.has(W))B.add(W);if(W!==void 0)H.push({id:W,type:P(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,W),candidate:!1,invalid:"roster",stamp:"none",...K?{staged:K}:{}});continue}B.add(W);let j=Y.type==="api"?"api":"oauth",q=Object.hasOwn(z,W),D=q?bJ(z[W],X):void 0,F=xJ(Y,G[W]),_=Y.enabled!==!1,R=D?D.credentialEpoch:q?void 0:1,M=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,N={id:W,type:j,enabled:_,needsFirstReading:D?D.needsFirstReading:j==="oauth",hasEntry:q,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...M!==void 0?{identity:M}:{},...F?{credential:F,fingerprint:z1(F)}:{},...D?{credentialEpoch:D.credentialEpoch}:{},...K?{staged:K}:{},...D?.disabledReason!==void 0?{disabledReason:D.disabledReason}:{},...D&&"quota"in D?{quota:D.quota}:{},...kJ(G[W],F,R,M,J),stamp:RJ(F,R,M,G[W])};if(q&&!D)N.invalid="entry";else N.candidate=_&&F!==void 0&&!U;H.push(N)}return H}function kJ($,Z,X,J,z){if(!P($)||!Object.hasOwn($,Q0))return{};let G=A$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let B=$[Q0];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(e1(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function d($){return $.identity??$.id}function S$($,Z){if($===void 0||$>Z+W3)return Z;return Math.max(Z,$+1)}function K3($,Z){return S$($,Z)>Z+W3}function Z$($){let{id:Z,credential:X,identity:J,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:X.type,addedAt:G,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function O8($,Z){if($.type==="api")return{apiKey:$.apiKey};return{...$.access!==void 0?{access:$.access}:{},refresh:$.refresh,...$.expires!==void 0?{expires:$.expires}:{},...Z!==void 0?{lastRefreshedAt:Z}:{}}}function P8($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function C8($,Z={}){if(!P($))return"credential must be an object";if($.type==="oauth"){if(typeof $.refresh!=="string"||!$.refresh.trim())return"oauth credential needs a refresh token";return}if($.type==="api"){if(typeof $.apiKey!=="string"||!$.apiKey.trim())return"api credential needs an api key";if($.apiKey.trim()!==$.apiKey)return"api key must not carry surrounding whitespace";if(!(Z.baseURLOptional&&$.baseURL===void 0)&&!V3($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var E2="transition",T8="transitionMark";function fJ($){if(!P($))return;let Z=$[E2];if(!P(Z))return;if(typeof Z.mark!=="string"||Z.mark.length===0)return;if(Z.enabled===!0)return{mark:Z.mark,enabled:!0};if(Z.enabled===!1&&typeof Z.reason==="string")return{mark:Z.mark,enabled:!1,reason:Z.reason};return}function R$($,Z,X){if(X.enabled)O$($,Z);else Z1($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[T8]:X.mark}),!X.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)o1($,z.identity)}function yJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function gJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function hJ($,Z,X,J={}){let z=P(Z.accounts)?Z.accounts:{},G=new Map;for(let B of G1($,Z,X)){if(B.invalid||B.staged||!B.credential)continue;let H=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!P(H))continue;let Y=j0(H[m]);if(!Y?.binding)continue;if(Y.digest!==g0(B.credential))continue;let Q=B.credentialEpoch??1;if(Y.credentialEpoch>Q){if(!gJ(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==a0(yJ(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===Q&&Y.dispatch!==void 0&&Y.dispatch===a0(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===Q&&Y.binding.identity===B.identity){if(J.requireCredentialStamps&&Y.dispatch!==a0(B.credential))continue;let W=fJ(H[m]);if(W&&h0($,B.id)?.[T8]!==W.mark)G.set(B.id,{kind:"transition",transition:W})}}return G}function D3($,Z,X,J){let G={...$.entry(Z)??{},credentialEpoch:X,needsFirstReading:!0};if(delete G.quota,J.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(r1))delete G.disabledReason;$.setEntry(Z,G);let B=$.rosterRow(Z);if(!B)return;if(J.identity!==void 0)B.accountId=J.identity;else delete B.accountId;if(J.baseURL!==void 0)B.baseURL=J.baseURL;if(J.authHeader!==void 0)B.authHeader=J.authHeader}function N3($,Z,X,J={}){let z=hJ($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),B={rows:()=>G1(G,Z,X),rosterRow:(H)=>A2(G,H),entry:(H)=>h0(G,H),setEntry:(H,Y)=>S2(G,H,Y)};for(let[H,Y]of z)if(Y.kind==="replace")D3(B,H,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[H,Y]of z)if(Y.kind==="identity")S1(B,H,Y.identity);else if(Y.kind==="transition")R$(B,H,Y.transition);else if(Y.stamp.binding.identity!==void 0)o1(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function q3($,Z,X,J={}){let{config:z,torn:G}=N3($,Z,X,J),B=G1(z,Z,X,J.providerState);for(let H of B){if(G.includes(H.id))H.torn=!0,H.candidate=!1;if(J.requireCredentialStamps&&H.stamp!=="bound")H.unbound=!0,H.candidate=!1}return B}async function F3($){try{return await L0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function A8($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function W0($){for(let Z=0;Z<3;Z++){let X=await F3($.configPath),J=await F3($.statePath),z=await F3($.configPath);if(X!==z){if(Z<2)await vJ(2+Math.floor(Math.random()*4));continue}let G=D8(A8(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=N8(A8(J));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:q3(G.config,B.state,$.codec,{requireCredentialStamps:$.requireCredentialStamps===!0,...$.providerState?{providerState:$.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function A0($,Z,X,J="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new y({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:$.reason});return new y({operation:Z,...X!==void 0?{rowId:X}:{},phase:J,retryable:!1,kind:$.status==="pending-migration"?"pending-migration":"load-error",message:$.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${$.file} file cannot be loaded: ${$.reason}`})}class S8{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,X,J,z){this.ctx=$,this.snapshot=Z,this.locks=X,this.progress=J,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return q3(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row($){return this.rows().find((Z)=>Z.id===$)}reservation($){if(this.rosterRow($)){let X=this.entry($);return X&&Object.hasOwn(X,"staged")?X.staged:void 0}let Z=this.stateAccount($)?.[m];return P(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){R1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),A2(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(P(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return j3(this.config)}entry($){return this.entries(),h0(this.config,$)}setEntry($,Z){S2(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=N3(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if(Z.length===0)return;this.config=$,await this.commitConfig({counted:!1})}stateAccount($){let Z=P(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return P(X)?X:void 0}dropStateAccount($){if(P(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!P(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,$,{value:Z,enumerable:!0,writable:!0,configurable:!0})}async commitConfig($={}){let Z=this.roster(),X=new Set;for(let Y of Z)if(P(Y)&&typeof Y.id==="string")X.add(Y.id);let J=new Set;for(let Y of $$(this.snapshot.config))if(P(Y)&&typeof Y.id==="string"&&!X.has(Y.id))J.add(Y.id);for(let Y of Object.keys(this.entries()))if(!X.has(Y))J.add(Y);_8(this.config,J);let z=this.entries(),G={};for(let[Y,Q]of Object.entries(z))if(X.has(Y))Object.defineProperty(G,Y,{value:Q,enumerable:!0,writable:!0,configurable:!0});let B=this.config[p],H={...this.config,version:T$,accounts:Z,[p]:{...B,schemaVersion:J1,[T0]:G}};await this.write(this.ctx.configPath,H,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of J)this.ctx.removedIds.add(Y);this.config=H}),this.config=H}async commitState($,Z={}){let X={...this.state,version:T$,accounts:P(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,X,"state",!0,Z.durable??!1),this.state=X,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await z3(this.ctx.statePath)}catch($){throw new y({operation:this.info.operation,rowId:this.info.rowId,phase:"before-first-write",kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await z3(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await J3($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function R8($,Z){let X=new y0($.lockDefaults,$.lockEnv),J={writes:0};try{for(let H of $.storeLocks)await X.acquire(H);let z=await W0($);if(z.status==="error")throw A0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[H,Y]of Object.entries(z.config))if(!Z.includes(H))G[H]=Y;G.version=T$,G[p]={schemaVersion:J1,[T0]:{}};let B={operation:"initialize",rowId:void 0};return await _0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",B),await X.assertAll()}}),J.writes++,await $.onStep?.("after-config-write",B),"initialized"}catch(z){throw B1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function n($,Z,X,J,z,G={}){let B=Z.held.length;try{for(let Q of $.storeLocks)await Z.acquire(Q);let H=await W0($);if(H.status!=="ready")throw A0(H,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let Y=new S8($,H,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))Y.assertNotStaged(J.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await Z.releaseTo(B)}}function B1($,Z,X,J){let z=Z==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?J.committed:void 0;if(Z==="publishRoster"&&J.publicationDecided)return new y({operation:Z,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:$});if(Z==="publishRoster"&&$ instanceof P$)return new y({operation:Z,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof y){if($.phase===z&&$.rowId===X&&$.operation===Z&&$.committed===G)return $;return new y({operation:Z,...X!==void 0?{rowId:X}:{},phase:$.kind==="after-persist-hook"?$.phase:z,retryable:$.retryable,kind:$.kind,...$.committed??G?{committed:$.committed??G}:{},message:$.message,...$.cause!==void 0?{cause:$.cause}:{}})}let B={operation:Z,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof X1)return new y({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${Z} lost a lease after its first write; the intermediate stays on disk`:`${Z} lost a lease before writing; nothing was written`});if($ instanceof s0)return new y({...B,retryable:!0,kind:"lock-contention",message:$.message});return new y({...B,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function H0($,Z,X,J,z){let G=new y0($.lockDefaults,$.lockEnv),B={writes:0};try{return await z(G,B)}catch(H){let Y=B1(H,Z,X,B);if(Y.kind!=="after-persist-hook")await U8(Z,J,X,Y,$.logger);throw Y}finally{await G.releaseAll()}}function F0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(d(Z))}`,path:$.ctx.statePath}}async function S0($,Z,X){let J=await W0($.ctx);if(J.status!=="ready")throw A0(J,Z,X);let z=J.rows.find((Q)=>Q.id===X),G=h0(J.config,X),B=J.state.accounts,H=P(B)&&Object.hasOwn(B,X)?B[X]:void 0,Y=P(H)?H[m]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))R1(Z,X,G.staged);if(!z&&P(Y)&&Object.hasOwn(Y,"staged"))R1(Z,X,Y.staged);if(!z)throw O0(Z,X);return{result:J,row:z}}function O0($,Z){return new y({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function V0($,Z){if(Z.unbound)throw O($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function O($,Z,X,J,z=!1){return new y({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:X,message:J})}function M3($,Z){if(!z0(Z?.credentialEpoch))throw O("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function E$($,Z,X){if(!X)throw O0("pull",$);if(X.invalid)throw O("pull",$,"invalid-row",`row ${$} is invalid`);if(!X.credential)throw O("pull",$,"no-credential",`row ${$} holds no credential`);if(V0("pull",X),X.torn||!X.hasEntry||X.credentialEpoch!==Z.credentialEpoch||X.identity!==Z.identity)throw new y({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function I$($,Z,X,J){let z=$.codec.merge(X,J);if(!$.codec.validate(z))throw O("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function I2($,Z,X,J){let{ctx:z}=$,G=new y0(z.lockDefaults,z.lockEnv),B={writes:0};try{M3(Z,X),await n(z,G,B,{operation:"pull",rowId:Z},async(H)=>{H.assertNotStaged(Z);let Y=H.row(Z);E$(Z,X,Y);let Q=H.entry(Z);if(!Q)throw O0("pull",Z);let W=I$(z,Z,Q.quota,J);H.setEntry(Z,{...Q,quota:W,needsFirstReading:!1}),await H.commitConfig()},{completeTorn:!1})}catch(H){throw B1(H,"pull",Z,B)}finally{await G.releaseAll()}}function i0($,Z,X,J,z="the provider state"){if(!$)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(J);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw O(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw O(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function b$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:i0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function E8($,Z,X,J,z){let G=$?.onReplace,B=G?G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:X,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...J!==void 0?{identity:J}:{},...z!==void 0?{incoming:structuredClone(z)}:{}}):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:i0($,"replace",Z.id,B,"the provider state onReplace returned")}}function I8($,Z,X,J,z){if(Z.kind==="set")return e1($,Z.value);if(Z.kind==="clear")return;return A$(X,J?.credential,z,J?.identity)}async function b8($,Z,X,J,z={}){B0("updateProviderState");let{ctx:G}=$,B="updateProviderState";return H0(G,B,Z,z.onFailure,async(H,Y)=>{let Q=G.providerState;if(!Q)throw O(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw O(B,Z,"invalid-input","a mutator is required");let W=P(X)?X.credentialEpoch:void 0;if(!z0(W))throw O(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await S0($,B,Z);await H.acquire(F0($,V));for(let U of z.extraLocks??[])await H.acquire(U);return n(G,H,Y,{operation:B,rowId:Z},async(U)=>{let K=U.row(Z);if(!K)throw O0(B,Z);if(d(K)!==d(V))throw O(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(K.invalid)throw O(B,Z,"invalid-row",`row ${Z} failed validation`);if(!K.credential)throw O(B,Z,"no-credential",`row ${Z} holds no credential`);if(V0(B,K),(K.credentialEpoch??1)!==W||K.identity!==X.identity)throw O(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let q=await L3(U,Q,B,K,J);if(q.kind!=="changed")return{id:Z,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return U.setStateAccount(Z,q.account),await U.commitState(),q.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:q.value}})})}var x8=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function L3($,Z,X,J,z,G=!1){let{id:B,credential:H}=J;if(!H)throw O(X,B,"no-credential",`row ${B} holds no credential`);let Y=J.credentialEpoch??1,Q=$.stateAccount(B),W=Q?.[m],V=j0(W);if(!P(W)||!V?.binding||V.digest!==g0(H)||V.credentialEpoch!==Y||V.binding.identity!==J.identity)throw O(X,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let U=J.providerState===void 0?void 0:structuredClone(J.providerState),K=await f0(X,()=>z(U,J));if(G&&K===x8)return{kind:"declined"};let j=K===void 0?void 0:i0(Z,X,B,K,"the provider state the mutator returned"),q=Q!==void 0&&Object.hasOwn(Q,Q0);if(j===void 0?!q:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(j))return{kind:"unchanged",...j!==void 0?{value:j}:{}};let D={...Q};if(j===void 0){delete D[Q0];let F={...W};delete F.providerState,D[m]=F}else{D[Q0]=j;let F=e1(Z,j);if(V.providerState!==F)D[m]={...W,providerState:F}}return{kind:"changed",...j!==void 0?{value:j}:{},account:D}}import{randomUUID as k8}from"node:crypto";async function f2($,Z,X){if(!X)return;let J=$.rows().map((G)=>{let{id:B,type:H,label:Y,enabled:Q,disabledReason:W,identity:V,credentialEpoch:U,stamp:K,staged:j,torn:q,invalid:D}=G;return{id:B,type:H,label:Y,enabled:Q,disabledReason:W,identity:V,credentialEpoch:U,stamp:K,staged:j,torn:q,invalid:D}}),z=await f0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw O($.info.operation,Z,"row-protected",z)}var mJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function wJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function pJ($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!P(J)){if(X.baseURL===void 0)throw O($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...X,baseURL:X.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:wJ(J),B=X.baseURL?.trim()??G.baseURL,H=X.authHeader??G.authHeader;if(B!==G.baseURL||H!==G.authHeader)throw O($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:B,authHeader:H}}function f8($,Z,X,J){let z=$.rosterRow(Z),G=$.row(Z),B=J??(G?G.identity:P(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function b2($,Z,X,J,z={}){let G=pJ(Z,X,J),B=Z.stateAccount(X),H=z.providerState??{kind:"keep"},Y=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,Q=typeof Y==="number"?Y:1,W=I8($.ctx.providerState,H,B,B&&Object.hasOwn(B,Q0)?Z.row(X):void 0,Q),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??S$(V,$.ctx.now()):void 0,K={...B??{}};for(let D of mJ)delete K[D];if(z.clearErrors)delete K.lastRefreshError,delete K.lastQuotaRefreshError,delete K.quota;if(H.kind==="clear")delete K[Q0];else if(H.kind==="set")K[Q0]=H.value;let j=P8(G,U),q={...K,...O8(G,U),[m]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[E2]:z.transition}:{},...U3(j,Q,z.binding??f8(Z,X,j,z.identity),{replace:z.binding!==void 0,...W!==void 0?{providerState:W}:{}})}};return{stored:j,account:q}}async function x2($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function y2($,Z,X,J,z={}){return x2(Z,X,b2($,Z,X,J,z))}async function lJ($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=A$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:U3(Z.credential,Z.credentialEpoch??1,f8($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function O3($,Z,X){let J=$==="add"?t1(Z):void 0;if(J)throw O($,Z,"invalid-input",J);let z=C8(X,{baseURLOptional:$==="rotate"});if(z)throw O($,Z,"invalid-input",z)}function g2($,Z,X,J){if(!X)throw O0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw O($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function J$($,Z,X){if(X!==void 0&&!z0(P(X)?X.credentialEpoch:void 0))throw O($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function h2($,Z,X,J){if(!X)throw O0($,Z);if(X.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw O($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function k2($,Z){return O($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function x$($,Z){return O($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function uJ($,Z,X,J){let{id:z,credential:G,identity:B}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!X$(Z.state,z))return;let H=()=>{throw O("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(z),Q=j0(Y?.[m]);if(!Q?.binding||Q.dispatch===void 0||Q.replace)return H();if(G.type==="api"&&(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0))return H();let W=G.type==="api"?{...G,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}:G,[V]=G1({accounts:[Z$({id:z,credential:W,identity:Q.binding.identity,addedAt:0})],[p]:{rows:{[z]:{credentialEpoch:R2(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return H();if(B!==void 0&&B!==V.identity)return H();if(g0(G)!==Q.digest)return H();if(G.type==="api"){if(G.baseURL.trim()!==Q.binding.baseURL)return H();if((G.authHeader??"authorization-bearer")!==Q.binding.authHeader)return H()}else if(a0(G)!==Q.dispatch)return H();if(Q.providerState!==void 0&&V.providerState===void 0)return H();if(J!==void 0&&e1($.ctx.providerState,J)!==Q.providerState)return H();return V}function dJ($,Z,X,J){let{id:z,credential:G,identity:B,label:H}=X,Y=Z.rosterRow(z),Q=()=>{throw O("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},W=Z.stateAccount(z),V=j0(W?.[m]),U=V?.staged;if(!V?.binding||!U||V.replace||V.dispatch===void 0)return Q();if(Y&&(Y.type!==G.type||Y.label!==H||Y.accountId!==B))return Q();if(U.reservation!==X.stage?.reservation||U.label!==H||U.disabledReason!==X.disabled?.reason||V.binding.identity!==B)return Q();let K=J===void 0?void 0:E1(J),j=W?.[Q0],q=j===void 0?void 0:E1(j);if(U.providerState!==K||U.providerState!==q)return Q();if(g0(G)!==V.digest||a0(G)!==V.dispatch)return Q();let D=Y?Z.config:{accounts:[{...Z$({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[p]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},F=G1(D,Z.state,$.ctx.codec,$.ctx.providerState).find((_)=>_.id===z);if(!F?.credential||F.invalid||F.stamp!=="bound"||F.type!==G.type||F.enabled||F.label!==U.label||F.identity!==V.binding.identity||F.disabledReason!==U.disabledReason||F.staged?.reservation!==U.reservation)return Q();if(Y)return{id:z,outcome:"exists",credential:F.credential,credentialEpoch:V.credentialEpoch};if(R2(Z.config,z)!==V.credentialEpoch)return Q();return Z.roster().push({...Z$({id:z,credential:G,identity:B,label:H,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:F.credential,credentialEpoch:V.credentialEpoch}))}async function y8($,Z,X={}){B0("add");let{ctx:J}=$,{id:z,credential:G,identity:B,label:H}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,Q=await H0(J,"add",z,X.onFailure,async(W,V)=>{O3("add",z,G);let U=X.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw O("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(U)||Z.stage!==void 0&&(H!==void 0&&typeof H!=="string"||B!==void 0&&(typeof B!=="string"||!B))||Z.disabled!==void 0&&(!P(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!P(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||U==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw O("add",z,"invalid-input","staging requires a reservation and a disabled reason");let K=Z.providerState===void 0?void 0:i0(J.providerState,"add",z,Z.providerState);if(await W.acquire(F0($,{id:z,identity:B})),G.type==="oauth")await W.acquire(X.providerLock??$.providerLock);for(let j of X.extraLocks??[])await W.acquire(j);return n(J,W,V,{operation:"add",rowId:z},async(j)=>{await f2(j,z,X.protect);let q=P(j.state.accounts)?j.state.accounts:{},D=Object.entries(q).find(([f,g])=>{if(f===z||j.rosterRow(f)||!P(g))return!1;let h=g[m];if(!P(h)||!Object.hasOwn(h,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(D)throw O("add",D[0],"row-staged",`orphan ${D[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(z))throw O("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&U!=="rotate"&&(j.rosterRow(z)||X$(j.state,z)))return dJ($,j,Z,K);if(U==="rotate"){j.assertNotStaged(z);let f=j.rows().find((g)=>g.fingerprint===z1(G));if(f)j.assertNotStaged(f.id)}if(U==="refuse"){let f=j.rows().find((r)=>r.fingerprint===z1(G)||r.id===z&&r.credential),g=P(j.state.accounts)?j.state.accounts:{},h=Object.entries(g).find(([,r])=>{if(!P(r))return!1;if(G.type==="oauth")return r.refresh===G.refresh;return typeof r.apiKey==="string"&&r.apiKey.trim()===G.apiKey.trim()})?.[0],e=f?.id??h??z;if(f||h!==void 0||X$(j.state,z))throw O("add",e,"credential-exists",`row ${e} already holds this secret or id`)}if(U==="stage-duplicate"&&(j.rosterRow(z)||X$(j.state,z)))throw O("add",z,"id-exists",`row ${z} already exists`);let F=uJ($,j,Z,K),_=j.rows(),R=z1(G),M=U==="rotate"&&!F&&_.find((f)=>f.invalid===void 0&&f.fingerprint===R);if(M){if(j.assertNotStaged(M.id),V0("add",M),B!==void 0&&M.identity!==void 0&&B!==M.identity)throw k2("add",M.id);let f=b2($,j,M.id,G,{...K!==void 0?{providerState:b$(J.providerState,"add",M.id,M.providerState,K)}:{}});await j.completeTorn(),j.assertNotStaged(M.id);let g=await x2(j,M.id,f);return{id:M.id,outcome:"rotated",credential:g,credentialEpoch:M.credentialEpoch??1}}let N=_.find((f)=>f.id===z);if(N){if(N.invalid)throw O("add",z,"invalid-row",`row ${z} is invalid`);if(N.credential)throw O("add",z,"id-exists",`row ${z} already holds a credential`);if(V0("add",N),N.type!==G.type)throw O("add",z,"type-mismatch",`row ${z} is a ${N.type} row`);if(B!==void 0&&N.identity!==void 0&&B!==N.identity)throw k2("add",z);if(!N.hasEntry)j.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let f=b2($,j,z,G,{clearErrors:!0,...K!==void 0?{providerState:{kind:"set",value:K}}:{}});await j.completeTorn();let g=await x2(j,z,f);if(!N.hasEntry)await j.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:N.credentialEpoch??1}}let L=R2(j.config,z);if(!z0(L))throw O("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let S=F?.identity??B;j.roster().push(Z$({id:z,credential:G,...S!==void 0?{identity:S}:{},...H!==void 0?{label:H}:{},addedAt:J.now()})),j.setEntry(z,{credentialEpoch:L,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let T="added";if(Z.disabled)Z1(j,z,Z.disabled.reason),T="added-disabled";if(!Z.disabled&&S!==void 0&&G.type==="oauth"){if(_.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===S))Z1(j,z,Z3),T="added-disabled"}if(F?.credential)return await j.commitConfig(),{id:z,outcome:T,credential:F.credential,credentialEpoch:F.credentialEpoch??L};j.dropStateAccount(z);let b=b2($,j,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...H!==void 0?{label:H}:{},...K!==void 0?{providerState:E1(K)}:{}}}:{},...K!==void 0?{providerState:{kind:"set",value:K}}:{}});if(U==="rotate")await j.completeTorn();let w=await x2(j,z,b);return await j.commitConfig(),{id:z,outcome:T,credential:w,credentialEpoch:L}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(Q.outcome==="added"||Q.outcome==="completed"))$.firePull(Q.id,"add");return Q}async function g8($,Z,X,J={},z={}){B0("replace");let{ctx:G}=$,B=await H0(G,"replace",Z,z.onFailure,async(H,Y)=>{O3("replace",Z,X),J$("replace",Z,z.attribution);let Q=J.providerState===void 0?void 0:i0(G.providerState,"replace",Z,J.providerState),{row:W}=await S0($,"replace",Z);if(await H.acquire(F0($,W)),X.type==="oauth")await H.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await H.acquire(V);return n(G,H,Y,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)h2("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let U=g2("replace",Z,V.row(Z),X);if(d(U)!==d(W))throw x$("replace",Z);let K=V.entry(Z)?.credentialEpoch,j=(typeof K==="number"?K:1)+1;if(!z0(j))throw O("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let q=E8(G.providerState,U,j,J.identity,Q),D={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(D3(V,Z,j,D),J.identity!==void 0)o1(V,J.identity);let F=await y2($,V,Z,X,{clearErrors:!0,binding:D,providerState:q});return await V.commitConfig(),{id:Z,credential:F,credentialEpoch:j}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return B}async function h8($,Z,X,J={},z={}){B0("rotate");let{ctx:G}=$;return H0(G,"rotate",Z,z.onFailure,async(B,H)=>{O3("rotate",Z,X),J$("rotate",Z,z.attribution);let Y=J.providerState===void 0?void 0:i0(G.providerState,"rotate",Z,J.providerState),{row:Q}=await S0($,"rotate",Z);if(await B.acquire(F0($,Q)),J.identity!==void 0&&X.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await B.acquire(W);return n(G,B,H,{operation:"rotate",rowId:Z},async(W)=>{if(z.attribution!==void 0)h2("rotate",Z,W.row(Z),z.attribution),await W.completeTorn();let V=g2("rotate",Z,W.row(Z),X);if(d(V)!==d(Q))throw x$("rotate",Z);if(V0("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw k2("rotate",Z);let U=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,K=await y2($,W,Z,X,{identity:U,...Y!==void 0?{providerState:b$(G.providerState,"rotate",Z,V.providerState,Y)}:{}}),j=!1;if(!V.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),j=!0;if(J.identity!==void 0&&V.identity!==J.identity)S1(W,Z,J.identity),j=!0;if(j)await W.commitConfig();return{id:Z,credential:K}},{completeTorn:z.attribution===void 0})})}async function v8($,Z,X,J,z){B0(Z);let{ctx:G}=$,B=G.providerState,H=z.attribution,Y=z.providerState;return H0(G,Z,X,z.onFailure,async(Q,W)=>{if(J$(Z,X,H),Y!==void 0){if(typeof Y!=="function")throw O(Z,X,"invalid-input","the provider-state mutator must be a function");if(H===void 0)throw O(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw O(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await S0($,Z,X);await Q.acquire(F0($,V));for(let U of z.extraLocks??[])await Q.acquire(U);return n(G,Q,W,{operation:Z,rowId:X},async(U)=>{await f2(U,X,z.protect),U.assertNotStaged(X);let K=U.row(X),j=J.enabled?g2("enable",X,K):K;if(!j||!U.rosterRow(X))throw O0(Z,X);if(d(j)!==d(V))throw x$(Z,X);if(H!==void 0)h2(Z,X,j,H);if(J.enabled&&j.disabledReason?.startsWith(r1))throw O("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let q=!J.enabled||!j.enabled||j.disabledReason!==void 0;if(J.enabled&&q&&j.type==="oauth"){let M=j.identity===void 0?void 0:U.rows().find((N)=>N.id!==X&&N.invalid===void 0&&N.type==="oauth"&&N.enabled&&N.identity===j.identity);if(M)throw O("enable",X,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${X}`)}if(Y===void 0||B===void 0){if(await U.completeTorn(),!q)return{id:X};if(J.enabled)O$(U,X);else Z1(U,X,J.reason);return await U.commitConfig(),{id:X}}if(!j.credential)throw O(Z,X,"no-credential",`row ${X} holds no credential`);V0(Z,j);let D=await L3(U,B,Z,j,Y,!0);if(D.kind==="declined")return{id:X,declined:!0};await U.completeTorn();let F={id:X,providerStateOutcome:D.kind==="unchanged"?"unchanged":D.value===void 0?"cleared":"updated",...D.value!==void 0?{providerState:D.value}:{}};if(D.kind==="unchanged"){if(q){if(J.enabled)O$(U,X);else Z1(U,X,J.reason);await U.commitConfig()}return F}if(!q)return U.setStateAccount(X,D.account),await U.commitState(),F;let _=J.enabled?{mark:k8(),enabled:!0}:{mark:k8(),enabled:!1,reason:J.reason},R=D.account[m];return U.setStateAccount(X,{...D.account,[m]:{...R,[E2]:_}}),await U.commitState(),R$(U,X,_),await U.commitConfig(),F},{completeTorn:!1})})}function m8($,Z,X,J={}){return v8($,"disable",Z,{enabled:!1,reason:X},J)}function w8($,Z,X={}){return v8($,"enable",Z,{enabled:!0},X)}async function p8($,Z,X={}){B0("remove");let{ctx:J}=$;return H0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw O("remove",Z,"invalid-input","id must be non-empty");let B=X.attribution;if(J$("remove",Z,B),X.staged!==void 0&&(!P(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw O("remove",Z,"invalid-input","a staged removal needs a reservation");let H=await W0(J);if(H.status!=="ready")throw A0(H,"remove",Z);let Y=H.rows.find((W)=>W.id===Z);if(!Y&&!X$(H.state,Z))throw O0("remove",Z);let Q=d(Y??{id:Z});await z.acquire(F0($,Y??{id:Z}));for(let W of X.extraLocks??[])await z.acquire(W);return n(J,z,G,{operation:"remove",rowId:Z},async(W)=>{let V=W.reservation(Z);if(V!==void 0){if(!P(V)||!X.staged||V.reservation!==X.staged.reservation)throw O("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw O("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=W.row(Z),K=X$(W.state,Z);if(!U&&!K)throw O0("remove",Z);if(d(U??{id:Z})!==Q)throw x$("remove",Z);if(B!==void 0)if(U)v2(Z,U,B);else cJ($,W,Z,B);let j=X.protect;if(j){let q={row:U,config:W.snapshot.config,state:W.snapshot.state},D=await f0("remove",()=>j(Z,q));if(D!==void 0)throw O("remove",Z,"row-protected",D)}if(U){if(B===void 0)await W.completeTorn();W.dropRosterRows(Z),await W.commitConfig()}if(K)W.dropStateAccount(Z),await W.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function v2($,Z,X,J="remove"){if(h2(J,$,Z,X),Z.torn)throw O(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw O(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function cJ($,Z,X,J){let z=()=>O("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(X),B=j0(G?.[m]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let H;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();H={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")H={type:"oauth",refresh:G.refresh};else throw z();let[Y]=G1({accounts:[Z$({id:X,credential:H,identity:B.binding.identity,addedAt:0})],[p]:{rows:{[X]:{credentialEpoch:B.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==J.credentialEpoch||B.binding.identity!==J.identity)throw O("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function X$($,Z){let X=$.accounts;return P(X)&&Object.hasOwn(X,Z)}function _3($){return P($)&&typeof $.id==="string"?$.id:void 0}function sJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let B=_3(G);if(B!==void 0)X.add(B)}let J=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(J.has(G))return`id ${G} appears more than once`;if(!X.has(G))return`id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function aJ($,Z){let X=new Map;for(let G of $){let B=_3(G);if(B===void 0)continue;let H=X.get(B);if(H)H.push(G);else X.set(B,[G])}let J=Z.flatMap((G)=>X.get(G)??[]),z=0;return $.map((G)=>_3(G)===void 0?G:J[z++])}async function l8($,Z,X={}){B0("reorder");let{ctx:J}=$,z=X.onFailure;return H0(J,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let H of X.extraLocks??[])await G.acquire(H);return n(J,G,B,{operation:"reorder",rowId:void 0},async(H)=>{let Y=H.roster(),Q=sJ(Y,Z);if(Q)throw new y({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Q});let W=[...Z],V=aJ(Y,W);if(V.every((U,K)=>U===Y[K]))return{ids:W,outcome:"unchanged"};return H.config.accounts=V,await H.commitConfig(),{ids:W,outcome:"reordered"}},{completeTorn:!1})})}async function u8($,Z,X,J,z={}){return B0("recordIdentity"),H0($.ctx,"recordIdentity",Z,z.onFailure,async(G,B)=>{if(typeof X!=="string"||X.length===0)throw O("recordIdentity",Z,"invalid-input","identity must be non-empty");let H=P(J)?J.credentialEpoch:void 0;if(!z0(H))throw O("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await S0($,"recordIdentity",Z);await G.acquire(F0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let Q of z.extraLocks??[])await G.acquire(Q);return n($.ctx,G,B,{operation:"recordIdentity",rowId:Z},async(Q)=>{let W=g2("recordIdentity",Z,Q.row(Z));if(d(W)!==d(Y))throw x$("recordIdentity",Z);if(V0("recordIdentity",W),(W.credentialEpoch??1)!==H)throw O("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(W.identity!==void 0&&W.identity!==X)throw k2("recordIdentity",Z);if(W.identity===void 0)await lJ(Q,W,X);let V=S1(Q,Z,X);return await Q.commitConfig(),{id:Z,disabled:V}})})}function c8($){let Z=$[p];return P(Z)&&P(Z.publications)?Z.publications:{}}function s8($,Z){let X=c8($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!P(J)||J.operationId!==Z||typeof J.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(J.planDigest)||!["committed","cleaned"].includes(String(J.phase))||!Array.isArray(J.removed)||!Array.isArray(J.finalized)||J.removed.some((z)=>!P(z)||typeof z.id!=="string"||!z0(z.credentialEpoch))||J.finalized.some((z)=>!P(z)||typeof z.id!=="string"||!z0(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw O("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function a8($,Z){let X=await W0($.ctx);if(X.status!=="ready")throw A0(X,"publishRoster",Z);return s8(X.config,Z)}function iJ($,Z){let X=()=>{throw O("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!P(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))X();let J=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!P(z)||typeof z.id!=="string"||t1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),J$("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))X()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")X();for(let z of Z.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))X();if(Z.order.some((z)=>typeof z!=="string"||t1(z))||new Set(Z.order).size!==Z.order.length)X()}function i8($,Z){$.entries();let X=$.config[p],J={...c8($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function nJ($,Z,X){let J=new Set;for(let B of $$($.config)){if(!P(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw O("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(B.id)}let z=new Set(Z.remove.map((B)=>B.id)),G=X.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==Z.order.length||Z.order.some((B)=>!G.some((H)=>H.id===B))||G.some((B)=>!Z.order.includes(B.id)))throw O("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function d8($,Z){await $.assertAll();for(let J of Z.removed)if(j0($.stateAccount(J.id)?.[m])?.credentialEpoch===J.credentialEpoch&&!$.rosterRow(J.id))$.dropStateAccount(J.id);for(let J of Z.finalized){let z=$.stateAccount(J.id),G=j0(z?.[m]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let B={...z[m]};delete B.staged,$.setStateAccount(J.id,{...z,[m]:B})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return i8($,X),await $.commitConfig({durable:!0}),X}async function n8($,Z,X={}){return B0("publishRoster"),H0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!P(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw O("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=E1(Z),B=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((H)=>P(H)&&typeof H.id==="string");for(let H=0;;H++){let Y=await W0($.ctx);if(Y.status!=="ready")throw A0(Y,"publishRoster",Z.operationId);let Q=new Map(B.map(({id:V})=>[V,d(Y.rows.find((U)=>U.id===V)??{id:V})]));for(let V of[...new Set(Q.values())].sort())await J.acquire(F0($,{id:V}));await J.acquire(X.providerLock??$.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let W=await n($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let U=V.rows();if(B.some(({id:N})=>d(U.find((L)=>L.id===N)??{id:N})!==Q.get(N)))return;let K=s8(V.config,Z.operationId);if(K){if(K.planDigest!==G)throw O("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(K.phase==="cleaned")return{outcome:"already-cleaned",receipt:K};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await d8(V,K)}}iJ($,Z);let j=nJ(V,Z,U),q=[];for(let N of Z.remove){V.assertNotStaged(N.id);let L=U.find((S)=>S.id===N.id);if(!L)throw O("publishRoster",N.id,"attribution","the removed row no longer exists");if(v2(N.id,L,N.attribution,"publishRoster"),!L.credential||N.fingerprint!==void 0&&z1(L.credential)!==N.fingerprint)throw O("publishRoster",N.id,"attribution","the removed secret no longer matches");q.push(L)}let D=[];for(let N of Z.finalize){let L=U.find((g)=>g.id===N.id),S=j0(V.stateAccount(N.id)?.[m]);if(!L||L.staged?.reservation!==N.reservation||S?.staged?.reservation!==N.reservation||L.enabled)throw O("publishRoster",N.id,"row-staged","the finalized row is not disabled under this reservation");let T=V.stateAccount(N.id),b=V.rosterRow(N.id),w=T?.[Q0],f=w===void 0?void 0:E1(w);if(!S?.staged||S.staged.label!==b?.label||S.staged.disabledReason!==L.disabledReason||S.staged.providerState!==f)throw O("publishRoster",N.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");v2(N.id,L,N.attribution,"publishRoster"),D.push(L)}let F=j.find((N)=>N.torn);if(F)throw O("publishRoster",Z.operationId,"attribution",`Row ${F.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let _=new Set;for(let N of j){if(!(Z.finalize.find((S)=>S.id===N.id)?.enabled??N.enabled)||N.type!=="oauth"||N.identity===void 0)continue;if(_.has(N.identity))throw O("publishRoster",N.id,"invalid-input","the final enabled roster repeats a known identity");_.add(N.identity)}for(let N of j)if(N.identity!==void 0&&N.fingerprint!==void 0&&j.some((L)=>L.id!==N.id&&L.identity!==void 0&&L.identity!==N.identity&&L.fingerprint===N.fingerprint))throw O("publishRoster",N.id,"attribution","the resulting pool gives the same secret different known identities");for(let N of D)if(N.identity!==void 0&&q.some((L)=>L.identity!==void 0&&L.identity!==N.identity&&L.fingerprint===N.fingerprint))throw O("publishRoster",N.id,"attribution","the staged secret belonged to a different known identity");await f2(V,Z.operationId,X.protect);let R={operationId:Z.operationId,planDigest:G,phase:"committed",removed:q.map((N)=>({id:N.id,credentialEpoch:N.credentialEpoch??1})),finalized:Z.finalize.map((N,L)=>({id:N.id,credentialEpoch:D[L]?.credentialEpoch??1,reservation:N.reservation,enabled:N.enabled}))};for(let N of Z.remove)V.dropRosterRows(N.id);for(let N of Z.finalize){let L=V.rosterRow(N.id);L.enabled=N.enabled;let S={...V.entry(N.id)};if(delete S.staged,N.enabled)delete S.disabledReason;else S.disabledReason=N.disabledReason;V.setEntry(N.id,S)}let M=V.roster().filter((N)=>!P(N)||typeof N.id!=="string"||U.find((L)=>L.id===N.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((N)=>V.rosterRow(N)),...M],i8(V,R),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await d8(V,R)}},{completeTorn:!1});if(W)return W;if(await J.releaseAll(),H>=1)throw O("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class P3{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,X,J,z){this.rt=$,this.hook=Z,this.onFailure=X,this.firedAtLoad=J,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let X=this.run($,Z);this.inflight.add(X),X.finally(()=>this.inflight.delete(X))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let X=this.rt(),{ctx:J}=X,z=new y0(J.lockDefaults,J.lockEnv),G={writes:0};try{let B=await n(J,z,G,{operation:"pull",rowId:$},async(Q)=>{if(Q.reservation($)!==void 0)return;await Q.completeTorn();let W=Q.row($);if(W?.unbound&&W.enabled&&W.type==="oauth"&&W.credential&&!W.invalid)V0("pull",W);if(!W?.candidate||W.type!=="oauth")return;if(!W.hasEntry)Q.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await Q.commitConfig();let V=Q.row($);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:$,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let H;try{H=await this.hook?.(B)}catch(Q){throw new y({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Q})}await(X.publishQuota??((Q,W,V)=>I2(X,Q,W,V)))($,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},H)}catch(B){this.firedAtLoad.delete($);let H=B1(B,"pull",$,G);if(this.onFailure)try{await this.onFailure($,H)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:H.kind})}finally{await z.releaseAll()}}}var r8=100,m2=128;class C3{rt;timeoutMs;pending=new Map;warned=new Set;wake=new Set;logger;timer;running;closing;closed=!1;stopped=!1;failures=0;constructor($,Z=1000){this.rt=$,this.timeoutMs=Z,this.logger=$.ctx.logger??u("store")}async record($,Z,X){try{this.assertOpen($),M3($,Z);let J=structuredClone({id:$,attribution:Z,observation:X}),{row:z,result:G}=await S0(this.rt,"pull",$);E$($,J.attribution,z),I$(this.rt.ctx,$,this.overlayRow({...z,quota:h0(G.config,$)?.quota}).quota,J.observation),await this.room($),this.assertOpen($);let B=this.pending.get($)??[];if(B.push(J),this.pending.set($,B),B.length>=m2)this.flushNow();else this.schedule(r8)}catch(J){throw B1(J,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<m2)return;let{ctx:Z}=this.rt,X=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),J=performance.now()+X;while(this.queued($)>=m2){this.assertOpen($),this.flushNow();let z=J-performance.now();if(z<=0)throw O("pull",$,"lock-contention",`pool quota queue for ${$} is full (${m2} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(H),this.wake.delete(B),G()},H=setTimeout(B,z);this.wake.add(B)})}}assertOpen($){if(this.closed)throw O("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let X of this.pending.get($.id)??[])try{E$($.id,X.attribution,$),Z={...Z,quota:I$(this.rt.ctx,$.id,Z.quota,X.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;if(this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},$),!this.closed)this.timer.unref?.()}flushNow(){if(this.running)return;clearTimeout(this.timer),this.timer=void 0,this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return;let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((J)=>({...J,timeoutMs:Math.min(J.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},X=new y0(Z.lockDefaults,Z.lockEnv);this.running=(async()=>{try{await n(Z,X,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of $){let{id:H,attribution:Y,observation:Q}=B,W=JSON.stringify([H,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(H),E$(H,Y,z.row(H))}catch(K){if(!(K instanceof y))throw K;if(!this.warned.has(W))this.warned.add(W),this.warn("pool quota publication dropped; account binding changed",{id:H,kind:K.kind});continue}let V=z.entry(H);if(!V)continue;let U;try{U=I$(Z,H,V.quota,Q)}catch(K){let j=`codec:${W}`;if(!this.warned.has(j))this.warned.add(j),this.warn("pool quota publication dropped; the quota codec refused it",{id:H,error:K instanceof Error?K.message:String(K)});continue}z.setEntry(H,{...V,quota:U,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig()},{completeTorn:!1});let J=new Set($);for(let[z,G]of this.pending){let B=G.filter((H)=>!J.has(H));if(B.length)this.pending.set(z,B);else this.pending.delete(z)}this.failures=0}catch(J){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{await X.releaseAll(),this.running=void 0;for(let z of this.wake)z();let J=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):r8;this.schedule(J)}})()}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){clearTimeout(this.timer),this.timer=void 0;let $,Z,X=new Promise((J)=>{Z=()=>{if(!this.pending.size)J()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([X,new Promise((J)=>{$=setTimeout(J,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),clearTimeout(this.timer),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((J,z)=>J+z.length,0)});this.pending.clear();for(let J of this.wake)J()}}}import{randomUUID as rJ}from"node:crypto";function T3($,Z){if(R1("refresh",$,Z?.staged),!Z)throw O("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw O("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw O("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw O("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function o8($){return O("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function t8($,Z,X,J={}){B0("refresh");let{ctx:z}=$;return H0(z,"refresh",Z,J.onFailure,async(G,B)=>{let{row:H}=await S0($,"refresh",Z);T3(Z,H);let Y=await J.refuse?.(H);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let Q=d(H),W;for(let j=0;;j++){await G.acquire(F0($,{id:Z,identity:Q===Z?void 0:Q})),await G.acquire(J.providerLock??$.providerLock);for(let F of J.extraLocks??[])await G.acquire(F);let D=await n(z,G,{writes:0},{operation:"refresh",rowId:Z},async(F)=>{let _=T3(Z,F.row(Z));if(V0("refresh",_),!_.hasEntry)F.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await F.commitConfig(),_=T3(Z,F.row(Z));if(d(_)!==Q)return{keyNow:d(_)};let R=await J.refuse?.(_);if(R!==void 0)return{refused:R};return{row:_,credential:_.credential,credentialEpoch:_.credentialEpoch,identity:_.identity}});if("refused"in D)return{status:"refused",rowId:Z,reason:D.refused};if("keyNow"in D){if(await G.releaseAll(),j>=1)throw O("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Q=D.keyNow;continue}W=D;break}if(K3(W.credential.lastRefreshedAt,z.now()))throw o8(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await X(W.credential,W.row)}catch(j){throw new y({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:j})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw O("refresh",Z,"provider","the provider returned no refresh token",!0);let U=V.providerState===void 0?void 0:i0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),K=await n(z,G,B,{operation:"refresh",rowId:Z},async(j)=>{let q=j.row(Z),D=j.entry(Z);if(!q||q.invalid||!D||D.credentialEpoch!==W.credentialEpoch||q.identity!==W.identity)throw new y({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${Z} changed credential while its refresh was in flight; the rotation is discarded`});V0("refresh",q);let F=await J.refuse?.(q);if(F!==void 0)return{refused:F};let _=z.now(),R=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(K3(R,_))throw o8(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},N=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,L=N?{mark:rJ(),enabled:!1,reason:`${r1}${JSON.stringify(N)}`}:void 0,S=q.identity===void 0&&V.identity?V.identity:void 0,T=await y2($,j,Z,M,{stamp:S$(R,_),transition:L,identity:S,...U!==void 0?{providerState:b$(z.providerState,"refresh",Z,q.providerState,U)}:{}});if(L!==void 0)R$(j,Z,L),await j.commitConfig();let b=q.identity;if(S!==void 0)S1(j,Z,S),b=S,await j.commitConfig();return{stored:T,identity:b,contradiction:N,refused:void 0}});if(K.refused!==void 0)return{status:"refused",rowId:Z,reason:K.refused};if(K.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...K.contradiction,credential:K.stored};if(J.onPersisted)try{let j=J.onPersisted;await f0("refresh",()=>j(Z,K.stored))}catch(j){throw new y({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:K.stored,message:"the after-persist hook threw; the rotation stays committed",cause:j})}return{status:"rotated",rowId:Z,credential:K.stored,...K.identity!==void 0?{identity:K.identity}:{}}})}import{isDeepStrictEqual as oJ}from"node:util";var p2=Object.freeze(["version","accounts",p]);function A3($){let Z={};for(let[X,J]of Object.entries($))if(!p2.includes(X))w2(Z,X,J);return Z}function w2($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function tJ($,Z){let X={};for(let[J,z]of Object.entries($))if(p2.includes(J))w2(X,J,z);else if(Object.hasOwn(Z,J))w2(X,J,Z[J]);for(let[J,z]of Object.entries(Z))if(!Object.hasOwn($,J))w2(X,J,z);return X}function e8($){return new y({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function $9($){let Z=await W0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:A3(Z.config)}}async function Z9($,Z,X={}){B0("updateSettings");let{ctx:J}=$,z=X.onFailure;return H0(J,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of X.extraLocks??[])await G.acquire(Y);let H=G.held.length;try{for(let D of J.storeLocks)await G.acquire(D);let Y=await W0(J);if(Y.status!=="ready")throw A0(Y,"updateSettings",void 0);let Q=A3(Y.config),W=structuredClone(Q),V=await f0("updateSettings",()=>Z(W)),U=V===void 0?W:V;if(!P(U))throw e8("the settings mutator must produce an object");let K=p2.filter((D)=>Object.hasOwn(U,D));if(K.length>0)throw e8(`settings cannot set the pool-owned key(s) ${K.join(", ")}`);if(oJ(U,Q))return{settings:Q,outcome:"unchanged"};let j=tJ(Y.config,U),q={operation:"updateSettings",rowId:void 0};return await _0(J.configPath,j,{beforeRename:async()=>{await J.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await J.onStep?.("after-config-write",q),{settings:A3(j),outcome:"updated"}}finally{await G.releaseTo(H)}})}var X9=new Map;function eJ($){let Z=X9.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},X9.set($,Z);return Z}function J9($){if($.status==="ready")return{status:"ready",schemaVersion:J1,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function S3($){let Z=eJ($.configPath),X={...Q3,...$.lockOptions},J={provider:$.provider,configPath:$.configPath,statePath:$.statePath,codec:$.quota,...$.providerState?{providerState:$.providerState}:{},now:$.now??Date.now,storeLocks:$.storeLocks??[{name:"save",path:$.configPath},{name:"save",path:$.statePath}],lockDefaults:X,lockEnv:{...$.onLockEvent?{onLockEvent:$.onLockEvent}:{},...$.onLockStep?{onLockStep:$.onLockStep}:{},...$.onRenewalTimer?{onRenewalTimer:$.onRenewalTimer}:{}},removedIds:Z.removedIds,requireCredentialStamps:$.requireCredentialStamps===!0,requireRemovedFingerprint:$.requireRemovedFingerprint===!0,...$.logger?{logger:$.logger}:{},...$.onStep?{onStep:$.onStep}:{},...$.hold?{hold:$.hold}:{}},z=new P3(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Q,W)=>z.fire(Q,W)},B=$.coalesceQuota?new C3(G,$.quotaDrainTimeoutMs):void 0,H=(Q,W,V)=>B?B.record(Q,W,V):I2(G,Q,W,V);G.publishQuota=H;let Y=(Q)=>{if(Q.status==="ready"&&B)return{...Q,rows:B.overlay(Q.rows)};return Q};return{async load(){let Q=Y(await W0(J));if(Q.status==="ready"){for(let W of Q.rows)if((W.candidate||W.torn&&W.enabled)&&W.type==="oauth"&&W.needsFirstReading)z.fire(W.id,"load")}return J9(Q)},async read(){return J9(Y(await W0(J)))},async initialize(Q={}){return{status:await R8(J,Q.dropKeys??[])}},add:(Q,W)=>y8(G,Q,W),publishRoster:(Q,W)=>n8(G,Q,W),publication:(Q)=>a8(G,Q),replace:(Q,W,V,U)=>g8(G,Q,W,V,U),rotate:(Q,W,V,U)=>h8(G,Q,W,V,U),updateProviderState:(Q,W,V,U)=>b8(G,Q,W,V,U),disable:(Q,W,V)=>m8(G,Q,W,V),enable:(Q,W)=>w8(G,Q,W),remove:(Q,W)=>p8(G,Q,W),reorder:(Q,W)=>l8(G,Q,W),readSettings:()=>$9(G),updateSettings:(Q,W)=>Z9(G,Q,W),recordIdentity:(Q,W,V,U)=>u8(G,Q,W,V,U),refresh:(Q,W,V)=>t8(G,Q,W,V),recordQuota:H,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(Q)=>z.fire(Q,"admission"),pullsSettled:()=>z.settled()}}var $z=[/\b[\w-]*(?:secret|token|password|passwd|api[_-]?key|authorization|verifier)["']?\s*[:=]\s*["']?(?:(?:Bearer|Basic)\s+)?[^\s"'&,;}]+/gi,/\b[0-9a-fA-F]{32,}\b/g];function I3($={}){let{redactStrings:Z}=k0({...$,extraValuePatterns:[...$z,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class o extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var z9=/^[a-z][a-z0-9-]{0,63}$/,R3={code:"action-failed",text:"That action failed."},Zz=new Set(["unknown-row","invalid-row","invalid-input","id-exists","id-removed","type-mismatch","no-credential","row-disabled","row-protected","duplicate-identity","row-key-changed","invalid-order","pending-migration","provider","pull","attribution"]);function k$($){if($ instanceof o)return{code:z9.test($.code)?$.code:R3.code,text:$.message};if($ instanceof y)return{code:`pool-${$.kind}`,text:Zz.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return R3}var G9="This cannot be undone. Continue?",Xz=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function Jz($){let Z=$.toLowerCase().replace(/[-_]/g,"");return Xz.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function zz($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function E3($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>E3(z,`${Z}[${G}]`,X));if(!zz($))return $;let J={};for(let[z,G]of Object.entries($)){if(Jz(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:E3(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function B9($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=E3($,"payload",J);if(J.dropped.length>0)X.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:J.dropped});if(J.redacted.length>0)X.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:J.redacted});return z}function Gz($){return{value:String($.value),label:String($.label)}}function Bz($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(Gz),...$.value!==void 0?{value:$.value}:{}};case"toggle":return{kind:"toggle",id:$.id,label:$.label,value:$.value===!0};case"number":return{kind:"number",id:$.id,label:$.label,...$.value!==void 0?{value:$.value}:{},...$.min!==void 0?{min:$.min}:{},...$.max!==void 0?{max:$.max}:{},...$.required?{required:!0}:{}};case"text":return{kind:"text",id:$.id,label:$.label,...$.value!==void 0&&!$.masked?{value:$.value}:{},...$.placeholder!==void 0?{placeholder:$.placeholder}:{},...$.masked?{masked:!0}:{},...$.required?{required:!0}:{}}}}function b3($){if($.irreversible===!0)return{message:$.confirm||G9,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function H9($){let Z=b3($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(Bz),...Z?{confirm:Z}:{}}}function Hz($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function Yz($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:Hz($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(H9)}}function Qz($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(Yz),actions:(Z.actions??[]).map(H9),...Z.facts!==void 0?{facts:Z.facts}:{}}}function Y9($,Z,X){return{command:$,title:Z,sections:X.map(Qz)}}function Q9($,Z,X,J){return B9({command:$,menu:Y9($,Z,X)},$,J)}function W9($,Z,X,J,z){return B9({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:z9.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:Y9($,Z,X)},$,z)}var j9="disabled from the command menu";function Wz($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function n0($){return Wz($)?{...$}:{}}function Vz($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((X)=>{if(Z.has(X.id))return!1;return Z.add(X.id),!0})}function Uz($,Z){return $.label??Z??$.id}function l2($,Z){return X0($.quota)?s($.quota,Z):void 0}function K9($,Z){return`${$} ${Z}${$===1?"":"s"}`}var f$="Actions";function jz($){if($.status==="pending-migration")return"The account pool has not been migrated yet.";if($.status==="error")return`The ${$.file} file cannot be read: ${$.reason}`;return}function V9($,Z){switch(Z.outcome){case"added":return`Added ${$}.`;case"added-disabled":return`Added ${$}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${$}.`;case"rotated":return`${$} was already in the pool; its credential was updated.`;case"exists":return`${$} was already in the pool; its credential is unchanged.`}}function U9($){return k$($).text}async function Kz($){let{store:Z}=$,X=await Z.read(),J=await Z.readSettings(),z=await $.routing?.vaultOrder?.();return{load:X,rows:Vz(X),settings:J.status==="error"?{}:J.settings,...z?{vault:z}:{}}}function u2($,Z){let X=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...X!==void 0?{identity:X}:{}},name:Uz($,X)}}function Dz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((V)=>V.id),B=jz(Z.load),H=Z.rows.filter((V)=>V.enabled).length,Y=Z.rows.map((V,U)=>{let{account:K,name:j}=u2(V,$),q=[V.type==="api"?"API key":"OAuth",...K.identity!==void 0?[K.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),D=V.invalid?"invalid":V.enabled?"enabled":"disabled",F=[];if(!V.invalid&&V.enabled)F.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,j9,z),`Disabled ${j}.`}});if(!V.invalid&&!V.enabled)F.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${j}.`}});if(G.length>1)F.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((_,R)=>({value:String(R+1),label:String(R+1)})),value:String(U+1)}],run:async({values:_})=>{let R=Number(_.position),M=G.filter((L)=>L!==V.id);return M.splice(R-1,0,V.id),(await X.reorder(M,z)).outcome==="unchanged"?`${j} is already at position ${R}.`:`Moved ${j} to position ${R}.`}});return F.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${j}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${j}.`}}),{id:V.id,label:j,detail:q,group:"Accounts",status:D,account:K,actions:F}}),Q=$.accounts?.login,W=[];if(Q&&!B)W.push({id:"add",label:Q.label??"Add account",group:f$,knobs:Q.knobs??[],run:async({values:V,invocation:U})=>{let K=await Q.run(V,U);if(K.status==="cancelled")return{ok:!1,text:K.message??"Login cancelled."};if(K.status==="ready"){let j=await X.add(K.account,z);return V9(K.account.label??j.id,j)}return K.completion.then(async(j)=>{if(!j){U.notify("Login cancelled.","warning");return}let q=await X.add(j,z);U.notify(V9(j.label??q.id,q))},(j)=>{U.notify(`Adding the account failed: ${U9(j)}`,"error")}).catch((j)=>{U.notify(`Adding the account failed: ${U9(j)}`,"error")}),K.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${K9(Z.rows.length,"account")}, ${H} enabled`],items:B?[]:Y,actions:W}}}function Nz($,Z){let X=$.quota?.scope??"all",J=$.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(W,V)=>{if($.quota?.check)await $.quota.check(W,V);else{for(let U of W)$.store.requestReading(U);await $.store.pullsSettled()}},B=Z.rows.filter((W)=>W.candidate),H=B.map((W)=>{let{account:V,name:U}=u2(W,$),K=l2(W,X);return{id:W.id,label:U,group:z,status:C0(K,{now:J,form:"compact"}),detail:C0(K,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:j})=>{return await G([W.id],j),`Checked quota for ${U}.`}}]}}),Y=Z.rows.filter((W)=>!W.candidate).map((W)=>{let{name:V}=u2(W,$),U=W.invalid?"invalid":!W.enabled?"disabled":W.credential===void 0?"no credential":"unavailable",K=C0(l2(W,X),{now:J,form:"compact"});return`${V} (${U}): ${K}`}),Q=[];if(B.length>0)Q.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:f$,run:async({invocation:W})=>{let V=B.map((U)=>U.id);return await G(V,W),`Checked quota for ${K9(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:H,actions:Q}}}async function qz($,Z){try{return await $.reorder(Z)}catch(X){if(X instanceof Error&&X.name==="ClaustrumConsumerError"&&X.kind==="invalid-order")throw new o("vault-invalid-order",X.message,{cause:X});throw X}}function x3($){return new o("vault-invalid-order",$)}function Fz($){let Z=$.rows.map((J)=>({id:J.id,label:J.label.trim()||J.id})),X=(J)=>Z.filter((z)=>z.id===J||z.label===J);return{ids:Z.map((J)=>J.id),nameOf:(J)=>Z.find((z)=>z.id===J)?.label??J,entryOf:(J)=>{let z=Z.find((G)=>G.id===J);return z&&!/[,\n]/.test(z.label)&&X(z.label).length===1?z.label:J},resolve:(J)=>{let z=[];for(let G of J){let B=X(G);if(B.length===0)throw x3(`"${G}" is not a vault account.`);if(B.length>1)throw x3(`"${G}" matches more than one vault account; enter those accounts by route id.`);let H=B[0].id;if(z.includes(H))throw x3(`"${G}" names an account already in the order.`);z.push(H)}return z}}}function Mz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=n0(Z.settings.routing).mode,H=typeof B==="string"&&G.some((D)=>D.value===B)?B:"ordered",Y=l6(H),Q=Z.vault?Fz(Z.vault):void 0,W=Q?Q.ids:Z.rows.map((D)=>D.id),V=(D)=>Q?Q.nameOf(D):D,U=s1(W,Y.placement,$.routing?.formerMainId??F2),j=[`Mode: ${G.find((D)=>D.value===H)?.label??H}`];if(W.length>0)j.push(`${Q?"Vault account order":"Roster order"}: ${W.map(V).join(", ")}`);if(Y.mode==="ordered"&&U.join()!==W.join())j.push(`Tried in order: ${U.map(V).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:f$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:H}],run:async({values:D})=>{let F=String(D.mode);return await X.updateSettings((_)=>{_.routing={...n0(_.routing),mode:F};return},z),`Routing mode set to ${G.find((_)=>_.value===F)?.label??F}.`}}];if(W.length>1)q.push({id:"order",label:"Set order",group:f$,knobs:[{kind:"text",id:"order",label:Q?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:Q?W.map(Q.entryOf).join(", "):W.join(", "),required:!0}],run:async({values:D})=>{let _=String(D.order).split(Q?/[,\n]+/:/[\s,]+/).map((M)=>M.trim()).filter((M)=>M.length>0),R=Z.vault&&Q?await qz(Z.vault,Q.resolve(_)):await X.reorder(_,z);return R.outcome==="unchanged"?"The order is unchanged.":`Order set to ${R.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:q}}}function Lz($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let z of Z.rows)for(let G of l2(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function _z($,Z){let X=$.quota?.scope??"all",J=new Map;for(let z of Z.rows)for(let G of l2(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,N2(G));return(z)=>J.get(z)??z}function Oz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=n0(Z.settings.killswitch),B=G.enabled===!0,H=n0(G.accounts),Y=Lz($,Z),Q=_z($,Z),W=B?"on":"off",V=Z.rows.map((U)=>{let{account:K,name:j}=u2(U,$),q=n0(H[U.id]),D=Y.filter((F)=>typeof q[F]==="number");return{id:U.id,label:j,group:`Floors · killswitch ${W}`,status:D.length===0?"no floors":D.map((F)=>`${Q(F)} ≥${q[F]}%`).join(" · "),account:K,actions:[{id:"floors",label:"Set floors",knobs:Y.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${Q(F)}`,min:0,max:100,...typeof q[F]==="number"?{value:q[F]}:{}})),run:async({values:F})=>{return await X.updateSettings((_)=>{let R=n0(_.killswitch),M=n0(R.accounts),N=n0(M[U.id]);for(let L of Y){let S=F[L];if(typeof S==="number")N[L]=S;else if(S===null)delete N[L]}if(Object.keys(N).length>0)M[U.id]=N;else delete M[U.id];if(Object.keys(M).length>0)R.accounts=M;else delete R.accounts;_.killswitch=R;return},z),`Floors updated for ${j}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${W}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:f$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:U})=>{let K=U.enabled===!0;return await X.updateSettings((j)=>{j.killswitch={...n0(j.killswitch),enabled:K};return},z),`Killswitch ${K?"on":"off"}.`}}]}}}async function D9($){let Z=await Kz($);return[Dz($,Z),Nz($,Z),Mz($,Z),Oz($,Z)]}var Pz=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),k3=["accounts","quota","routing","limits"];function N9($,Z){let{sessionId:X}=$,J=$.notify.bind($);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(z,G)=>G===void 0?J(Z(String(z))):J(Z(String(z)),G)})}function Cz($,Z){switch($.kind){case"choice":{let X=Z??$.value;if(typeof X==="string"&&$.choices.some((J)=>J.value===X))return{value:X};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let X=Z??$.value;return typeof X==="boolean"?{value:X}:{problem:`${$.label} must be on or off.`}}case"number":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let J=typeof X==="number"?X:Number(X);if(typeof X==="boolean"||!Number.isFinite(J))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&J<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&J>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:J}}case"text":{let X=Z===void 0?$.value??null:Z;if(X===null||X==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof X==="string"?{value:X}:{problem:`${$.label} must be text.`}}}}function Tz($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=Cz(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function Az($,Z){let X=$.find((z)=>z.id===Z.sectionId);if(!X)return;return(Z.itemId===void 0?X.content.actions:X.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function I1($){let Z=$.logger??u("commands"),X=I3($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],B=$.replace??{},H=k3.filter((U)=>!B[U]);for(let U of k3)if(B[U]&&$[U]!==void 0)throw Error(`the ${U} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(H.length>0&&!Y)throw Error(`a store is required for the built-in ${H.join(", ")} section${H.length>1?"s":""}`);let Q=new Set;for(let U of G){if(Pz.has(U.id)||Q.has(U.id))throw Error(`extra section id ${U.id} is taken`);Q.add(U.id)}async function W(U,K,j,q){try{return{id:U,slot:K,title:j.title,content:await j.build(q)}}catch(D){return Z.warn("command menu section failed to build",{command:$.command,section:U,error:X(D instanceof Error?D.message:String(D))}),{id:U,slot:K,title:j.title,content:{lines:["This section could not be loaded."]}}}}async function V(U){let K=Y&&H.length>0?await D9({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],j=[];for(let q of k3){let D=B[q];if(D)j.push(await W(q,q,D,U));else{let F=K.find((_)=>_.slot===q);if(F)j.push(F)}}if($.cache)j.push(await W("cache","cache",$.cache,U));if($.diagnostics)j.push(await W("diagnostics","diagnostics",$.diagnostics,U));for(let q of G)j.push(await W(q.id,"extra",q,U));return j}return{command:$.command,async open(U){let K=N9(U,X);return Q9($.command,$.title,await V(K),J)},async apply(U,K){let j=N9(K,X),q=async(M)=>W9($.command,$.title,await V(j),M,J),D=U.command===$.command?Az(await V(j),U):void 0;if(!D)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let F=b3(D);if(F&&U.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:F.message,needsConfirmation:!0});let _=Tz(D.knobs??[],U.values);if("problem"in _)return q({ok:!1,code:"invalid-input",text:_.problem});let R;try{let M=await D.run({values:_.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:j});R=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let N=k$(M);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:N.code,error:X(M instanceof Error?M.message:String(M))}),R={ok:!1,...N}}return q(R)}}}async function y$($,Z,X){let J=new Map,z=[];for(let B of X){let H=B.label;for(let Y=2;J.has(H);Y++)H=`${B.label} (${Y})`;J.set(H,B.value),z.push(H)}let G=await $.select(Z,z);return G===void 0?void 0:J.get(G)}function q9($,Z){return Z.length>0?`${$}
9
9
  ${Z.join(`
10
- `)}`:$}function p2($){return $.status?`${$.label} · ${$.status}`:$.label}function _z($){let Z=[...$.lines],X;for(let J of $.items){if(J.actions.length>0)continue;if(J.group!==void 0&&J.group!==X)Z.push(J.group);X=J.group,Z.push(J.group!==void 0?` ${p2(J)}`:p2(J))}return Z}function Lz($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return V9(p2($),Z)}async function Oz($,Z){switch(Z.kind){case"choice":{let X=await k$($,Z.label,Z.choices.map((J)=>({label:J.value===Z.value?`${J.label} (current)`:J.label,value:J.value})));return X===void 0?void 0:{value:X}}case"toggle":{let X=await k$($,Z.label,[{label:Z.value?"On (current)":"On",value:!0},{label:Z.value?"Off":"Off (current)",value:!1}]);return X===void 0?void 0:{value:X}}case"number":{let X=Z.min!==void 0&&Z.max!==void 0?` (${Z.min}-${Z.max}${Z.required?"":", empty clears"})`:Z.required?"":" (empty clears)",J=await $.input(`${Z.label}${X}`,Z.value!==void 0?String(Z.value):void 0);if(J===void 0)return;let z=J.trim();if(z==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};let G=Number(z);if(!Number.isFinite(G)){$.notify(`${Z.label} needs a number.`,"error");return}return{value:G}}case"text":{let X=await $.input(Z.label,Z.value??Z.placeholder);if(X===void 0)return;let J=X.trim();if(J==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};return{value:J}}}}async function Pz($,Z){let X={};for(let J of Z.knobs){let z=await Oz($,J);if(!z)return;X[J.id]=z.value}return X}async function EZ($,Z,X={}){let J={...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:(G,B)=>Z.notify(G,B)},z=(await $.open(J)).menu;for(;;){let G=await k$(Z,z.title,z.sections.map((B)=>({label:B.lines[0]?`${B.title}: ${B.lines[0]}`:B.title,value:B.id})));if(G===void 0)return;for(;;){let B=z.sections.find((j)=>j.id===G);if(!B)break;let H=[...B.items.filter((j)=>j.actions.length>0).map((j)=>({label:p2(j),value:{kind:"item",item:j}})),...B.actions.map((j)=>({label:j.label,value:{kind:"action",action:j}}))],Y=_z(B);if(H.length===0&&Y.length===0){Z.notify("Nothing to do here.");break}let Q=await k$(Z,V9(B.title,Y),[...H,{label:"Back",value:{kind:"back"}}]);if(!Q||Q.kind==="back")break;let W,V;if(Q.kind==="item"){if(V=Q.item,W=await k$(Z,Lz(V),V.actions.map((j)=>({label:j.label,value:j}))),!W)continue}else W=Q.action;let U=await Pz(Z,W);if(!U)continue;if(W.confirm){if(!await Z.confirm(W.label,W.confirm.message)){Z.notify("Cancelled.");continue}}let K=await $.apply({command:z.command,sectionId:B.id,...V?{itemId:V.id}:{},actionId:W.id,values:U,...W.confirm?{confirmed:!0}:{},...X.sessionId!==void 0?{sessionId:X.sessionId}:{}},J);Z.notify(K.text,K.ok?"info":"error"),z=K.menu}}}import{createHash as eG,randomUUID as $B}from"node:crypto";import{setTimeout as ZB}from"node:timers/promises";var Cz=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{createHash as Tz}from"node:crypto";var Sz=86400000,Az=300000,Rz=3600000,Ez=60000,Iz=900000,bz=300000;function IZ($){return $ instanceof Error?$.message:String($)}function bZ($){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 xZ($){let Z=IZ($),X=$?.status;if(typeof X==="number")return X===429||X>=500;if(!($ instanceof Error))return!1;let J=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||J==="ECONNRESET"||J==="ECONNREFUSED"||J==="ETIMEDOUT"||J==="UND_ERR_CONNECT_TIMEOUT"}function z$($){return Tz("sha256").update($).digest("hex")}function u2($){let Z=z$($.refreshToken),J=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,z,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)z=G*1000;else if(bZ($.error))z=Math.min(Rz,Az*2**Math.min(J-1,6));else z=Sz;return{message:IZ($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:J,tokenHash:Z}}function B1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===z$(Z)}function f$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function y$($){let X=($.previous?.retryCount??0)+1,J,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(xZ($.error))J=Math.min(Iz,Ez*2**Math.min(X-1,6));else J=bz;return{message:IZ($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function G$($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function kZ($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let X=Date.parse($);if(Number.isFinite(X)){let J=Math.ceil((X-Date.now())/1000);return J>0?J:void 0}return}function xz($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var U9=x0({extraSecretKeys:xz}),MU=U9.redact,j9=U9.redactStrings;import{createServer as K9}from"node:http";import{setTimeout as kz}from"node:timers/promises";var c2="app_EMoamEEZ73f0CkXaXp7hrann",x1="https://auth.openai.com",h$=1455,fz=3000,yz="cortexkit-opencode-openai-auth";function q9($){return`${yz}/${$}`}var N9="main",gz=`"${N9}" is a reserved account id; choose a different label.`;function F9($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function hz(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=F9(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function B$($){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 H$($){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 J=$.organizations;if(Array.isArray(J)){let z=J[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function v$($){if($.id_token){let Z=B$($.id_token),X=Z&&H$(Z);if(X)return X}if($.access_token){let Z=B$($.access_token);return Z?H$(Z):void 0}return}function vz($){return typeof $==="string"&&$.toLowerCase()===N9}function fZ($){if(vz($))throw Error(gz);return $}function mz($,Z,X){let J=new URLSearchParams({response_type:"code",client_id:c2,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`${x1}/oauth/authorize?${J.toString()}`}async function wz($,Z,X){let J=await fetch(`${x1}/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:c2,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function pz($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var uz=`<!doctype html>
10
+ `)}`:$}function d2($){return $.status?`${$.label} · ${$.status}`:$.label}function Sz($){let Z=[...$.lines],X;for(let J of $.items){if(J.actions.length>0)continue;if(J.group!==void 0&&J.group!==X)Z.push(J.group);X=J.group,Z.push(J.group!==void 0?` ${d2(J)}`:d2(J))}return Z}function Rz($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return q9(d2($),Z)}async function Ez($,Z){switch(Z.kind){case"choice":{let X=await y$($,Z.label,Z.choices.map((J)=>({label:J.value===Z.value?`${J.label} (current)`:J.label,value:J.value})));return X===void 0?void 0:{value:X}}case"toggle":{let X=await y$($,Z.label,[{label:Z.value?"On (current)":"On",value:!0},{label:Z.value?"Off":"Off (current)",value:!1}]);return X===void 0?void 0:{value:X}}case"number":{let X=Z.min!==void 0&&Z.max!==void 0?` (${Z.min}-${Z.max}${Z.required?"":", empty clears"})`:Z.required?"":" (empty clears)",J=await $.input(`${Z.label}${X}`,Z.value!==void 0?String(Z.value):void 0);if(J===void 0)return;let z=J.trim();if(z==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};let G=Number(z);if(!Number.isFinite(G)){$.notify(`${Z.label} needs a number.`,"error");return}return{value:G}}case"text":{let X=await $.input(Z.label,Z.value??Z.placeholder);if(X===void 0)return;let J=X.trim();if(J==="")return Z.required&&Z.value!==void 0?{value:Z.value}:{value:null};return{value:J}}}}async function Iz($,Z){let X={};for(let J of Z.knobs){let z=await Ez($,J);if(!z)return;X[J.id]=z.value}return X}async function f3($,Z,X={}){let J={...X.sessionId!==void 0?{sessionId:X.sessionId}:{},notify:(G,B)=>Z.notify(G,B)},z=(await $.open(J)).menu;for(;;){let G=await y$(Z,z.title,z.sections.map((B)=>({label:B.lines[0]?`${B.title}: ${B.lines[0]}`:B.title,value:B.id})));if(G===void 0)return;for(;;){let B=z.sections.find((j)=>j.id===G);if(!B)break;let H=[...B.items.filter((j)=>j.actions.length>0).map((j)=>({label:d2(j),value:{kind:"item",item:j}})),...B.actions.map((j)=>({label:j.label,value:{kind:"action",action:j}}))],Y=Sz(B);if(H.length===0&&Y.length===0){Z.notify("Nothing to do here.");break}let Q=await y$(Z,q9(B.title,Y),[...H,{label:"Back",value:{kind:"back"}}]);if(!Q||Q.kind==="back")break;let W,V;if(Q.kind==="item"){if(V=Q.item,W=await y$(Z,Rz(V),V.actions.map((j)=>({label:j.label,value:j}))),!W)continue}else W=Q.action;let U=await Iz(Z,W);if(!U)continue;if(W.confirm){if(!await Z.confirm(W.label,W.confirm.message)){Z.notify("Cancelled.");continue}}let K=await $.apply({command:z.command,sectionId:B.id,...V?{itemId:V.id}:{},actionId:W.id,values:U,...W.confirm?{confirmed:!0}:{},...X.sessionId!==void 0?{sessionId:X.sessionId}:{}},J);Z.notify(K.text,K.ok?"info":"error"),z=K.menu}}}import{createHash as BB,randomUUID as HB}from"node:crypto";import{setTimeout as YB}from"node:timers/promises";var bz=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{createHash as xz}from"node:crypto";var kz=86400000,fz=300000,yz=3600000,gz=60000,hz=900000,vz=300000;function y3($){return $ instanceof Error?$.message:String($)}function g3($){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 h3($){let Z=y3($),X=$?.status;if(typeof X==="number")return X===429||X>=500;if(!($ instanceof Error))return!1;let J=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||J==="ECONNRESET"||J==="ECONNREFUSED"||J==="ETIMEDOUT"||J==="UND_ERR_CONNECT_TIMEOUT"}function z$($){return xz("sha256").update($).digest("hex")}function c2($){let Z=z$($.refreshToken),J=($.previous?.tokenHash===Z?$.previous.retryCount??0:0)+1,z,G=$.error?.retryAfter;if(typeof G==="number"&&G>0)z=G*1000;else if(g3($.error))z=Math.min(yz,fz*2**Math.min(J-1,6));else z=kz;return{message:y3($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:J,tokenHash:Z}}function H1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===z$(Z)}function g$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function h$($){let X=($.previous?.retryCount??0)+1,J,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(h3($.error))J=Math.min(hz,gz*2**Math.min(X-1,6));else J=vz;return{message:y3($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function G$($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function v3($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let X=Date.parse($);if(Number.isFinite(X)){let J=Math.ceil((X-Date.now())/1000);return J>0?J:void 0}return}function mz($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var F9=k0({extraSecretKeys:mz}),yU=F9.redact,M9=F9.redactStrings;import{createServer as L9}from"node:http";import{setTimeout as wz}from"node:timers/promises";var i2="app_EMoamEEZ73f0CkXaXp7hrann",k1="https://auth.openai.com",m$=1455,pz=3000,lz="cortexkit-opencode-openai-auth";function O9($){return`${lz}/${$}`}var P9="main",uz=`"${P9}" is a reserved account id; choose a different label.`;function C9($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function dz(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=C9(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function B$($){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 H$($){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 J=$.organizations;if(Array.isArray(J)){let z=J[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function w$($){if($.id_token){let Z=B$($.id_token),X=Z&&H$(Z);if(X)return X}if($.access_token){let Z=B$($.access_token);return Z?H$(Z):void 0}return}function cz($){return typeof $==="string"&&$.toLowerCase()===P9}function m3($){if(cz($))throw Error(uz);return $}function sz($,Z,X){let J=new URLSearchParams({response_type:"code",client_id:i2,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`${k1}/oauth/authorize?${J.toString()}`}async function az($,Z,X){let J=await fetch(`${k1}/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:i2,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function iz($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var nz=`<!doctype html>
11
11
  <html>
12
12
  <head>
13
13
  <title>CortexKit OpenAI Auth - Authorization Successful</title>
@@ -47,7 +47,7 @@ ${Z.join(`
47
47
  setTimeout(() => window.close(), 2000)
48
48
  </script>
49
49
  </body>
50
- </html>`,l2=($)=>`<!doctype html>
50
+ </html>`,s2=($)=>`<!doctype html>
51
51
  <html>
52
52
  <head>
53
53
  <title>CortexKit OpenAI Auth - Authorization Failed</title>
@@ -90,13 +90,13 @@ ${Z.join(`
90
90
  <div class="container">
91
91
  <h1>Authorization Failed</h1>
92
92
  <p>An error occurred during authorization.</p>
93
- <div class="error">${pz($)}</div>
93
+ <div class="error">${iz($)}</div>
94
94
  </div>
95
95
  </body>
96
- </html>`,d2=[],g$,i0=new Map;function D9($,Z){return new Promise((X,J)=>{let z=(B)=>{$.off("listening",G),J(B)},G=()=>{$.off("error",z),X()};$.once("error",z),$.once("listening",G),$.listen(h$,Z)})}function M9($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function I1(){return i0.size}function k1($){if(i0.delete($),I1()===0)b1()}async function lz(){let $=`http://localhost:${h$}/auth/callback`;if(d2.length>0)return{port:h$,redirectUri:$};if(g$)return g$;g$=(async()=>{let Z=(G,B)=>{let H=new URL(G.url||"/",`http://127.0.0.1:${h$}`);if(H.pathname==="/auth/callback"){let Y=H.searchParams.get("code"),Q=H.searchParams.get("state"),W=H.searchParams.get("error"),V=H.searchParams.get("error_description");if(W){let K=V||W;if(Q){let j=i0.get(Q);if(j)j.reject(Error(K)),k1(Q);else if(I1()===0)b1()}else if(I1()===0)b1();B.writeHead(200,{"Content-Type":"text/html"}),B.end(l2(K));return}if(!Q){if(I1()===0)b1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Missing state parameter"));return}if(!Y){if(I1()===0)b1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Missing authorization code"));return}let U=i0.get(Q);if(!U){if(I1()===0)b1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Unknown state — authorization may have expired"));return}k1(Q),wz(Y,$,U.pkce).then((K)=>U.resolve(K)).catch((K)=>U.reject(K)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(uz);return}if(H.pathname==="/cancel"){let Y=H.searchParams.get("state"),Q=Y?[Y]:[...i0.keys()];B.writeHead(200),B.end("Login cancelled");for(let W of Q){let V=i0.get(W);if(!V)continue;V.reject(Error("Login cancelled")),k1(W)}if(I1()===0)b1();return}B.writeHead(404),B.end("Not found")},X=K9(Z);await D9(X,"127.0.0.1");let J=[X],z=K9(Z);try{await D9(z,"::1"),J.push(z)}catch(G){let B=G.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw M9(X),G}return d2=J,{port:h$,redirectUri:$}})();try{return await g$}finally{g$=void 0}}function b1(){let $=d2;d2=[];for(let Z of $)M9(Z)}function dz($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){k1(Z),G(Error("Login cancelled"));return}let B=setTimeout(()=>{if(i0.get(Z))k1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),H=()=>{if(clearTimeout(B),i0.get(Z))k1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",H);i0.set(Z,{pkce:$,state:Z,resolve:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",H);z(Y)},reject:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",H);G(Y)}})})}async function cz($){let Z=await fetch(`${x1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":q9($)},body:JSON.stringify({client_id:c2})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${x1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function sz($,Z,X){let J=Math.max(parseInt($.interval,10)||5,1)*1000,z=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(z)&&z>0?z*1000:900000,B=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>G)throw Error("Device authorization expired");let H=await fetch(`${x1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":q9(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(H.ok){let W=await H.json(),V=await fetch(`${x1}/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:`${x1}/deviceauth/callback`,client_id:c2,code_verifier:W.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(H.status!==403&&H.status!==404)throw Error(`Device authorization failed: ${H.status}`);let Y=G-(Date.now()-B);if(Y<=0)throw Error("Device authorization expired");let Q=Math.min(J+fz,Y);try{await kz(Q,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function _9($){let{label:Z,headless:X=!1,signal:J,version:z}=$;if(fZ(Z),X){let{deviceData:W,url:V,instructions:U}=await cz(z),K=(async()=>{let j=await sz(W,z,J),N=Date.now(),D=v$(j);return{id:fZ(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:N+(j.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:D}})();return{url:V,instructions:U,completion:K}}let{redirectUri:G}=await lz(),B=await hz(),H=F9(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=mz(G,B,H),Q=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let W=await dz(B,H,void 0,J),V=Date.now(),U=v$(W);return{id:fZ(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:V+(W.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:U}}finally{k1(H)}})();return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}import{basename as az,dirname as iz,join as nz}from"node:path";var s2="openai-auth.json",L9="openai-auth-state.json";function yZ($){return az($)===s2?nz(iz($),L9):`${$}.state.json`}function a2($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let J=Z<100000000000?Z*1000:Z,z=new Date(J);return Number.isNaN(z.getTime())?void 0:z.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function gZ($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function O9($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function P9($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let J=Number(X);if(!Number.isFinite(J)||J<0||J>100)return;let z=Z.slice(0,-13),G=gZ($.get(`${z}-window-minutes`)),B=a2($.get(`${z}-reset-at`)??void 0);if(J===0&&$.get(`${z}-window-minutes`)==="0"&&!B)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:B,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var A9=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function R9($,Z){let X=$.get(Z);if(X===null)return"absent";if(X.trim()==="")return"invalid";let J=Number(X);return Number.isFinite(J)&&J>=0&&J<=100?"valid":"invalid"}function E9($){if(A9.some((G)=>R9($,G)==="invalid"))return{};let Z={},X=P9($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=P9($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;let z=rz($);if(z)Z.credits=z;return Z}function C9($,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 rz($){let Z=C9($,"x-codex-credits-has-credits"),X=C9($,"x-codex-credits-unlimited");if(Z===void 0||X===void 0)return;let J=H1($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:X,...J!==void 0?{balance:J}:{},checkedAt:Date.now()}}function I9($){let Z=A9.map((X)=>R9($,X));return Z.includes("valid")&&!Z.includes("invalid")}function T9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=gZ($.window_minutes),X=a2($.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 b9($){let Z={},X=T9($.rate_limits?.primary);if(X)Z.primary=X;let J=T9($.rate_limits?.secondary);if(J)Z.secondary=J;let z=oz($.credits);if(z)Z.credits=z;return Z}function oz($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let X=H1(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 H1($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function S9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=gZ($.limit_window_seconds),X=a2($.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 x9($){let Z={},X=S9($.rate_limit?.primary_window);if(X)Z.primary=X;let J=S9($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=O9($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=O9($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let B=$.spend_control?.individual_limit;if($.spend_control===null||B===null)Z.spendControlCleared=!0;if(B&&typeof $.spend_control?.reached==="boolean"){let Y=H1(B.limit),Q=H1(B.used),W=H1(B.remaining),V=H1(B.used_percent),U=H1(B.remaining_percent);if(Y!==void 0&&Q!==void 0&&W!==void 0&&V!==void 0&&U!==void 0)Z.spendControl={limit:Y,used:Q,remaining:W,usedPercent:V,remainingPercent:U,resetsAt:a2(B.reset_at),unit:B.unit,source:B.source,reached:$.spend_control.reached}}let H=$.credits;if(H&&typeof H.has_credits==="boolean"&&typeof H.unlimited==="boolean"&&typeof H.overage_limit_reached==="boolean"){let Y=H1(H.balance);Z.credits={hasCredits:H.has_credits,unlimited:H.unlimited,overageLimitReached:H.overage_limit_reached,...Y!==void 0?{balance:Y}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as vG}from"@cortexkit/claustrum-client";import{resolve as k9}from"node:path";import{storeIdentity as XG}from"@cortexkit/claustrum-client";import{SubcClient as f9}from"@cortexkit/subc-client";import{ClaustrumCredentialError as tz}from"@cortexkit/claustrum-client";import{SocketClosedError as ez,SocketTimeoutError as $G,SubcCallError as ZG}from"@cortexkit/subc-client";class E extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var hZ=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class f1 extends E{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function Y1($){if($ instanceof f1||$ instanceof ez||$ instanceof $G)return"unreachable";let Z=$ instanceof tz||$ instanceof ZG?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(hZ,Z))return"answered";return hZ[Z]}var vZ=300000,i2=300000,mZ=1000;class m${#$;#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 n2{#$;#Z;#z;#J=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#J=!0,this.#z;return this.#z=(async()=>{do{this.#J=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#J)})().finally(()=>{this.#z=void 0}),this.#z}}class r2{#$;#Z=new m$;#z;#J="polling";#Y;#B;#X=!1;#W;#Q=!1;#H=0;constructor($){this.#$=$,this.#z=new n2(async()=>{let Z=this.#Q;if(this.#Q=!1,Z||this.#W!==this.#$.view())await this.#$.discover(this.#W??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#J}start(){if(this.#X||this.#Y||this.#B)return;if(typeof this.#$.client.watchScoped!=="function"){this.#G("fallback","client-without-watch");return}this.#K(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#B)(this.#$.clearTimeoutImpl??clearTimeout)(this.#B);this.#B=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#G($,Z){if(this.#J===$)return;this.#J=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#V($,Z){this.#B=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#B=void 0,!this.#X)Z()},$),this.#B.unref?.()}async#K($){let Z;try{Z=await this.#$.enrollmentToken()}catch(B){if(this.#X)return;this.#$.onError?.(B),this.#F("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#X||this.#Y||!X)return;this.#Z.restart(),this.#Q=$;let J,z;try{z=X.call(this.#$.client,(B)=>{if(this.#X||!J||this.#Y!==J)return;if(J.notices++,J.notices===1)this.#$.onReachable?.(),J.acceptedAt=(this.#$.now??Date.now)(),this.#G("watching","accepted");if(!this.#Z.continuous(B))this.#Q=!0;this.#W=B.view,this.#z.request()},{enrollmentToken:Z})}catch(B){this.#$.onError?.(B),this.#F("watch-failed");return}J={handle:z,notices:0},this.#Y=J,this.#G("polling",$?"resubscribing":"opening");let G=J;z.closed.then((B)=>this.#U(G,B),(B)=>this.#U(G,{kind:"transport_lost",error:B}))}#U($,Z){if(this.#X||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#G("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("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.#H=0;let J=Math.min(1000*2**Math.min(this.#H,16),300000);this.#H++,this.#G("polling","resubscribing"),this.#V(J,()=>void this.#K(!0));return}this.#F(Z.kind)}#F($){this.#G("fallback",$),this.#V(300000,()=>void this.#K(!1))}}function g9($){let Z=$.identity??XG($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,J=!1,z,G=new Promise((H,Y)=>{z=setTimeout(()=>Y(Error("insula usage timeout")),3000),z.unref?.()}),B=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await f9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let H=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(H,{method:"usage.get",params:{}})})();try{return await Promise.race([B,G])}finally{J=!0,clearTimeout(z),X?.close()}},watchUsage(X){let J,z,G=!1,B=(async()=>{let H,Y=new Promise((W,V)=>{H=setTimeout(()=>V(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),H.unref?.()}),Q=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),V=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await f9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(J=V,G){V.close();return}let U=await V.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){V.close();return}z=V.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([Q,Y])}catch(W){throw G=!0,W}finally{clearTimeout(H)}if(z)await z.closed})().finally(()=>{G=!0,J?.close()});return{stop(){if(G)return;G=!0,z?.unsubscribe(),J?.close()},closed:B}}}}var t2=60000,y9=4*t2,JG=2*t2,wZ=new Map,o2=new Map;function w$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function zG($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!w$(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 GG($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class h9{transport;key;#$=[];#Z=!1;#z=new Set;#J=new Map;#Y=new n2(async()=>{try{let $=await this.transport.getUsage();if(!w$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>w$(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#z=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#z)this.#J.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#B=new m$;#X="polling";#W=0;#Q=0;#H=new Map;#G;#V;#K={};#U=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Y.running)return this.#Y.running;if(this.#X==="watching")return Promise.resolve();for(let[X,J]of o2)if($-J>=t2)o2.delete(X);let Z=o2.get(this.key);if(Z!==void 0&&$-Z<t2)return Promise.resolve();return o2.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#W++;let Z=$.provider;if(Z===void 0)this.#Q++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#W===1)this.#K=$,this.#j();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#Q--;else{let J=(this.#H.get(Z)??1)-1;if(J>0)this.#H.set(Z,J);else this.#H.delete(Z)}if(--this.#W===0)this.#F()}}#F(){if(this.#V)(this.#K.clearTimeoutImpl??clearTimeout)(this.#V);this.#V=void 0;let $=this.#G;this.#G=void 0,$?.handle?.stop(),this.#X="polling"}#D($){this.#V=(this.#K.setTimeoutImpl??setTimeout)(()=>{if(this.#V=void 0,this.#W>0&&!this.#G)this.#j()},$),this.#V.unref?.()}#j(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#B.restart();let Z={notices:0};this.#G=Z;let X;try{X=$.call(this.transport,(J)=>this.#N(Z,J))}catch(J){this.#M(Z,J);return}Z.handle=X,X.closed.then(()=>this.#M(Z,void 0),(J)=>this.#M(Z,J))}#N($,Z){if(this.#G!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#U=0;let X=zG(Z);if(!X)this.#B.restart();if(!(X?this.#B.continuous(X):!1)||X?.provider===void 0||this.#Q>0||this.#H.has(X.provider))this.#Y.request()}#M($,Z){if(this.#G!==$)return;this.#G=void 0;let X=GG(Z);if(X==="unknown_method"||X==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let J=Math.min(mZ*2**Math.min(this.#U,16),i2);this.#U++,this.#X="polling",this.#D(J);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||Y1(Z)==="unreachable")this.#D(i2)}current($,Z,X){for(let J of this.#$){if(J.provider!==$||typeof J.account!=="string"||J.account.trim()!==Z)continue;if(J.stale!==void 0||J.errorClass!==void 0||!w$(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=y9)continue;return{entry:J,context:{fetchedAt:z,...typeof J.source==="string"&&{source:J.source}}}}return}lookup($,Z,X){if(!this.#Z)return{miss:"unreachable"};let J=this.#$.find((B)=>B.provider===$&&typeof B.account==="string"&&B.account.trim()===Z),z=(J??this.#$.find((B)=>B.provider===$&&B.account===void 0&&B.errorClass!==void 0))?.errorClass;if(z==="upstream_failed")return{miss:"upstream-failed"};if(z==="credential_absent"||z==="credential_unusable"||z==="credential_rejected")return{miss:"credential"};if(z!==void 0)return{miss:"unreachable"};if(J){let B=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!w$(J.usage)||!Number.isFinite(B))return{miss:"unreachable"};let H={entry:J,context:{fetchedAt:B,...typeof J.source==="string"&&{source:J.source}}};return X>=B+y9||J.stale!==void 0?{miss:"stale",reading:H}:{reading:H}}if(this.#z.has($))return{miss:"absent"};let G=this.#J.get($)??X;return this.#J.set($,G),{miss:X-G>=JG?"unreachable":"cold"}}}function pZ($,Z){let X=JSON.stringify([k9($.connectionFile),k9(Z)]),J=wZ.get(X);if(!J)J={source:new h9($,X),refs:0},wZ.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)wZ.delete(X)}}}import{ClaustrumCredentialError as wj}from"@cortexkit/claustrum-client";function uZ($){let Z=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:H,listener:Y}of X)H.removeEventListener("abort",Y);X.length=0},G=(H)=>{if(J||Z.signal.aborted)return;Z.abort(H),z()},B=$.find((H)=>H.aborted);if(B)return Z.abort(B.reason),{signal:Z.signal,dispose:z};for(let H of $){if(Z.signal.aborted)break;let Y=()=>G(H.reason);if(X.push({source:H,listener:Y}),H.addEventListener("abort",Y,{once:!0}),H.aborted)G(H.reason)}return{signal:Z.signal,dispose:z}}import{ClaustrumCredentialError as G5}from"@cortexkit/claustrum-client";import{createHash as BG,randomBytes as HG,randomUUID as YG}from"node:crypto";import{constants as v9}from"node:fs";import{chmod as QG,mkdir as WG,open as l9,readFile as lZ,realpath as VG,rename as UG,stat as d9,unlink as cZ}from"node:fs/promises";import{basename as c9,dirname as W1,extname as m9,isAbsolute as w9,join as sZ,resolve as jG}from"node:path";import{ClaustrumCredentialError as KG,ClaustrumClient as DG,writeEnrollmentTokenFile as qG}from"@cortexkit/claustrum-client";var NG=1,$3=16384,s9=30000,aZ=/^[0-9a-f]{64}$/,a9="unknown_method",i9=new Set([a9,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),n9=new Set(["pending_queue_full"]);function dZ($){if(!($ instanceof KG))return;if(i9.has($.code))return{code:$.code,disposition:"terminal"};if(n9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function iZ($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new E("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function nZ($){return DG.connect($)}function r9($){let Z=m9($)||".json",X=c9($,m9($));return{statePath:sZ(W1($),`${X}-state${Z}`),tokenPath:$}}function rZ($){let Z=$.override?.trim();if(Z&&!w9(Z)&&!$.cwd)throw new E("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?w9(Z)?Z:jG($.cwd,Z):sZ($.stateDir,`${$.host}-enrollment.json`);return r9(X)}function o9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function t9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function p$(){return new E("invalid-state","invalid Claustrum enrollment state")}function X3($){if(!o9($)||$.version!==NG||typeof $.proposedName!=="string"||$.proposedName.length===0)throw p$();if($.phase==="pending"){if(!aZ.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!e2($.createdAt)||!e2($.updatedAt))throw p$();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!t9($.tokenGeneration)||!e2($.updatedAt))throw p$();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!e2($.updatedAt))throw p$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw p$()}function oZ($){if(!o9($)||!aZ.test(String($.token??""))||!t9($.token_generation))throw new E("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function FG($){if(!$.isFile())throw new E("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new E("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new E("unsafe-file","Claustrum enrollment file must be owned by the current user")}function p9($){try{return JSON.parse($)}catch{throw new E("invalid-state","Claustrum enrollment file is not valid JSON")}}async function V1($){if(I)try{await N0(W1($));let X=await _0($,!0);if(Buffer.byteLength(X)>$3)throw new E("unsafe-file","Claustrum enrollment file is too large");return p9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await l9($,v9.O_RDONLY|v9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new E("unsafe-file","Claustrum enrollment file could not be opened safely")}try{FG(await Z.stat());let X=Buffer.alloc($3+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>$3)throw new E("unsafe-file","Claustrum enrollment file is too large");return p9(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function u9($,Z){let X=[];for(let J of $.split(`
97
- `)){if(J.trim()===""||J.startsWith("#"))continue;let z=J.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;X.push(z)}return X}async function MG($,Z,X){try{let[J,z]=await Promise.all([lZ(X.passwdPath??"/etc/passwd","utf8"),lZ(X.groupPath??"/etc/group","utf8")]),G=u9(J,7),B=u9(z,4);if(!G||!B)return!1;let H=G.filter((V)=>Number(V[2])===$),Y=B.filter((V)=>Number(V[2])===Z);if(H.length!==1||Y.length!==1)return!1;let Q=H[0]?.[0],W=Y[0]?.[3]??"";return(W===""||W.split(",").every((V)=>V===Q))&&!G.some((V)=>Number(V[2])!==$&&Number(V[3])===Z)}catch{return!1}}function e9($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>lZ(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function $5($,Z={}){if(!I){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await VG($)}catch{return}let G;for(;;){let B=await d9(z).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(G===void 0)G=J!==void 0&&await MG(X,J,Z);if((B.mode&2)!==0||B.uid!==X||B.gid!==J||!G)throw new E("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let H=W1(z);if(H===z)return;z=H}}try{await p0($,e9(Z))}catch(X){if(!(X instanceof i))throw X;throw new E("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function Z3($,Z={}){if(I){await N0($,!1,e9(Z));return}await WG($,{recursive:!0,mode:448});let X=await d9($),J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new E("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((X.mode&63)!==0)await QG($,448)}async function y1($,Z,X={}){let J=W1($);await Z3(J,X),await $5(J,X);let z=`${JSON.stringify(Z)}
98
- `;if(Buffer.byteLength(z)>$3)throw new E("invalid-state","Claustrum enrollment state is too large");if(I)return i1($,z);let G=sZ(J,`.${c9($)}.${process.pid}.${YG()}.tmp`),B,H=!1;try{B=await l9(G,"wx",384),H=!0,await B.writeFile(z,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await UG(G,$),H=!1}finally{if(await B?.close().catch(()=>{}),H)await cZ(G).catch(()=>{})}}async function u$($,Z){let X=await V1($.tokenPath),J=X===void 0?void 0:oZ(X),z=await V1($.statePath),G=z===void 0?void 0:X3(z);if(J)return{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return Q1(G)}async function tZ($,Z){let X;try{X=await u$($,Z)}catch(J){if(!(J instanceof E)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await V1($.statePath);if(z===void 0)return"unreadable";let G=X3(z);return G.phase==="approved"&&G.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 U1($){let Z=await V1($);if(Z===void 0)throw new E("not-enrolled","Claustrum enrollment is not configured");return oZ(Z)}function Q1($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function Z5(){return new E("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class J3{#$;#Z;#z;#J;#Y;#B;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#J=$.now??Date.now,this.#Y=$.mintSecret??(()=>HG(32).toString("hex")),this.#B=$.writeTokenFile??qG}async status(){return u$(this.#Z,this.#z)}async resetTerminal(){return X5(this.#Z,this.#z)}async#W($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await y1(this.#Z.statePath,X,this.#X),Q1(X)}async reconcile(){await Z3(W1(this.#Z.statePath),this.#X);let $=await J0({name:"ceremony",path:this.#Z.statePath,ttlMs:s9,renew:!0});if(!$)return{state:"busy"};try{let Z=await V1(this.#Z.tokenPath),X=Z===void 0?void 0:oZ(Z),J=await V1(this.#Z.statePath),z=J===void 0?void 0:X3(J);if(z&&z.proposedName!==this.#z)throw Z5();if(X){if(!z||z.phase==="pending"){let B={version:1,phase:"approved",proposedName:z?.proposedName??this.#z,tokenGeneration:X.token_generation,updatedAt:this.#J()};await y1(this.#Z.statePath,B,this.#X),z=B}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:X.token_generation}}if(z?.phase==="approved"){let B={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#J()};return await y1(this.#Z.statePath,B,this.#X),Q1(B)}if(z&&z.phase!=="pending")return Q1(z);if(!z){let B=this.#J();if(z={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#Y(),createdAt:B,updatedAt:B},!aZ.test(z.requestSecret))throw new E("invalid-state","invalid minted Claustrum enrollment secret");await y1(this.#Z.statePath,z,this.#X)}if(!z.requestId)try{let B=BG("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),H=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:B});z={...z,requestId:H.requestId,updatedAt:this.#J()},await y1(this.#Z.statePath,z,this.#X)}catch(B){let H=dZ(B);if(!H)throw B;if(H.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:H.code};if(H.code===a9)return await $.assertOwned(),await cZ(this.#Z.statePath).catch((Y)=>{if(Y.code!=="ENOENT")throw Y}),{state:"unavailable",proposedName:z.proposedName,code:H.code};return this.#W(z,H.code)}let G=z.requestId;if(!G)return Q1(z);try{let B=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(B.status==="pending")return Q1(z);if(B.status==="denied"){let Y={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#J()};return await y1(this.#Z.statePath,Y,this.#X),Q1(Y)}await Z3(W1(this.#Z.tokenPath),this.#X),await $5(W1(this.#Z.tokenPath),this.#X),await this.#B(this.#Z.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let H={version:1,phase:"approved",proposedName:z.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,updatedAt:this.#J()};return await y1(this.#Z.statePath,H,this.#X),Q1(H)}catch(B){let H=dZ(B);if(!H)throw B;if(H.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:H.code};return this.#W(z,H.code)}}finally{await $.release()}}}async function X5($,Z){await Z3(W1($.statePath));let X=await J0({name:"ceremony",path:$.statePath,ttlMs:s9,renew:!0});if(!X)return"busy";try{if(await V1($.tokenPath)!==void 0)return"refused-approved";let J=await V1($.statePath);if(J===void 0)return"idle";let z=X3(J);if(z.proposedName!==Z)throw Z5();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await cZ($.statePath),"reset"}finally{await X.release()}}var l$="claustrum-tombstone:v1:";function z3($){return`${l$}${$}`}function eZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G3($){return typeof $==="string"&&$.startsWith(l$)}function J5($,Z){if(!eZ($)||$.type!=="oauth")return!1;return $.refresh===z3(Z)}function z5($,Z){if(J5($,Z))return"placeholder";if(eZ($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!G3($.refresh))return"login";if(eZ($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function $4($){let Z=z5($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new E("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 E("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function B5($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function _G($,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 X4=d("claustrum");function z4($,Z,X,J=X4){let z=B5(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:_G(Z,X)}),z}var J4=300000,H5=60000;function Z4(){return new E("invalid-material","Claustrum returned invalid credential material")}function LG($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw Z4()}if(!X||typeof X!=="object")throw Z4();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(l$))throw Z4();return Z}function OG($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}function PG($){let{grants:Z,grantTuples:X}=$;if(Z===void 0||X===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(X.map(({selectorKind:J,selector:z,operation:G})=>Object.freeze({selectorKind:J,selector:z,operation:G})))})}class B3{#$;#Z;#z;#J;#Y;#B;#X;#W=new WeakMap;#Q=new WeakMap;#H=new Map;#G=new WeakMap;#V;#K;#U=!1;#F=new f1;#D;#j=!1;#N=-1/0;#M=2000;#q=!1;#_;#O=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>U1(Z);else throw new E("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#J=$.family,this.#Y=$.parseIdentity,this.#B=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#X=$.logger??X4,this.#V=$.setTimeoutImpl??setTimeout,this.#K=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#q||this.#U)return;this.#U=!0,this.#F=$ instanceof G5?$:new f1,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#C()}reachable(){if(this.#q||!this.#U)return;if(this.#U=!1,this.#D)this.#K(this.#D);this.#D=void 0,this.#M=2000;for(let $ of this.#H.values())$.since=null;(this.#X.info??X4.info)("vault receipt serving resumed",{reason:"reachable"})}#C(){if(this.#q||!this.#U||this.#D||this.#j)return;this.#D=this.#V(()=>{this.#D=void 0,this.#P(!0)},this.#M),this.#D.unref?.()}#P($=!1){if(this.#q||!this.#U||this.#j)return;if(this.#z()-this.#N<1000){this.#C();return}this.#N=this.#z(),this.#j=!0,this.#A().catch(()=>{if($&&this.#U)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#j=!1,this.#C()})}#L($){if(this.#q)throw new E("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#T($){this.#L($);let Z=await this.#Z();if(this.#L($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new E("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#S($,Z){this.#L(Z);let X,J;try{let z=$();X=Z?await Promise.race([z,new Promise((G,B)=>{let H=()=>B(Z.reason);if(Z.addEventListener("abort",H,{once:!0}),J=()=>Z.removeEventListener("abort",H),Z.aborted)H()})]):await z}catch(z){if(this.#L(Z),Y1(z)==="unreachable")this.transportLost(z);else this.reachable();if(z instanceof G5)throw z;if(Y1(z)==="unreachable")throw new f1;throw new E("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#L(Z),this.reachable(),X}async discover($){let Z=await this.#A($);return this.#_=Z.view,Z}async#A($){let Z,X;try{X=await this.#T($)}catch(Y){throw this.#H.clear(),Y}try{Z=await this.#S(()=>this.#$.listScoped(X),$)}catch(Y){throw this.listFailed(Y),Y}let J=[],z=[],G=new Map;for(let Y of Z.rows){let Q=OG(Y,this.#J);if(!Q)continue;z.push({row:Y,type:Q}),G.set(Y.id,(G.get(Y.id)??0)+1)}let B=[];for(let{row:Y,type:Q}of z){let W;if(!Y.id.trim())W="empty credential id";else if((G.get(Y.id)??0)>1)W="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())W="blank account identity";else if(!Y.state.trim())W="empty state";if(W){J.push({...Y.id.trim()&&{credentialId:Y.id},reason:W});continue}B.push(Object.freeze({credentialId:Y.id,credentialType:Q,...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of J)this.#X.warn("skipped malformed vault record",Y);let H=PG(Z);return{view:Z.view,credentials:Object.freeze(B),skipped:Object.freeze(J),...H&&{grantReach:H}}}listFailed($){if(Y1($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear()}forget($){this.#H.delete($)}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,J]of this.#H){let z=Z.get(X);if(!z?.enabled||z.state!=="active"||z.credentialType!==J.attempt.credentialType||z.accountIdentity!==J.attempt.expectedAccountIdentity)this.forget(X)}}keptReceiptState(){let $=null;for(let[Z,X]of this.#H){if(!this.#R(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#R($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#z()>H5}async authorize($,Z,X="vault"){this.#L(Z);let{credentialId:J,credentialType:z,accountIdentity:G}=$,B=this.#H.get(J);if(B&&(B.attempt.credentialType!==z||B.attempt.expectedAccountIdentity!==G))this.forget(J),B=void 0;let H;try{H=await this.#T(Z)}catch(Y){throw this.#H.clear(),Y}if(this.#U&&B)return this.#P(),this.#E(J,B,H,X);try{let Y=await this.#I({credentialId:J,credentialType:z,accountIdentity:G},H,Z);return this.#H.set(J,{attempt:Y,routeId:X,since:null}),Y}catch(Y){if(this.#L(Z),Y1(Y)!=="unreachable")throw this.forget(J),Y;return this.#E(J,B,H,X,Y)}}#E($,Z,X,J,z=this.#F){if(!Z||this.#H.get($)!==Z||!this.#R(Z.attempt))throw this.forget($),z;if(Z.since===null)Z.since=this.#z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#W.set(G,X),this.#G.set(G,J),G}async#I($,Z,X){if(!$.credentialId)throw new E("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:z,accountIdentity:G}=$;if(this.#B&&G===void 0)throw new E("identity-unasserted","Claustrum dispatch requires a known account identity");let B=await this.#S(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Z,...z==="oauth"&&{minTtlMs:J4}}),X);if(B.credentialId!==void 0&&B.credentialId!==J)throw new E("identity-changed","Claustrum served credential identity changed");let H=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||H===null&&z==="oauth"||H!==null&&(!Number.isFinite(H)||H-this.#z()<J4))throw new E("insufficient-validity","Claustrum served credential has insufficient validity");let Y=LG(B.material),Q=B.accountId?.trim()?B.accountId:void 0;if(this.#B&&(B.credentialId===void 0||Q===void 0))throw new E("identity-unasserted","Claustrum served credential did not assert its identity");let W=Q===void 0?this.#Y?.(Y):void 0,V=Q??W;if(G!==void 0&&V!==void 0&&V!==G)throw new E("identity-changed","Claustrum served credential identity changed");let U=V??G,j=Object.freeze(Object.defineProperty({credentialId:J,credentialType:z,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":W!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:H},"accessToken",{value:Y,enumerable:!1}));return this.#W.set(j,Z),j}async reportFailure($,Z,X){if(Z!==401)return;this.#L();let J=this.#W.get($);if(!J)throw new E("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#G.get($);if(z!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:z,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let B=this.#Q.get($);if(B)return B;let H=this.#S(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#Q.set($,H);try{await H,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(Y){throw this.#Q.delete($),Y}}watchRoster($){this.#L();let Z=new r2({client:this.#$,enrollmentToken:()=>this.#T(),view:$.view??(()=>this.#_),discover:async(X)=>{await $.onView(X)},onRefused:(X)=>{this.listFailed(X),$.onRefused?.(X)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#z,setTimeoutImpl:this.#V,clearTimeoutImpl:this.#K});return this.#O.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#O.delete(Z),Z.stop()}}}close(){if(this.#q)return;if(this.#q=!0,this.#D)this.#K(this.#D);this.#D=void 0;for(let $ of this.#O)$.stop();this.#O.clear(),this.#H.clear(),this.#$.close()}}import{resolve as N4}from"node:path";import{createHash as CG}from"node:crypto";import{resolve as W5}from"node:path";function Y5($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function G4($,Z,X){return $.some((J)=>Y5(J,Z,X))}function B4($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function H4($,Z,X){return $.filter((J)=>!Z.some((z)=>Y5(J,z,X)))}var V5="vault:";function TG($){return CG("sha256").update($).digest("hex")}function SG($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function AG($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function j1($){return[$.credentialId,...$.aliases??[]]}function U5($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??V5,G=X.reservedRouteIds??new Set,B=$?.rows??[],H=[...$?.declined??[]],Y=Z.skipped.length===0,Q=new Set(Z.credentials.map((M)=>M.credentialId)),W=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),V=Z.skipped.some((M)=>M.credentialId===void 0),U=(M)=>!Q.has(M)&&(W.has(M)||V),K=new Map;for(let M of B){if(M.accountIdentity===void 0)continue;for(let q of j1(M))if(!K.has(q))K.set(q,M.accountIdentity)}let j=new Map;for(let M of Z.credentials){let q=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:K.get(M.credentialId),claimed:!1},_=AG(q),A=j.get(_)??[];A.push(q),j.set(_,A)}let N=new Set,D=new Set(G),F=[],L=(M,q)=>M.credential.credentialId.localeCompare(q.credential.credentialId),R=[...j.values()].map((M)=>M.toSorted(L)).sort((M,q)=>M[0]&&q[0]?L(M[0],q[0]):0);for(let M of R){let q=M[0]?.identity,_=M.filter((v)=>v.credential.state==="active"),A=_.length?_:M,T=A.filter((v)=>v.claimed),b=T.length?T:A,w=new Set(M.map((v)=>v.credential.credentialId)),f=B.find((v)=>!N.has(v)&&j1(v).some((v0)=>w.has(v0))&&(v.accountIdentity===void 0||v.accountIdentity===q)),y=b.find((v)=>v.credential.credentialId===f?.credentialId)??b[0];if(!y)continue;let h=y.credential,e=f??(q===void 0?void 0:B.find((v)=>!N.has(v)&&v.accountIdentity===q));if(e)N.add(e);let n=e?.routeId;if(!n||G.has(n)){let v=`${z}${h.credentialId}${q===void 0?"":`~${TG(q).slice(0,10)}`}`;n=v;for(let v0=2;D.has(n);v0++)n=`${v}~${v0}`}D.add(n);let H2=e?j1(e).filter(U):[],p1=[...new Set([...M.map((v)=>v.credential.credentialId),...H2])].filter((v)=>v!==h.credentialId).sort((v,v0)=>v.localeCompare(v0)),Y2=X.mapAccount?.(h)??{};F.push({previousIndex:e?B.indexOf(e):1/0,row:{routeId:n,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...p1.length&&{aliases:p1},state:h.state,label:Y2.label?.trim()||SG(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...p1].some((v)=>G4(H,v,q)),addedAt:e?.addedAt??J,...e?.quota!==void 0&&{quota:e.quota},...!y.claimed&&q!==void 0&&{unclaimed:!0}}})}return B.forEach((M,q)=>{if(N.has(M)||!j1(M).some(U))return;if(D.has(M.routeId))return;let[_,...A]=j1(M).filter((w)=>!Q.has(w));if(_===void 0)return;D.add(M.routeId);let{aliases:T,...b}=M;F.push({previousIndex:q,row:{...b,credentialId:_,...A.length&&{aliases:A},stale:!0}})}),F.sort((M,q)=>M.previousIndex===q.previousIndex?M.row.credentialId.localeCompare(q.row.credentialId):M.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:Y,...!Y&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:F.map((M)=>M.row),declined:H}}function Y4($){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 d$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y$($){return $===void 0||typeof $==="string"}function RG($){let Z=d$($)?C1($.quota):void 0;if(!d$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!Y$($.accountIdentity)||!Y$($.email)||!Y$($.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 EG=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function Q5($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!d$(X)||!Y$(X.credentialId)||typeof X.reason!=="string"||!EG.has(X.reason))return;Z.push(X)}return Z}function IG($){if(!d$($)||$.version!==1||!Y$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!Q5($.rejected))throw new E("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=RG(z);if(!G)throw new E("invalid-state","Claustrum roster file is not valid");Z.push(G)}let X=[];for(let z of $.declined){if(!d$(z)||typeof z.credentialId!=="string"||!Y$(z.accountIdentity))throw new E("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=Q5($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function K0($){let Z;try{Z=await _0($,I)}catch(J){if(J.code==="ENOENT")return;throw J}let X;try{X=JSON.parse(Z)}catch{throw new E("invalid-state","Claustrum roster file is not valid")}return IG(X)}var bG={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},xG={name:"claustrum-roster",ttlMs:30000};async function g1($,Z,X={}){return GZ($,{...bG,signal:X.signal},async(J)=>{let z=await K0($),{next:G,result:B}=await Z(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await L0($,G,{beforeRename:async()=>{await X.beforePublish?.(),X.signal?.throwIfAborted(),await J.assertOwned()}});return B})}function Q4($,Z){return g1($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z);if(!X||!J)throw new E("route-unavailable","Claustrum route is not in the roster");let z=B4(X.declined,J.credentialId,J.accountIdentity);return{next:{...X,declined:z,rows:X.rows.map((G)=>G===J?{...G,enabled:!1}:G)},result:void 0}})}function W4($,Z){return g1($,(X)=>{let J=X?.rows.find((z)=>z.routeId===Z);if(!X||!J)throw new E("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:H4(X.declined,j1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function kG($){return new E("invalid-order",$)}function fG($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let X=new Set($.map((G)=>G.routeId)),J=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(J.has(G))return`route id ${G} appears more than once`;if(!X.has(G))return`route id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G)).length;if(z>0)return`the order leaves out ${z} roster route id${z===1?"":"s"}`;return}function V4($,Z,X={}){return g1($,(J)=>{let z=J?.rows??[],G=fG(z,Z);if(G)throw kG(G);let B=new Map;for(let Q of z){let W=B.get(Q.routeId);if(W)W.push(Q);else B.set(Q.routeId,[Q])}let H=[...Z],Y=H.flatMap((Q)=>B.get(Q)??[]);if(!J||Y.every((Q,W)=>Q===z[W]))return{result:{ids:H,outcome:"unchanged"}};return{next:{...J,rows:Y},result:{ids:H,outcome:"reordered"}}},{...X.signal&&{signal:X.signal}})}function yG($,Z){if(!j1($).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")&&j1($).length===1)return"bind";return"refuse"}async function U4($,Z){let{routeId:X,observation:J,...z}=Z;return j5($,{routeId:X,observation:J,accountIdentity:z.accountIdentity,receipt:z})}async function j5($,Z){if(!l1(Z.observation))return!1;let X=y0($,await K0($));if(!K1(X,Z).kept)return!1;return K5($,Z)}function j4($,Z){return j5($,Z)}function K1($,Z){let X=$?.rows.find((B)=>B.routeId===Z.routeId),J=!X?"refuse":Z.receipt?yG(X,Z.receipt):X.accountIdentity!==void 0&&X.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!X||J==="refuse")return{roster:$,kept:!1};let z=w0(X.quota,Z.observation),G=J==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((B)=>B===X?{...B,...G,quota:z}:B)},kept:!0}}var H3=new Map;function K4($){H3.delete(W5($))}async function D4($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){K4($.path);return}let X=await J0({...xG,path:$.path,renew:!0});if(!X){let G=await K0($.path);if($.signal?.throwIfAborted(),!G?.view)throw new E("roster-busy","Claustrum account discovery is already in progress");return G}let J=W5($.path),z;try{let G=await K0($.path),B=H3.get(J);z=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},H3.delete(J);let{inventory:H}=z;return $.onInventory?.(H),$.signal?.throwIfAborted(),await g1($.path,async(Y)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let Q=typeof $.projection==="function"?$.projection():$.projection,W=U5(Y,H,Q);return{...JSON.stringify(Y)!==JSON.stringify(W)&&{next:W},result:W}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(G){if(G instanceof l0&&z&&!$.signal?.aborted&&await Z())H3.set(J,z);throw G}finally{await X.release()}}var Q$=new Map,gG=d("claustrum"),D5=100;function q5($){let Z=N4($),X=Q$.get(Z);if(!X)X={path:Z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},Q$.set(Z,X);return X}function N5($,Z){let X=q5($);X.listeners.add(Z);let J;return()=>J??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():q4($)})()}function hG($){let Z=new Map,{observation:X}=$,J=JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]),z=(H,Y,Q)=>Z.set(`${J}:${H}`,{at:Y,order:0,publication:{...$,observation:Q}}),G=(H,Y)=>JSON.stringify([H??"all",Y]),B=new Set;for(let H of X.readings??[]){let Y=G(H.scope,H.label);B.add(Y),z(Y,X.checkedAt,{checkedAt:X.checkedAt,readings:[{...H}]})}for(let H of X.coverage??[]){let Y=G(H.scope,H.label);if(!B.has(Y))z(Y,X.checkedAt,{checkedAt:X.checkedAt,coverage:[{...H}]})}if(X.budget)z("budget",X.checkedAt,{checkedAt:X.checkedAt,budget:{...X.budget}});for(let[H,Y]of Object.entries(X.counters??{}))z(`counter:${H}`,Y.checkedAt,{checkedAt:X.checkedAt,counters:{[H]:{...Y}}});if(X.credits)z("credits",X.credits.checkedAt,{checkedAt:X.checkedAt,credits:{...X.credits}});if(!Z.size)z("empty",X.checkedAt,{checkedAt:X.checkedAt});return Z}function K5($,Z){if(!l1(Z.observation))return Promise.resolve(!1);let X=q5($),J=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),z=X.pending.get(J)??new Map;for(let[G,B]of hG(Z)){let H=z.get(G);if(!H||B.at>=H.at){if(B.order=++X.order,B.publication.observation.coverage)B.priorReading=H?.publication.observation.readings?H.publication:H?.priorReading;z.set(G,B)}}if(z.size)X.pending.set(J,z);for(let G of X.listeners)G(Z);return M5(X,D5),Promise.resolve(!0)}function F5($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function y0($,Z){let X=Q$.get(N4($));if(X)for(let J of F5(X.pending)){if(J.priorReading)Z=K1(Z,J.priorReading).roster;Z=K1(Z,J.publication).roster}return Z}function M5($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,_5($)},Z),!$.draining)$.timer.unref?.()}function _5($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([X,J])=>[X,new Map(J)]));$.running=(async()=>{try{await g1($.path,(X)=>{let J=X;for(let z of F5(Z)){if(z.priorReading)J=K1(J,z.priorReading).roster;J=K1(J,z.publication).roster}return{...J!==X&&{next:J},result:void 0}},{signal:$.abort.signal});for(let[X,J]of Z){let z=$.pending.get(X);for(let[G,B]of J)if(z?.get(G)===B)z.delete(G);if(!z?.size)$.pending.delete(X)}$.failures=0}catch(X){if(!$.abort.signal.aborted&&$.failures++===0)gG.warn("vault quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{$.running=void 0;for(let J of $.wake)J();let X=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):D5;M5($,X)}})()}async function q4($,Z=1000){let X=N4($),J=Q$.get(X);if(!J)return;J.draining=!0,clearTimeout(J.timer),J.timer=void 0;let z,G,B=new Promise((H)=>{G=()=>{if(!J.pending.size||J.abort.signal.aborted)H()},J.wake.add(G),G()});try{if(J.pending.size)_5(J);await Promise.race([B,new Promise((H)=>{z=setTimeout(H,Math.max(0,Z))})])}finally{if(clearTimeout(z),G)J.wake.delete(G);if(J.draining=!1,!J.listeners.size){if(J.abort.abort(),clearTimeout(J.timer),J.pending.clear(),Q$.get(X)===J)Q$.delete(X)}}}class Y3{#$;#Z=new AbortController;#z;#J;#Y;#B;#X;#W;#Q;#H=!1;#G;#V;#K;#U=new Map;#F;#D;constructor($){this.#$=$,this.#z=$.logger??d("claustrum"),this.#D=N5($.rosterPath,(Z)=>{this.#X=K1(this.#X,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#N(){return await this.#$.isCustodyActive?.()??!0}#M($,Z){let X=uZ([this.#Z.signal,...Z?[Z]:[]]);return new Promise((J,z)=>{let G=()=>{X.signal.removeEventListener("abort",B),X.dispose()},B=()=>{G(),z(X.signal.reason)};if(X.signal.addEventListener("abort",B,{once:!0}),$.then((H)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(H)},(H)=>{G(),z(H)}),X.signal.aborted)B()})}async#q(){if(this.#j(),this.#J)return this.#J;if(!this.#Y)this.#Y=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#j();if(this.#J=new B3({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#G=pZ($.insula,this.#$.tokenPath);return this.#J}).finally(()=>{this.#Y=void 0});return this.#M(this.#Y)}snapshot(){return this.#X}grantReach(){let $=this.#W;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#V?.mode??"polling",...this.#$.insula&&{insula:this.#G?.source.watchMode()??"polling"}})}#_(){this.#V?.close(),this.#V=void 0,this.#K?.(),this.#K=void 0}keptReceiptState(){return this.#J?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return Y4(this.#X)}refresh(){if(this.#j(),this.#B)return this.#B;return this.#B=(async()=>{if(!await this.#N()){this.#X=void 0,this.#W=void 0,this.#_(),this.#J?.close(),this.#J=void 0,this.#G?.release(),this.#G=void 0;return}let $=await this.#q(),Z,X=await D4({path:this.#$.rosterPath,custody:$,onInventory:(z)=>{Z=z},isActive:()=>this.#N(),signal:this.#Z.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#j();let J=X?.view!==this.#X?.view;if(this.#X=y0(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&&J)this.#$.onRoster?.(X);return this.#F=(this.#$.now??Date.now)(),X})().finally(()=>{this.#B=void 0}),this.#B}start(){if(this.#H)return;this.#j(),this.#H=!0;let $=async()=>{try{if(await this.#O())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,$()},Z),this.#Q.unref?.()};$()}async#O(){if(this.#V?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=vZ)return!0;return!await this.#N()}#C(){let $=this.#J;if(this.#Z.signal.aborted||!$)return;if(this.#V??=$.watchRoster({view:()=>this.#X?.view,onView:async()=>{while(this.#B)await this.#B.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#G&&!this.#K)this.#K=this.#G.source.watch({provider:this.#$.insula.provider,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{await U1(this.#$.tokenPath),await this.#q(),await this.#G?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{return await U1(this.#$.tokenPath),this.#P($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{await U1(this.#$.tokenPath);let X=y0(this.#$.rosterPath,await K0(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$);return this.#P(X?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#N())return{miss:"unreachable"};try{await U1(this.#$.tokenPath);let J=y0(this.#$.rosterPath,await K0(this.#$.rosterPath))?.rows.find((B)=>B.routeId===$)?.accountIdentity;if(!J||!this.#G)return{miss:"unreachable"};let z=this.#G.source.lookup(Z.provider,J,(this.#$.now??Date.now)()),G=z.reading&&Z.normalize(z.reading.entry,z.reading.context);if(z.miss)return{miss:z.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let X=await this.lookupInsulaQuotaForRoute($);if(X.miss==="cold"||X.miss==="upstream-failed"){if(this.#U.get($)!==X.miss)this.#U.set($,X.miss),this.#z.warn("skipped insula provider poll",{reason:X.miss});return}return this.#U.delete($),X.miss?Z():X.reading}#P($){if(!this.#$.insula||!$)return;let Z=this.#G?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#j(Z);let X=this.#X??await this.#M(this.refresh(),Z);if(!X||!await this.#N())throw this.#J?.close(),this.#J=void 0,this.#_(),this.#G?.release(),this.#G=void 0,new E("not-active","Claustrum scoped custody is not active");let J=y0(this.#$.rosterPath,await K0(this.#$.rosterPath));this.#j(Z);let z=X.rows.find((Y)=>Y.routeId===$),G=J?.rows.find((Y)=>Y.routeId===$);if(G&&!G.enabled){if(z)this.#J?.forget(z.credentialId);throw new E("route-declined","Claustrum route is disabled")}if(!z||!G||G.state!=="active"||G.credentialId!==z.credentialId||G.accountIdentity!==z.accountIdentity||G.credentialType!==z.credentialType){if(z)this.#J?.forget(z.credentialId);throw new E("route-unavailable","Claustrum route is disabled, removed or changed")}let B=await this.#M(this.#q(),Z),H=uZ([this.#Z.signal,...Z?[Z]:[]]);try{return await B.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H.signal,$)}finally{H.dispose()}}async reportFailure($,Z,X){if(this.#j(),!this.#J)throw new E("no-receipt","Claustrum dispatch receipt has no active owner");await this.#J.reportFailure($,Z,X)}async send($,Z,X){let J=X.signal,z=await this.authorize($,J),G=await Z(z,J);if(G.status===401&&z.fromKeptReceipt)return await this.reportFailure(z,401,X.reporterSource??"direct"),G;if(G.status===401&&!J?.aborted){let B;try{B=await this.authorize($,J),J?.throwIfAborted()}catch(H){if(J?.aborted)throw H}if(z4(X.site,z,B,this.#z))await G.body?.cancel().catch(()=>{}),z=B,G=await Z(B,J)}if(G.status===401)await this.reportFailure(z,401,X.reporterSource??"direct").catch((B)=>this.#$.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(B)});return G}async decline($){this.#j(),await Q4(this.#$.rosterPath,$),this.#X=y0(this.#$.rosterPath,await K0(this.#$.rosterPath)),this.#J?.retain(this.#X?.rows??[])}async accept($){this.#j(),await W4(this.#$.rosterPath,$),this.#X=y0(this.#$.rosterPath,await K0(this.#$.rosterPath))}async reorder($){this.#j();let Z=await V4(this.#$.rosterPath,$);return this.#X=y0(this.#$.rosterPath,await K0(this.#$.rosterPath)),Z}async recordQuota($,Z,X){return this.#j(),U4(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.#j(),j4(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new E("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#_(),this.#J?.close(),this.#G?.release(),this.#G=void 0,this.#X=void 0,this.#W=void 0,this.#D(),K4(this.#$.rosterPath)}async dispose(){this.close(),await this.#D()}}async function L5($){let Z=await vG.connect($);return Object.assign(Z,{insula:g9($)})}var mG=z3("openai");function O5($){return G3($)}function g0($){if(!$||$.corrupt===!0)return!1;return O5($.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 Q3($){if(O5($))throw new c$}function n0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var wG=d("quota");var pG="app_EMoamEEZ73f0CkXaXp7hrann",uG="https://auth.openai.com";async function P5($){Q3($.refreshToken);let Z=await $.fetchImpl(`${uG}/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:pG}).toString()});if(!Z.ok){let z=kZ(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,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 J=typeof X.refresh_token==="string"&&X.refresh_token?X.refresh_token:$.refreshToken;return{access:X.access_token,refresh:J,expires:$.now()+X.expires_in*1000,expiresIn:X.expires_in}}var lG="https://chatgpt.com/backend-api/wham/usage";async function W$($){let Z=$.logger??wG,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await $.fetchImpl(lG,{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(!z.ok){let B=kZ(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:B})}let G=x9(await z.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:z.status,elapsedMs:Date.now()-J}),G}catch(z){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof z?.status==="number"?z.status:"error",elapsedMs:Date.now()-J,error:n0(z)}),z}}import{createHash as sG}from"node:crypto";var aG=globalThis.setTimeout,iG=5;function s$($){let Z=$?.quota?.checkIntervalMinutes??iG;return Math.max(1,Z)*60000}function nG($){return $?.quota?.enabled!==!1}function M4($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function rG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function C5($,Z,X){if(!nG(Z))return X+s$(Z);let J=rG(Z),z=[];for(let G of["primary","secondary"]){let B=$?.[G];if(!B)continue;if(B.remainingPercent>=J[G])continue;let H=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(H)||H<=X)return X+s$(Z);z.push(H)}if(!z.length)return X+s$(Z);return Math.min(...z)+60000}function oG($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function tG($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function O0($){return sG("sha256").update($).digest("hex").slice(0,16)}class D1{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!==O0($))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($)!==O0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!T5(Z.quota))return;if(this.mainTokenFp=O0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,F4(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,J=!1,z){if(!J&&!T5(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(z&&G&&z!==G)this.clearRateLimited($);let B=z??G;if(this.fallbacks.set($,{...Z,accountId:B}),X)this.fallbackTokenFps.set($,O0(X));else this.fallbackTokenFps.delete($);if(F4(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=O0($);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=D1.fallbackInflightKey($,Z),J=this.inflightFallbacks.get(X);if(J)return J;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,z),z}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(g0(X)||!X.access)continue;let J=this.getFallback(X.id,X.access);if(J&&Z<J.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground($){let Z=O0($);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=tG(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=oG($);if(!X)return;let J=Z?O0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:C5(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!J||!this.mainTokenFp||this.mainTokenFp===J))return;if(this.main=z,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&&G$(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=s$(this.storage);for(let X of $){if(X.enabled===!1)continue;if(!X.quota)continue;let J=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(J<=0)continue;let z=this.getFallback(X.id,X.access);if(z&&z.checkedAt>=J)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:J+Z,checkedAt:J},X.access,!1,X.accountId)}}isBackedOff(){return G$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==O0(Z))return!1}return G$(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,O0(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let J=this.now()-this.lastApiCallAt;if(J<D1.API_CALL_GAP_MS)await new Promise((z)=>{let G=aG(z,D1.API_CALL_GAP_MS-J);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=O0($);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 J0({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let J=this.main;if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=this.now(),z=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=O0($),this.main={quota:z,refreshAfter:C5(z,this.storage,G),checkedAt:G},F4(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,G,this.mainTokenFp,J),z}catch(J){throw this._handleMainFetchError(J),J}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 J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let X=await J0({name:D1.quotaLockName($),ttlMs:30000,path:this.configPath});if(!X){let J=this.getFallback($,Z);if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=await this._fetchQuota(Z),z=this.now();return this.setFallback($,{quota:J,refreshAfter:z+s$(this.storage),checkedAt:z},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),J}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError($,Z,X),X}finally{this.inflightFallbacks.delete(D1.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(D1.isAuthError($))return;this.mainLastApiError=y$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(D1.isAuthError(X))return;let J=O0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,y$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function T5($){return Boolean($.primary||$.secondary)}function F4($){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{readFile as KB}from"node:fs/promises";var h1=d("refresh"),O4=d("accounts"),XB=1e4,JB=15000,_4=50;function q1($){return $.type==="oauth"&&$.corrupt!==!0}function zB($){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 U$="floors-v1";class V3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var GB=[401,403,429],S5={primary:0,secondary:0},BB=!1,N1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var HB=new Set(["__proto__","constructor","prototype"]);function S4($){return $.length>0&&!HB.has($)}function YB($){return $ instanceof V3||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function W3($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():$B(),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 A5($){if(!k($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let X=Number($.nextRetryAt),J=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(J)?J:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function QB($){if(!k($))return;let Z={};for(let z of["primary","secondary"]){let G=$[z];if(!k(G))continue;let B=Number(G.usedPercent),H=Number(G.remainingPercent),Y=Number(G.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(H)||!Number.isFinite(Y))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[z]={usedPercent:B,remainingPercent:H,checkedAt:Y,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let z of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[z]==="number"?$[z]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[z]=G}let X=$.spendControl;if(k(X)){let z=Number(X.limit),G=Number(X.used),B=Number(X.remaining),H=Number(X.usedPercent),Y=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&Number.isFinite(Y)&&typeof X.reached==="boolean")Z.spendControl={limit:z,used:G,remaining:B,usedPercent:H,remainingPercent:Y,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 J=$.credits;if(k(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&(J.overageLimitReached===void 0||typeof J.overageLimitReached==="boolean")){let z=Number(J.balance),G=typeof J.checkedAt==="number"?J.checkedAt:Number.NaN;Z.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,...typeof J.overageLimitReached==="boolean"?{overageLimitReached:J.overageLimitReached}:{},...Number.isFinite(z)?{balance:z}:{},...Number.isFinite(G)?{checkedAt:G}:{}}}return Object.keys(Z).length?Z:void 0}function WB($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!zB(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...W3($),type:"api",apiKey:X||void 0,baseURL:Z,authHeader:J}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...W3($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...W3($),type:"oauth",corrupt:!0}}return{...W3($),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:A5($.lastRefreshError),lastQuotaRefreshError:A5($.lastQuotaRefreshError),quota:QB($.quota)}}function VB($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!S4(X)||!k(J))continue;let z={};if(k(J.inFlight))z.inFlight={...J.inFlight};if(k(J.lastOutcome)&&typeof J.lastOutcome.code==="string"&&J.lastOutcome.code.length>0&&typeof J.lastOutcome.at==="number"&&Number.isFinite(J.lastOutcome.at))z.lastOutcome={code:J.lastOutcome.code,at:J.lastOutcome.at,...k(J.lastOutcome.previousOutcome)&&typeof J.lastOutcome.previousOutcome.code==="string"&&J.lastOutcome.previousOutcome.code.length>0&&typeof J.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(J.lastOutcome.previousOutcome.at)?{previousOutcome:{code:J.lastOutcome.previousOutcome.code,at:J.lastOutcome.previousOutcome.at}}:{}};if(typeof J.cooldownUntil==="number"&&Number.isFinite(J.cooldownUntil))z.cooldownUntil=J.cooldownUntil;if(Object.keys(z).length>0)Z[X]=z}return Object.keys(Z).length>0?Z:void 0}var R5=new Set;function UB($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(R5.has(Z))return;R5.add(Z),O4.warn("account load-dropped, preserved on disk",{droppedIds:$})}function jB($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(WB).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let B of Z)if(k(B)&&typeof B.id==="string"&&B.id.trim())J.add(B.id.trim());let z=new Set(X.map((B)=>B.id)),G=[];for(let B of J)if(!z.has(B))G.push(B);UB(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:k($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:k($.refresh)?$.refresh:void 0,quota:k($.quota)?$.quota:void 0,reset:VB($.reset),dump:k($.dump)?$.dump:void 0,costZeroing:k($.costZeroing)?$.costZeroing:void 0,killswitch:k($.killswitch)?$.killswitch:void 0,logging:k($.logging)?$.logging:void 0,cachekeep:k($.cachekeep)?$.cachekeep:void 0,cacheKeep:k($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}async function U3($){try{return{exists:!0,value:JSON.parse(await KB($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function j3($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function DB($){let Z;try{Z=(await U3($)).value}catch{return null}return TB(Z)}function qB($,Z){if(!k($))return $;let X=k(Z)?Z:{},J=k(X.main)?X.main:void 0,z=k(X.accounts)?X.accounts:{},G=k($.quota)?$.quota:{},B=k($.refresh)?$.refresh:{},H=J??G,Y=J??B,W=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:Y.refreshLeaseId,until:Y.refreshLeaseUntil,tokenHash:Y.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((K)=>{if(!k(K))return K;let j=typeof K.id==="string"&&k(z[K.id])?z[K.id]:{};return{...K,...j}}):void 0;return NB({...$,refresh:j3({...B,mainLastRefreshError:B.mainLastRefreshError??Y.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:j3({...G,mainQuota:H.quota,mainQuotaCheckedAt:H.quotaCheckedAt,mainQuotaToken:H.quotaToken,mainLastQuotaApiError:H.lastQuotaApiError}),accounts:U})}async function A4($){let Z=await U3($.configPath);if(!Z.exists)return null;let X=await U3($.statePath);return jB(qB(Z.value,X.value))}function NB($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function FB($){if($.type==="api")return j3({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return j3({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function K3($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function a$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function MB($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function _B($,Z){if(!MB($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var LB=300000;function E5($,Z){if($===void 0)return 0;return $>Z+LB?0:$}function OB($,Z,X){let J=Date.now(),z=E5(Z.lastRefreshedAt,J),G=E5(X.lastRefreshedAt,J),B=Z.expires??0,H=X.expires??0,Y=G>z?X:z>G?Z:H>B?X:B>H?Z:_B(Z,X);a$($,Y,"access"),a$($,Y,"refresh"),a$($,Y,"expires"),a$($,Y,"lastRefreshedAt"),a$($,Y,"lastRefreshError")}function PB($,Z){if(!k($))return Z;let X=$,J=K3(X.quota),z=K3(Z.quota),G=J>z,B=G?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete B.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))B.lastUsed=X.lastUsed;return OB(B,X,Z),B}async function CB($,Z=!1){let X=Date.now(),J=X+JB,z=0;while(Date.now()<=J){z++;let H=await J0({name:"save",ttlMs:XB,path:$,renew:Z});if(H)return H;let Y=J-Date.now();if(Y<=0)break;await ZB(Math.min(_4+g5(_4),Y))}let G=Date.now()-X,B=Math.round(G/Math.max(1,z));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${z} attempts, ~${B}ms apart; retry interval is ${_4}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 TB($){if(!k($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!k(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;Z.add(J)}return Z}function SB($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:K3($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:K3(Z.quota?.mainQuota);if(X>J)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function AB($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function P4($){if(Array.isArray($))return $.map(P4);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,P4(X)]))}async function RB($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await CB(z);try{let B=(await U3(z)).value,H=k(B)?{...B,version:1}:{version:1};if(X.mainQuota)SB(H,$);if(X.mainRefresh)AB(H,$);if(X.accounts){let Y=X.accounts===!0?null:new Set(X.accounts),Q=await DB(Z.configPath);H.accounts={...k(H.accounts)?H.accounts:{}};for(let W of $.accounts){if(Y&&!Y.has(W.id))continue;if(Q&&!Q.has(W.id))continue;H.accounts[W.id]=PB(H.accounts[W.id],FB(W))}if(Y){for(let W of Y)if(!$.accounts.some((V)=>V.id===W))delete H.accounts[W]}if(Q){for(let W of Object.keys(H.accounts))if(!Q.has(W))delete H.accounts[W]}}if(J&&!J())return;await L0(z,P4(H))}finally{await G.release()}}function f5($){return $?.fallbackOn?.length?$.fallbackOn:GB}function EB($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??S5.primary,secondary:Z.secondary??Z["1w"]??S5.secondary}}function C4($){return $?.quota?.enabled!==!1}function n$($){return $?.quota?.failClosedOnUnknownQuota??BB}function D3($,Z,X=Date.now()){if(!C4(Z))return!0;if(!$)return!n$(Z);let J=EB(Z),z=n$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(M4(B,X)){if(z)return!1;continue}if(B.remainingPercent<J[G])return!1}return!0}function R4($){return $?.killswitch?.enabled===!0}function I5($){return{primary:$?.primary??$?.["5h"]??N1.primary,secondary:$?.secondary??$?.["1w"]??N1.secondary}}function b5($){return typeof $==="number"&&Number.isFinite($)?$:0}function F1($,Z){if(!$?.killswitch)return N1;if($.killswitch.schema===U$){let{accounts:X,defaults:J}=$.killswitch,z=Z??"main",G=k(X)&&Object.hasOwn(X,z)&&k(X[z])?X[z]:k(J)?J:void 0;return{primary:b5(G?.primary),secondary:b5(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return I5($.killswitch.accounts[Z]);return I5($.killswitch.main)}function y5($,Z,X,J=Date.now()){if(!R4(Z))return!0;if(!$)return!n$(Z);let z=F1(Z,X),G=n$(Z);for(let B of["primary","secondary"]){let H=$[B];if(!H)continue;if(M4(H,J)){if(G)return!1;continue}if(H.remainingPercent<z[B])return!1}return!0}function IB($){return $?.refresh?.enabled!==!1}function E4($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function g5($){return Math.floor(Math.random()*($+1))}function v1($,Z,X){return!$.access||!$.expires||$.expires-X<=E4(Z)}function bB($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function V$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class h5 extends Error{constructor($){super(`Refusing to refresh account ${$}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}function D0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function i$($){return $ instanceof Error?$.message:String($)}function T4($,Z,X){if(Z instanceof c$)return;$.lastRefreshError=u2({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function L4($,Z,X){if(Z instanceof c$)return;if($.lastQuotaRefreshError=y$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)T4($,Z,X)}function x5($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function xB($,Z){if(!$)return!1;return x5($.primary,Z)||x5($.secondary,Z)}function kB($,Z,X){if(!$)return!1;let J=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,J)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return X-G<z}function k5($,Z,X){return!kB($.quota,Z,X)}function fB($,Z,X,J){return xZ(X)&&D3($.quota,Z,J)&&xB($.quota,J)}function yB($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var gB=60000,hB=60000,vB=600000;function mB($){return`fallback-oauth-refresh-${eG("sha256").update($).digest("base64url").slice(0,16)}`}var wB=1e4,pB=100;class uB{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($)Q3($.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 J=this.quotaManager.getFallback($.id,$.access);if(J&&J.checkedAt>=X)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:X+yB(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return A4(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await RB($,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(()=>{})},gB+g5(hB)),"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=[],J=!1;for(let z of Z.accounts){if(z.enabled===!1||!q1(z))continue;if(V$(Z,z))continue;if(g0(z))continue;let G=!1,B=z;try{if(v1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&B1(H,B.refresh,this.now()))throw G=!0,Error(f$(H,this.now()));try{B=await this.refreshAccount(B,Z),J=!0}catch(Y){if(YB(Y))continue;G=!0;let Q=Z.accounts.find((W)=>W.id===z.id&&q1(W));if(Q&&!B1(Q.lastRefreshError,Q.refresh,this.now()))T4(Q,Y,this.now()),D0(Z,Q),J=!0;throw Y}}if(this.seedFallbackQuota(B,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),Z))X.push(B)}catch(H){let Y=bB(B,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(fB(B,Z,H,this.now()))h1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:i$(H)}),X.push(B);else if(!n$(Z))X.push(B)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{O4.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:i$(G)})})}return X}async markUsed($){try{let Z=await this.load();if(!Z)return;let X=Z.accounts.find((J)=>J.id===$.id);if(!X)return;X.lastUsed=this.now(),await this.save(Z,[X.id])}catch(Z){O4.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:i$(Z)})}}accountPassesQuotaPolicy($,Z){return D3($.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(!$||!IB($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!q1(X))continue;if(V$($,X))continue;if(g0(X))continue;if(!v1(X,$,this.now()))continue;if(B1(X.lastRefreshError,X.refresh,this.now()))continue;try{h1.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(J){h1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:i$(J)}),T4(X,J,this.now()),D0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!C4($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!q1(X))continue;if(V$($,X))continue;if(g0(X))continue;let J=X;try{if(v1(J,$,this.now())){if(B1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(G$(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):k5(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){L4(X,z,this.now()),D0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!C4(Z))return{storage:Z,errors:X};if(!this.options.fetchQuotaFn)return{storage:Z,errors:X};let J=$.force??!1,z=!1;for(let G of Z.accounts){if(G.enabled===!1||!q1(G))continue;if(V$(Z,G))continue;if(g0(G))continue;let B=G;try{if(v1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&B1(H,B.refresh,this.now()))throw Error(f$(H,this.now()));B=await this.refreshAccount(B,Z),z=!0}if(!J&&!k5(B,Z,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,D0(Z,B),z=!0;continue}await this.refreshAccountQuota(B,Z),z=!0}catch(H){L4(G,H,this.now()),D0(Z,G),z=!0,X.push({accountId:G.id,message:i$(H)})}}if(z)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let J=this.refreshPromises.get($.id);if(J){let B=await J;return D0(Z,B),B}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return D0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+wB;while(Date.now()<z){await new Promise((Q)=>setTimeout(Q,pB));let G=await this.load(),B=G?.accounts.find((Q)=>Q.id===$.id&&q1(Q));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==X.access||B.refresh!==X.refresh||(B.expires??0)>(X.expires??0)+60000)&&(J.force||!v1(B,G,this.now())))return D0(Z,B),h1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let Y=B.lastRefreshError;if(Y&&B1(Y,B.refresh,this.now()))throw D0(Z,B),Error(f$(Y,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(V$($,Z))throw new h5(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((H)=>H.id===$.id&&q1(H));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!v1(z,J,this.now()))return D0(Z,z),z;let G=z??$,B=await J0({name:mB(G.id),ttlMs:vB,path:this.paths.configPath,renew:!0});if(!B){h1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let H=await this.waitForConcurrentFallbackRefresh($,Z,G,X);if(H)return H;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((W)=>W.id===$.id&&q1(W)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!v1(z,J,this.now()))return D0(Z,z),z;if(!z)throw new V3($.id);G=z;let H=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});h1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:X.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let Y=await H({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,D0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new V3($.id);return h1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await B.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let J=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(G)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,G):J({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await z(X.access);X.quota=G,X.lastQuotaRefreshError=void 0,D0(Z,X),await this.save(Z)}catch(G){throw L4($,G,this.now()),D0(Z,$),G}}}var v5="/backend-api/wham/rate-limit-reset-credits",SK=`https://chatgpt.com${v5}`,lB=`${v5}/consume`,AK=`https://chatgpt.com${lB}`;function a($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as nB}from"node:fs";import{rm as u5}from"node:fs/promises";import{dirname as rB,join as l5}from"node:path";import{resolveClaustrumConnectionPath as oB}from"@cortexkit/claustrum-client";function m5($,Z){if(!$)return;let X=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(X)||X<0||X>100)return;return{usedPercent:X,remainingPercent:100-X,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function I4($){if(!a($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function dB($){let Z=I4($.total),X=I4($.remaining);if(Z===void 0||X===void 0||Z<0||X<0)return;let J=Z-X,z=$.spendable===!1,G=Z>0?J/Z*100:z?100:0;return{limit:Z,used:J,remaining:X,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...a($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function cB($,Z){if(!a($))return;let X=I4($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...X!==void 0&&X>=0&&{balance:X},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function b4($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&a(Z)&&a(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function w5($,Z){let X=m5($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=m5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Q)=>a(Q)&&Q.id==="individual_limit"):void 0,G=a(z)?dB(z):void 0,B=Array.isArray($.spend)?$.spend.find((Q)=>a(Q)&&Q.id==="credits"):void 0,H=cB(B,Z.fetchedAt),Y=a($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...H&&{credits:H},...H&&a(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...J&&{secondary:J},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var p5=["primary","secondary"];function q3($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function j$($){return typeof $==="number"&&Number.isFinite($)}function sB($,Z){if(!q3(Z))return;let X=Z.usedPercent;if(!j$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...j$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function aB($){let Z=$.spendControl;if(q3(Z)&&typeof Z.reached==="boolean"){let X=(J)=>j$(Z[J])?{[J]:Z[J]}:{};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 iB($,Z){if(!q3($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...j$($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function A0($,Z,X){if(!q3($)||!j$(Z))return;let J=[],z=[];for(let Q of p5){let W=sB(Q,$[Q]);if(W)J.push(W);else if(X)z.push({label:Q})}let G=aB($),B=$.resetCreditsAvailable,H=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:Z}}:void 0,Y=iB($.credits,Z);if(J.length===0&&z.length===0&&!G&&!H&&!Y)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{},...H?{counters:H}:{},...Y?{credits:Y}:{}}}function K$($){if(!X0($))return;let Z=s($),X={};for(let J of p5){let z=Z.limits.find((B)=>B.label===J&&B.kind==="reading");if(!z||!j$(z.usedPercent))continue;let G={usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,checkedAt:z.checkedAt,...z.resetsAt!==void 0?{resetsAt:z.resetsAt}:{},...z.windowMinutes!==void 0?{windowMinutes:z.windowMinutes}:{}};X[J]=G}return X.primary||X.secondary?X:void 0}function x4($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var k4="ck auth reclassify --from-registry";function N3($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${x4($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${k4}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var R0=d("vault"),tB="openai-auth",d5={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},eB={opencode:"OpenCode",pi:"Pi"};function $H($){return iZ(tB,$)}function F3($){return l5(rB($),"openai-auth-vault")}function ZH($,Z){return{...rZ({stateDir:$,host:Z}),rosterPath:l5($,`${Z}-roster.json`)}}var M3=2000;var XH={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${k4} to fill empty category sets, then check the CATEGORIES column with ck auth status. Or disconnect this host from the vault.`,"vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function c5($,Z){if($!=="vault-no-grant")return XH[$];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${x4(Z)}`}function s5($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let X=$.grantReach();if(X!==void 0)return X.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function JH($){let Z=B$($);return Z?H$(Z):void 0}class a5 extends Y3{#$;constructor($,Z){super($);this.#$=Z}refresh(){let $=super.refresh();return this.#$($),$}}class f4{host;name;paths;#$;#Z;#z=new Map;#J=new Map;#Y=new Map;#B;#X;#W;#Q;#H=!1;#G=!1;#V=Promise.withResolvers();#K="unknown";#U;constructor($){this.#$=$,this.host=$.host,this.name=$H($.host),this.paths=ZH($.stateDir,$.host),this.#Z=new a5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:d5,connect:()=>this.#j(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:JH,insula:{provider:"codex",normalize:w5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#X=void 0},onError:(Z)=>this.#q("vault roster refresh failed",Z),logger:{...R0,warn:(Z,X)=>{if(Z!=="skipped insula provider poll")R0.warn(Z,X)}}},(Z)=>this.#C(Z))}#F(){return(this.#$.connectionFile??oB)()}#D(){return{connectionFile:this.#F(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>R0.debug("vault transport error",{errorClass:$})}}#j(){return(this.#$.connectScoped?.()??L5(this.#D())).then(($)=>{return this.#B=$.insula!==void 0,$})}#N($,Z,X){let J=this.#Y.get($);if(J?.source===Z&&J.reason===X)return;this.#Y.set($,{source:Z,reason:X}),R0.info("vault background quota source changed",{routeId:$,source:Z,reason:X})}#M(){return this.#$.connectEnrollment?.()??nZ(this.#D())}#q($,Z){this.#X=n0(Z),R0.warn($,{host:this.host,error:this.#X})}#_(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=nB($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#_(),Z=await tZ(this.paths,this.name);if($===this.#_())return this.#K=Z,this.#U=$,Z;return"unreadable"}enrolled(){return this.#U!==this.#_()||this.#K!=="local"}async#O(){if(this.#U!==this.#_())await this.authority();return this.enrolled()}start(){if(this.#H||this.#G)return;this.#H=!0,this.#Z.start()}#C($){if(this.#Q===$)return;this.#Q=$,$.finally(()=>{if(this.#Q===$)this.#Q=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#Z.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let $=this.#Q;if($)await $.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#Q??this.#P()).catch((X)=>{this.#q("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let $=this.#Q;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#X=void 0,Z}catch($){return this.#q("vault roster refresh failed",$),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#Z.routingRows().map((Z)=>{let X=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...X!==void 0?{identity:X}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,X){let J=!1;try{return await this.#Z.send($,(z)=>{return J=!0,Z(z.accessToken,z)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(z){if(J)throw z;this.#q("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#q("vault refused to serve an account",X);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#Z.reportFailure($,401,"direct")}catch(X){this.#q("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let z=A0(Z,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota($,z,J).then(()=>{},(G)=>this.#q("vault quota write failed",G))}pollQuota($,Z=!0){let X=this.#J.get($);if(X)return X;let J=this.#L($,Z).finally(()=>{this.#J.delete($)});return this.#J.set($,J),J}async#L($,Z){if(Z){await this.authority(),await this.#Z.refreshInsulaQuota();let X=(await K0(this.paths.rosterPath))?.rows.find((H)=>H.routeId===$),J,z=await this.#Z.pollInsulaQuotaForRoute($,async()=>{this.#N($,"fallback",this.#B===!1?"insula-not-configured":"no-insula-reading"),J=await this.#T($,Z);return});if(J)return J;if(z!==void 0&&X?.accountIdentity){let H=A0(b4(z,this.routes().find((Q)=>Q.id===$)?.quota),z.primary.checkedAt,!0);if(!H)return this.#N($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota($,X.accountIdentity,H))return this.#N($,"insula",null),{ok:!0};return this.#N($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute($),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#N($,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#T($,Z)}async#T($,Z){let X,J=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,B)=>{try{let H=Z?void 0:await this.#Z.cachedInsulaQuota(B);if(H!==void 0){let Q=A0(b4(H,this.routes().find((W)=>W.id===$)?.quota),H.primary.checkedAt,!0);if(!Q)throw Error("unusable insula reading");return await this.#Z.recordQuota($,Q,B),new Response(null,{status:200})}let Y=await W$({accessToken:G,fetchImpl:J,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:$,logger:R0});return await this.recordSnapshot($,Y,!0,B),X=void 0,new Response(null,{status:200})}catch(H){X=n0(H);let Y=H?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw H}},{site:"quota"}).catch((G)=>{X=n0(G);return});if(!z)return{ok:!1,error:X??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:X??`status ${z.status}`}}requestReading($){let Z=this.#z.get($);if(Z)return Z;let X=this.pollQuota($,!1).catch((J)=>{R0.warn("vault quota poll failed",{routeId:$,error:n0(J)})}).finally(()=>{this.#z.delete($)});return this.#z.set($,X),X}async pollStale($){let Z=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let z=zH(J.quota);if(z!==void 0&&Z-z<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async reorder($){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder($)}async decline($){await this.#Z.decline($),R0.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),R0.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await u$(this.paths,this.name)}catch(Z){this.#q("vault enrollment state unreadable",Z),$={state:"blocked",proposedName:this.name,code:Z instanceof E?Z.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:$,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#X?{lastError:this.#X}:{}}}async connectStep(){let $=await this.#M().catch((Z)=>{throw new r("vault-unreachable",`Could not reach the Claustrum vault (${this.#F()}): ${n0(Z)}. Is the vault running?`)});try{let Z=new J3({client:$,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),X=await Z.status();if(X.state==="denied"||X.state==="blocked")await Z.resetTerminal();let J=await Z.reconcile();if(R0.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#X=void 0,await this.refresh();return J}finally{$.close()}}waitForApproval($={}){return this.#W??=(async()=>{let Z=$.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),X=$.pollIntervalMs??2000,J=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=J)return z;await Z(X),z=await this.connectStep()}return z})().finally(()=>{this.#W=void 0}),this.#W}async disconnect(){await u5(this.paths.tokenPath,{force:!0}),await u5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,R0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())$4({mode:"custody",auth:$,provider:"openai"})}close(){this.#G=!0,this.#V.resolve(),this.#Z.close()}}function zH($){if(!$)return;let Z=s($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function _3($,Z){if(Z.state!=="pending")return[];if(!Z.requestId)return[`The vault did not take the enrollment request yet${Z.retryCode?` (${Z.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${Z.requestId} for ${$} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${Z.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${$} --selector-kind category --selector ${d5.category} --operation read`]}function i5($,Z,X){let J=`${eB[$]} (${Z})`;switch(X.state){case"approved":return`${J}: connected to the Claustrum vault.`;case"idle":return`${J}: not connected to the Claustrum vault.`;case"pending":return X.requestId?`${J}: waiting for approval of request ${X.requestId}.`:`${J}: enrollment request not taken yet${X.retryCode?` (${X.retryCode})`:""}.`;case"denied":return`${J}: the vault denied the enrollment request.`;case"blocked":return`${J}: enrollment stopped (${X.code}).`;case"unavailable":return`${J}: the vault is unavailable (${X.code}).`;case"busy":return`${J}: another process is enrolling right now.`}}function y4($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${$.name}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${N3($.name,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[..._3($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
99
- `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var n5=`${String.fromCharCode(27)}\\[[0-9;]*m`,tK=new RegExp(n5,"g"),eK=new RegExp(`^${n5}`);function M1($){return $.authority!=="local"}async function E0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function t5($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(X)=>X instanceof Error?X.message:String(X)),new Promise((X)=>{Z=setTimeout(()=>X("Vault roster refresh did not finish within the roster wait budget."),M3)})])}finally{clearTimeout(Z)}}function r0($){return $.email||$.label||$.routeId}var h4="Accounts are managed in the vault with ck. Disconnect to use local accounts.",D$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var I0="main";function O3($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function $7($,Z,X){let J=new Map;if(R4(Z))for(let z of $)J.set(z.id,y5(K$(z.quota),Z,z.id===I0?void 0:z.id,X));return J}var Z7=5,v4=5000;function X7($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function J7($,Z=v4){let X=$.rows.filter((B)=>B.kind==="oauth"&&$.killswitch.get(B.id)!==!1&&s(B.quota).limits.length===0);if(X.length===0)return;if(b0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>$.killswitch.get(B.id)!==!1))return;let z=[];if(b0({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(B)=>{let H=$.requestPull(B);if(H)z.push(H.catch(()=>{}))}}),z.length===0)return;let G;return Promise.race([Promise.all(z),new Promise((B)=>{G=setTimeout(B,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function L3($){return $.reason==="exhausted"||$.reason==="budget-spent"}function KH($,Z){if(!m0($))return!1;let X=$;if(!(Z-X.checkedAt<=L$))return!1;if(X.overageLimitReached===!0)return!1;if(X.unlimited)return!0;return X.hasCredits&&(X.balance===void 0||X.balance>0)}function P3($,Z,X){let J=(H)=>Z.killswitch.get(H)!==!1,z=new Set(X.admitted.filter((H)=>H.lastPath!==!0&&J(H.id)).map((H)=>H.id)),G=new Map(X.refused.map((H)=>[H.id,H])),B=$.filter((H)=>{if(H.kind!=="oauth"||!J(H.id))return!1;if(G.get(H.id)?.reason!=="exhausted")return!1;let Y=s(H.quota);if(T1(Y,Z.now))return!1;return KH(Y.credits,Z.now)}).map((H)=>H.id);return{free:z,credits:B}}function DH($,Z=$.rows){return b0({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class m4{#$=new Set;served($,Z,X){let J=DH($),z=P3($.rows,$,J),G=new Set(z.credits);if(z.free.has(Z)){this.#$.clear();return}for(let B of[...this.#$])if(!G.has(B))this.#$.delete(B);if(!G.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 z7($,Z,X){if($===void 0)return{reason:"no-credential"};if(X.get($)===!1)return{reason:"killswitch"};let J=Z.excluded.find((G)=>G.id===$);if(J?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:J.until};if(J)return{reason:"no-credential"};let z=Z.refused.find((G)=>G.id===$);if(z&&"resetAtMs"in z)return{reason:"quota-exhausted",resetAtMs:z.resetAtMs};if(z)return{reason:"quota-unknown"};return{reason:"no-credential"}}function e5($,Z,X){if(Z.refused.find((z)=>!L3(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return z7($[0],Z,X)}function G7($){let Z=$.replayable!==!1,X=$.mainId===void 0?I0:$.mainId??"",J=Z?$.placement:"main-first",z=w3({rows:$.rows,placement:J,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=c1($.rows.map((V)=>V.id),J,X),B=new Set(z.admission.refused.filter((V)=>L3(V)&&$.killswitch.get(V.id)!==!1).map((V)=>V.id)),H=G.filter((V)=>B.has(V)),Y=P3($.rows,$,z.admission),Q=z.order.filter((V)=>Y.free.has(V)),W=G.filter((V)=>Y.credits.includes(V));if(!Z){let V=G.includes(X),U=V?X:Q[0]??W[0]??z.order[0]??H[0];if(U!==void 0&&z.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&W.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&B.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:V?z7(X,z.admission,$.killswitch):e5(G,z.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(W.length>0){let V=z.order.length>0?z.order:H;return{kind:"send",order:[...W,...V.filter((U)=>!W.includes(U))],lastPath:!1}}if(z.order.length>0)return{kind:"send",order:z.order,lastPath:!1};if(H.length>0)return{kind:"send",order:H,lastPath:!0};return{kind:"block",block:e5(G,z.admission,$.killswitch)}}function w4($){let Z=b0({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,s(J.quota));for(let J of Z.admitted)if(J.projection)X.set(J.id,J.projection);return{projections:X,excluded:new Set(Z.excluded.map((J)=>J.id))}}function B7($,Z,X){let J=X.exclude,z=J?$.rows.filter((B)=>!J.has(B.id)):$.rows,G=new Map;for(let B of z){let H=Z.resetCredits(B.id);if(H!==void 0)G.set(B.id,H)}return s3({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(B)=>Z.reservePercent(B.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function H7($,Z,X,J){let z=B7($,Z,{exclude:X,pendingBytes:J}),G=$.rows.filter((W)=>!X.has(W.id)),B=P3(G,$,z.admission),H=z.outcome==="dispatch"&&z.source!=="pin"?{accountId:z.accountId,source:z.source,...z.quotaCheckedAt===void 0?{}:{quotaCheckedAt:z.quotaCheckedAt}}:void 0;if(H&&B.free.has(H.accountId))return H;let Y=B.credits[0];if(Y===void 0)return H;let Q=s(G.find((W)=>W.id===Y)?.quota).checkedAt;return{accountId:Y,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function Y7($,Z,X){let J=$.killswitch.get(X)===!1,z={kind:"move",reason:J?"killswitch":"exhausted"},G=B7($,Z,{pin:X}),B=P3($.rows,$,G.admission),H=B.credits.includes(X),Y=B.credits.some((V)=>V!==X);if(G.outcome==="dispatch"){let V=!B.free.has(G.accountId);if(G.pin.action==="assign"){if(V&&H)return{kind:"serve"};return z}if(G.accountId!==X)return{kind:"detour"};if(V&&Y)return z;return{kind:"serve"}}let Q=G.admission.refused.find((V)=>V.id===X),W=J||Q!==void 0&&L3(Q);if(H)return{kind:"serve"};if(Y)return W?z:{kind:"detour"};if(!J&&Q&&L3(Q))return{kind:"last-path"};return{kind:"none"}}function Q7($,Z,X,J){let z=$.killswitch.get(X);return c3({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...z===void 0?{}:{killswitchPasses:z}})}function W7($){return a($)?{...$}:{}}function p4($,Z){let X=X0(Z)?M$(Z.credits):void 0;return X?`${$} · prepaid ${X}`:$}function V7($,Z){return{...$,sections:$.sections.map((X)=>X.id!=="quota"?X:{...X,items:X.items.map((J)=>J.detail===void 0?J:{...J,detail:p4(J.detail,Z.get(J.id))})})}}function C3($,Z,X,J){let z=X.confirm?.irreversible?{irreversible:!0,confirm:X.confirm.message}:{...X.confirm?{confirm:X.confirm.message}:{}};return{id:X.id,label:X.label,...X.description?{description:X.description}:{},...X.group?{group:X.group}:{},knobs:X.knobs,...z,run:async({values:G,invocation:B})=>{let H=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},B);return{ok:H.ok,text:H.text,...H.code?{code:H.code}:{}}}}}function u4($,Z){return new Proxy($,{get(X,J){if(J==="read")return async()=>{let G=await X.read();if(G.status!=="ready")return G;let B={...G,rows:G.rows.map((Q)=>({...Q,label:Q.label??Q.id}))};if(!Z)return B;let H=await E0(Z);if(!M1(H))return B;let Y=[...H.status.accounts.map((Q)=>({id:Q.routeId,label:r0(Q),type:"oauth",enabled:Q.enabled,identity:Q.accountIdentity,quota:Q.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Y}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!Z)return G;let B=await E0(Z),H=W7(G.settings.killswitch);if(!M1(B)||!G.settings.killswitch)return G;let Y=W7(H.accounts);for(let Q of B.status.accounts)Y[Q.routeId]=F1({version:1,accounts:[],...G.settings},Q.routeId);return{...G,settings:{...G.settings,killswitch:{...H,accounts:Y}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function l4($,Z,X={}){let J=E1($),z=(Q)=>E1({command:$.command,title:$.title,store:u4($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Q??"",vaultOrder:async()=>{let W=await E0(Z);if(!M1(W))return;return{rows:W.status.accounts.map((V)=>({id:V.routeId,label:r0(V)})),reorder:async(V)=>{if(!M1(await E0(Z)))throw new r("vault-local-action",D$);return Z.reorder(V)}}}},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Q,W)=>{let V=await E0(Z),U=M1(V),K=O3(V.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),j=U?z(K):J,D=(await j.open(W)).menu.sections.find((T)=>T.id===Q);if(!D)throw new r("unavailable","The account menu is unavailable.");if(!U)return{lines:D.lines,items:D.items.map((T)=>({...T,actions:T.actions.map((b)=>C3(j,Q,b,T.id))})),actions:D.actions.map((T)=>C3(j,Q,T))};let F=new Map(V.status.accounts.map((T)=>[T.routeId,T])),L=($.now??Date.now)(),R=(T)=>({id:"check",label:T?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await E0(Z)).routes].filter((f)=>!T||f===T);if(T&&w.length===0)throw new r("unavailable","This vault account cannot be checked right now.");for(let f of w){let y=await Z.pollQuota(f);if(!y.ok)throw new r("quota-check-failed",`${f}: ${y.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(Q==="quota"){let T=(b,w)=>P0(s(b.quota,$.quota?.scope),{now:L,form:w});return{lines:V.status.accounts.filter((b)=>!V.routes.has(b.routeId)).map((b)=>`${r0(b)} (${b.enabled?b.state:"disabled"}): ${p4(T(b,"compact"),b.quota)}`),items:V.status.accounts.filter((b)=>V.routes.has(b.routeId)).map((b)=>({id:b.routeId,label:r0(b),group:"Accounts",status:T(b,"compact"),detail:p4(T(b,"full"),b.quota),actions:[R(b.routeId)]})),actions:V.routes.size>0?[R()]:[]}}let M=D.items.map((T)=>{let b=F.get(T.id),w=b&&Q==="accounts"?`Vault · ${b.credentialType==="oauth"?"login":"API key"} · ${b.state} · ${b.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:w,group:T.group,status:b&&Q==="accounts"?b.enabled?b.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:b&&Q!=="limits"?[]:T.actions.map((f)=>C3(j,Q,f,T.id))}}),q=D.actions.filter((T)=>Q==="limits"||Q==="routing"&&(T.id==="mode"||T.id==="order")).map((T)=>C3(j,Q,T)),_=D.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),A=Q==="routing"&&K===null&&_?.kind==="choice"&&(_.value==="main-first"||_.value==="fallback-first");return{lines:Q==="accounts"?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`,h4]:[...D.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:M,actions:q}},B=E1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Q)=>G("accounts",Q)},quota:{title:"Quota",build:(Q)=>G("quota",Q)},routing:{title:"Routing",build:(Q)=>G("routing",Q)},limits:{title:"Limits",build:(Q)=>G("limits",Q)}},extras:$.extras?.map((Q)=>Q.id!=="reset"?Q:{...Q,build:async(W)=>{let V=await E0(Z);if(M1(V))return{lines:[h4]};return Q.build(W)}})}),H=async()=>{if(!M1(await E0(Z)))return{menu:J,error:void 0};let Q=X.refresh===!1?void 0:await t5(Z);return{menu:B,error:Q}},Y=async(Q,W)=>{let V=await Q.menu.open(W);if(Q.error)V.menu.sections.find((K)=>K.id==="vault")?.lines.push(`Last error: ${Q.error}`);return V};return{command:$.command,open:async(Q)=>Y(await H(),Q),apply:async(Q,W)=>{let V=await H(),{menu:U}=V;if(U===B&&(Q.sectionId==="accounts"||Q.sectionId==="reset"||Q.sectionId==="quota"&&(await E0(Z)).routes.size===0||Q.sectionId==="limits"&&Q.itemId!==void 0&&!(await E0(Z)).status.accounts.some((K)=>K.routeId===Q.itemId)))return{...await Y(V,W),ok:!1,code:"vault-local-action",text:D$};if(X.refuseApply)return{...await Y(V,W),ok:!1,...X.refuseApply};return U.apply(Q,W)}}}var _1="openai",a4="OpenAI accounts",m1="main",j7="that account is already your main account, so it was not added again",r$=d("commands"),K7=new Set(["__proto__","constructor","prototype"]);function D7($,Z){let X={version:1,accounts:[],killswitch:$},J=a($.accounts)?Object.keys($.accounts):[],z={};for(let H of new Set([m1,...Z,...J])){if(K7.has(H))continue;let Y=F1(X,H===m1?void 0:H);z[H]={primary:Y.primary,secondary:Y.secondary}}let G=F1(X,void 0),B={...$};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=U$,B}function q7($,Z){let X=a($.accounts)?{...$.accounts}:{};for(let z of new Set([m1,...Z])){if(K7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:N1.primary,secondary:N1.secondary}}let J=a($.defaults)?$.defaults:{primary:N1.primary,secondary:N1.secondary};return{...$,accounts:X,defaults:J,schema:U$}}function d4($,Z){let X=!1;if(a($.cachekeep))$.cacheKeep={...$.cachekeep,...a($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(a(J)&&J.schema!==U$)$.killswitch=D7(J,Z),X=!0;return X}async function U7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function N7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return d4(z,await U7($)),{...J,settings:z}},X=async(J,z)=>{let G=await U7($);return $.updateSettings(async(B)=>{d4(B,G);let H=await J(B)??B;if(a(H.killswitch)&&H.killswitch.schema!==U$)H.killswitch=q7(H.killswitch,G);return H},z)};return new Proxy($,{get(J,z){if(z==="readSettings")return Z;if(z==="updateSettings")return X;let G=Reflect.get(J,z,J);return typeof G==="function"?G.bind(J):G}})}function F7($,Z){let X=(Y,Q)=>Z.rowLocks?Z.rowLocks(Y):Q,J=(Y,Q)=>{let W=X(Y,Q?.extraLocks);return{...Q??{},...W?{extraLocks:W}:{}}},z=(Y,Q,W,V)=>$.replace(Y,Q,W,J(Y,V)),H={add:async(Y,Q)=>{let W=await $.read(),U=(W.status==="ready"?W.rows:[]).filter((D)=>D.type==="oauth"&&!D.invalid),K=Y.identity?U.find((D)=>D.identity===Y.identity):void 0;if(K?.id===m1)throw new r("main-account",j7);let j=K??U.find((D)=>D.id===Y.id&&D.id!==m1);if(!j||Y.credential.type!=="oauth")return $.add(Y,Q);let N=await z(j.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},Q?.extraLocks?{extraLocks:Q.extraLocks}:void 0);return r$.info("account signed in again",{id:j.id}),{id:N.id,outcome:"rotated",credential:N.credential,credentialEpoch:N.credentialEpoch}},replace:z,enable:(Y,Q)=>$.enable(Y,J(Y,Q)),disable:(Y,Q,W)=>$.disable(Y,Q,J(Y,W)),remove:(Y,Q)=>$.remove(Y,J(Y,Q))};return new Proxy($,{get(Y,Q){if(Object.hasOwn(H,Q))return H[Q];let W=Reflect.get(Y,Q,Y);return typeof W==="function"?W.bind(Y):W}})}var M7="migration";function c4($){let Z=["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",$.length>0?"These processes still hold the move back:":"No running process holds the move back."],X={command:_1,title:a4,sections:[{id:M7,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((J,z)=>({id:`blocker-${z}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return s4(X)}var qH=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function NH($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(qH.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function T3($,Z,X){if(Array.isArray($))return $.map((z,G)=>T3(z,`${Z}[${G}]`,X));if(!a($))return $;let J={};for(let[z,G]of Object.entries($)){if(NH(z)){X.push(`${Z}.${z}`);continue}J[z]=T3(G,`${Z}.${z}`,X)}return J}function s4($){let Z=[],X=T3($,"menu",Z);if(Z.length>0)r$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function _7($){return{id:$.id,credential:{type:"oauth",refresh:$.refresh,...$.access!==void 0?{access:$.access}:{},...$.expires!==void 0?{expires:$.expires}:{}},...$.accountId!==void 0?{identity:$.accountId}:{},...$.label!==void 0?{label:$.label}:{}}}function L7($,Z){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(X)=>{let J=typeof X.label==="string"&&X.label.trim().length>0?X.label.trim():void 0,z=X.headless===!0,G=await $.begin({...J!==void 0?{label:J}:{},headless:z}),B=z?`Open this verification URL:
96
+ </html>`,a2=[],v$,r0=new Map;function _9($,Z){return new Promise((X,J)=>{let z=(B)=>{$.off("listening",G),J(B)},G=()=>{$.off("error",z),X()};$.once("error",z),$.once("listening",G),$.listen(m$,Z)})}function T9($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function b1(){return r0.size}function f1($){if(r0.delete($),b1()===0)x1()}async function rz(){let $=`http://localhost:${m$}/auth/callback`;if(a2.length>0)return{port:m$,redirectUri:$};if(v$)return v$;v$=(async()=>{let Z=(G,B)=>{let H=new URL(G.url||"/",`http://127.0.0.1:${m$}`);if(H.pathname==="/auth/callback"){let Y=H.searchParams.get("code"),Q=H.searchParams.get("state"),W=H.searchParams.get("error"),V=H.searchParams.get("error_description");if(W){let K=V||W;if(Q){let j=r0.get(Q);if(j)j.reject(Error(K)),f1(Q);else if(b1()===0)x1()}else if(b1()===0)x1();B.writeHead(200,{"Content-Type":"text/html"}),B.end(s2(K));return}if(!Q){if(b1()===0)x1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(s2("Missing state parameter"));return}if(!Y){if(b1()===0)x1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(s2("Missing authorization code"));return}let U=r0.get(Q);if(!U){if(b1()===0)x1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(s2("Unknown state — authorization may have expired"));return}f1(Q),az(Y,$,U.pkce).then((K)=>U.resolve(K)).catch((K)=>U.reject(K)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(nz);return}if(H.pathname==="/cancel"){let Y=H.searchParams.get("state"),Q=Y?[Y]:[...r0.keys()];B.writeHead(200),B.end("Login cancelled");for(let W of Q){let V=r0.get(W);if(!V)continue;V.reject(Error("Login cancelled")),f1(W)}if(b1()===0)x1();return}B.writeHead(404),B.end("Not found")},X=L9(Z);await _9(X,"127.0.0.1");let J=[X],z=L9(Z);try{await _9(z,"::1"),J.push(z)}catch(G){let B=G.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw T9(X),G}return a2=J,{port:m$,redirectUri:$}})();try{return await v$}finally{v$=void 0}}function x1(){let $=a2;a2=[];for(let Z of $)T9(Z)}function oz($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){f1(Z),G(Error("Login cancelled"));return}let B=setTimeout(()=>{if(r0.get(Z))f1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),H=()=>{if(clearTimeout(B),r0.get(Z))f1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",H);r0.set(Z,{pkce:$,state:Z,resolve:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",H);z(Y)},reject:(Y)=>{if(clearTimeout(B),J)J.removeEventListener("abort",H);G(Y)}})})}async function tz($){let Z=await fetch(`${k1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":O9($)},body:JSON.stringify({client_id:i2})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${k1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function ez($,Z,X){let J=Math.max(parseInt($.interval,10)||5,1)*1000,z=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(z)&&z>0?z*1000:900000,B=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>G)throw Error("Device authorization expired");let H=await fetch(`${k1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":O9(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(H.ok){let W=await H.json(),V=await fetch(`${k1}/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:`${k1}/deviceauth/callback`,client_id:i2,code_verifier:W.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(H.status!==403&&H.status!==404)throw Error(`Device authorization failed: ${H.status}`);let Y=G-(Date.now()-B);if(Y<=0)throw Error("Device authorization expired");let Q=Math.min(J+pz,Y);try{await wz(Q,void 0,{signal:X})}catch(W){if(W instanceof Error&&W.name==="AbortError")throw Error("Device authorization cancelled");throw W}}}async function A9($){let{label:Z,headless:X=!1,signal:J,version:z}=$;if(m3(Z),X){let{deviceData:W,url:V,instructions:U}=await tz(z),K=(async()=>{let j=await ez(W,z,J),q=Date.now(),D=w$(j);return{id:m3(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:j.access_token,refresh:j.refresh_token,expires:q+(j.expires_in??3600)*1000,enabled:!0,addedAt:q,lastUsed:q,lastRefreshedAt:q,accountId:D}})();return{url:V,instructions:U,completion:K}}let{redirectUri:G}=await rz(),B=await dz(),H=C9(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=sz(G,B,H),Q=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let W=await oz(B,H,void 0,J),V=Date.now(),U=w$(W);return{id:m3(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:W.access_token,refresh:W.refresh_token,expires:V+(W.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:U}}finally{f1(H)}})();return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}import{basename as $G,dirname as ZG,join as XG}from"node:path";var n2="openai-auth.json",S9="openai-auth-state.json";function w3($){return $G($)===n2?XG(ZG($),S9):`${$}.state.json`}function r2($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let J=Z<100000000000?Z*1000:Z,z=new Date(J);return Number.isNaN(z.getTime())?void 0:z.toISOString()}let X=new Date($);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function p3($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function R9($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function E9($,Z){let X=$.get(Z);if(X===null||X.trim()==="")return;let J=Number(X);if(!Number.isFinite(J)||J<0||J>100)return;let z=Z.slice(0,-13),G=p3($.get(`${z}-window-minutes`)),B=r2($.get(`${z}-reset-at`)??void 0);if(J===0&&$.get(`${z}-window-minutes`)==="0"&&!B)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:B,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var k9=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function f9($,Z){let X=$.get(Z);if(X===null)return"absent";if(X.trim()==="")return"invalid";let J=Number(X);return Number.isFinite(J)&&J>=0&&J<=100?"valid":"invalid"}function y9($){if(k9.some((G)=>f9($,G)==="invalid"))return{};let Z={},X=E9($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=E9($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;let z=JG($);if(z)Z.credits=z;return Z}function I9($,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 JG($){let Z=I9($,"x-codex-credits-has-credits"),X=I9($,"x-codex-credits-unlimited");if(Z===void 0||X===void 0)return;let J=Y1($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:X,...J!==void 0?{balance:J}:{},checkedAt:Date.now()}}function g9($){let Z=k9.map((X)=>f9($,X));return Z.includes("valid")&&!Z.includes("invalid")}function b9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=p3($.window_minutes),X=r2($.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 h9($){let Z={},X=b9($.rate_limits?.primary);if(X)Z.primary=X;let J=b9($.rate_limits?.secondary);if(J)Z.secondary=J;let z=zG($.credits);if(z)Z.credits=z;return Z}function zG($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let X=Y1(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 Y1($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function x9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=p3($.limit_window_seconds),X=r2($.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 v9($){let Z={},X=x9($.rate_limit?.primary_window);if(X)Z.primary=X;let J=x9($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=R9($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=R9($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let B=$.spend_control?.individual_limit;if($.spend_control===null||B===null)Z.spendControlCleared=!0;if(B&&typeof $.spend_control?.reached==="boolean"){let Y=Y1(B.limit),Q=Y1(B.used),W=Y1(B.remaining),V=Y1(B.used_percent),U=Y1(B.remaining_percent);if(Y!==void 0&&Q!==void 0&&W!==void 0&&V!==void 0&&U!==void 0)Z.spendControl={limit:Y,used:Q,remaining:W,usedPercent:V,remainingPercent:U,resetsAt:r2(B.reset_at),unit:B.unit,source:B.source,reached:$.spend_control.reached}}let H=$.credits;if(H&&typeof H.has_credits==="boolean"&&typeof H.unlimited==="boolean"&&typeof H.overage_limit_reached==="boolean"){let Y=Y1(H.balance);Z.credits={hasCredits:H.has_credits,unlimited:H.unlimited,overageLimitReached:H.overage_limit_reached,...Y!==void 0?{balance:Y}:{},checkedAt:Date.now()}}return Z}import{ClaustrumClient as cG}from"@cortexkit/claustrum-client";import{resolve as m9}from"node:path";import{storeIdentity as QG}from"@cortexkit/claustrum-client";import{SubcClient as w9}from"@cortexkit/subc-client";import{ClaustrumCredentialError as GG}from"@cortexkit/claustrum-client";import{SocketClosedError as BG,SocketTimeoutError as HG,SubcCallError as YG}from"@cortexkit/subc-client";class E extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var l3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class y1 extends E{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function Q1($){if($ instanceof y1||$ instanceof BG||$ instanceof HG)return"unreachable";let Z=$ instanceof GG||$ instanceof YG?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(l3,Z))return"answered";return l3[Z]}var u3=300000,o2=300000,d3=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 t2{#$;#Z;#z;#J=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#J=!0,this.#z;return this.#z=(async()=>{do{this.#J=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#J)})().finally(()=>{this.#z=void 0}),this.#z}}class e2{#$;#Z=new p$;#z;#J="polling";#Y;#B;#X=!1;#W;#Q=!1;#H=0;constructor($){this.#$=$,this.#z=new t2(async()=>{let Z=this.#Q;if(this.#Q=!1,Z||this.#W!==this.#$.view())await this.#$.discover(this.#W??"")},(Z)=>{if(!this.#X)this.#$.onError?.(Z)})}get mode(){return this.#J}start(){if(this.#X||this.#Y||this.#B)return;if(typeof this.#$.client.watchScoped!=="function"){this.#G("fallback","client-without-watch");return}this.#K(!1)}stop(){if(this.#X)return;if(this.#X=!0,this.#B)(this.#$.clearTimeoutImpl??clearTimeout)(this.#B);this.#B=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#G($,Z){if(this.#J===$)return;this.#J=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#V($,Z){this.#B=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#B=void 0,!this.#X)Z()},$),this.#B.unref?.()}async#K($){let Z;try{Z=await this.#$.enrollmentToken()}catch(B){if(this.#X)return;this.#$.onError?.(B),this.#F("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#X||this.#Y||!X)return;this.#Z.restart(),this.#Q=$;let J,z;try{z=X.call(this.#$.client,(B)=>{if(this.#X||!J||this.#Y!==J)return;if(J.notices++,J.notices===1)this.#$.onReachable?.(),J.acceptedAt=(this.#$.now??Date.now)(),this.#G("watching","accepted");if(!this.#Z.continuous(B))this.#Q=!0;this.#W=B.view,this.#z.request()},{enrollmentToken:Z})}catch(B){this.#$.onError?.(B),this.#F("watch-failed");return}J={handle:z,notices:0},this.#Y=J,this.#G("polling",$?"resubscribing":"opening");let G=J;z.closed.then((B)=>this.#U(G,B),(B)=>this.#U(G,{kind:"transport_lost",error:B}))}#U($,Z){if(this.#X||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#G("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#F("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.#H=0;let J=Math.min(1000*2**Math.min(this.#H,16),300000);this.#H++,this.#G("polling","resubscribing"),this.#V(J,()=>void this.#K(!0));return}this.#F(Z.kind)}#F($){this.#G("fallback",$),this.#V(300000,()=>void this.#K(!1))}}function l9($){let Z=$.identity??QG($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,J=!1,z,G=new Promise((H,Y)=>{z=setTimeout(()=>Y(Error("insula usage timeout")),3000),z.unref?.()}),B=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await w9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let H=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(H,{method:"usage.get",params:{}})})();try{return await Promise.race([B,G])}finally{J=!0,clearTimeout(z),X?.close()}},watchUsage(X){let J,z,G=!1,B=(async()=>{let H,Y=new Promise((W,V)=>{H=setTimeout(()=>V(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),H.unref?.()}),Q=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),V=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await w9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(J=V,G){V.close();return}let U=await V.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){V.close();return}z=V.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([Q,Y])}catch(W){throw G=!0,W}finally{clearTimeout(H)}if(z)await z.closed})().finally(()=>{G=!0,J?.close()});return{stop(){if(G)return;G=!0,z?.unsubscribe(),J?.close()},closed:B}}}}var Z6=60000,p9=4*Z6,WG=2*Z6,c3=new Map,$6=new Map;function l$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function VG($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!l$(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 UG($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class u9{transport;key;#$=[];#Z=!1;#z=new Set;#J=new Map;#Y=new t2(async()=>{try{let $=await this.transport.getUsage();if(!l$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>l$(Z)&&typeof Z.provider==="string"),this.#Z=this.#$.length===$.result.length&&($.completeProviders===void 0||Array.isArray($.completeProviders)&&$.completeProviders.every((Z)=>typeof Z==="string")),this.#z=new Set(this.#Z&&Array.isArray($.completeProviders)?$.completeProviders:[]);for(let Z of this.#z)this.#J.delete(Z)}catch{this.#$=[],this.#Z=!1,this.#z.clear()}},()=>{});#B=new p$;#X="polling";#W=0;#Q=0;#H=new Map;#G;#V;#K={};#U=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Y.running)return this.#Y.running;if(this.#X==="watching")return Promise.resolve();for(let[X,J]of $6)if($-J>=Z6)$6.delete(X);let Z=$6.get(this.key);if(Z!==void 0&&$-Z<Z6)return Promise.resolve();return $6.set(this.key,$),this.#Y.request()}watchMode(){return this.#X}watch($={}){this.#W++;let Z=$.provider;if(Z===void 0)this.#Q++;else this.#H.set(Z,(this.#H.get(Z)??0)+1);if(this.#W===1)this.#K=$,this.#j();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#Q--;else{let J=(this.#H.get(Z)??1)-1;if(J>0)this.#H.set(Z,J);else this.#H.delete(Z)}if(--this.#W===0)this.#F()}}#F(){if(this.#V)(this.#K.clearTimeoutImpl??clearTimeout)(this.#V);this.#V=void 0;let $=this.#G;this.#G=void 0,$?.handle?.stop(),this.#X="polling"}#D($){this.#V=(this.#K.setTimeoutImpl??setTimeout)(()=>{if(this.#V=void 0,this.#W>0&&!this.#G)this.#j()},$),this.#V.unref?.()}#j(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#B.restart();let Z={notices:0};this.#G=Z;let X;try{X=$.call(this.transport,(J)=>this.#q(Z,J))}catch(J){this.#M(Z,J);return}Z.handle=X,X.closed.then(()=>this.#M(Z,void 0),(J)=>this.#M(Z,J))}#q($,Z){if(this.#G!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#U=0;let X=VG(Z);if(!X)this.#B.restart();if(!(X?this.#B.continuous(X):!1)||X?.provider===void 0||this.#Q>0||this.#H.has(X.provider))this.#Y.request()}#M($,Z){if(this.#G!==$)return;this.#G=void 0;let X=UG(Z);if(X==="unknown_method"||X==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let J=Math.min(d3*2**Math.min(this.#U,16),o2);this.#U++,this.#X="polling",this.#D(J);return}if(this.#X="fallback",this.#Y.request(),Z===void 0||Q1(Z)==="unreachable")this.#D(o2)}current($,Z,X){for(let J of this.#$){if(J.provider!==$||typeof J.account!=="string"||J.account.trim()!==Z)continue;if(J.stale!==void 0||J.errorClass!==void 0||!l$(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=p9)continue;return{entry:J,context:{fetchedAt:z,...typeof J.source==="string"&&{source:J.source}}}}return}lookup($,Z,X){if(!this.#Z)return{miss:"unreachable"};let J=this.#$.find((B)=>B.provider===$&&typeof B.account==="string"&&B.account.trim()===Z),z=(J??this.#$.find((B)=>B.provider===$&&B.account===void 0&&B.errorClass!==void 0))?.errorClass;if(z==="upstream_failed")return{miss:"upstream-failed"};if(z==="credential_absent"||z==="credential_unusable"||z==="credential_rejected")return{miss:"credential"};if(z!==void 0)return{miss:"unreachable"};if(J){let B=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!l$(J.usage)||!Number.isFinite(B))return{miss:"unreachable"};let H={entry:J,context:{fetchedAt:B,...typeof J.source==="string"&&{source:J.source}}};return X>=B+p9||J.stale!==void 0?{miss:"stale",reading:H}:{reading:H}}if(this.#z.has($))return{miss:"absent"};let G=this.#J.get($)??X;return this.#J.set($,G),{miss:X-G>=WG?"unreachable":"cold"}}}function s3($,Z){let X=JSON.stringify([m9($.connectionFile),m9(Z)]),J=c3.get(X);if(!J)J={source:new u9($,X),refs:0},c3.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)c3.delete(X)}}}import{ClaustrumCredentialError as zK}from"@cortexkit/claustrum-client";function a3($){let Z=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:H,listener:Y}of X)H.removeEventListener("abort",Y);X.length=0},G=(H)=>{if(J||Z.signal.aborted)return;Z.abort(H),z()},B=$.find((H)=>H.aborted);if(B)return Z.abort(B.reason),{signal:Z.signal,dispose:z};for(let H of $){if(Z.signal.aborted)break;let Y=()=>G(H.reason);if(X.push({source:H,listener:Y}),H.addEventListener("abort",Y,{once:!0}),H.aborted)G(H.reason)}return{signal:Z.signal,dispose:z}}import{ClaustrumCredentialError as V5}from"@cortexkit/claustrum-client";import{createHash as jG,randomBytes as KG,randomUUID as DG}from"node:crypto";import{constants as d9}from"node:fs";import{chmod as NG,mkdir as qG,open as n9,readFile as i3,realpath as FG,rename as MG,stat as r9,unlink as r3}from"node:fs/promises";import{basename as o9,dirname as V1,extname as c9,isAbsolute as s9,join as o3,resolve as LG}from"node:path";import{ClaustrumCredentialError as _G,ClaustrumClient as OG,writeEnrollmentTokenFile as PG}from"@cortexkit/claustrum-client";var CG=1,J6=16384,t9=30000,t3=/^[0-9a-f]{64}$/,e9="unknown_method",$5=new Set([e9,"invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),Z5=new Set(["pending_queue_full"]);function n3($){if(!($ instanceof _G))return;if($5.has($.code))return{code:$.code,disposition:"terminal"};if(Z5.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function e3($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new E("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function $Z($){return OG.connect($)}function X5($){let Z=c9($)||".json",X=o9($,c9($));return{statePath:o3(V1($),`${X}-state${Z}`),tokenPath:$}}function ZZ($){let Z=$.override?.trim();if(Z&&!s9(Z)&&!$.cwd)throw new E("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?s9(Z)?Z:LG($.cwd,Z):o3($.stateDir,`${$.host}-enrollment.json`);return X5(X)}function J5($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function X6($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function z5($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function u$(){return new E("invalid-state","invalid Claustrum enrollment state")}function G6($){if(!J5($)||$.version!==CG||typeof $.proposedName!=="string"||$.proposedName.length===0)throw u$();if($.phase==="pending"){if(!t3.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!X6($.createdAt)||!X6($.updatedAt))throw u$();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!z5($.tokenGeneration)||!X6($.updatedAt))throw u$();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!X6($.updatedAt))throw u$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw u$()}function XZ($){if(!J5($)||!t3.test(String($.token??""))||!z5($.token_generation))throw new E("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function TG($){if(!$.isFile())throw new E("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new E("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new E("unsafe-file","Claustrum enrollment file must be owned by the current user")}function a9($){try{return JSON.parse($)}catch{throw new E("invalid-state","Claustrum enrollment file is not valid JSON")}}async function U1($){if(I)try{await q0(V1($));let X=await L0($,!0);if(Buffer.byteLength(X)>J6)throw new E("unsafe-file","Claustrum enrollment file is too large");return a9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await n9($,d9.O_RDONLY|d9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new E("unsafe-file","Claustrum enrollment file could not be opened safely")}try{TG(await Z.stat());let X=Buffer.alloc(J6+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>J6)throw new E("unsafe-file","Claustrum enrollment file is too large");return a9(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function i9($,Z){let X=[];for(let J of $.split(`
97
+ `)){if(J.trim()===""||J.startsWith("#"))continue;let z=J.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;X.push(z)}return X}async function AG($,Z,X){try{let[J,z]=await Promise.all([i3(X.passwdPath??"/etc/passwd","utf8"),i3(X.groupPath??"/etc/group","utf8")]),G=i9(J,7),B=i9(z,4);if(!G||!B)return!1;let H=G.filter((V)=>Number(V[2])===$),Y=B.filter((V)=>Number(V[2])===Z);if(H.length!==1||Y.length!==1)return!1;let Q=H[0]?.[0],W=Y[0]?.[3]??"";return(W===""||W.split(",").every((V)=>V===Q))&&!G.some((V)=>Number(V[2])!==$&&Number(V[3])===Z)}catch{return!1}}function G5($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>i3(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function B5($,Z={}){if(!I){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await FG($)}catch{return}let G;for(;;){let B=await r9(z).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(G===void 0)G=J!==void 0&&await AG(X,J,Z);if((B.mode&2)!==0||B.uid!==X||B.gid!==J||!G)throw new E("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let H=V1(z);if(H===z)return;z=H}}try{await d0($,G5(Z))}catch(X){if(!(X instanceof i))throw X;throw new E("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function z6($,Z={}){if(I){await q0($,!1,G5(Z));return}await qG($,{recursive:!0,mode:448});let X=await r9($),J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new E("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((X.mode&63)!==0)await NG($,448)}async function g1($,Z,X={}){let J=V1($);await z6(J,X),await B5(J,X);let z=`${JSON.stringify(Z)}
98
+ `;if(Buffer.byteLength(z)>J6)throw new E("invalid-state","Claustrum enrollment state is too large");if(I)return n1($,z);let G=o3(J,`.${o9($)}.${process.pid}.${DG()}.tmp`),B,H=!1;try{B=await n9(G,"wx",384),H=!0,await B.writeFile(z,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await MG(G,$),H=!1}finally{if(await B?.close().catch(()=>{}),H)await r3(G).catch(()=>{})}}async function d$($,Z){let X=await U1($.tokenPath),J=X===void 0?void 0:XZ(X),z=await U1($.statePath),G=z===void 0?void 0:G6(z);if(J)return{state:"approved",proposedName:G?.proposedName??Z,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return W1(G)}async function JZ($,Z){let X;try{X=await d$($,Z)}catch(J){if(!(J instanceof E)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await U1($.statePath);if(z===void 0)return"unreadable";let G=G6(z);return G.phase==="approved"&&G.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 j1($){let Z=await U1($);if(Z===void 0)throw new E("not-enrolled","Claustrum enrollment is not configured");return XZ(Z)}function W1($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function H5(){return new E("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class B6{#$;#Z;#z;#J;#Y;#B;#X;constructor($){this.#X=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#J=$.now??Date.now,this.#Y=$.mintSecret??(()=>KG(32).toString("hex")),this.#B=$.writeTokenFile??PG}async status(){return d$(this.#Z,this.#z)}async resetTerminal(){return Y5(this.#Z,this.#z)}async#W($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await g1(this.#Z.statePath,X,this.#X),W1(X)}async reconcile(){await z6(V1(this.#Z.statePath),this.#X);let $=await J0({name:"ceremony",path:this.#Z.statePath,ttlMs:t9,renew:!0});if(!$)return{state:"busy"};try{let Z=await U1(this.#Z.tokenPath),X=Z===void 0?void 0:XZ(Z),J=await U1(this.#Z.statePath),z=J===void 0?void 0:G6(J);if(z&&z.proposedName!==this.#z)throw H5();if(X){if(!z||z.phase==="pending"){let B={version:1,phase:"approved",proposedName:z?.proposedName??this.#z,tokenGeneration:X.token_generation,updatedAt:this.#J()};await g1(this.#Z.statePath,B,this.#X),z=B}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:X.token_generation}}if(z?.phase==="approved"){let B={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#J()};return await g1(this.#Z.statePath,B,this.#X),W1(B)}if(z&&z.phase!=="pending")return W1(z);if(!z){let B=this.#J();if(z={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#Y(),createdAt:B,updatedAt:B},!t3.test(z.requestSecret))throw new E("invalid-state","invalid minted Claustrum enrollment secret");await g1(this.#Z.statePath,z,this.#X)}if(!z.requestId)try{let B=jG("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),H=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:B});z={...z,requestId:H.requestId,updatedAt:this.#J()},await g1(this.#Z.statePath,z,this.#X)}catch(B){let H=n3(B);if(!H)throw B;if(H.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:H.code};if(H.code===e9)return await $.assertOwned(),await r3(this.#Z.statePath).catch((Y)=>{if(Y.code!=="ENOENT")throw Y}),{state:"unavailable",proposedName:z.proposedName,code:H.code};return this.#W(z,H.code)}let G=z.requestId;if(!G)return W1(z);try{let B=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(B.status==="pending")return W1(z);if(B.status==="denied"){let Y={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#J()};return await g1(this.#Z.statePath,Y,this.#X),W1(Y)}await z6(V1(this.#Z.tokenPath),this.#X),await B5(V1(this.#Z.tokenPath),this.#X),await this.#B(this.#Z.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let H={version:1,phase:"approved",proposedName:z.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,updatedAt:this.#J()};return await g1(this.#Z.statePath,H,this.#X),W1(H)}catch(B){let H=n3(B);if(!H)throw B;if(H.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:H.code};return this.#W(z,H.code)}}finally{await $.release()}}}async function Y5($,Z){await z6(V1($.statePath));let X=await J0({name:"ceremony",path:$.statePath,ttlMs:t9,renew:!0});if(!X)return"busy";try{if(await U1($.tokenPath)!==void 0)return"refused-approved";let J=await U1($.statePath);if(J===void 0)return"idle";let z=G6(J);if(z.proposedName!==Z)throw H5();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await r3($.statePath),"reset"}finally{await X.release()}}var c$="claustrum-tombstone:v1:";function H6($){return`${c$}${$}`}function zZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y6($){return typeof $==="string"&&$.startsWith(c$)}function Q5($,Z){if(!zZ($)||$.type!=="oauth")return!1;return $.refresh===H6(Z)}function W5($,Z){if(Q5($,Z))return"placeholder";if(zZ($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!Y6($.refresh))return"login";if(zZ($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function GZ($){let Z=W5($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new E("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 E("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function U5($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function SG($,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 HZ=u("claustrum");function QZ($,Z,X,J=HZ){let z=U5(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:SG(Z,X)}),z}var YZ=300000,j5=60000;function BZ(){return new E("invalid-material","Claustrum returned invalid credential material")}function RG($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw BZ()}if(!X||typeof X!=="object")throw BZ();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(c$))throw BZ();return Z}function EG($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}function IG($){let{grants:Z,grantTuples:X}=$;if(Z===void 0||X===void 0)return;return Object.freeze({grants:Z,tuples:Object.freeze(X.map(({selectorKind:J,selector:z,operation:G})=>Object.freeze({selectorKind:J,selector:z,operation:G})))})}class Q6{#$;#Z;#z;#J;#Y;#B;#X;#W=new WeakMap;#Q=new WeakMap;#H=new Map;#G=new WeakMap;#V;#K;#U=!1;#F=new y1;#D;#j=!1;#q=-1/0;#M=2000;#N=!1;#L;#O=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>j1(Z);else throw new E("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#J=$.family,this.#Y=$.parseIdentity,this.#B=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#X=$.logger??HZ,this.#V=$.setTimeoutImpl??setTimeout,this.#K=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#N||this.#U)return;this.#U=!0,this.#F=$ instanceof V5?$:new y1,this.#X.warn("serving kept vault receipt",{reason:"unreachable"}),this.#C()}reachable(){if(this.#N||!this.#U)return;if(this.#U=!1,this.#D)this.#K(this.#D);this.#D=void 0,this.#M=2000;for(let $ of this.#H.values())$.since=null;(this.#X.info??HZ.info)("vault receipt serving resumed",{reason:"reachable"})}#C(){if(this.#N||!this.#U||this.#D||this.#j)return;this.#D=this.#V(()=>{this.#D=void 0,this.#P(!0)},this.#M),this.#D.unref?.()}#P($=!1){if(this.#N||!this.#U||this.#j)return;if(this.#z()-this.#q<1000){this.#C();return}this.#q=this.#z(),this.#j=!0,this.#S().catch(()=>{if($&&this.#U)this.#M=Math.min(this.#M*2,30000)}).finally(()=>{this.#j=!1,this.#C()})}#_($){if(this.#N)throw new E("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#T($){this.#_($);let Z=await this.#Z();if(this.#_($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new E("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#A($,Z){this.#_(Z);let X,J;try{let z=$();X=Z?await Promise.race([z,new Promise((G,B)=>{let H=()=>B(Z.reason);if(Z.addEventListener("abort",H,{once:!0}),J=()=>Z.removeEventListener("abort",H),Z.aborted)H()})]):await z}catch(z){if(this.#_(Z),Q1(z)==="unreachable")this.transportLost(z);else this.reachable();if(z instanceof V5)throw z;if(Q1(z)==="unreachable")throw new y1;throw new E("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#_(Z),this.reachable(),X}async discover($){let Z=await this.#S($);return this.#L=Z.view,Z}async#S($){let Z,X;try{X=await this.#T($)}catch(Y){throw this.#H.clear(),Y}try{Z=await this.#A(()=>this.#$.listScoped(X),$)}catch(Y){throw this.listFailed(Y),Y}let J=[],z=[],G=new Map;for(let Y of Z.rows){let Q=EG(Y,this.#J);if(!Q)continue;z.push({row:Y,type:Q}),G.set(Y.id,(G.get(Y.id)??0)+1)}let B=[];for(let{row:Y,type:Q}of z){let W;if(!Y.id.trim())W="empty credential id";else if((G.get(Y.id)??0)>1)W="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())W="blank account identity";else if(!Y.state.trim())W="empty state";if(W){J.push({...Y.id.trim()&&{credentialId:Y.id},reason:W});continue}B.push(Object.freeze({credentialId:Y.id,credentialType:Q,...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of J)this.#X.warn("skipped malformed vault record",Y);let H=IG(Z);return{view:Z.view,credentials:Object.freeze(B),skipped:Object.freeze(J),...H&&{grantReach:H}}}listFailed($){if(Q1($)==="unreachable")this.transportLost($);else this.reachable(),this.#H.clear()}forget($){this.#H.delete($)}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,J]of this.#H){let z=Z.get(X);if(!z?.enabled||z.state!=="active"||z.credentialType!==J.attempt.credentialType||z.accountIdentity!==J.attempt.expectedAccountIdentity)this.forget(X)}}keptReceiptState(){let $=null;for(let[Z,X]of this.#H){if(!this.#R(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#R($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#z()>j5}async authorize($,Z,X="vault"){this.#_(Z);let{credentialId:J,credentialType:z,accountIdentity:G}=$,B=this.#H.get(J);if(B&&(B.attempt.credentialType!==z||B.attempt.expectedAccountIdentity!==G))this.forget(J),B=void 0;let H;try{H=await this.#T(Z)}catch(Y){throw this.#H.clear(),Y}if(this.#U&&B)return this.#P(),this.#E(J,B,H,X);try{let Y=await this.#I({credentialId:J,credentialType:z,accountIdentity:G},H,Z);return this.#H.set(J,{attempt:Y,routeId:X,since:null}),Y}catch(Y){if(this.#_(Z),Q1(Y)!=="unreachable")throw this.forget(J),Y;return this.#E(J,B,H,X,Y)}}#E($,Z,X,J,z=this.#F){if(!Z||this.#H.get($)!==Z||!this.#R(Z.attempt))throw this.forget($),z;if(Z.since===null)Z.since=this.#z();let G=Object.freeze(Object.defineProperty({...Z.attempt,fromKeptReceipt:!0},"accessToken",{value:Z.attempt.accessToken,enumerable:!1}));return this.#W.set(G,X),this.#G.set(G,J),G}async#I($,Z,X){if(!$.credentialId)throw new E("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:z,accountIdentity:G}=$;if(this.#B&&G===void 0)throw new E("identity-unasserted","Claustrum dispatch requires a known account identity");let B=await this.#A(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Z,...z==="oauth"&&{minTtlMs:YZ}}),X);if(B.credentialId!==void 0&&B.credentialId!==J)throw new E("identity-changed","Claustrum served credential identity changed");let H=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||H===null&&z==="oauth"||H!==null&&(!Number.isFinite(H)||H-this.#z()<YZ))throw new E("insufficient-validity","Claustrum served credential has insufficient validity");let Y=RG(B.material),Q=B.accountId?.trim()?B.accountId:void 0;if(this.#B&&(B.credentialId===void 0||Q===void 0))throw new E("identity-unasserted","Claustrum served credential did not assert its identity");let W=Q===void 0?this.#Y?.(Y):void 0,V=Q??W;if(G!==void 0&&V!==void 0&&V!==G)throw new E("identity-changed","Claustrum served credential identity changed");let U=V??G,j=Object.freeze(Object.defineProperty({credentialId:J,credentialType:z,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":W!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:H},"accessToken",{value:Y,enumerable:!1}));return this.#W.set(j,Z),j}async reportFailure($,Z,X){if(Z!==401)return;this.#_();let J=this.#W.get($);if(!J)throw new E("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#G.get($);if(z!==void 0){this.forget($.credentialId),this.#X.debug("scoped 401 not reported",{routeId:z,reason:"kept-receipt"});return}let G=this.#H.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let B=this.#Q.get($);if(B)return B;let H=this.#A(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#Q.set($,H);try{await H,this.#X.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(Y){throw this.#Q.delete($),Y}}watchRoster($){this.#_();let Z=new e2({client:this.#$,enrollmentToken:()=>this.#T(),view:$.view??(()=>this.#L),discover:async(X)=>{await $.onView(X)},onRefused:(X)=>{this.listFailed(X),$.onRefused?.(X)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:$.onError,onMode:$.onMode,logger:this.#X,now:this.#z,setTimeoutImpl:this.#V,clearTimeoutImpl:this.#K});return this.#O.add(Z),Z.start(),{get mode(){return Z.mode},close:()=>{this.#O.delete(Z),Z.stop()}}}close(){if(this.#N)return;if(this.#N=!0,this.#D)this.#K(this.#D);this.#D=void 0;for(let $ of this.#O)$.stop();this.#O.clear(),this.#H.clear(),this.#$.close()}}import{resolve as OZ}from"node:path";function K5($,Z=""){let X=new Map,{observation:J}=$,z=(H,Y,Q)=>X.set(`${Z}:${H}`,{at:Y,order:0,publication:{...$,observation:Q}}),G=(H,Y)=>JSON.stringify([H??"all",Y]),B=new Set;for(let H of J.readings??[]){let Y=G(H.scope,H.label);B.add(Y),z(Y,J.checkedAt,{checkedAt:J.checkedAt,readings:[{...H}]})}for(let H of J.coverage??[]){let Y=G(H.scope,H.label);if(!B.has(Y))z(Y,J.checkedAt,{checkedAt:J.checkedAt,coverage:[{...H}]})}if(J.budget)z("budget",J.checkedAt,{checkedAt:J.checkedAt,budget:{...J.budget}});for(let[H,Y]of Object.entries(J.counters??{}))z(`counter:${H}`,Y.checkedAt,{checkedAt:J.checkedAt,counters:{[H]:{...Y}}});if(J.credits)z("credits",J.credits.checkedAt,{checkedAt:J.checkedAt,credits:{...J.credits}});if(!X.size)z("empty",J.checkedAt,{checkedAt:J.checkedAt});return X}import{createHash as bG}from"node:crypto";import{resolve as q5}from"node:path";function D5($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function WZ($,Z,X){return $.some((J)=>D5(J,Z,X))}function VZ($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function UZ($,Z,X){return $.filter((J)=>!Z.some((z)=>D5(J,z,X)))}var F5="vault:";function xG($){return bG("sha256").update($).digest("hex")}function kG($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function fG($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function K1($){return[$.credentialId,...$.aliases??[]]}function M5($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??F5,G=X.reservedRouteIds??new Set,B=$?.rows??[],H=[...$?.declined??[]],Y=Z.skipped.length===0,Q=new Set(Z.credentials.map((M)=>M.credentialId)),W=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),V=Z.skipped.some((M)=>M.credentialId===void 0),U=(M)=>!Q.has(M)&&(W.has(M)||V),K=new Map;for(let M of B){if(M.accountIdentity===void 0)continue;for(let N of K1(M))if(!K.has(N))K.set(N,M.accountIdentity)}let j=new Map;for(let M of Z.credentials){let N=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:K.get(M.credentialId),claimed:!1},L=fG(N),S=j.get(L)??[];S.push(N),j.set(L,S)}let q=new Set,D=new Set(G),F=[],_=(M,N)=>M.credential.credentialId.localeCompare(N.credential.credentialId),R=[...j.values()].map((M)=>M.toSorted(_)).sort((M,N)=>M[0]&&N[0]?_(M[0],N[0]):0);for(let M of R){let N=M[0]?.identity,L=M.filter((v)=>v.credential.state==="active"),S=L.length?L:M,T=S.filter((v)=>v.claimed),b=T.length?T:S,w=new Set(M.map((v)=>v.credential.credentialId)),f=B.find((v)=>!q.has(v)&&K1(v).some((p0)=>w.has(p0))&&(v.accountIdentity===void 0||v.accountIdentity===N)),g=b.find((v)=>v.credential.credentialId===f?.credentialId)??b[0];if(!g)continue;let h=g.credential,e=f??(N===void 0?void 0:B.find((v)=>!q.has(v)&&v.accountIdentity===N));if(e)q.add(e);let r=e?.routeId;if(!r||G.has(r)){let v=`${z}${h.credentialId}${N===void 0?"":`~${xG(N).slice(0,10)}`}`;r=v;for(let p0=2;D.has(r);p0++)r=`${v}~${p0}`}D.add(r);let Q2=e?K1(e).filter(U):[],l1=[...new Set([...M.map((v)=>v.credential.credentialId),...Q2])].filter((v)=>v!==h.credentialId).sort((v,p0)=>v.localeCompare(p0)),W2=X.mapAccount?.(h)??{};F.push({previousIndex:e?B.indexOf(e):1/0,row:{routeId:r,credentialId:h.credentialId,credentialType:h.credentialType,...N!==void 0&&{accountIdentity:N},...l1.length&&{aliases:l1},state:h.state,label:W2.label?.trim()||kG(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...l1].some((v)=>WZ(H,v,N)),addedAt:e?.addedAt??J,...e?.quota!==void 0&&{quota:e.quota},...!g.claimed&&N!==void 0&&{unclaimed:!0}}})}return B.forEach((M,N)=>{if(q.has(M)||!K1(M).some(U))return;if(D.has(M.routeId))return;let[L,...S]=K1(M).filter((w)=>!Q.has(w));if(L===void 0)return;D.add(M.routeId);let{aliases:T,...b}=M;F.push({previousIndex:N,row:{...b,credentialId:L,...S.length&&{aliases:S},stale:!0}})}),F.sort((M,N)=>M.previousIndex===N.previousIndex?M.row.credentialId.localeCompare(N.row.credentialId):M.previousIndex-N.previousIndex),{version:1,view:Z.view,complete:Y,...!Y&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:F.map((M)=>M.row),declined:H}}function jZ($){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 s$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y$($){return $===void 0||typeof $==="string"}function yG($){let Z=s$($)?T1($.quota):void 0;if(!s$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!Y$($.accountIdentity)||!Y$($.email)||!Y$($.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 gG=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function N5($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!s$(X)||!Y$(X.credentialId)||typeof X.reason!=="string"||!gG.has(X.reason))return;Z.push(X)}return Z}function hG($){if(!s$($)||$.version!==1||!Y$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!N5($.rejected))throw new E("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=yG(z);if(!G)throw new E("invalid-state","Claustrum roster file is not valid");Z.push(G)}let X=[];for(let z of $.declined){if(!s$(z)||typeof z.credentialId!=="string"||!Y$(z.accountIdentity))throw new E("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=N5($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function K0($){let Z;try{Z=await L0($,I)}catch(J){if(J.code==="ENOENT")return;throw J}let X;try{X=JSON.parse(Z)}catch{throw new E("invalid-state","Claustrum roster file is not valid")}return hG(X)}var vG={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},mG={name:"claustrum-roster",ttlMs:30000};async function h1($,Z,X={}){return Y3($,{...vG,signal:X.signal},async(J)=>{let z=await K0($),{next:G,result:B}=await Z(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await _0($,G,{beforeRename:async()=>{await X.beforePublish?.(),X.signal?.throwIfAborted(),await J.assertOwned()}});return B})}function KZ($,Z){return h1($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z);if(!X||!J)throw new E("route-unavailable","Claustrum route is not in the roster");let z=VZ(X.declined,J.credentialId,J.accountIdentity);return{next:{...X,declined:z,rows:X.rows.map((G)=>G===J?{...G,enabled:!1}:G)},result:void 0}})}function DZ($,Z){return h1($,(X)=>{let J=X?.rows.find((z)=>z.routeId===Z);if(!X||!J)throw new E("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:UZ(X.declined,K1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function wG($){return new E("invalid-order",$)}function pG($,Z){if(!Array.isArray(Z))return"route ids must be an array of route ids";let X=new Set($.map((G)=>G.routeId)),J=new Set;for(let G of Z){if(typeof G!=="string")return"route ids must be an array of route ids";if(J.has(G))return`route id ${G} appears more than once`;if(!X.has(G))return`route id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G)).length;if(z>0)return`the order leaves out ${z} roster route id${z===1?"":"s"}`;return}function NZ($,Z,X={}){return h1($,(J)=>{let z=J?.rows??[],G=pG(z,Z);if(G)throw wG(G);let B=new Map;for(let Q of z){let W=B.get(Q.routeId);if(W)W.push(Q);else B.set(Q.routeId,[Q])}let H=[...Z],Y=H.flatMap((Q)=>B.get(Q)??[]);if(!J||Y.every((Q,W)=>Q===z[W]))return{result:{ids:H,outcome:"unchanged"}};return{next:{...J,rows:Y},result:{ids:H,outcome:"reordered"}}},{...X.signal&&{signal:X.signal}})}function lG($,Z){if(!K1($).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")&&K1($).length===1)return"bind";return"refuse"}async function qZ($,Z){let{routeId:X,observation:J,...z}=Z;return L5($,{routeId:X,observation:J,accountIdentity:z.accountIdentity,receipt:z})}async function L5($,Z){if(!d1(Z.observation))return!1;let X=v0($,await K0($));if(!D1(X,Z).kept)return!1;return _5($,Z)}function FZ($,Z){return L5($,Z)}function D1($,Z){let X=$?.rows.find((B)=>B.routeId===Z.routeId),J=!X?"refuse":Z.receipt?lG(X,Z.receipt):X.accountIdentity!==void 0&&X.accountIdentity===Z.accountIdentity?"hold":"refuse";if(!$||!X||J==="refuse")return{roster:$,kept:!1};let z=u0(X.quota,Z.observation),G=J==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{roster:{...$,rows:$.rows.map((B)=>B===X?{...B,...G,quota:z}:B)},kept:!0}}var W6=new Map;function MZ($){W6.delete(q5($))}async function LZ($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){MZ($.path);return}let X=await J0({...mG,path:$.path,renew:!0});if(!X){let G=await K0($.path);if($.signal?.throwIfAborted(),!G?.view)throw new E("roster-busy","Claustrum account discovery is already in progress");return G}let J=q5($.path),z;try{let G=await K0($.path),B=W6.get(J);z=B&&(B.previousView===G?.view||B.inventory.view===G?.view)?B:{inventory:await $.custody.discover($.signal),previousView:G?.view},W6.delete(J);let{inventory:H}=z;return $.onInventory?.(H),$.signal?.throwIfAborted(),await h1($.path,async(Y)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let Q=typeof $.projection==="function"?$.projection():$.projection,W=M5(Y,H,Q);return{...JSON.stringify(Y)!==JSON.stringify(W)&&{next:W},result:W}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(G){if(G instanceof s0&&z&&!$.signal?.aborted&&await Z())W6.set(J,z);throw G}finally{await X.release()}}var Q$=new Map,uG=u("claustrum"),O5=100;function P5($){let Z=OZ($),X=Q$.get(Z);if(!X)X={path:Z,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},Q$.set(Z,X);return X}function C5($,Z){let X=P5($);X.listeners.add(Z);let J;return()=>J??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():_Z($)})()}function dG($){return K5($,JSON.stringify([$.routeId,$.receipt?.credentialId,$.receipt?.accountIdentitySource,$.receipt?.expectedAccountIdentity]))}function _5($,Z){if(!d1(Z.observation))return Promise.resolve(!1);let X=P5($),J=JSON.stringify([Z.accountIdentity??null,Z.accountIdentity===void 0?Z.routeId:null]),z=X.pending.get(J)??new Map;for(let[G,B]of dG(Z)){let H=z.get(G);if(!H||B.at>=H.at){if(B.order=++X.order,B.publication.observation.coverage)B.priorReading=H?.publication.observation.readings?H.publication:H?.priorReading;z.set(G,B)}}if(z.size)X.pending.set(J,z);for(let G of X.listeners)G(Z);return A5(X,O5),Promise.resolve(!0)}function T5($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function v0($,Z){let X=Q$.get(OZ($));if(X)for(let J of T5(X.pending)){if(J.priorReading)Z=D1(Z,J.priorReading).roster;Z=D1(Z,J.publication).roster}return Z}function A5($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,S5($)},Z),!$.draining)$.timer.unref?.()}function S5($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([X,J])=>[X,new Map(J)]));$.running=(async()=>{try{await h1($.path,(X)=>{let J=X;for(let z of T5(Z)){if(z.priorReading)J=D1(J,z.priorReading).roster;J=D1(J,z.publication).roster}return{...J!==X&&{next:J},result:void 0}},{signal:$.abort.signal});for(let[X,J]of Z){let z=$.pending.get(X);for(let[G,B]of J)if(z?.get(G)===B)z.delete(G);if(!z?.size)$.pending.delete(X)}$.failures=0}catch(X){if(!$.abort.signal.aborted&&$.failures++===0)uG.warn("vault quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{$.running=void 0;for(let J of $.wake)J();let X=$.failures?Math.min(5000,100*2**Math.min($.failures,6))*(0.5+Math.random()):O5;A5($,X)}})()}async function _Z($,Z=1000){let X=OZ($),J=Q$.get(X);if(!J)return;J.draining=!0,clearTimeout(J.timer),J.timer=void 0;let z,G,B=new Promise((H)=>{G=()=>{if(!J.pending.size||J.abort.signal.aborted)H()},J.wake.add(G),G()});try{if(J.pending.size)S5(J);await Promise.race([B,new Promise((H)=>{z=setTimeout(H,Math.max(0,Z))})])}finally{if(clearTimeout(z),G)J.wake.delete(G);if(J.draining=!1,!J.listeners.size){if(J.abort.abort(),clearTimeout(J.timer),J.pending.clear(),Q$.get(X)===J)Q$.delete(X)}}}class V6{#$;#Z=new AbortController;#z;#J;#Y;#B;#X;#W;#Q;#H=!1;#G;#V;#K;#U=new Map;#F;#D;constructor($){this.#$=$,this.#z=$.logger??u("claustrum"),this.#D=C5($.rosterPath,(Z)=>{this.#X=D1(this.#X,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#q(){return await this.#$.isCustodyActive?.()??!0}#M($,Z){let X=a3([this.#Z.signal,...Z?[Z]:[]]);return new Promise((J,z)=>{let G=()=>{X.signal.removeEventListener("abort",B),X.dispose()},B=()=>{G(),z(X.signal.reason)};if(X.signal.addEventListener("abort",B,{once:!0}),$.then((H)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(H)},(H)=>{G(),z(H)}),X.signal.aborted)B()})}async#N(){if(this.#j(),this.#J)return this.#J;if(!this.#Y)this.#Y=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#j();if(this.#J=new Q6({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#z,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl}),this.#$.insula&&$.insula)this.#G=s3($.insula,this.#$.tokenPath);return this.#J}).finally(()=>{this.#Y=void 0});return this.#M(this.#Y)}snapshot(){return this.#X}grantReach(){let $=this.#W;return $&&this.#X?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#V?.mode??"polling",...this.#$.insula&&{insula:this.#G?.source.watchMode()??"polling"}})}#L(){this.#V?.close(),this.#V=void 0,this.#K?.(),this.#K=void 0}keptReceiptState(){return this.#J?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return jZ(this.#X)}refresh(){if(this.#j(),this.#B)return this.#B;return this.#B=(async()=>{if(!await this.#q()){this.#X=void 0,this.#W=void 0,this.#L(),this.#J?.close(),this.#J=void 0,this.#G?.release(),this.#G=void 0;return}let $=await this.#N(),Z,X=await LZ({path:this.#$.rosterPath,custody:$,onInventory:(z)=>{Z=z},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.#j();let J=X?.view!==this.#X?.view;if(this.#X=v0(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&&J)this.#$.onRoster?.(X);return this.#F=(this.#$.now??Date.now)(),X})().finally(()=>{this.#B=void 0}),this.#B}start(){if(this.#H)return;this.#j(),this.#H=!0;let $=async()=>{try{if(await this.#O())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,$()},Z),this.#Q.unref?.()};$()}async#O(){if(this.#V?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#F===void 0||$-this.#F>=u3)return!0;return!await this.#q()}#C(){let $=this.#J;if(this.#Z.signal.aborted||!$)return;if(this.#V??=$.watchRoster({view:()=>this.#X?.view,onView:async()=>{while(this.#B)await this.#B.catch(()=>{});await this.refresh()},onRefused:(Z)=>this.#$.onError?.(Z),onError:(Z)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Z)}}),this.#$.insula&&this.#G&&!this.#K)this.#K=this.#G.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{await j1(this.#$.tokenPath),await this.#N(),await this.#G?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#q())return;try{return await j1(this.#$.tokenPath),this.#P($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#q())return;try{await j1(this.#$.tokenPath);let X=v0(this.#$.rosterPath,await K0(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$);return this.#P(X?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute($){let Z=this.#$.insula;if(!Z||this.#Z.signal.aborted||!await this.#q())return{miss:"unreachable"};try{await j1(this.#$.tokenPath);let J=v0(this.#$.rosterPath,await K0(this.#$.rosterPath))?.rows.find((B)=>B.routeId===$)?.accountIdentity;if(!J||!this.#G)return{miss:"unreachable"};let z=this.#G.source.lookup(Z.provider,J,(this.#$.now??Date.now)()),G=z.reading&&Z.normalize(z.reading.entry,z.reading.context);if(z.miss)return{miss:z.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute($,Z){let X=await this.lookupInsulaQuotaForRoute($);if(X.miss==="cold"||X.miss==="upstream-failed"){if(this.#U.get($)!==X.miss)this.#U.set($,X.miss),this.#z.warn("skipped insula provider poll",{reason:X.miss});return}return this.#U.delete($),X.miss?Z():X.reading}#P($){if(!this.#$.insula||!$)return;let Z=this.#G?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#j(Z);let X=this.#X??await this.#M(this.refresh(),Z);if(!X||!await this.#q())throw this.#J?.close(),this.#J=void 0,this.#L(),this.#G?.release(),this.#G=void 0,new E("not-active","Claustrum scoped custody is not active");let J=v0(this.#$.rosterPath,await K0(this.#$.rosterPath));this.#j(Z);let z=X.rows.find((Y)=>Y.routeId===$),G=J?.rows.find((Y)=>Y.routeId===$);if(G&&!G.enabled){if(z)this.#J?.forget(z.credentialId);throw new E("route-declined","Claustrum route is disabled")}if(!z||!G||G.state!=="active"||G.credentialId!==z.credentialId||G.accountIdentity!==z.accountIdentity||G.credentialType!==z.credentialType){if(z)this.#J?.forget(z.credentialId);throw new E("route-unavailable","Claustrum route is disabled, removed or changed")}let B=await this.#M(this.#N(),Z),H=a3([this.#Z.signal,...Z?[Z]:[]]);try{return await B.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},H.signal,$)}finally{H.dispose()}}async reportFailure($,Z,X){if(this.#j(),!this.#J)throw new E("no-receipt","Claustrum dispatch receipt has no active owner");await this.#J.reportFailure($,Z,X)}async send($,Z,X){let J=X.signal,z=await this.authorize($,J),G=await Z(z,J);if(G.status===401&&z.fromKeptReceipt)return await this.reportFailure(z,401,X.reporterSource??"direct"),G;if(G.status===401&&!J?.aborted){let B;try{B=await this.authorize($,J),J?.throwIfAborted()}catch(H){if(J?.aborted)throw H}if(QZ(X.site,z,B,this.#z))await G.body?.cancel().catch(()=>{}),z=B,G=await Z(B,J)}if(G.status===401)await this.reportFailure(z,401,X.reporterSource??"direct").catch((B)=>this.#$.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(B)});return G}async decline($){this.#j(),await KZ(this.#$.rosterPath,$),this.#X=v0(this.#$.rosterPath,await K0(this.#$.rosterPath)),this.#J?.retain(this.#X?.rows??[])}async accept($){this.#j(),await DZ(this.#$.rosterPath,$),this.#X=v0(this.#$.rosterPath,await K0(this.#$.rosterPath))}async reorder($){this.#j();let Z=await NZ(this.#$.rosterPath,$);return this.#X=v0(this.#$.rosterPath,await K0(this.#$.rosterPath)),Z}async recordQuota($,Z,X){return this.#j(),qZ(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.#j(),FZ(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X})}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new E("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#L(),this.#J?.close(),this.#G?.release(),this.#G=void 0,this.#X=void 0,this.#W=void 0,this.#D(),MZ(this.#$.rosterPath)}async dispose(){this.close(),await this.#D()}}async function R5($){let Z=await cG.connect($);return Object.assign(Z,{insula:l9($)})}var sG=H6("openai");function E5($){return Y6($)}function m0($){if(!$||$.corrupt===!0)return!1;return E5($.refresh)}class a$ 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 U6($){if(E5($))throw new a$}function o0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var aG=u("quota");var iG="app_EMoamEEZ73f0CkXaXp7hrann",nG="https://auth.openai.com";async function I5($){U6($.refreshToken);let Z=await $.fetchImpl(`${nG}/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:iG}).toString()});if(!Z.ok){let z=v3(Z.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${Z.status}`),{status:Z.status,retryAfter:z,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 J=typeof X.refresh_token==="string"&&X.refresh_token?X.refresh_token:$.refreshToken;return{access:X.access_token,refresh:J,expires:$.now()+X.expires_in*1000,expiresIn:X.expires_in}}var rG="https://chatgpt.com/backend-api/wham/usage";async function W$($){let Z=$.logger??aG,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await $.fetchImpl(rG,{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(!z.ok){let B=v3(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:B})}let G=v9(await z.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:z.status,elapsedMs:Date.now()-J}),G}catch(z){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof z?.status==="number"?z.status:"error",elapsedMs:Date.now()-J,error:o0(z)}),z}}import{createHash as eG}from"node:crypto";var $B=globalThis.setTimeout,ZB=5;function i$($){let Z=$?.quota?.checkIntervalMinutes??ZB;return Math.max(1,Z)*60000}function XB($){return $?.quota?.enabled!==!1}function CZ($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function JB($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function b5($,Z,X){if(!XB(Z))return X+i$(Z);let J=JB(Z),z=[];for(let G of["primary","secondary"]){let B=$?.[G];if(!B)continue;if(B.remainingPercent>=J[G])continue;let H=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(H)||H<=X)return X+i$(Z);z.push(H)}if(!z.length)return X+i$(Z);return Math.min(...z)+60000}function zB($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function GB($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function P0($){return eG("sha256").update($).digest("hex").slice(0,16)}class N1{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!==P0($))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($)!==P0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!x5(Z.quota))return;if(this.mainTokenFp=P0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,PZ(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,J=!1,z){if(!J&&!x5(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(z&&G&&z!==G)this.clearRateLimited($);let B=z??G;if(this.fallbacks.set($,{...Z,accountId:B}),X)this.fallbackTokenFps.set($,P0(X));else this.fallbackTokenFps.delete($);if(PZ(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=P0($);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=N1.fallbackInflightKey($,Z),J=this.inflightFallbacks.get(X);if(J)return J;if(this.isFallbackBackedOff($,Z)){let G=this.getFallback($,Z);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback($,Z);return this.inflightFallbacks.set(X,z),z}async refreshAllFallbacks($){let Z=this.now();for(let X of $){if(X.enabled===!1)continue;if(m0(X)||!X.access)continue;let J=this.getFallback(X.id,X.access);if(J&&Z<J.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground($){let Z=P0($);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=GB(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=zB($);if(!X)return;let J=Z?P0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:b5(X.quota,$,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!J||!this.mainTokenFp||this.mainTokenFp===J))return;if(this.main=z,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&&G$(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 J=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(J<=0)continue;let z=this.getFallback(X.id,X.access);if(z&&z.checkedAt>=J)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:J+Z,checkedAt:J},X.access,!1,X.accountId)}}isBackedOff(){return G$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==P0(Z))return!1}return G$(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,P0(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let J=this.now()-this.lastApiCallAt;if(J<N1.API_CALL_GAP_MS)await new Promise((z)=>{let G=$B(z,N1.API_CALL_GAP_MS-J);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},X=this.apiGate.then(Z,Z);return this.apiGate=X.catch(()=>{}),X}async _fetchMain($){let Z=P0($);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 J0({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let J=this.main;if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=this.now(),z=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=P0($),this.main={quota:z,refreshAfter:b5(z,this.storage,G),checkedAt:G},PZ(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,G,this.mainTokenFp,J),z}catch(J){throw this._handleMainFetchError(J),J}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 J=this.getFallback($,Z);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let X=await J0({name:N1.quotaLockName($),ttlMs:30000,path:this.configPath});if(!X){let J=this.getFallback($,Z);if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=await this._fetchQuota(Z),z=this.now();return this.setFallback($,{quota:J,refreshAfter:z+i$(this.storage),checkedAt:z},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),J}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError($,Z,X),X}finally{this.inflightFallbacks.delete(N1.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(N1.isAuthError($))return;this.mainLastApiError=h$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(N1.isAuthError(X))return;let J=P0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,h$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function x5($){return Boolean($.primary||$.secondary)}function PZ($){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{readFile as _B}from"node:fs/promises";var v1=u("refresh"),SZ=u("accounts"),QB=1e4,WB=15000,TZ=50;function q1($){return $.type==="oauth"&&$.corrupt!==!0}function VB($){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 U$="floors-v1";class K6 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var UB=[401,403,429],k5={primary:0,secondary:0},jB=!1,F1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var KB=new Set(["__proto__","constructor","prototype"]);function bZ($){return $.length>0&&!KB.has($)}function DB($){return $ instanceof K6||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function j6($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():HB(),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 f5($){if(!k($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let X=Number($.nextRetryAt),J=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(J)?J:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function NB($){if(!k($))return;let Z={};for(let z of["primary","secondary"]){let G=$[z];if(!k(G))continue;let B=Number(G.usedPercent),H=Number(G.remainingPercent),Y=Number(G.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(H)||!Number.isFinite(Y))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[z]={usedPercent:B,remainingPercent:H,checkedAt:Y,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let z of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[z]==="number"?$[z]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[z]=G}let X=$.spendControl;if(k(X)){let z=Number(X.limit),G=Number(X.used),B=Number(X.remaining),H=Number(X.usedPercent),Y=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(H)&&Number.isFinite(Y)&&typeof X.reached==="boolean")Z.spendControl={limit:z,used:G,remaining:B,usedPercent:H,remainingPercent:Y,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 J=$.credits;if(k(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&(J.overageLimitReached===void 0||typeof J.overageLimitReached==="boolean")){let z=Number(J.balance),G=typeof J.checkedAt==="number"?J.checkedAt:Number.NaN;Z.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,...typeof J.overageLimitReached==="boolean"?{overageLimitReached:J.overageLimitReached}:{},...Number.isFinite(z)?{balance:z}:{},...Number.isFinite(G)?{checkedAt:G}:{}}}return Object.keys(Z).length?Z:void 0}function qB($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!VB(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...j6($),type:"api",apiKey:X||void 0,baseURL:Z,authHeader:J}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...j6($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...j6($),type:"oauth",corrupt:!0}}return{...j6($),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:f5($.lastRefreshError),lastQuotaRefreshError:f5($.lastQuotaRefreshError),quota:NB($.quota)}}function FB($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!bZ(X)||!k(J))continue;let z={};if(k(J.inFlight))z.inFlight={...J.inFlight};if(k(J.lastOutcome)&&typeof J.lastOutcome.code==="string"&&J.lastOutcome.code.length>0&&typeof J.lastOutcome.at==="number"&&Number.isFinite(J.lastOutcome.at))z.lastOutcome={code:J.lastOutcome.code,at:J.lastOutcome.at,...k(J.lastOutcome.previousOutcome)&&typeof J.lastOutcome.previousOutcome.code==="string"&&J.lastOutcome.previousOutcome.code.length>0&&typeof J.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(J.lastOutcome.previousOutcome.at)?{previousOutcome:{code:J.lastOutcome.previousOutcome.code,at:J.lastOutcome.previousOutcome.at}}:{}};if(typeof J.cooldownUntil==="number"&&Number.isFinite(J.cooldownUntil))z.cooldownUntil=J.cooldownUntil;if(Object.keys(z).length>0)Z[X]=z}return Object.keys(Z).length>0?Z:void 0}var y5=new Set;function MB($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(y5.has(Z))return;y5.add(Z),SZ.warn("account load-dropped, preserved on disk",{droppedIds:$})}function LB($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(qB).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let B of Z)if(k(B)&&typeof B.id==="string"&&B.id.trim())J.add(B.id.trim());let z=new Set(X.map((B)=>B.id)),G=[];for(let B of J)if(!z.has(B))G.push(B);MB(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:k($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:k($.refresh)?$.refresh:void 0,quota:k($.quota)?$.quota:void 0,reset:FB($.reset),dump:k($.dump)?$.dump:void 0,costZeroing:k($.costZeroing)?$.costZeroing:void 0,killswitch:k($.killswitch)?$.killswitch:void 0,logging:k($.logging)?$.logging:void 0,cachekeep:k($.cachekeep)?$.cachekeep:void 0,cacheKeep:k($.cacheKeep)?$.cacheKeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,accounts:X}}async function D6($){try{return{exists:!0,value:JSON.parse(await _B($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function N6($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function OB($){let Z;try{Z=(await D6($)).value}catch{return null}return xB(Z)}function PB($,Z){if(!k($))return $;let X=k(Z)?Z:{},J=k(X.main)?X.main:void 0,z=k(X.accounts)?X.accounts:{},G=k($.quota)?$.quota:{},B=k($.refresh)?$.refresh:{},H=J??G,Y=J??B,W=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:Y.refreshLeaseId,until:Y.refreshLeaseUntil,tokenHash:Y.refreshLeaseTokenHash},U=Array.isArray($.accounts)?$.accounts.map((K)=>{if(!k(K))return K;let j=typeof K.id==="string"&&k(z[K.id])?z[K.id]:{};return{...K,...j}}):void 0;return CB({...$,refresh:N6({...B,mainLastRefreshError:B.mainLastRefreshError??Y.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:N6({...G,mainQuota:H.quota,mainQuotaCheckedAt:H.quotaCheckedAt,mainQuotaToken:H.quotaToken,mainLastQuotaApiError:H.lastQuotaApiError}),accounts:U})}async function xZ($){let Z=await D6($.configPath);if(!Z.exists)return null;let X=await D6($.statePath);return LB(PB(Z.value,X.value))}function CB($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function TB($){if($.type==="api")return N6({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return N6({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function q6($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function n$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function AB($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function SB($,Z){if(!AB($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var RB=300000;function g5($,Z){if($===void 0)return 0;return $>Z+RB?0:$}function EB($,Z,X){let J=Date.now(),z=g5(Z.lastRefreshedAt,J),G=g5(X.lastRefreshedAt,J),B=Z.expires??0,H=X.expires??0,Y=G>z?X:z>G?Z:H>B?X:B>H?Z:SB(Z,X);n$($,Y,"access"),n$($,Y,"refresh"),n$($,Y,"expires"),n$($,Y,"lastRefreshedAt"),n$($,Y,"lastRefreshError")}function IB($,Z){if(!k($))return Z;let X=$,J=q6(X.quota),z=q6(Z.quota),G=J>z,B=G?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete B.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))B.lastUsed=X.lastUsed;return EB(B,X,Z),B}async function bB($,Z=!1){let X=Date.now(),J=X+WB,z=0;while(Date.now()<=J){z++;let H=await J0({name:"save",ttlMs:QB,path:$,renew:Z});if(H)return H;let Y=J-Date.now();if(Y<=0)break;await YB(Math.min(TZ+u5(TZ),Y))}let G=Date.now()-X,B=Math.round(G/Math.max(1,z));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${z} attempts, ~${B}ms apart; retry interval is ${TZ}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 xB($){if(!k($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let X of $.accounts){if(!k(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;Z.add(J)}return Z}function kB($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:q6($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:q6(Z.quota?.mainQuota);if(X>J)return;$.main.quota=Z.quota?.mainQuota,$.main.quotaCheckedAt=Z.quota?.mainQuotaCheckedAt,$.main.quotaToken=Z.quota?.mainQuotaToken,$.main.lastQuotaApiError=Z.quota?.mainLastQuotaApiError}function fB($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function RZ($){if(Array.isArray($))return $.map(RZ);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,RZ(X)]))}async function yB($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await bB(z);try{let B=(await D6(z)).value,H=k(B)?{...B,version:1}:{version:1};if(X.mainQuota)kB(H,$);if(X.mainRefresh)fB(H,$);if(X.accounts){let Y=X.accounts===!0?null:new Set(X.accounts),Q=await OB(Z.configPath);H.accounts={...k(H.accounts)?H.accounts:{}};for(let W of $.accounts){if(Y&&!Y.has(W.id))continue;if(Q&&!Q.has(W.id))continue;H.accounts[W.id]=IB(H.accounts[W.id],TB(W))}if(Y){for(let W of Y)if(!$.accounts.some((V)=>V.id===W))delete H.accounts[W]}if(Q){for(let W of Object.keys(H.accounts))if(!Q.has(W))delete H.accounts[W]}}if(J&&!J())return;await _0(z,RZ(H))}finally{await G.release()}}function p5($){return $?.fallbackOn?.length?$.fallbackOn:UB}function gB($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??k5.primary,secondary:Z.secondary??Z["1w"]??k5.secondary}}function EZ($){return $?.quota?.enabled!==!1}function o$($){return $?.quota?.failClosedOnUnknownQuota??jB}function F6($,Z,X=Date.now()){if(!EZ(Z))return!0;if(!$)return!o$(Z);let J=gB(Z),z=o$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(CZ(B,X)){if(z)return!1;continue}if(B.remainingPercent<J[G])return!1}return!0}function kZ($){return $?.killswitch?.enabled===!0}function h5($){return{primary:$?.primary??$?.["5h"]??F1.primary,secondary:$?.secondary??$?.["1w"]??F1.secondary}}function v5($){return typeof $==="number"&&Number.isFinite($)?$:0}function M1($,Z){if(!$?.killswitch)return F1;if($.killswitch.schema===U$){let{accounts:X,defaults:J}=$.killswitch,z=Z??"main",G=k(X)&&Object.hasOwn(X,z)&&k(X[z])?X[z]:k(J)?J:void 0;return{primary:v5(G?.primary),secondary:v5(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return h5($.killswitch.accounts[Z]);return h5($.killswitch.main)}function l5($,Z,X,J=Date.now()){if(!kZ(Z))return!0;if(!$)return!o$(Z);let z=M1(Z,X),G=o$(Z);for(let B of["primary","secondary"]){let H=$[B];if(!H)continue;if(CZ(H,J)){if(G)return!1;continue}if(H.remainingPercent<z[B])return!1}return!0}function hB($){return $?.refresh?.enabled!==!1}function fZ($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function u5($){return Math.floor(Math.random()*($+1))}function m1($,Z,X){return!$.access||!$.expires||$.expires-X<=fZ(Z)}function vB($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function V$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class d5 extends Error{constructor($){super(`Refusing to refresh account ${$}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}function D0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function r$($){return $ instanceof Error?$.message:String($)}function IZ($,Z,X){if(Z instanceof a$)return;$.lastRefreshError=c2({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function AZ($,Z,X){if(Z instanceof a$)return;if($.lastQuotaRefreshError=h$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)IZ($,Z,X)}function m5($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function mB($,Z){if(!$)return!1;return m5($.primary,Z)||m5($.secondary,Z)}function wB($,Z,X){if(!$)return!1;let J=Z?.quota?.checkIntervalMinutes??5,z=Math.max(1,J)*60000,G=Math.max($.primary?.checkedAt??0,$.secondary?.checkedAt??0);return X-G<z}function w5($,Z,X){return!wB($.quota,Z,X)}function pB($,Z,X,J){return h3(X)&&F6($.quota,Z,J)&&mB($.quota,J)}function lB($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var uB=60000,dB=60000,cB=600000;function sB($){return`fallback-oauth-refresh-${BB("sha256").update($).digest("base64url").slice(0,16)}`}var aB=1e4,iB=100;class nB{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($)U6($.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 J=this.quotaManager.getFallback($.id,$.access);if(J&&J.checkedAt>=X)return;this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:X+lB(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return xZ(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await yB($,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(()=>{})},uB+u5(dB)),"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=[],J=!1;for(let z of Z.accounts){if(z.enabled===!1||!q1(z))continue;if(V$(Z,z))continue;if(m0(z))continue;let G=!1,B=z;try{if(m1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&H1(H,B.refresh,this.now()))throw G=!0,Error(g$(H,this.now()));try{B=await this.refreshAccount(B,Z),J=!0}catch(Y){if(DB(Y))continue;G=!0;let Q=Z.accounts.find((W)=>W.id===z.id&&q1(W));if(Q&&!H1(Q.lastRefreshError,Q.refresh,this.now()))IZ(Q,Y,this.now()),D0(Z,Q),J=!0;throw Y}}if(this.seedFallbackQuota(B,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),Z))X.push(B)}catch(H){let Y=vB(B,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(pB(B,Z,H,this.now()))v1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:r$(H)}),X.push(B);else if(!o$(Z))X.push(B)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{SZ.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:r$(G)})})}return X}async markUsed($){try{let Z=await this.load();if(!Z)return;let X=Z.accounts.find((J)=>J.id===$.id);if(!X)return;X.lastUsed=this.now(),await this.save(Z,[X.id])}catch(Z){SZ.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:r$(Z)})}}accountPassesQuotaPolicy($,Z){return F6($.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(!$||!hB($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!q1(X))continue;if(V$($,X))continue;if(m0(X))continue;if(!m1(X,$,this.now()))continue;if(H1(X.lastRefreshError,X.refresh,this.now()))continue;try{v1.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(J){v1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:r$(J)}),IZ(X,J,this.now()),D0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!EZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!q1(X))continue;if(V$($,X))continue;if(m0(X))continue;let J=X;try{if(m1(J,$,this.now())){if(H1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(G$(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):w5(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){AZ(X,z,this.now()),D0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!EZ(Z))return{storage:Z,errors:X};if(!this.options.fetchQuotaFn)return{storage:Z,errors:X};let J=$.force??!1,z=!1;for(let G of Z.accounts){if(G.enabled===!1||!q1(G))continue;if(V$(Z,G))continue;if(m0(G))continue;let B=G;try{if(m1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&H1(H,B.refresh,this.now()))throw Error(g$(H,this.now()));B=await this.refreshAccount(B,Z),z=!0}if(!J&&!w5(B,Z,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,D0(Z,B),z=!0;continue}await this.refreshAccountQuota(B,Z),z=!0}catch(H){AZ(G,H,this.now()),D0(Z,G),z=!0,X.push({accountId:G.id,message:r$(H)})}}if(z)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let J=this.refreshPromises.get($.id);if(J){let B=await J;return D0(Z,B),B}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return D0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+aB;while(Date.now()<z){await new Promise((Q)=>setTimeout(Q,iB));let G=await this.load(),B=G?.accounts.find((Q)=>Q.id===$.id&&q1(Q));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==X.access||B.refresh!==X.refresh||(B.expires??0)>(X.expires??0)+60000)&&(J.force||!m1(B,G,this.now())))return D0(Z,B),v1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let Y=B.lastRefreshError;if(Y&&H1(Y,B.refresh,this.now()))throw D0(Z,B),Error(g$(Y,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(V$($,Z))throw new d5(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((H)=>H.id===$.id&&q1(H));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!m1(z,J,this.now()))return D0(Z,z),z;let G=z??$,B=await J0({name:sB(G.id),ttlMs:cB,path:this.paths.configPath,renew:!0});if(!B){v1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let H=await this.waitForConcurrentFallbackRefresh($,Z,G,X);if(H)return H;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((W)=>W.id===$.id&&q1(W)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!m1(z,J,this.now()))return D0(Z,z),z;if(!z)throw new K6($.id);G=z;let H=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});v1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:X.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let Y=await H({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=Y.access,G.refresh=Y.refresh,G.expires=Y.expires,G.lastRefreshedAt=Y.expires-Y.expiresIn*1000,G.lastRefreshError=void 0,D0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new K6($.id);return v1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await B.release()}}async refreshAccountQuota($,Z){let X=$;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${$.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let J=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(G)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,G):J({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${$.id} has no access token`);let G=await z(X.access);X.quota=G,X.lastQuotaRefreshError=void 0,D0(Z,X),await this.save(Z)}catch(G){throw AZ($,G,this.now()),D0(Z,$),G}}}var c5="/backend-api/wham/rate-limit-reset-credits",dK=`https://chatgpt.com${c5}`,rB=`${c5}/consume`,cK=`https://chatgpt.com${rB}`;function a($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as XH}from"node:fs";import{rm as n5}from"node:fs/promises";import{dirname as JH,join as r5}from"node:path";import{resolveClaustrumConnectionPath as zH}from"@cortexkit/claustrum-client";function s5($,Z){if(!$)return;let X=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(X)||X<0||X>100)return;return{usedPercent:X,remainingPercent:100-X,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function yZ($){if(!a($)||typeof $.minor!=="number"||!Number.isSafeInteger($.minor)||typeof $.exponent!=="number"||!Number.isInteger($.exponent))return;let Z=$.minor/10**$.exponent;return Number.isFinite(Z)?Z:void 0}function oB($){let Z=yZ($.total),X=yZ($.remaining);if(Z===void 0||X===void 0||Z<0||X<0)return;let J=Z-X,z=$.spendable===!1,G=Z>0?J/Z*100:z?100:0;return{limit:Z,used:J,remaining:X,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...a($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function tB($,Z){if(!a($))return;let X=yZ($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...X!==void 0&&X>=0&&{balance:X},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function gZ($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&a(Z)&&a(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function a5($,Z){let X=s5($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=s5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Q)=>a(Q)&&Q.id==="individual_limit"):void 0,G=a(z)?oB(z):void 0,B=Array.isArray($.spend)?$.spend.find((Q)=>a(Q)&&Q.id==="credits"):void 0,H=tB(B,Z.fetchedAt),Y=a($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...H&&{credits:H},...H&&a(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...J&&{secondary:J},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var i5=["primary","secondary"];function M6($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function j$($){return typeof $==="number"&&Number.isFinite($)}function eB($,Z){if(!M6(Z))return;let X=Z.usedPercent;if(!j$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...j$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function $H($){let Z=$.spendControl;if(M6(Z)&&typeof Z.reached==="boolean"){let X=(J)=>j$(Z[J])?{[J]:Z[J]}:{};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 ZH($,Z){if(!M6($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...j$($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function R0($,Z,X){if(!M6($)||!j$(Z))return;let J=[],z=[];for(let Q of i5){let W=eB(Q,$[Q]);if(W)J.push(W);else if(X)z.push({label:Q})}let G=$H($),B=$.resetCreditsAvailable,H=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:Z}}:void 0,Y=ZH($.credits,Z);if(J.length===0&&z.length===0&&!G&&!H&&!Y)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{},...H?{counters:H}:{},...Y?{credits:Y}:{}}}function K$($){if(!X0($))return;let Z=s($),X={};for(let J of i5){let z=Z.limits.find((B)=>B.label===J&&B.kind==="reading");if(!z||!j$(z.usedPercent))continue;let G={usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,checkedAt:z.checkedAt,...z.resetsAt!==void 0?{resetsAt:z.resetsAt}:{},...z.windowMinutes!==void 0?{windowMinutes:z.windowMinutes}:{}};X[J]=G}return X.primary||X.secondary?X:void 0}function hZ($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var vZ="ck auth reclassify --from-registry";function L6($,Z){if(Z===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if(Z.grants===0)return`The vault has no grant letting ${$} read OpenAI accounts. Grant it with \`${hZ($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${vZ}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var E0=u("vault"),GH="openai-auth",o5={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},BH={opencode:"OpenCode",pi:"Pi"};function HH($){return e3(GH,$)}function _6($){return r5(JH($),"openai-auth-vault")}function YH($,Z){return{...ZZ({stateDir:$,host:Z}),rosterPath:r5($,`${Z}-roster.json`)}}var O6=2000;var QH={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${vZ} to fill empty category sets, then check the CATEGORIES column with ck auth status. Or disconnect this host from the vault.`,"vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function t5($,Z){if($!=="vault-no-grant")return QH[$];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${hZ(Z)}`}function e5($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let X=$.grantReach();if(X!==void 0)return X.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function WH($){let Z=B$($);return Z?H$(Z):void 0}class $7 extends V6{#$;constructor($,Z){super($);this.#$=Z}refresh(){let $=super.refresh();return this.#$($),$}}class mZ{host;name;paths;#$;#Z;#z=new Map;#J=new Map;#Y=new Map;#B;#X;#W;#Q;#H=!1;#G=!1;#V=Promise.withResolvers();#K="unknown";#U;constructor($){this.#$=$,this.host=$.host,this.name=HH($.host),this.paths=YH($.stateDir,$.host),this.#Z=new $7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:o5,connect:()=>this.#j(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:WH,insula:{provider:"codex",normalize:a5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#X=void 0},onError:(Z)=>this.#N("vault roster refresh failed",Z),logger:{...E0,warn:(Z,X)=>{if(Z!=="skipped insula provider poll")E0.warn(Z,X)}}},(Z)=>this.#C(Z))}#F(){return(this.#$.connectionFile??zH)()}#D(){return{connectionFile:this.#F(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>E0.debug("vault transport error",{errorClass:$})}}#j(){return(this.#$.connectScoped?.()??R5(this.#D())).then(($)=>{return this.#B=$.insula!==void 0,$})}#q($,Z,X){let J=this.#Y.get($);if(J?.source===Z&&J.reason===X)return;this.#Y.set($,{source:Z,reason:X}),E0.info("vault background quota source changed",{routeId:$,source:Z,reason:X})}#M(){return this.#$.connectEnrollment?.()??$Z(this.#D())}#N($,Z){this.#X=o0(Z),E0.warn($,{host:this.host,error:this.#X})}#L(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=XH($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#L(),Z=await JZ(this.paths,this.name);if($===this.#L())return this.#K=Z,this.#U=$,Z;return"unreadable"}enrolled(){return this.#U!==this.#L()||this.#K!=="local"}async#O(){if(this.#U!==this.#L())await this.authority();return this.enrolled()}start(){if(this.#H||this.#G)return;this.#H=!0,this.#Z.start()}#C($){if(this.#Q===$)return;this.#Q=$,$.finally(()=>{if(this.#Q===$)this.#Q=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#Z.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let $=this.#Q;if($)await $.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#Q??this.#P()).catch((X)=>{this.#N("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let $=this.#Q;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#X=void 0,Z}catch($){return this.#N("vault roster refresh failed",$),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap(($)=>$.accountIdentity!==void 0?[$.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let $=new Map((this.snapshot()?.rows??[]).map((Z)=>[Z.routeId,Z]));return this.#Z.routingRows().map((Z)=>{let X=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...X!==void 0?{identity:X}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,X){let J=!1;try{return await this.#Z.send($,(z)=>{return J=!0,Z(z.accessToken,z)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(z){if(J)throw z;this.#N("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#N("vault refused to serve an account",X);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#Z.reportFailure($,401,"direct")}catch(X){this.#N("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let z=R0(Z,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota($,z,J).then(()=>{},(G)=>this.#N("vault quota write failed",G))}pollQuota($,Z=!0){let X=this.#J.get($);if(X)return X;let J=this.#_($,Z).finally(()=>{this.#J.delete($)});return this.#J.set($,J),J}async#_($,Z){if(Z){await this.authority(),await this.#Z.refreshInsulaQuota();let X=(await K0(this.paths.rosterPath))?.rows.find((H)=>H.routeId===$),J,z=await this.#Z.pollInsulaQuotaForRoute($,async()=>{this.#q($,"fallback",this.#B===!1?"insula-not-configured":"no-insula-reading"),J=await this.#T($,Z);return});if(J)return J;if(z!==void 0&&X?.accountIdentity){let H=R0(gZ(z,this.routes().find((Q)=>Q.id===$)?.quota),z.primary.checkedAt,!0);if(!H)return this.#q($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota($,X.accountIdentity,H))return this.#q($,"insula",null),{ok:!0};return this.#q($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute($),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#q($,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#T($,Z)}async#T($,Z){let X,J=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,B)=>{try{let H=Z?void 0:await this.#Z.cachedInsulaQuota(B);if(H!==void 0){let Q=R0(gZ(H,this.routes().find((W)=>W.id===$)?.quota),H.primary.checkedAt,!0);if(!Q)throw Error("unusable insula reading");return await this.#Z.recordQuota($,Q,B),new Response(null,{status:200})}let Y=await W$({accessToken:G,fetchImpl:J,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:$,logger:E0});return await this.recordSnapshot($,Y,!0,B),X=void 0,new Response(null,{status:200})}catch(H){X=o0(H);let Y=H?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw H}},{site:"quota"}).catch((G)=>{X=o0(G);return});if(!z)return{ok:!1,error:X??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:X??`status ${z.status}`}}requestReading($){let Z=this.#z.get($);if(Z)return Z;let X=this.pollQuota($,!1).catch((J)=>{E0.warn("vault quota poll failed",{routeId:$,error:o0(J)})}).finally(()=>{this.#z.delete($)});return this.#z.set($,X),X}async pollStale($){let Z=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let z=VH(J.quota);if(z!==void 0&&Z-z<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async reorder($){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder($)}async decline($){await this.#Z.decline($),E0.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),E0.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await d$(this.paths,this.name)}catch(Z){this.#N("vault enrollment state unreadable",Z),$={state:"blocked",proposedName:this.name,code:Z instanceof E?Z.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:$,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#X?{lastError:this.#X}:{}}}async connectStep(){let $=await this.#M().catch((Z)=>{throw new o("vault-unreachable",`Could not reach the Claustrum vault (${this.#F()}): ${o0(Z)}. Is the vault running?`)});try{let Z=new B6({client:$,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),X=await Z.status();if(X.state==="denied"||X.state==="blocked")await Z.resetTerminal();let J=await Z.reconcile();if(E0.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#X=void 0,await this.refresh();return J}finally{$.close()}}waitForApproval($={}){return this.#W??=(async()=>{let Z=$.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),X=$.pollIntervalMs??2000,J=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=J)return z;await Z(X),z=await this.connectStep()}return z})().finally(()=>{this.#W=void 0}),this.#W}async disconnect(){await n5(this.paths.tokenPath,{force:!0}),await n5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,E0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())GZ({mode:"custody",auth:$,provider:"openai"})}close(){this.#G=!0,this.#V.resolve(),this.#Z.close()}}function VH($){if(!$)return;let Z=s($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function P6($,Z){if(Z.state!=="pending")return[];if(!Z.requestId)return[`The vault did not take the enrollment request yet${Z.retryCode?` (${Z.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${Z.requestId} for ${$} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${Z.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${$} --selector-kind category --selector ${o5.category} --operation read`]}function Z7($,Z,X){let J=`${BH[$]} (${Z})`;switch(X.state){case"approved":return`${J}: connected to the Claustrum vault.`;case"idle":return`${J}: not connected to the Claustrum vault.`;case"pending":return X.requestId?`${J}: waiting for approval of request ${X.requestId}.`:`${J}: enrollment request not taken yet${X.retryCode?` (${X.retryCode})`:""}.`;case"denied":return`${J}: the vault denied the enrollment request.`;case"blocked":return`${J}: enrollment stopped (${X.code}).`;case"unavailable":return`${J}: the vault is unavailable (${X.code}).`;case"busy":return`${J}: another process is enrolling right now.`}}function wZ($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${$.name}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${L6($.name,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...P6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
99
+ `)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var X7=`${String.fromCharCode(27)}\\[[0-9;]*m`,ND=new RegExp(X7,"g"),qD=new RegExp(`^${X7}`);function L1($){return $.authority!=="local"}async function I0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function G7($){let Z;try{return await Promise.race([Promise.resolve().then(()=>$.refresh()).then(()=>{return},(X)=>X instanceof Error?X.message:String(X)),new Promise((X)=>{Z=setTimeout(()=>X("Vault roster refresh did not finish within the roster wait budget."),O6)})])}finally{clearTimeout(Z)}}function t0($){return $.email||$.label||$.routeId}var lZ="Accounts are managed in the vault with ck. Disconnect to use local accounts.",D$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var b0="main";function T6($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function H7($,Z,X){let J=new Map;if(kZ(Z))for(let z of $)J.set(z.id,l5(K$(z.quota),Z,z.id===b0?void 0:z.id,X));return J}var Y7=5,uZ=5000;function Q7($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function W7($,Z=uZ){let X=$.rows.filter((B)=>B.kind==="oauth"&&$.killswitch.get(B.id)!==!1&&s(B.quota).limits.length===0);if(X.length===0)return;if(x0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>$.killswitch.get(B.id)!==!1))return;let z=[];if(x0({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(B)=>{let H=$.requestPull(B);if(H)z.push(H.catch(()=>{}))}}),z.length===0)return;let G;return Promise.race([Promise.all(z),new Promise((B)=>{G=setTimeout(B,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function C6($){return $.reason==="exhausted"||$.reason==="budget-spent"}function _H($,Z){if(!l0($))return!1;let X=$;if(!(Z-X.checkedAt<=_$))return!1;if(X.overageLimitReached===!0)return!1;if(X.unlimited)return!0;return X.hasCredits&&(X.balance===void 0||X.balance>0)}function A6($,Z,X){let J=(H)=>Z.killswitch.get(H)!==!1,z=new Set(X.admitted.filter((H)=>H.lastPath!==!0&&J(H.id)).map((H)=>H.id)),G=new Map(X.refused.map((H)=>[H.id,H])),B=$.filter((H)=>{if(H.kind!=="oauth"||!J(H.id))return!1;if(G.get(H.id)?.reason!=="exhausted")return!1;let Y=s(H.quota);if(A1(Y,Z.now))return!1;return _H(Y.credits,Z.now)}).map((H)=>H.id);return{free:z,credits:B}}function OH($,Z=$.rows){return x0({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class dZ{#$=new Set;served($,Z,X){let J=OH($),z=A6($.rows,$,J),G=new Set(z.credits);if(z.free.has(Z)){this.#$.clear();return}for(let B of[...this.#$])if(!G.has(B))this.#$.delete(B);if(!G.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 V7($,Z,X){if($===void 0)return{reason:"no-credential"};if(X.get($)===!1)return{reason:"killswitch"};let J=Z.excluded.find((G)=>G.id===$);if(J?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:J.until};if(J)return{reason:"no-credential"};let z=Z.refused.find((G)=>G.id===$);if(z&&"resetAtMs"in z)return{reason:"quota-exhausted",resetAtMs:z.resetAtMs};if(z)return{reason:"quota-unknown"};return{reason:"no-credential"}}function B7($,Z,X){if(Z.refused.find((z)=>!C6(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return V7($[0],Z,X)}function U7($){let Z=$.replayable!==!1,X=$.mainId===void 0?b0:$.mainId??"",J=Z?$.placement:"main-first",z=u6({rows:$.rows,placement:J,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=s1($.rows.map((V)=>V.id),J,X),B=new Set(z.admission.refused.filter((V)=>C6(V)&&$.killswitch.get(V.id)!==!1).map((V)=>V.id)),H=G.filter((V)=>B.has(V)),Y=A6($.rows,$,z.admission),Q=z.order.filter((V)=>Y.free.has(V)),W=G.filter((V)=>Y.credits.includes(V));if(!Z){let V=G.includes(X),U=V?X:Q[0]??W[0]??z.order[0]??H[0];if(U!==void 0&&z.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&W.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&B.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:V?V7(X,z.admission,$.killswitch):B7(G,z.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(W.length>0){let V=z.order.length>0?z.order:H;return{kind:"send",order:[...W,...V.filter((U)=>!W.includes(U))],lastPath:!1}}if(z.order.length>0)return{kind:"send",order:z.order,lastPath:!1};if(H.length>0)return{kind:"send",order:H,lastPath:!0};return{kind:"block",block:B7(G,z.admission,$.killswitch)}}function cZ($){let Z=x0({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,s(J.quota));for(let J of Z.admitted)if(J.projection)X.set(J.id,J.projection);return{projections:X,excluded:new Set(Z.excluded.map((J)=>J.id))}}function j7($,Z,X){let J=X.exclude,z=J?$.rows.filter((B)=>!J.has(B.id)):$.rows,G=new Map;for(let B of z){let H=Z.resetCredits(B.id);if(H!==void 0)G.set(B.id,H)}return n6({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(B)=>Z.reservePercent(B.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function K7($,Z,X,J){let z=j7($,Z,{exclude:X,pendingBytes:J}),G=$.rows.filter((W)=>!X.has(W.id)),B=A6(G,$,z.admission),H=z.outcome==="dispatch"&&z.source!=="pin"?{accountId:z.accountId,source:z.source,...z.quotaCheckedAt===void 0?{}:{quotaCheckedAt:z.quotaCheckedAt}}:void 0;if(H&&B.free.has(H.accountId))return H;let Y=B.credits[0];if(Y===void 0)return H;let Q=s(G.find((W)=>W.id===Y)?.quota).checkedAt;return{accountId:Y,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function D7($,Z,X){let J=$.killswitch.get(X)===!1,z={kind:"move",reason:J?"killswitch":"exhausted"},G=j7($,Z,{pin:X}),B=A6($.rows,$,G.admission),H=B.credits.includes(X),Y=B.credits.some((V)=>V!==X);if(G.outcome==="dispatch"){let V=!B.free.has(G.accountId);if(G.pin.action==="assign"){if(V&&H)return{kind:"serve"};return z}if(G.accountId!==X)return{kind:"detour"};if(V&&Y)return z;return{kind:"serve"}}let Q=G.admission.refused.find((V)=>V.id===X),W=J||Q!==void 0&&C6(Q);if(H)return{kind:"serve"};if(Y)return W?z:{kind:"detour"};if(!J&&Q&&C6(Q))return{kind:"last-path"};return{kind:"none"}}function N7($,Z,X,J){let z=$.killswitch.get(X);return i6({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...z===void 0?{}:{killswitchPasses:z}})}function q7($){return a($)?{...$}:{}}function sZ($,Z){let X=X0(Z)?M$(Z.credits):void 0;return X?`${$} · prepaid ${X}`:$}function F7($,Z){return{...$,sections:$.sections.map((X)=>X.id!=="quota"?X:{...X,items:X.items.map((J)=>J.detail===void 0?J:{...J,detail:sZ(J.detail,Z.get(J.id))})})}}function S6($,Z,X,J){let z=X.confirm?.irreversible?{irreversible:!0,confirm:X.confirm.message}:{...X.confirm?{confirm:X.confirm.message}:{}};return{id:X.id,label:X.label,...X.description?{description:X.description}:{},...X.group?{group:X.group}:{},knobs:X.knobs,...z,run:async({values:G,invocation:B})=>{let H=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},B);return{ok:H.ok,text:H.text,...H.code?{code:H.code}:{}}}}}function aZ($,Z){return new Proxy($,{get(X,J){if(J==="read")return async()=>{let G=await X.read();if(G.status!=="ready")return G;let B={...G,rows:G.rows.map((Q)=>({...Q,label:Q.label??Q.id}))};if(!Z)return B;let H=await I0(Z);if(!L1(H))return B;let Y=[...H.status.accounts.map((Q)=>({id:Q.routeId,label:t0(Q),type:"oauth",enabled:Q.enabled,identity:Q.accountIdentity,quota:Q.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:Y}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!Z)return G;let B=await I0(Z),H=q7(G.settings.killswitch);if(!L1(B)||!G.settings.killswitch)return G;let Y=q7(H.accounts);for(let Q of B.status.accounts)Y[Q.routeId]=M1({version:1,accounts:[],...G.settings},Q.routeId);return{...G,settings:{...G.settings,killswitch:{...H,accounts:Y}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function iZ($,Z,X={}){let J=I1($),z=(Q)=>I1({command:$.command,title:$.title,store:aZ($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Q??"",vaultOrder:async()=>{let W=await I0(Z);if(!L1(W))return;return{rows:W.status.accounts.map((V)=>({id:V.routeId,label:t0(V)})),reorder:async(V)=>{if(!L1(await I0(Z)))throw new o("vault-local-action",D$);return Z.reorder(V)}}}},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Q,W)=>{let V=await I0(Z),U=L1(V),K=T6(V.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),j=U?z(K):J,D=(await j.open(W)).menu.sections.find((T)=>T.id===Q);if(!D)throw new o("unavailable","The account menu is unavailable.");if(!U)return{lines:D.lines,items:D.items.map((T)=>({...T,actions:T.actions.map((b)=>S6(j,Q,b,T.id))})),actions:D.actions.map((T)=>S6(j,Q,T))};let F=new Map(V.status.accounts.map((T)=>[T.routeId,T])),_=($.now??Date.now)(),R=(T)=>({id:"check",label:T?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await I0(Z)).routes].filter((f)=>!T||f===T);if(T&&w.length===0)throw new o("unavailable","This vault account cannot be checked right now.");for(let f of w){let g=await Z.pollQuota(f);if(!g.ok)throw new o("quota-check-failed",`${f}: ${g.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(Q==="quota"){let T=(b,w)=>C0(s(b.quota,$.quota?.scope),{now:_,form:w});return{lines:V.status.accounts.filter((b)=>!V.routes.has(b.routeId)).map((b)=>`${t0(b)} (${b.enabled?b.state:"disabled"}): ${sZ(T(b,"compact"),b.quota)}`),items:V.status.accounts.filter((b)=>V.routes.has(b.routeId)).map((b)=>({id:b.routeId,label:t0(b),group:"Accounts",status:T(b,"compact"),detail:sZ(T(b,"full"),b.quota),actions:[R(b.routeId)]})),actions:V.routes.size>0?[R()]:[]}}let M=D.items.map((T)=>{let b=F.get(T.id),w=b&&Q==="accounts"?`Vault · ${b.credentialType==="oauth"?"login":"API key"} · ${b.state} · ${b.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:w,group:T.group,status:b&&Q==="accounts"?b.enabled?b.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:b&&Q!=="limits"?[]:T.actions.map((f)=>S6(j,Q,f,T.id))}}),N=D.actions.filter((T)=>Q==="limits"||Q==="routing"&&(T.id==="mode"||T.id==="order")).map((T)=>S6(j,Q,T)),L=D.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),S=Q==="routing"&&K===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:Q==="accounts"?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`,lZ]:[...D.lines,...S?["No default vault account, so this mode orders like Ordered"]:[]],items:M,actions:N}},B=I1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Q)=>G("accounts",Q)},quota:{title:"Quota",build:(Q)=>G("quota",Q)},routing:{title:"Routing",build:(Q)=>G("routing",Q)},limits:{title:"Limits",build:(Q)=>G("limits",Q)}},extras:$.extras?.map((Q)=>Q.id!=="reset"?Q:{...Q,build:async(W)=>{let V=await I0(Z);if(L1(V))return{lines:[lZ]};return Q.build(W)}})}),H=async()=>{if(!L1(await I0(Z)))return{menu:J,error:void 0};let Q=X.refresh===!1?void 0:await G7(Z);return{menu:B,error:Q}},Y=async(Q,W)=>{let V=await Q.menu.open(W);if(Q.error)V.menu.sections.find((K)=>K.id==="vault")?.lines.push(`Last error: ${Q.error}`);return V};return{command:$.command,open:async(Q)=>Y(await H(),Q),apply:async(Q,W)=>{let V=await H(),{menu:U}=V;if(U===B&&(Q.sectionId==="accounts"||Q.sectionId==="reset"||Q.sectionId==="quota"&&(await I0(Z)).routes.size===0||Q.sectionId==="limits"&&Q.itemId!==void 0&&!(await I0(Z)).status.accounts.some((K)=>K.routeId===Q.itemId)))return{...await Y(V,W),ok:!1,code:"vault-local-action",text:D$};if(X.refuseApply)return{...await Y(V,W),ok:!1,...X.refuseApply};return U.apply(Q,W)}}}var _1="openai",tZ="OpenAI accounts",w1="main",L7="that account is already your main account, so it was not added again",t$=u("commands"),_7=new Set(["__proto__","constructor","prototype"]);function O7($,Z){let X={version:1,accounts:[],killswitch:$},J=a($.accounts)?Object.keys($.accounts):[],z={};for(let H of new Set([w1,...Z,...J])){if(_7.has(H))continue;let Y=M1(X,H===w1?void 0:H);z[H]={primary:Y.primary,secondary:Y.secondary}}let G=M1(X,void 0),B={...$};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=U$,B}function P7($,Z){let X=a($.accounts)?{...$.accounts}:{};for(let z of new Set([w1,...Z])){if(_7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:F1.primary,secondary:F1.secondary}}let J=a($.defaults)?$.defaults:{primary:F1.primary,secondary:F1.secondary};return{...$,accounts:X,defaults:J,schema:U$}}function nZ($,Z){let X=!1;if(a($.cachekeep))$.cacheKeep={...$.cachekeep,...a($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(a(J)&&J.schema!==U$)$.killswitch=O7(J,Z),X=!0;return X}async function M7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function C7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return nZ(z,await M7($)),{...J,settings:z}},X=async(J,z)=>{let G=await M7($);return $.updateSettings(async(B)=>{nZ(B,G);let H=await J(B)??B;if(a(H.killswitch)&&H.killswitch.schema!==U$)H.killswitch=P7(H.killswitch,G);return H},z)};return new Proxy($,{get(J,z){if(z==="readSettings")return Z;if(z==="updateSettings")return X;let G=Reflect.get(J,z,J);return typeof G==="function"?G.bind(J):G}})}function T7($,Z){let X=(Y,Q)=>Z.rowLocks?Z.rowLocks(Y):Q,J=(Y,Q)=>{let W=X(Y,Q?.extraLocks);return{...Q??{},...W?{extraLocks:W}:{}}},z=(Y,Q,W,V)=>$.replace(Y,Q,W,J(Y,V)),H={add:async(Y,Q)=>{let W=await $.read(),U=(W.status==="ready"?W.rows:[]).filter((D)=>D.type==="oauth"&&!D.invalid),K=Y.identity?U.find((D)=>D.identity===Y.identity):void 0;if(K?.id===w1)throw new o("main-account",L7);let j=K??U.find((D)=>D.id===Y.id&&D.id!==w1);if(!j||Y.credential.type!=="oauth")return $.add(Y,Q);let q=await z(j.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},Q?.extraLocks?{extraLocks:Q.extraLocks}:void 0);return t$.info("account signed in again",{id:j.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:z,enable:(Y,Q)=>$.enable(Y,J(Y,Q)),disable:(Y,Q,W)=>$.disable(Y,Q,J(Y,W)),remove:(Y,Q)=>$.remove(Y,J(Y,Q))};return new Proxy($,{get(Y,Q){if(Object.hasOwn(H,Q))return H[Q];let W=Reflect.get(Y,Q,Y);return typeof W==="function"?W.bind(Y):W}})}var A7="migration";function rZ($){let Z=["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",$.length>0?"These processes still hold the move back:":"No running process holds the move back."],X={command:_1,title:tZ,sections:[{id:A7,slot:"extra",title:"Accounts are moving",lines:Z,items:$.map((J,z)=>({id:`blocker-${z}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return oZ(X)}var PH=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function CH($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(PH.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function R6($,Z,X){if(Array.isArray($))return $.map((z,G)=>R6(z,`${Z}[${G}]`,X));if(!a($))return $;let J={};for(let[z,G]of Object.entries($)){if(CH(z)){X.push(`${Z}.${z}`);continue}J[z]=R6(G,`${Z}.${z}`,X)}return J}function oZ($){let Z=[],X=R6($,"menu",Z);if(Z.length>0)t$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function S7($){return{id:$.id,credential:{type:"oauth",refresh:$.refresh,...$.access!==void 0?{access:$.access}:{},...$.expires!==void 0?{expires:$.expires}:{}},...$.accountId!==void 0?{identity:$.accountId}:{},...$.label!==void 0?{label:$.label}:{}}}function R7($,Z){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(X)=>{let J=typeof X.label==="string"&&X.label.trim().length>0?X.label.trim():void 0,z=X.headless===!0,G=await $.begin({...J!==void 0?{label:J}:{},headless:z}),B=z?`Open this verification URL:
100
100
 
101
101
  ${G.url}
102
102
 
@@ -108,15 +108,15 @@ ${G.url}
108
108
 
109
109
  ${G.instructions}
110
110
 
111
- The account is added when you finish.`,H=G.completion.then(async(Y)=>{if(Z&&await Z.authority()!=="local")throw new r("vault-local-action",D$);let Q=await $.mainIdentity?.();if(Y.id===m1||Y.accountId&&Q&&Y.accountId===Q)throw r$.warn("account add rejected (main identity)",{id:Y.id}),new r("main-account",j7);return r$.info("account added",{id:Y.id}),_7(Y)});return{status:"pending",message:B,completion:H}}}}function i4($){return{id:"session",title:"This session",build:async(Z)=>{let X=Z.sessionId;if(!X)return{lines:["No current session"]};let J=await $.getPin?.(X);return{lines:[J?`Pinned to ${J}`:"No sticky pin"],actions:$.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:z})=>{if(!z.sessionId)return"No current session.";return await $.clearPin?.(z.sessionId),r$.info("routing session pin cleared"),"This session's pin was cleared. The next request may choose the same account if it remains the best selection."}}]:[]}}}}function n4($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let X=await Z.status(),J=await Z.authority()!=="local",z=Z.routes().length;return{lines:[J?`Connected · ${X.accounts.length} account${X.accounts.length===1?"":"s"}`:X.enrollment.state==="idle"?"Not connected":`Enrollment ${X.enrollment.state}`,i5(X.host,X.name,X.enrollment),..._3(X.name,X.enrollment),...J?[X.accounts.length===0?N3(X.name,Z.grantReach()):`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${z} can route now.`]:[],...J&&Z.snapshot()?.complete===!1?["The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."]:[],...X.lastError?[`Last error: ${X.lastError}`]:[]],items:X.accounts.map((G)=>({id:G.routeId,label:r0(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await Z.decline(G.routeId),await $.changed?.(),`${r0(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(G.routeId),await $.changed?.(),`${r0(G)} is enabled on this host.`}}]})),actions:J?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await Z.disconnect(),await $.changed?.(),`Disconnected: ${Z.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${Z.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:G})=>{let B=await Z.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await $.changed?.(),y4(Z,B);return Z.waitForApproval($.wait).then(async(H)=>{await $.changed?.();let Y=y4(Z,H);G.notify(Y.text,Y.ok?"info":"warning")}).catch((H)=>{G.notify(`Connecting to the vault failed: ${H instanceof Error?H.message:String(H)}`,"error")}),{ok:!0,text:[..._3(Z.name,B),"Waiting for the approval; you are told here when it lands."].join(`
112
- `)}}}]}}}}var O7=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],P7=["primary","secondary"];function r4($){let Z=new Set($.unavailableSections),X=(Q)=>({title:Q,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...$.extras??[]];if(Z.has("reset")){let Q={id:"reset",...X("Reset credits")},W=J.findIndex((V)=>V.id==="reset");if(W<0)J.unshift(Q);else J[W]=Q}let z={command:_1,title:a4,store:u4(N7(F7($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:L7($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:O7,formerMainId:m1},limits:{labels:P7},...Z.has("cache")?{cache:X("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:X("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:J,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},G=$.vault?l4(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):E1(z),B=$.vault?l4(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,H=(Q)=>{let{sessionId:W}=Q,V=Q.notify.bind(Q);return{...W!==void 0?{sessionId:W}:{},notify:V}},Y=async(Q)=>{if($.vault&&await $.vault.authority()!=="local")return Q;let W=await $.store.read().catch(()=>{return});if(W?.status!=="ready")return Q;return{...Q,menu:V7(Q.menu,new Map(W.rows.map((V)=>[V.id,V.quota])))}};return{command:_1,async open(Q){let W=H(Q),V=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(V&&!V.migrated)return{command:_1,menu:c4(V.blockers)};let U=await G.open(W);return Y({...U,menu:s4(U.menu)})},async apply(Q,W){let V=H(W),U=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(U&&!U.migrated)return{command:_1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:c4(U.blockers)};if($.readOnly&&$.vault)return G.apply(Q,V);if($.readOnly||$.allowAction&&!$.allowAction(Q)||Z.has(Q.sectionId)){if(B)return B.apply(Q,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let K=await G.apply(Q,V);if(K.ok)await $.afterApply?.();return Y({...K,menu:s4(K.menu)})}}}function C7($,Z,X){let J=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(J&&!Z.excludeAccountIds.includes(J.accountId)&&_$(J,z,Z.wireAccountIdByAccount[J.accountId])){if(Z.persist){let Y=Z.quotaCheckedAtByAccount[J.accountId];X(Z.sessionId,{accountId:J.accountId,inputBytes:Z.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:J.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),B=u3($,G,Z.sessionId),H=Z.select(B);if(!H)return;if(Z.persist){let Y=Z.wireAccountIdByAccount[H.accountId];X(Z.sessionId,{accountId:H.accountId,inputBytes:Z.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...H.quotaCheckedAt!==void 0?{quotaCheckedAt:H.quotaCheckedAt}:{}})}return{accountId:H.accountId}}import{statSync as FH}from"node:fs";var T7=30000,MH=8,_H=1800000;function S7($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function o4($){try{let Z=FH($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function w1($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function t4($,Z){try{return w0($,Z)}catch{return $}}function A7($,Z,X){let J=S7(Z);$.set(J,[...$.get(J)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:X}].slice(-MH))}function R7($,Z,X){let J=$;for(let z of Z.get(S7($))??[]){if(!(X-z.observation.checkedAt<=_H)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;J={...J,quota:t4(J.quota,z.observation)}}return J}function E7($,Z,X,J){let z=z$($);if(typeof Z?.status==="number"||bZ(Z)){let B=u2({error:Z,now:X,refreshToken:$,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:z,retryCount:B.retryCount}}return{nextRetryAt:X+T7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function I7($,Z,X,J){let z=new Map;for(let G of $){if(J(G,X))continue;let B=Z.get(G.id);z.set(G.id,B&&B.nextRetryAt>X?B.nextRetryAt:X+T7)}return z}var eq=d("quota");import{types as LH}from"node:util";var OH=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,PH=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function f7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,X,J)=>{if(X)return String.fromCharCode(Number.parseInt(X,16));return{b:"\b",f:"\f",n:`
113
- `,r:"\r",t:"\t"}[J]??J??Z})}function CH($,Z){if(!Z)return $;let X=$.split(Z).join("[credential]"),J=Z.replace(/\s/g,"");if(!J)return X;let z=X.replace(/\s/g,"");if(!z.includes(J))return X;let G=[];for(let Y=0;Y<X.length;Y++){let Q=X[Y]??"";if(!/\s/.test(Q))G.push(Y)}let B=[],H=0;for(let Y=z.indexOf(J);Y>=0;Y=z.indexOf(J,Y+J.length)){let Q=G[Y]??H,W=(G[Y+J.length-1]??Q)+1;B.push(X.slice(H,Q),"[credential]"),H=W}return B.length?B.join("")+X.slice(H):X}function b7($,Z){let X=CH($,Z);return j9(X).replaceAll("***REDACTED***","[credential]")}function L1($,Z){let X=b7($,Z),J=f7(X),z=b7(J,Z);return z===J?X:z}function x7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let X=Z[3]??"",J=(Z[2]??"")+X,z=0;while(J[z]==="0")z++;if(z===J.length)return"0";let G=J.length;while(J[G-1]==="0")G--;let B=Z[4]??"0",H=B.startsWith("-")||B.startsWith("+")?1:0;while(B[H]==="0")H++;let Y=B.slice(H)||"0";if(Y.length>16)return;let Q=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(X.length)+BigInt(J.length-G);return`${Z[1]}${J.slice(z,G)}e${Q}`}function y7($,Z){let X=Z?x7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(J)=>{if(!J.startsWith('"'))return Z&&(J===Z||X!==void 0&&x7(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let z=f7(J.slice(1,-1)),G=L1(z,Z);return G===z?J:JSON.stringify(G)})}function e4($,Z){let X=y7($,Z);try{return JSON.parse($),X}catch{return L1(X,Z)}}var TH=16384,SH=65536,AH=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function RH($){try{let Z=Z0(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let X=0,J,z=!0,G=!1,B;for(let H of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=H[0];if(Y==="{"||Y==="["){X++;continue}if(Y==="}"||Y==="]"){X--;continue}if(X!==1)continue;if(Y===","){z=!0,G=!1,J=void 0;continue}if(Y===":"){G=!0;continue}if(z&&Y.startsWith('"')){J=JSON.parse(Y),z=!1;continue}if(G&&J==="request_id"&&!Y.startsWith('"'))B=Y;G=!1}return B}catch{return}}function EH($,Z){let X=e4($,Z);if(Buffer.byteLength(X,"utf8")<=SH)return X;let J=AH.flatMap((G)=>G.exec(X)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(G))J.push(G);let z={retry:J};try{let G=JSON.parse(X);if(Z0(G,"type")==="error")z.type="error";let B=Z0(G,"error"),H={};for(let Q of["code","type"]){let W=Z0(B,Q);if(typeof W==="string")H[Q]=W.slice(0,256)}if(Object.keys(H).length)z.error=H;let Y={};for(let Q of["workspace","limitName"]){let W=Z0(Z0(G,"metadata"),Q);if(typeof W==="string")Y[Q]=W.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function S3($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(LH.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function Z0($,Z){if(!S3($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function o$($,Z){return L1($,Z).slice(0,TH)}function q$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var IH=q$(DOMException.prototype,"message"),bH=q$(DOMException.prototype,"name");function O1($,Z){let X=Z0($,"message"),J=Z0($,"name");if(S3($)&&$ instanceof DOMException)try{X=IH.call($),J=bH.call($)}catch{}let z=Error(o$(typeof X==="string"?X:typeof $==="string"?$:"Provider request failed",Z));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof J==="string"?o$(J,Z):"Error",configurable:!0,writable:!0});let G=(V,U,K)=>{let j=Z0(V,K);if(typeof j==="string"||typeof j==="number"&&Number.isFinite(j)||typeof j==="boolean")Object.defineProperty(U,K,{value:typeof j==="string"?o$(j,Z):j,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let U=Z0($,V);if(typeof U==="number"&&Number.isFinite(U))G($,z,V)}for(let V of["code","type","isRetryable"])G($,z,V);for(let V of["error","data"]){let U=Z0($,V),K=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])G(U,K,N);let j=Z0(U,"error");if(S3(j)){let N=Object.create(null);for(let D of["type","code","message","resets_at","resets_in_seconds"])G(j,N,D);K.error=N}if(Object.keys(K).length)Object.defineProperty(z,V,{value:K,enumerable:!0})}let B=Z0($,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let U of["retry-after-ms","retry-after"]){let K=Z0(B,U);if(typeof K==="string")V[U]=o$(K,Z)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let H=Z0($,"responseBody");if(typeof H==="string")Object.defineProperty(z,"responseBody",{value:EH(H,Z),enumerable:!0});let Y=Z0($,"request_id"),Q=Z0(B,"x-request-id"),W=typeof Y==="string"?Y:typeof Q==="string"?Q:typeof H==="string"?RH(e4(H,Z)):void 0;if(typeof W==="string")Object.defineProperty(z,"request_id",{value:o$(W,Z),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let U=Symbol.for(V);if(Z0($,U)===!0)Object.defineProperty(z,U,{value:!0})}return z}function xH($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!OH.test($)&&!PH.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return y7($,Z);return $}var kH=q$(Response.prototype,"status"),fH=q$(Response.prototype,"statusText"),yH=q$(Response.prototype,"headers"),gH=q$(Response.prototype,"body"),hH=Response.prototype.text,k7=Headers.prototype.entries;async function g7($,Z,X="http"){try{let K=function(j){let N=U&&j.startsWith("\uFEFF")?"\uFEFF":"";return U=!1,N+j.slice(N.length).replace(/^data: ?([^\r\n]*)/gm,(D,F)=>D.slice(0,D.length-F.length)+xH(F,Z))};if(!S3($))throw Error("Invalid provider response");let J=kH.call($),z=yH.call($),G=gH.call($),B=new Headers;for(let[j,N]of k7.call(z))B.append(j,N);let H={status:J,statusText:L1(fH.call($),Z),headers:B};if(J<200||J>299){for(let[N,D]of k7.call(z)){if(L1(N,Z?.toLowerCase())!==N){H.headers.delete(N);continue}try{H.headers.set(N,L1(D,Z))}catch{H.headers.delete(N)}}H.headers.delete("content-length");let j=await hH.call($);return new Response(e4(j,Z),H)}if(!G||X==="http")return $;H.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(G),Q=new TextDecoder("utf-8",{ignoreBOM:!0}),W=new TextEncoder,V="",U=!0;return new Response(new ReadableStream({async pull(j){try{for(;;){let N=await Y.read();V+=Q.decode(N.value,{stream:!N.done});let D=!1;for(;;){let F=/\r?\n\r?\n/.exec(V);if(!F)break;let L=F.index+F[0].length;j.enqueue(W.encode(K(V.slice(0,L)))),V=V.slice(L),D=!0}if(N.done){if(V)j.enqueue(W.encode(K(V)));j.close();return}if(D)return}}catch(N){j.error(O1(N,Z))}},async cancel(j){try{await Y.cancel(j)}catch(N){throw O1(N,Z)}finally{Y.releaseLock()}}}),H)}catch(J){throw O1(J,Z)}}var h7={name:"@cortexkit/pi-openai-auth",version:"1.5.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.25.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};var A3=new Map;function v7($){return A3.get($)?.accountId}function m7($){return A3.delete($)}function w7($){return C7(A3,$,(Z,X)=>A3.set(Z,X))}import{join as o7}from"node:path";import{createHash as sH}from"node:crypto";import{constants as d7}from"node:fs";import{lstat as n7,mkdir as c7,open as r7,unlink as aH}from"node:fs/promises";import{dirname as N$,resolve as s7}from"node:path";import{setTimeout as iH}from"node:timers/promises";import{rmdirSync as mH,statSync as u7,utimesSync as wH}from"node:fs";import{mkdir as pH,rmdir as uH,stat as $6,utimes as lH}from"node:fs/promises";var dH=30000,R3=1e4,cH=3000,Z6,t$=new Map;process.once("exit",()=>{for(let[$,Z]of t$)try{if(Z.renewedAt+R3<Date.now())continue;let X=u7($);if(X6(X,Z)&&X.mtime.getTime()===Z.mtime)mH($)}catch{}});function X6($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function e$($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function p7(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function J6($){try{await uH($)}catch(Z){if(e$(Z)!=="ENOENT")throw Z}}async function z6($,Z){try{await pH($)}catch(X){if(e$(X)!=="EEXIST")throw X;if(Z<=0)throw p7();let J;try{J=(await $6($)).mtime.getTime()}catch(z){if(e$(z)==="ENOENT")return z6($,0);throw z}if(!(J<Date.now()-Z))throw p7();return await J6($),z6($,0)}try{if(!Z6){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await lH($,z,z)}let X=await $6($),J=X.mtime.getTime();return Z6??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await J6($).catch(()=>{}),X}}async function l7($,Z,X){let J=`${$}.lock`,z=await z6(J,dH),G=z.mtime,B=Date.now(),H=!1,Y;t$.set(J,{...z,renewedAt:B});function Q(){if(H=!0,Y)clearTimeout(Y);t$.delete(J),Z()}function W(){if(!H&&B+R3<Date.now())Q()}function V(j=cH){if(H)return;Y=setTimeout(()=>{K()},j),Y.unref()}function U(j){if(H)return;if(e$(j)==="ENOENT"||B+R3<Date.now())Q();else V(1000)}async function K(){if(W(),H)return;let j;try{j=u7(J)}catch(D){U(D);return}if(W(),H)return;if(!X6(j,z)||j.mtime.getTime()!==G){Q();return}let N=new Date(Z6==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{wH(J,N,N)}catch(D){U(D);return}if(W(),H)return;G=N.getTime(),B=Date.now(),t$.set(J,{...z,mtime:G,renewedAt:B}),V()}return X?.(async()=>{if(Y)clearTimeout(Y);await K()}),V(),{assertFresh:W,async release(){if(H)return;if(H=!0,Y)clearTimeout(Y);t$.delete(J);let j=()=>B+R3<Date.now();if(j()){Q();return}let N;try{N=await $6(J)}catch(D){if(e$(D)!=="ENOENT")throw D;Q();return}if(j()||!X6(N,z)||G!==N.mtime.getTime()){Q();return}await J6(J)}}}class o extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function nH($){let Z=$.indexOf("{")+1,X={offset:Z-1,children:[]},J=()=>{while(/\s/.test($[Z]??"")&&Z<$.length)Z++},z=()=>{Z++;while(Z<$.length){if($[Z++]==='"')return;if($[Z-1]==="\\")Z++}};J();while($[Z]!=="}"){let G=Z;z();let B=JSON.parse($.slice(G,Z));J(),Z++,J();let H=Z,Y=0;while(Z<$.length){let W=$[Z];if(W==='"'){z();continue}if(W==="{"||W==="[")Y++;if(W==="}"||W==="]"){if(Y===0)break;Y--}if(W===","&&Y===0)break;Z++}let Q=Z;while(/\s/.test($[Q-1]??""))Q--;if(X.children.push({key:B,offset:G,length:Q-G,value:{offset:H,length:Q-H}}),J(),$[Z]==="}")break;Z++,J()}return X}function Z2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B6($){if(Array.isArray($))return`[${$.map(B6).join(",")}]`;if(Z2($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${B6($[Z])}`).join(",")}}`;return JSON.stringify($)}function h0($){return sH("sha256").update(B6($)).digest("hex")}function $2($){return Z2($)?$.code:void 0}async function a7($,Z=!1,X){if(I)try{await X?.($);let z=await i3($,!0),G=z.toString("utf8");if(!z.equals(Buffer.from(G)))throw new o(Z?"invalid-stash":"invalid-auth");return G}catch(z){if($2(z)==="ENOENT")return;throw z}let J;try{J=await r7($,d7.O_RDONLY|d7.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new o("unsafe-path");await X?.($);let G=await n7($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new o("unsafe-path");let B=await J.readFile(),H=B.toString("utf8");if(!B.equals(Buffer.from(H)))throw new o(Z?"invalid-stash":"invalid-auth");return H}catch(z){if($2(z)==="ENOENT"&&!J)return;if($2(z)==="ELOOP"||$2(z)==="ENOENT")throw new o("unsafe-path");throw z}finally{await J?.close()}}function rH($,Z){try{let X=JSON.parse($);if(!Z2(X))throw Error();let J=nH($),z=J.children,G=z.map((Y)=>Y.key);if(new Set(G).size!==G.length)throw Error();let B=z.find((Y)=>Y.key===Z),H=B?X[Z]:null;if(H!==null&&!Z2(H))throw Error();if(B&&H===null)throw Error();return{text:$,root:J,property:B,entry:H}}catch{throw new o("invalid-auth")}}function oH($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function i7($,Z,X){let{text:J,root:z,property:G}=$,B=z.children??[];if(G){let Q=G.value;if(!Q)throw new o("invalid-auth");if(X!==null)return J.slice(0,Q.offset)+X+J.slice(Q.offset+Q.length);let W=B.indexOf(G),V=B[W-1],U=B[W+1],K=V?V.offset+V.length:G.offset,j=!V&&U?U.offset:G.offset+G.length;return J.slice(0,K)+J.slice(j)}if(X===null)return J;let H=B.at(-1),Y=H?H.offset+H.length:z.offset+1;return`${J.slice(0,Y)}${H?",":""}${JSON.stringify(Z)}:${X}${J.slice(Y)}`}async function tH($){if(I)return;let Z=await r7($,"r");try{await Z.sync()}finally{await Z.close()}}async function G6($,Z,X,J){await L0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function H6($){return eH($)}function eH($,Z,X){let{provider:J,placeholderKey:z}=$,G=$.lockTimeoutMs??30000;if(!J||!$.authPath||!$.stashPath||!z||z.startsWith("!")||z.includes("$")||!Number.isFinite(G)||G<0)throw new o("invalid-options");let B=s7($.authPath),H=s7($.stashPath);if(B===H||H===`${B}.lock`)throw new o("invalid-options");let Y=h0(B),Q=h0(z),W={type:"api_key",key:z},V=(D)=>h0(D)===h0(W);async function U(){let D=await a7(H,!0,X?.afterReadCheck);if(D===void 0)return;try{let F=JSON.parse(D);if(F.version!==1||F.provider!==J||F.authIdentity!==Y||F.placeholderIdentity!==Q||F.entry!==null&&!Z2(F.entry)||F.sha256!==h0(F.entry)||(F.entry===null?F.entryJson!==null:typeof F.entryJson!=="string"||h0(JSON.parse(F.entryJson))!==F.sha256))throw Error();return F}catch{throw new o("invalid-stash")}}async function K(D){let F,L,R=!1,M=()=>{if(L?.(),R)throw new o("lock-compromised")};try{if(I)await N0(N$(B));else await c7(N$(B),{recursive:!0,mode:448});let q=Date.now()+G,_=0;while(!F)try{let T=await l7(B,()=>{R=!0},X?.onRenew);F=T.release,L=T.assertFresh}catch(T){if($2(T)!=="ELOCKED")throw T;let b=q-Date.now();if(b<=0)throw new o("lock-timeout");await iH(Math.min(Math.round(Math.min(10*2**_++,1000)*(1+Math.random())),b))}M();let A=await D(M);return M(),A}catch(q){if(q instanceof o||q instanceof i)throw q;throw new o("io")}finally{await F?.().catch(()=>{}),M()}}async function j(){let D=rH(await a7(B,!1,X?.afterReadCheck)??"{}",J),F=await U();return{auth:D,stash:F}}async function N(D){D(),await aH(H),await tH(N$(H)),Z?.("stash-deleted")}return{inspect:()=>K(async()=>{let{auth:D,stash:F}=await j();return{slot:V(D.entry)?"placeholder":D.entry===null?"empty":!F||h0(D.entry)===F.sha256?"original":"foreign",stash:F?"valid":"missing"}}),enterVault:()=>K(async(D)=>{let{auth:F,stash:L}=await j();if(V(F.entry)){if(!L)throw new o("missing-stash");return}if(L&&h0(F.entry)!==L.sha256)throw new o("conflict");if(!L){if(I)await N0(N$(H));else{await c7(N$(H),{recursive:!0,mode:448});let M=await n7(N$(H));if(!M.isDirectory()||(M.mode&511)!==448)throw new o("unsafe-path")}let R={version:1,provider:J,authIdentity:Y,placeholderIdentity:Q,entry:F.entry,entryJson:oH(F),sha256:h0(F.entry)};await G6(H,JSON.stringify(R),D,X?.beforeRename),Z?.("stash-written")}await G6(B,i7(F,J,JSON.stringify(W)),D,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>K(async(D)=>{let{auth:F,stash:L}=await j();if(!L){if(V(F.entry))throw new o("missing-stash");return"nothing-to-do"}if(V(F.entry))await G6(B,i7(F,J,L.entryJson),D,X?.beforeRename),Z?.("auth-written");else if(h0(F.entry)!==L.sha256)return"conflict";return await N(D),"restored"})}}import{getAgentDir as $Y}from"@earendil-works/pi-coding-agent";var X2="openai-auth-vault-mode-not-a-credential",t7="Request refused locally: Pi has not loaded the credential vault placeholder. Reopen the session or disconnect Pi from the vault in /openai; local credentials are not used while connected.",e7="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function $X($){return H6({authPath:o7($Y(),"auth.json"),provider:"openai-codex",stashPath:o7(F3($),"pi-openai-codex-login.json"),placeholderKey:X2})}function ZY($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=s({limits:["primary","secondary"].flatMap((B)=>{let H=Z?.[B];return H?[{...H,kind:"reading",scope:"all",label:B,checkedAt:H.checkedAt??X}]:[]}),...Z?.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:X}}:{}}),z=d1(J,{now:X}),G=M$(Z?.credits);return{lines:["Managed by Pi /login",...z.length>0?z:[P0(J,{now:X})],...G?[`prepaid ${G}`]:[]]}}}}function XY($,Z={}){let X=Z.beginAccountLogin??_9,J=Z.packageVersion??h7.version,z=n4({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=r4({store:$.store(),vault:$.vault,login:{begin:(B)=>X({...B,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(B)=>{if(B.length===1){let Y=$.store();for(let Q of B)await Y.requestReading(Q);await Y.pullsSettled();return}let H=(await $.refreshAllQuota()).filter((Y)=>!Y.ok);if(H.length>0)throw new r("quota-check-failed",H.map((Y)=>`${Y.account}: ${Y.error??"quota check failed"}`).join(`
114
- `))},extras:[ZY(()=>$.mainQuota()),i4({getPin:async(B)=>v7(B),clearPin:async(B)=>m7(B)}),{...z,build:async(B)=>{let H=await z.build(B),Y={id:"disconnect",label:"Disconnect",confirm:"Disconnect this Pi host from the vault and restore its original login?",run:async()=>{let W;try{W=await $.disconnectVault?.()}catch{let V=!1;try{await Z.afterApply?.()}catch{V=!0}let U=await $.readAuthority();throw new r("vault-disconnect-failed",[U==="local"?"Disconnect did not finish cleanly; local accounts are active. Retry Disconnect if Pi login restoration did not complete.":"Disconnect failed; Pi is still enrolled or enrollment is unreadable. Local accounts remain disabled; retry Disconnect to restore the login.",...V?["Pi could not reload its auth snapshot; reopen the session."]:[]].join(`
115
- `))}return await Z.afterApply?.(),[`Disconnected: ${$.vault.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.vault.name}\` to revoke it in the vault too.`,...W==="conflict"?[e7]:[]].join(`
116
- `)}},Q=H.actions??[];return{...H,actions:[...Q.map((W)=>W.id==="disconnect"&&$.disconnectVault?{...W,run:Y.run}:W),...$.vaultMode()&&$.disconnectVault&&!Q.some((W)=>W.id==="disconnect")?[Y]:[]]}}}],afterApply:async()=>{return await Z.afterApply?.(),$.reload()}});return{command:G.command,open:async(B)=>{return await $.readAuthority(),G.open(B)},apply:async(B,H)=>{return await $.readAuthority(),G.apply(B,H)}}}async function JY($,Z){let X=Z.pool;if(!X){$.ui.notify("The OpenAI account pool is not available.","error");return}if(Z.onContext?.($),Z.afterApply)await Z.afterApply();else await X.syncVaultSlot?.(()=>$.modelRegistry.refresh(),!0);if(!X.vaultMode())try{await X.observeLogin(await $.modelRegistry?.getApiKeyForProvider("openai-codex"))}catch{}await EZ(XY(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function ZX($,Z={}){$.registerCommand(_1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>JY(J,Z)})}import{connect as zY}from"node:net";import{connect as GY}from"node:tls";var BY="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",XX=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class Y6{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,X){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let X of[...this.listeners[$]??[]])try{X(Z)}catch{}}async connect($,Z){let X=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),J=X.hostname,z=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,B=crypto.getRandomValues(new Uint8Array(16)),H=Buffer.from(B).toString("base64"),Y=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(H+BY));this.expectedAccept=Buffer.from(new Uint8Array(Y)).toString("base64");let Q={};for(let[U,K]of Object.entries(Z))Q[U.toLowerCase()]=K;let W=[`GET ${G} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${H}`];for(let U of XX)if(Q[U]!==void 0)W.push(`${HY(U)}: ${Q[U]}`);for(let[U,K]of Object.entries(Z))if(!XX.includes(U.toLowerCase())&&U.toLowerCase()!=="content-length")W.push(`${U}: ${K}`);let V=`${W.join(`\r
111
+ The account is added when you finish.`,H=G.completion.then(async(Y)=>{if(Z&&await Z.authority()!=="local")throw new o("vault-local-action",D$);let Q=await $.mainIdentity?.();if(Y.id===w1||Y.accountId&&Q&&Y.accountId===Q)throw t$.warn("account add rejected (main identity)",{id:Y.id}),new o("main-account",L7);return t$.info("account added",{id:Y.id}),S7(Y)});return{status:"pending",message:B,completion:H}}}}function eZ($){return{id:"session",title:"This session",build:async(Z)=>{let X=Z.sessionId;if(!X)return{lines:["No current session"]};let J=await $.getPin?.(X);return{lines:[J?`Pinned to ${J}`:"No sticky pin"],actions:$.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:z})=>{if(!z.sessionId)return"No current session.";return await $.clearPin?.(z.sessionId),t$.info("routing session pin cleared"),"This session's pin was cleared. The next request may choose the same account if it remains the best selection."}}]:[]}}}}function $4($){let{vault:Z}=$;return{id:"vault",title:"Vault",build:async()=>{let X=await Z.status(),J=await Z.authority()!=="local",z=Z.routes().length;return{lines:[J?`Connected · ${X.accounts.length} account${X.accounts.length===1?"":"s"}`:X.enrollment.state==="idle"?"Not connected":`Enrollment ${X.enrollment.state}`,Z7(X.host,X.name,X.enrollment),...P6(X.name,X.enrollment),...J?[X.accounts.length===0?L6(X.name,Z.grantReach()):`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${z} can route now.`]:[],...J&&Z.snapshot()?.complete===!1?["The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."]:[],...X.lastError?[`Last error: ${X.lastError}`]:[]],items:X.accounts.map((G)=>({id:G.routeId,label:t0(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await Z.decline(G.routeId),await $.changed?.(),`${t0(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(G.routeId),await $.changed?.(),`${t0(G)} is enabled on this host.`}}]})),actions:J?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await Z.disconnect(),await $.changed?.(),`Disconnected: ${Z.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${Z.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:G})=>{let B=await Z.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await $.changed?.(),wZ(Z,B);return Z.waitForApproval($.wait).then(async(H)=>{await $.changed?.();let Y=wZ(Z,H);G.notify(Y.text,Y.ok?"info":"warning")}).catch((H)=>{G.notify(`Connecting to the vault failed: ${H instanceof Error?H.message:String(H)}`,"error")}),{ok:!0,text:[...P6(Z.name,B),"Waiting for the approval; you are told here when it lands."].join(`
112
+ `)}}}]}}}}var E7=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],I7=["primary","secondary"];function Z4($){let Z=new Set($.unavailableSections),X=(Q)=>({title:Q,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...$.extras??[]];if(Z.has("reset")){let Q={id:"reset",...X("Reset credits")},W=J.findIndex((V)=>V.id==="reset");if(W<0)J.unshift(Q);else J[W]=Q}let z={command:_1,title:tZ,store:aZ(C7(T7($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:R7($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:E7,formerMainId:w1},limits:{labels:I7},...Z.has("cache")?{cache:X("Cache")}:$.cache?{cache:$.cache}:{},...Z.has("diagnostics")?{diagnostics:X("Diagnostics")}:$.diagnostics?{diagnostics:$.diagnostics}:{},extras:J,...$.logger?{logger:$.logger}:{},...$.now?{now:$.now}:{}},G=$.vault?iZ(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):I1(z),B=$.vault?iZ(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,H=(Q)=>{let{sessionId:W}=Q,V=Q.notify.bind(Q);return{...W!==void 0?{sessionId:W}:{},notify:V}},Y=async(Q)=>{if($.vault&&await $.vault.authority()!=="local")return Q;let W=await $.store.read().catch(()=>{return});if(W?.status!=="ready")return Q;return{...Q,menu:F7(Q.menu,new Map(W.rows.map((V)=>[V.id,V.quota])))}};return{command:_1,async open(Q){let W=H(Q),V=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(V&&!V.migrated)return{command:_1,menu:rZ(V.blockers)};let U=await G.open(W);return Y({...U,menu:oZ(U.menu)})},async apply(Q,W){let V=H(W),U=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(U&&!U.migrated)return{command:_1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:rZ(U.blockers)};if($.readOnly&&$.vault)return G.apply(Q,V);if($.readOnly||$.allowAction&&!$.allowAction(Q)||Z.has(Q.sectionId)){if(B)return B.apply(Q,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let K=await G.apply(Q,V);if(K.ok)await $.afterApply?.();return Y({...K,menu:oZ(K.menu)})}}}function b7($,Z,X){let J=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(J&&!Z.excludeAccountIds.includes(J.accountId)&&L$(J,z,Z.wireAccountIdByAccount[J.accountId])){if(Z.persist){let Y=Z.quotaCheckedAtByAccount[J.accountId];X(Z.sessionId,{accountId:J.accountId,inputBytes:Z.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:J.accountId}}let G=new Map(Object.entries(Z.quotaCheckedAtByAccount)),B=c6($,G,Z.sessionId),H=Z.select(B);if(!H)return;if(Z.persist){let Y=Z.wireAccountIdByAccount[H.accountId];X(Z.sessionId,{accountId:H.accountId,inputBytes:Z.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...H.quotaCheckedAt!==void 0?{quotaCheckedAt:H.quotaCheckedAt}:{}})}return{accountId:H.accountId}}import{statSync as TH}from"node:fs";var x7=30000,AH=8,SH=1800000;function k7($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function X4($){try{let Z=TH($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function p1($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function J4($,Z){try{return u0($,Z)}catch{return $}}function f7($,Z,X){let J=k7(Z);$.set(J,[...$.get(J)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:X}].slice(-AH))}function y7($,Z,X){let J=$;for(let z of Z.get(k7($))??[]){if(!(X-z.observation.checkedAt<=SH)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;J={...J,quota:J4(J.quota,z.observation)}}return J}function g7($,Z,X,J){let z=z$($);if(typeof Z?.status==="number"||g3(Z)){let B=c2({error:Z,now:X,refreshToken:$,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:z,retryCount:B.retryCount}}return{nextRetryAt:X+x7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function h7($,Z,X,J){let z=new Map;for(let G of $){if(J(G,X))continue;let B=Z.get(G.id);z.set(G.id,B&&B.nextRetryAt>X?B.nextRetryAt:X+x7)}return z}var qq=u("quota");import{types as RH}from"node:util";var EH=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,IH=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function p7($){return $.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,(Z,X,J)=>{if(X)return String.fromCharCode(Number.parseInt(X,16));return{b:"\b",f:"\f",n:`
113
+ `,r:"\r",t:"\t"}[J]??J??Z})}function bH($,Z){if(!Z)return $;let X=$.split(Z).join("[credential]"),J=Z.replace(/\s/g,"");if(!J)return X;let z=X.replace(/\s/g,"");if(!z.includes(J))return X;let G=[];for(let Y=0;Y<X.length;Y++){let Q=X[Y]??"";if(!/\s/.test(Q))G.push(Y)}let B=[],H=0;for(let Y=z.indexOf(J);Y>=0;Y=z.indexOf(J,Y+J.length)){let Q=G[Y]??H,W=(G[Y+J.length-1]??Q)+1;B.push(X.slice(H,Q),"[credential]"),H=W}return B.length?B.join("")+X.slice(H):X}function v7($,Z){let X=bH($,Z);return M9(X).replaceAll("***REDACTED***","[credential]")}function O1($,Z){let X=v7($,Z),J=p7(X),z=v7(J,Z);return z===J?X:z}function m7($){let Z=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec($);if(!Z)return;let X=Z[3]??"",J=(Z[2]??"")+X,z=0;while(J[z]==="0")z++;if(z===J.length)return"0";let G=J.length;while(J[G-1]==="0")G--;let B=Z[4]??"0",H=B.startsWith("-")||B.startsWith("+")?1:0;while(B[H]==="0")H++;let Y=B.slice(H)||"0";if(Y.length>16)return;let Q=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(X.length)+BigInt(J.length-G);return`${Z[1]}${J.slice(z,G)}e${Q}`}function l7($,Z){let X=Z?m7(Z):void 0;return $.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(J)=>{if(!J.startsWith('"'))return Z&&(J===Z||X!==void 0&&m7(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let z=p7(J.slice(1,-1)),G=O1(z,Z);return G===z?J:JSON.stringify(G)})}function z4($,Z){let X=l7($,Z);try{return JSON.parse($),X}catch{return O1(X,Z)}}var xH=16384,kH=65536,fH=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function yH($){try{let Z=Z0(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let X=0,J,z=!0,G=!1,B;for(let H of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=H[0];if(Y==="{"||Y==="["){X++;continue}if(Y==="}"||Y==="]"){X--;continue}if(X!==1)continue;if(Y===","){z=!0,G=!1,J=void 0;continue}if(Y===":"){G=!0;continue}if(z&&Y.startsWith('"')){J=JSON.parse(Y),z=!1;continue}if(G&&J==="request_id"&&!Y.startsWith('"'))B=Y;G=!1}return B}catch{return}}function gH($,Z){let X=z4($,Z);if(Buffer.byteLength(X,"utf8")<=kH)return X;let J=fH.flatMap((G)=>G.exec(X)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(G))J.push(G);let z={retry:J};try{let G=JSON.parse(X);if(Z0(G,"type")==="error")z.type="error";let B=Z0(G,"error"),H={};for(let Q of["code","type"]){let W=Z0(B,Q);if(typeof W==="string")H[Q]=W.slice(0,256)}if(Object.keys(H).length)z.error=H;let Y={};for(let Q of["workspace","limitName"]){let W=Z0(Z0(G,"metadata"),Q);if(typeof W==="string")Y[Q]=W.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function E6($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(RH.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function Z0($,Z){if(!E6($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function e$($,Z){return O1($,Z).slice(0,xH)}function N$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var hH=N$(DOMException.prototype,"message"),vH=N$(DOMException.prototype,"name");function P1($,Z){let X=Z0($,"message"),J=Z0($,"name");if(E6($)&&$ instanceof DOMException)try{X=hH.call($),J=vH.call($)}catch{}let z=Error(e$(typeof X==="string"?X:typeof $==="string"?$:"Provider request failed",Z));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof J==="string"?e$(J,Z):"Error",configurable:!0,writable:!0});let G=(V,U,K)=>{let j=Z0(V,K);if(typeof j==="string"||typeof j==="number"&&Number.isFinite(j)||typeof j==="boolean")Object.defineProperty(U,K,{value:typeof j==="string"?e$(j,Z):j,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let U=Z0($,V);if(typeof U==="number"&&Number.isFinite(U))G($,z,V)}for(let V of["code","type","isRetryable"])G($,z,V);for(let V of["error","data"]){let U=Z0($,V),K=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])G(U,K,q);let j=Z0(U,"error");if(E6(j)){let q=Object.create(null);for(let D of["type","code","message","resets_at","resets_in_seconds"])G(j,q,D);K.error=q}if(Object.keys(K).length)Object.defineProperty(z,V,{value:K,enumerable:!0})}let B=Z0($,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let U of["retry-after-ms","retry-after"]){let K=Z0(B,U);if(typeof K==="string")V[U]=e$(K,Z)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let H=Z0($,"responseBody");if(typeof H==="string")Object.defineProperty(z,"responseBody",{value:gH(H,Z),enumerable:!0});let Y=Z0($,"request_id"),Q=Z0(B,"x-request-id"),W=typeof Y==="string"?Y:typeof Q==="string"?Q:typeof H==="string"?yH(z4(H,Z)):void 0;if(typeof W==="string")Object.defineProperty(z,"request_id",{value:e$(W,Z),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let U=Symbol.for(V);if(Z0($,U)===!0)Object.defineProperty(z,U,{value:!0})}return z}function mH($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!EH.test($)&&!IH.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return l7($,Z);return $}var wH=N$(Response.prototype,"status"),pH=N$(Response.prototype,"statusText"),lH=N$(Response.prototype,"headers"),uH=N$(Response.prototype,"body"),dH=Response.prototype.text,w7=Headers.prototype.entries;async function u7($,Z,X="http"){try{let K=function(j){let q=U&&j.startsWith("\uFEFF")?"\uFEFF":"";return U=!1,q+j.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(D,F)=>D.slice(0,D.length-F.length)+mH(F,Z))};if(!E6($))throw Error("Invalid provider response");let J=wH.call($),z=lH.call($),G=uH.call($),B=new Headers;for(let[j,q]of w7.call(z))B.append(j,q);let H={status:J,statusText:O1(pH.call($),Z),headers:B};if(J<200||J>299){for(let[q,D]of w7.call(z)){if(O1(q,Z?.toLowerCase())!==q){H.headers.delete(q);continue}try{H.headers.set(q,O1(D,Z))}catch{H.headers.delete(q)}}H.headers.delete("content-length");let j=await dH.call($);return new Response(z4(j,Z),H)}if(!G||X==="http")return $;H.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(G),Q=new TextDecoder("utf-8",{ignoreBOM:!0}),W=new TextEncoder,V="",U=!0;return new Response(new ReadableStream({async pull(j){try{for(;;){let q=await Y.read();V+=Q.decode(q.value,{stream:!q.done});let D=!1;for(;;){let F=/\r?\n\r?\n/.exec(V);if(!F)break;let _=F.index+F[0].length;j.enqueue(W.encode(K(V.slice(0,_)))),V=V.slice(_),D=!0}if(q.done){if(V)j.enqueue(W.encode(K(V)));j.close();return}if(D)return}}catch(q){j.error(P1(q,Z))}},async cancel(j){try{await Y.cancel(j)}catch(q){throw P1(q,Z)}finally{Y.releaseLock()}}}),H)}catch(J){throw P1(J,Z)}}var d7={name:"@cortexkit/pi-openai-auth",version:"1.6.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.26.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.13.0","@cortexkit/private-files":"^0.2.1","@cortexkit/subc-client":"^0.22.0"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};var I6=new Map;function c7($){return I6.get($)?.accountId}function s7($){return I6.delete($)}function a7($){return b7(I6,$,(Z,X)=>I6.set(Z,X))}import{join as zX}from"node:path";import{createHash as eH}from"node:crypto";import{constants as o7}from"node:fs";import{lstat as XX,mkdir as t7,open as JX,unlink as $Y}from"node:fs/promises";import{dirname as q$,resolve as e7}from"node:path";import{setTimeout as ZY}from"node:timers/promises";import{rmdirSync as sH,statSync as n7,utimesSync as aH}from"node:fs";import{mkdir as iH,rmdir as nH,stat as G4,utimes as rH}from"node:fs/promises";var oH=30000,b6=1e4,tH=3000,B4,$2=new Map;process.once("exit",()=>{for(let[$,Z]of $2)try{if(Z.renewedAt+b6<Date.now())continue;let X=n7($);if(H4(X,Z)&&X.mtime.getTime()===Z.mtime)sH($)}catch{}});function H4($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function Z2($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function i7(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function Y4($){try{await nH($)}catch(Z){if(Z2(Z)!=="ENOENT")throw Z}}async function Q4($,Z){try{await iH($)}catch(X){if(Z2(X)!=="EEXIST")throw X;if(Z<=0)throw i7();let J;try{J=(await G4($)).mtime.getTime()}catch(z){if(Z2(z)==="ENOENT")return Q4($,0);throw z}if(!(J<Date.now()-Z))throw i7();return await Y4($),Q4($,0)}try{if(!B4){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await rH($,z,z)}let X=await G4($),J=X.mtime.getTime();return B4??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await Y4($).catch(()=>{}),X}}async function r7($,Z,X){let J=`${$}.lock`,z=await Q4(J,oH),G=z.mtime,B=Date.now(),H=!1,Y;$2.set(J,{...z,renewedAt:B});function Q(){if(H=!0,Y)clearTimeout(Y);$2.delete(J),Z()}function W(){if(!H&&B+b6<Date.now())Q()}function V(j=tH){if(H)return;Y=setTimeout(()=>{K()},j),Y.unref()}function U(j){if(H)return;if(Z2(j)==="ENOENT"||B+b6<Date.now())Q();else V(1000)}async function K(){if(W(),H)return;let j;try{j=n7(J)}catch(D){U(D);return}if(W(),H)return;if(!H4(j,z)||j.mtime.getTime()!==G){Q();return}let q=new Date(B4==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{aH(J,q,q)}catch(D){U(D);return}if(W(),H)return;G=q.getTime(),B=Date.now(),$2.set(J,{...z,mtime:G,renewedAt:B}),V()}return X?.(async()=>{if(Y)clearTimeout(Y);await K()}),V(),{assertFresh:W,async release(){if(H)return;if(H=!0,Y)clearTimeout(Y);$2.delete(J);let j=()=>B+b6<Date.now();if(j()){Q();return}let q;try{q=await G4(J)}catch(D){if(Z2(D)!=="ENOENT")throw D;Q();return}if(j()||!H4(q,z)||G!==q.mtime.getTime()){Q();return}await Y4(J)}}}class t extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function XY($){let Z=$.indexOf("{")+1,X={offset:Z-1,children:[]},J=()=>{while(/\s/.test($[Z]??"")&&Z<$.length)Z++},z=()=>{Z++;while(Z<$.length){if($[Z++]==='"')return;if($[Z-1]==="\\")Z++}};J();while($[Z]!=="}"){let G=Z;z();let B=JSON.parse($.slice(G,Z));J(),Z++,J();let H=Z,Y=0;while(Z<$.length){let W=$[Z];if(W==='"'){z();continue}if(W==="{"||W==="[")Y++;if(W==="}"||W==="]"){if(Y===0)break;Y--}if(W===","&&Y===0)break;Z++}let Q=Z;while(/\s/.test($[Q-1]??""))Q--;if(X.children.push({key:B,offset:G,length:Q-G,value:{offset:H,length:Q-H}}),J(),$[Z]==="}")break;Z++,J()}return X}function J2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function V4($){if(Array.isArray($))return`[${$.map(V4).join(",")}]`;if(J2($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${V4($[Z])}`).join(",")}}`;return JSON.stringify($)}function w0($){return eH("sha256").update(V4($)).digest("hex")}function X2($){return J2($)?$.code:void 0}async function $X($,Z=!1,X){if(I)try{await X?.($);let z=await o6($,!0),G=z.toString("utf8");if(!z.equals(Buffer.from(G)))throw new t(Z?"invalid-stash":"invalid-auth");return G}catch(z){if(X2(z)==="ENOENT")return;throw z}let J;try{J=await JX($,o7.O_RDONLY|o7.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new t("unsafe-path");await X?.($);let G=await XX($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new t("unsafe-path");let B=await J.readFile(),H=B.toString("utf8");if(!B.equals(Buffer.from(H)))throw new t(Z?"invalid-stash":"invalid-auth");return H}catch(z){if(X2(z)==="ENOENT"&&!J)return;if(X2(z)==="ELOOP"||X2(z)==="ENOENT")throw new t("unsafe-path");throw z}finally{await J?.close()}}function JY($,Z){try{let X=JSON.parse($);if(!J2(X))throw Error();let J=XY($),z=J.children,G=z.map((Y)=>Y.key);if(new Set(G).size!==G.length)throw Error();let B=z.find((Y)=>Y.key===Z),H=B?X[Z]:null;if(H!==null&&!J2(H))throw Error();if(B&&H===null)throw Error();return{text:$,root:J,property:B,entry:H}}catch{throw new t("invalid-auth")}}function zY($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function ZX($,Z,X){let{text:J,root:z,property:G}=$,B=z.children??[];if(G){let Q=G.value;if(!Q)throw new t("invalid-auth");if(X!==null)return J.slice(0,Q.offset)+X+J.slice(Q.offset+Q.length);let W=B.indexOf(G),V=B[W-1],U=B[W+1],K=V?V.offset+V.length:G.offset,j=!V&&U?U.offset:G.offset+G.length;return J.slice(0,K)+J.slice(j)}if(X===null)return J;let H=B.at(-1),Y=H?H.offset+H.length:z.offset+1;return`${J.slice(0,Y)}${H?",":""}${JSON.stringify(Z)}:${X}${J.slice(Y)}`}async function GY($){if(I)return;let Z=await JX($,"r");try{await Z.sync()}finally{await Z.close()}}async function W4($,Z,X,J){await _0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function U4($){return BY($)}function BY($,Z,X){let{provider:J,placeholderKey:z}=$,G=$.lockTimeoutMs??30000;if(!J||!$.authPath||!$.stashPath||!z||z.startsWith("!")||z.includes("$")||!Number.isFinite(G)||G<0)throw new t("invalid-options");let B=e7($.authPath),H=e7($.stashPath);if(B===H||H===`${B}.lock`)throw new t("invalid-options");let Y=w0(B),Q=w0(z),W={type:"api_key",key:z},V=(D)=>w0(D)===w0(W);async function U(){let D=await $X(H,!0,X?.afterReadCheck);if(D===void 0)return;try{let F=JSON.parse(D);if(F.version!==1||F.provider!==J||F.authIdentity!==Y||F.placeholderIdentity!==Q||F.entry!==null&&!J2(F.entry)||F.sha256!==w0(F.entry)||(F.entry===null?F.entryJson!==null:typeof F.entryJson!=="string"||w0(JSON.parse(F.entryJson))!==F.sha256))throw Error();return F}catch{throw new t("invalid-stash")}}async function K(D){let F,_,R=!1,M=()=>{if(_?.(),R)throw new t("lock-compromised")};try{if(I)await q0(q$(B));else await t7(q$(B),{recursive:!0,mode:448});let N=Date.now()+G,L=0;while(!F)try{let T=await r7(B,()=>{R=!0},X?.onRenew);F=T.release,_=T.assertFresh}catch(T){if(X2(T)!=="ELOCKED")throw T;let b=N-Date.now();if(b<=0)throw new t("lock-timeout");await ZY(Math.min(Math.round(Math.min(10*2**L++,1000)*(1+Math.random())),b))}M();let S=await D(M);return M(),S}catch(N){if(N instanceof t||N instanceof i)throw N;throw new t("io")}finally{await F?.().catch(()=>{}),M()}}async function j(){let D=JY(await $X(B,!1,X?.afterReadCheck)??"{}",J),F=await U();return{auth:D,stash:F}}async function q(D){D(),await $Y(H),await GY(q$(H)),Z?.("stash-deleted")}return{inspect:()=>K(async()=>{let{auth:D,stash:F}=await j();return{slot:V(D.entry)?"placeholder":D.entry===null?"empty":!F||w0(D.entry)===F.sha256?"original":"foreign",stash:F?"valid":"missing"}}),enterVault:()=>K(async(D)=>{let{auth:F,stash:_}=await j();if(V(F.entry)){if(!_)throw new t("missing-stash");return}if(_&&w0(F.entry)!==_.sha256)throw new t("conflict");if(!_){if(I)await q0(q$(H));else{await t7(q$(H),{recursive:!0,mode:448});let M=await XX(q$(H));if(!M.isDirectory()||(M.mode&511)!==448)throw new t("unsafe-path")}let R={version:1,provider:J,authIdentity:Y,placeholderIdentity:Q,entry:F.entry,entryJson:zY(F),sha256:w0(F.entry)};await W4(H,JSON.stringify(R),D,X?.beforeRename),Z?.("stash-written")}await W4(B,ZX(F,J,JSON.stringify(W)),D,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>K(async(D)=>{let{auth:F,stash:_}=await j();if(!_){if(V(F.entry))throw new t("missing-stash");return"nothing-to-do"}if(V(F.entry))await W4(B,ZX(F,J,_.entryJson),D,X?.beforeRename),Z?.("auth-written");else if(w0(F.entry)!==_.sha256)return"conflict";return await q(D),"restored"})}}import{getAgentDir as HY}from"@earendil-works/pi-coding-agent";var z2="openai-auth-vault-mode-not-a-credential",GX="Request refused locally: Pi has not loaded the credential vault placeholder. Reopen the session or disconnect Pi from the vault in /openai; local credentials are not used while connected.",BX="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function HX($){return U4({authPath:zX(HY(),"auth.json"),provider:"openai-codex",stashPath:zX(_6($),"pi-openai-codex-login.json"),placeholderKey:z2})}function YY($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=s({limits:["primary","secondary"].flatMap((B)=>{let H=Z?.[B];return H?[{...H,kind:"reading",scope:"all",label:B,checkedAt:H.checkedAt??X}]:[]}),...Z?.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:X}}:{}}),z=c1(J,{now:X}),G=M$(Z?.credits);return{lines:["Managed by Pi /login",...z.length>0?z:[C0(J,{now:X})],...G?[`prepaid ${G}`]:[]]}}}}function QY($,Z={}){let X=Z.beginAccountLogin??A9,J=Z.packageVersion??d7.version,z=$4({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=Z4({store:$.store(),vault:$.vault,login:{begin:(B)=>X({...B,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(B)=>{if(B.length===1){let Y=$.store();for(let Q of B)await Y.requestReading(Q);await Y.pullsSettled();return}let H=(await $.refreshAllQuota()).filter((Y)=>!Y.ok);if(H.length>0)throw new o("quota-check-failed",H.map((Y)=>`${Y.account}: ${Y.error??"quota check failed"}`).join(`
114
+ `))},extras:[YY(()=>$.mainQuota()),eZ({getPin:async(B)=>c7(B),clearPin:async(B)=>s7(B)}),{...z,build:async(B)=>{let H=await z.build(B),Y={id:"disconnect",label:"Disconnect",confirm:"Disconnect this Pi host from the vault and restore its original login?",run:async()=>{let W;try{W=await $.disconnectVault?.()}catch{let V=!1;try{await Z.afterApply?.()}catch{V=!0}let U=await $.readAuthority();throw new o("vault-disconnect-failed",[U==="local"?"Disconnect did not finish cleanly; local accounts are active. Retry Disconnect if Pi login restoration did not complete.":"Disconnect failed; Pi is still enrolled or enrollment is unreadable. Local accounts remain disabled; retry Disconnect to restore the login.",...V?["Pi could not reload its auth snapshot; reopen the session."]:[]].join(`
115
+ `))}return await Z.afterApply?.(),[`Disconnected: ${$.vault.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.vault.name}\` to revoke it in the vault too.`,...W==="conflict"?[BX]:[]].join(`
116
+ `)}},Q=H.actions??[];return{...H,actions:[...Q.map((W)=>W.id==="disconnect"&&$.disconnectVault?{...W,run:Y.run}:W),...$.vaultMode()&&$.disconnectVault&&!Q.some((W)=>W.id==="disconnect")?[Y]:[]]}}}],afterApply:async()=>{return await Z.afterApply?.(),$.reload()}});return{command:G.command,open:async(B)=>{return await $.readAuthority(),G.open(B)},apply:async(B,H)=>{return await $.readAuthority(),G.apply(B,H)}}}async function WY($,Z){let X=Z.pool;if(!X){$.ui.notify("The OpenAI account pool is not available.","error");return}if(Z.onContext?.($),Z.afterApply)await Z.afterApply();else await X.syncVaultSlot?.(()=>$.modelRegistry.refresh(),!0);if(!X.vaultMode())try{await X.observeLogin(await $.modelRegistry?.getApiKeyForProvider("openai-codex"))}catch{}await f3(QY(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function YX($,Z={}){$.registerCommand(_1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>WY(J,Z)})}import{connect as VY}from"node:net";import{connect as UY}from"node:tls";var jY="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",QX=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class j4{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,X){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let X of[...this.listeners[$]??[]])try{X(Z)}catch{}}async connect($,Z){let X=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),J=X.hostname,z=X.port?Number(X.port):X.protocol==="https:"?443:80,G=`${X.pathname}${X.search}`,B=crypto.getRandomValues(new Uint8Array(16)),H=Buffer.from(B).toString("base64"),Y=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(H+jY));this.expectedAccept=Buffer.from(new Uint8Array(Y)).toString("base64");let Q={};for(let[U,K]of Object.entries(Z))Q[U.toLowerCase()]=K;let W=[`GET ${G} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${H}`];for(let U of QX)if(Q[U]!==void 0)W.push(`${KY(U)}: ${Q[U]}`);for(let[U,K]of Object.entries(Z))if(!QX.includes(U.toLowerCase())&&U.toLowerCase()!=="content-length")W.push(`${U}: ${K}`);let V=`${W.join(`\r
117
117
  `)}\r
118
118
  \r
119
- `;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let U=()=>{this.socket?.write(V)},K=X.protocol==="https:"?GY({host:J,port:z,servername:J},U):zY({host:J,port:z},U);this.socket=K,K.on("data",(j)=>{this.onData(typeof j==="string"?Buffer.from(j,"binary"):j)}),K.on("error",(j)=>{this.readyState=3;let N=j instanceof Error?j.message:String(j);this.log("socket_error",{message:N}),this.emit("error",{message:N})}),K.on("close",(j)=>{this.readyState=3,this.log("socket_close",{hadError:j}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(U){this.readyState=3,this.log("connect_exception",{message:U instanceof Error?U.message:String(U)}),this.emit("error",{message:U instanceof Error?U.message:String(U)})}}onData($){if(this.rxBuffer=YY(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),X=Z.indexOf(`\r
119
+ `;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let U=()=>{this.socket?.write(V)},K=X.protocol==="https:"?UY({host:J,port:z,servername:J},U):VY({host:J,port:z},U);this.socket=K,K.on("data",(j)=>{this.onData(typeof j==="string"?Buffer.from(j,"binary"):j)}),K.on("error",(j)=>{this.readyState=3;let q=j instanceof Error?j.message:String(j);this.log("socket_error",{message:q}),this.emit("error",{message:q})}),K.on("close",(j)=>{this.readyState=3,this.log("socket_close",{hadError:j}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(U){this.readyState=3,this.log("connect_exception",{message:U instanceof Error?U.message:String(U)}),this.emit("error",{message:U instanceof Error?U.message:String(U)})}}onData($){if(this.rxBuffer=DY(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),X=Z.indexOf(`\r
120
120
  \r
121
121
  `);if(X===-1)return;let J=Z.slice(0,X),z=J.split(`\r
122
- `)[0]??"",G=J.match(/sec-websocket-accept:\s*(\S+)/i);if(!z.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:z}),this.emit("error",{message:`WS upgrade failed: ${z}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:z}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:z}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],X=$[1],J=(Z&128)!==0,z=Z&15,G=(X&128)!==0,B=X&127,H=2;if(B===126){if($.length<4)return;B=$[2]<<8|$[3],H=4}else if(B===127){if($.length<10)return;B=0;for(let Q=0;Q<8;Q++)B=B*256+$[2+Q];H=10}if(G)H+=4;if($.length<H+B)return;let Y=$.slice(H,H+B);this.rxBuffer=$.slice(H+B),this.handleFrame(J,z,Y)}}handleFrame($,Z,X){if(Z===9){this.writeFrame(10,X);return}if(Z===10)return;if(Z===8){let z=1005,G="";if(X.length>=2)z=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:z,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[X];else if(Z===0)this.fragChunks.push(X);if(!$)return;let J=QY(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let z=Buffer.from(J).toString("utf-8");this.emit("message",{data:z})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let X=Z.length,J=crypto.getRandomValues(new Uint8Array(4)),z;if(X<126)z=[128|$,128|X];else if(X<65536)z=[128|$,254,X>>8&255,X&255];else{z=[128|$,255];for(let H=7;H>=0;H--)z.push(X/2**(8*H)&255)}let G=new Uint8Array(X);for(let H=0;H<X;H++)G[H]=Z[H]^J[H%4];let B=new Uint8Array(z.length+4+X);B.set(z,0),B.set(J,z.length),B.set(G,z.length+4);try{this.socket?.write(B)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function HY($){return $}function YY($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function QY($){let Z=0;for(let z of $)Z+=z.length;let X=new Uint8Array(Z),J=0;for(let z of $)X.set(z,J),J+=z.length;return X}import{statSync as MY}from"node:fs";var WY=15000;function J2($){if(!$)return;let Z=B$($);return Z?H$(Z):void 0}class Q6{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=J2($);if(this.token!==void 0&&this.accountKey(this.token,this.identity)!==this.accountKey($,Z))this.quota=void 0,this.snapshot=void 0;this.token=$,this.identity=Z;let X=this.accountKey($,Z);if(this.firstPolledFor!==X)this.firstPolledFor=X,this.pollNow()}currentToken(){return this.token}currentIdentity(){return this.identity}quotaMap(){return this.quota}quotaSnapshot(){let $=K$(this.quota),Z=this.quota?.credits;if(!$&&!this.snapshot&&!Z)return;return{...this.snapshot?.resetCreditsAvailable!==void 0?{resetCreditsAvailable:this.snapshot.resetCreditsAvailable}:{},...this.snapshot?.spendControl?{spendControl:this.snapshot.spendControl}:{},...Z?{credits:{...Z}}:{},...$}}requestReading($=!1){let Z=this.now();if(!$&&this.lastPull!==void 0&&Z-this.lastPull<(this.deps.pullRetryMs??WY))return this.inflight;return this.pollNow()}pending(){return this.inflight}pollNow(){if(this.inflight)return this.inflight;let $=this.token;if(!$)return Promise.resolve({ok:!1,error:"Pi holds no OpenAI login"});let Z=this.identity;this.lastPull=this.now();let X=(async()=>{try{let J=await this.deps.poll($,Z);if(this.accountKey(this.token,this.identity)!==this.accountKey($,Z))return{ok:!0};return this.snapshot=J.snapshot,this.merge(J.observation),{ok:!0}}catch(J){let z=J instanceof Error?J.message:String(J);return this.deps.log?.warn("Pi login quota poll failed",{error:z}),{ok:!1,error:z}}})();return this.inflight=X,X.finally(()=>{if(this.inflight===X)this.inflight=void 0}),X}record($,Z,X){if(!this.owns(Z))return!1;let J=A0($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=J2($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=w0(this.quota,$);if(X0(Z))this.quota=Z}catch(Z){this.deps.log?.warn("Pi login quota observation not merged",{error:Z instanceof Error?Z.message:String(Z)})}}accountKey($,Z){if(Z)return`identity:${Z}`;return $?`token:${$}`:void 0}}import{homedir as VY}from"node:os";import{join as JX}from"node:path";function UY(){return process.env.PI_AGENT_DIR?.trim()||JX(VY(),".pi","agent")}function zX(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||JX(UY(),s2)}function jY($=zX()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||yZ($)}function GX($=zX()){return{configPath:$,statePath:jY($)}}function W6($){return $!==void 0&&($.vault===!0||!!$.token)}function BX($,Z,X,J,z=new Set){return $.filter((G)=>{if(!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(g0(G.credential))return!1;if(G.id===I0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return D3(K$(G.quota),Z,X)})}function E3($,Z){let X=$.now(),J=$7(Z,$.storage,X);return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...X0(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function HX($){let Z=$.accounts(),X=J7(E3($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await DY($,Z,$.sessionId);if(J)return J}return KY($,Z)}async function KY($,Z){let X=X7($.mode),J=E3($,Z),z=G7({...J,placement:X,mainId:$.mainId});if(z.kind==="block")return $.log?.debug("pool admission blocked the request",{reason:z.block.reason}),{kind:"blocked",block:z.block};if(z.lastPath)$.log?.debug("pool admission: every account is exhausted; probing anyway",{order:z.order});let G=new Map(Z.map((W)=>[W.id,W])),B=f5($.storage),H=[],Y=new Set,Q;for(;;){let W=p3(z.order.filter((K)=>!Y.has(K)),H,B);if(W===void 0)break;let V=G.get(W);if(!W6(V)){Y.add(W);continue}let U=await $.send(V);if(!U){Y.add(W);continue}Q={attempt:U,accountId:V.id},H.push({id:V.id,...U.status!==void 0?{status:U.status}:{}})}if(Q)return YX($,J,Q.accountId),{kind:"sent",...Q};return{kind:"blocked",block:{reason:"no-credential"}}}async function DY($,Z,X){let J=$.requestBytes,z=new Map(Z.map((D)=>[D.id,D])),G=E3($,Z),B=w4(G),H={requestBytes:J,reservePercent:(D)=>F1($.storage,D===I0?void 0:D),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},Y=(D,F,L)=>(R,M)=>{let q=new Set(R);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:D.rows.map((_)=>_.id).filter((_)=>!F.excluded.has(_)),excludeAccountIds:R,quotaCheckedAtByAccount:Object.fromEntries(D.rows.map((_)=>[_.id,F.projections.get(_.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(L.map((_)=>[_.id,_.identity])),select:(_)=>H7(D,H,q,_),persist:M})},Q=Y(G,B,Z),W=Q([],!0);if(!W)return;let V=W.accountId,U=(D)=>{let F=Q([V],!0);if(!F)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:V,toAccountId:F.accountId,reason:D}),V=F.accountId,!0},K=Y7(G,H,V);if(K.kind==="none")return;if(K.kind==="move"){if(!U(K.reason)&&K.reason==="killswitch")return}else if(K.kind==="detour"){let D=Q([V],!1);if(!D)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:V,servedAccountId:D.accountId}),V=D.accountId}let j=z.get(V);if(!W6(j))return;let N=await $.send(j);if(!N)return;if(N.status===401||N.status===403||N.status===429){let D=$.accounts();G=E3($,D),B=w4(G),Q=Y(G,B,D);let F=Q7(G,B,V,N.status);if(F.action==="migrate"){let L=V;if(U(F.reason)&&V!==L){let R=D.find((q)=>q.id===V),M=W6(R)?await $.send(R):void 0;if(R&&M)N=M,j=R;else V=L}}}return YX($,G,j.id),{kind:"sent",attempt:N,accountId:j.id}}function YX($,Z,X){let J=$.log,z=J?.info;$.creditsServing?.served(Z,X,J&&z?{info:(G,B)=>z.call(J,G,B)}:void 0)}var qY=500,NY=15000;function I3($,Z,X){return new Promise((J,z)=>{let G=setTimeout(()=>J(X()),Z);G.unref?.(),$.then((B)=>{clearTimeout(G),J(B)},(B)=>{clearTimeout(G),z(B)})})}var FY={info(){},warn(){}};class V6{deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;initializing;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;lastPull=new Map;quotaPulls=new Map;polled=new Set;polledSnapshots=new Map;pollOutcomes=new Map;disposed=!1;constructor($){this.deps=$,this.now=$.now??Date.now,this.log=$.log??FY}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){let $=this.filesKey();if(this.snapshot.key===$)return this.peek();let Z=await I3(this.startRead($),this.deps.readBudgetMs??qY,()=>this.snapshot);return{active:Z.active,rows:Z.rows}}async load(){let $=await this.startRead(this.filesKey());return{active:$.active,rows:$.rows}}poolStore(){return this.storeFor(this.deps.paths())}polledSnapshot($){return this.polledSnapshots.get($)}filesKey(){let $=this.deps.paths();return`${$.configPath}|${o4($.configPath)}|${o4($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=OZ({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:g3,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,J)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:J.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:J.kind,error:J.message})},logger:this.log,...this.deps.store,onStep:async(X,J)=>{if(await this.deps.store?.onStep?.(X,J),J.operation!=="updateSettings"&&X.startsWith("before-")&&(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:$.configPath,store:Z},Z}startRead($){if(this.inflightRead?.key===$)return this.inflightRead.promise;let Z=this.now(),X=this.read($,Z),J={key:$,promise:X};this.inflightRead=J;let z=()=>{if(this.inflightRead===J)this.inflightRead=void 0};return X.then(z,z),X}async read($,Z){let X=this.deps.paths(),J;try{J=await this.storeFor(X).read()}catch(G){return this.log.warn("account pool read failed",{error:G instanceof Error?G.message:String(G)}),this.snapshot}if(J.status==="pending-migration"){if(!this.setAside())this.initialize(X)}else if(J.status==="error")this.log.warn("account pool is unreadable",{file:J.file,reason:J.reason});let z=J.status==="ready"?{active:!0,rows:J.rows,key:$,readAt:Z}:{active:!1,rows:[],key:$,readAt:Z};if(Z>=this.snapshot.readAt)this.snapshot={...z,rows:this.withLocalState(z.rows)};if(this.snapshot.active)this.pollUnseenRows();return this.snapshot}initialize($){if(this.disposed||this.initializing?.configPath===$.configPath)return;let Z=this.storeFor($).initialize().then((X)=>{this.log.info("account pool initialized",{status:X.status})},(X)=>{if(this.log.warn("account pool initialization failed",{error:X instanceof Error?X.message:String(X)}),this.initializing?.promise===Z)this.initializing=void 0});this.initializing={configPath:$.configPath,promise:Z}}withLocalState($){let Z=this.now();return $.map((X)=>{let J=X,z=this.rotated.get(X.id);if(z?.type==="oauth"&&X.credential?.type==="oauth"){let G=X.credential.lastRefreshedAt??0,B=z.lastRefreshedAt??0;if(G>=B)this.rotated.delete(X.id);else J={...J,credential:z}}return R7(J,this.pending,Z)})}replaceRow($,Z){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===$?Z(X):X)}}pollUnseenRows(){if(this.disposed||this.setAside())return;for(let $ of this.snapshot.rows){let Z=$.torn===!0&&$.enabled;if(!($.candidate||Z)||$.type!=="oauth")continue;let X=`${$.id}\x00${$.credentialEpoch??0}\x00${$.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading($.id,!0)}}requestReading($,Z=!1){if(this.disposed||this.setAside())return;let X=this.now(),J=this.lastPull.get($);if(!Z&&J!==void 0&&X-J<(this.deps.pullRetryMs??NY))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set($,X);let z=this.storeFor(this.deps.paths());return z.requestReading($),z.pullsSettled()}coalescedPull($){let Z=JSON.stringify([this.deps.paths().configPath,$.id,$.credentialEpoch,$.identity]),X=this.quotaPulls.get(Z);if(X)return X;let J=this.pull($).finally(()=>this.quotaPulls.delete(Z));return this.quotaPulls.set(Z,J),J}async pull($){let Z;try{Z=await this.deps.pullQuota($)}catch(J){throw this.pollOutcomes.set($.id,{id:$.id,ok:!1,error:J instanceof Error?J.message:String(J)}),J}this.pollOutcomes.set($.id,{id:$.id,ok:!0}),this.polledSnapshots.set($.id,Z.snapshot);let X=this.snapshot.rows.find((J)=>J.id===$.id);if(X&&X.credentialEpoch===$.credentialEpoch&&X.identity===$.identity)this.applyObservation(X,Z.observation);return Z.observation}applyObservation($,Z){A7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:t4(X.quota,Z),needsFirstReading:!1}))}recordSnapshot($,Z,X,J){if(!this.snapshot.active||this.disposed||this.setAside())return;let z=this.snapshot.rows.find((U)=>U.id===$);if(z?.type!=="oauth")return;let G=J2(X);if(!(G&&z.identity?G===z.identity:w1(z)?.access===X))return;let H=A0(Z,this.now(),J);if(!H)return;if(this.applyObservation(z,H),z.credentialEpoch===void 0)return;let Y={credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Q=this.storeFor(this.deps.paths()),V=(this.writes.get(z.id)??Promise.resolve()).then(async()=>{if(this.disposed||(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))return;return Q.recordQuota(z.id,Y,H)}).catch((U)=>{this.log.warn("pool quota not recorded",{rowId:z.id,error:U instanceof Error?U.message:String(U)})});this.writes.set(z.id,V),V.finally(()=>{if(this.writes.get(z.id)===V)this.writes.delete(z.id)})}rowForToken($){let Z=J2($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:w1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=E4(Z),z=[];for(let G of $){if(!G.candidate)continue;let B=w1(G);if(!B)continue;let H=(B.expires??0)-X;if(!(!B.access||!B.expires||H<=J)||this.refreshBackedOff(G,X))continue;z.push(this.refresh(G.id))}return Promise.all(z).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=w1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===z$(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=w1($);if(!X?.access.trim())return;if(typeof X.expires!=="number"||X.expires<=Z)return;return X.access}refresh($){let Z=this.refreshing.get($);if(Z)return Z;let X=this.runRefresh($).finally(()=>{if(this.refreshing.get($)===X)this.refreshing.delete($)});return this.refreshing.set($,X),X}async runRefresh($){let Z=this.snapshot.rows.find((J)=>J.id===$),X=Z?w1(Z)?.refresh:void 0;try{let J=await this.storeFor(this.deps.paths()).refresh($,this.deps.refreshProvider,{refuse:()=>this.setAside()?"vault-mode":void 0});if(this.setAside())return;if(J.status==="rotated"){this.backoff.delete($),this.rotated.set($,J.credential),this.replaceRow($,(z)=>({...z,credential:J.credential,...J.identity!==void 0&&z.identity===void 0?{identity:J.identity}:{}}));return}if(J.status==="identity-contradicted"){this.backoff.delete($),this.replaceRow($,(z)=>({...z,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:$});return}this.recordRefreshFailure($,X,Error(J.reason))}catch(J){this.recordRefreshFailure($,X,J)}}recordRefreshFailure($,Z,X){if(this.log.warn("pool row refresh failed",{rowId:$,error:X instanceof Error?X.message:String(X)}),!Z)return;this.backoff.set($,E7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return I7($,this.backoff,this.now(),(Z,X)=>this.usableToken(Z,X))}async pollRows($){if(this.setAside())return[];let Z=await this.load();if(!Z.active||this.disposed)return[];let X=Z.rows.filter((J)=>J.candidate&&J.type==="oauth");if(X.length===0)return[];await this.refreshDueTokens(X,$);for(let J of X)this.pollOutcomes.delete(J.id),this.requestReading(J.id,!0);return await this.poolStore().pullsSettled(),X.map((J)=>this.pollOutcomes.get(J.id)??{id:J.id,ok:!1,error:"the quota poll did not run"})}setAside(){return this.deps.vaultMode?.()===!0}dispose(){this.disposed=!0}async settled(){for(;;){let $=[...this.writes.values(),...this.refreshing.values(),...this.initializing?[this.initializing.promise]:[]];if(await Promise.allSettled($),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0)return}}}var _Y=v4,LY=500,OY=d("routing"),PY=64;function CY(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function z2($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:CY(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function TY($){let Z=$.resetAtMs!==void 0?` It resets at ${new Date($.resetAtMs).toISOString()}.`:"";switch($.reason){case"quota-unknown":return`No OpenAI account has a quota reading yet; one is being taken now. Try again in ${Z7} seconds.`;case"quota-exhausted":return`Every OpenAI account has used up its quota.${Z}`;case"killswitch":return"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).";case"mid-stream-rate-limit":return`Every OpenAI account is rate-limited.${Z}`;case"no-credential":return"No OpenAI account holds a usable sign-in. Sign in with `/login` or add an account with `/openai`."}}function SY($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class U6{main;pool;vault;deps;creditsServing=new m4;vaultTokens=new Map;now;paths;slot;slotVaultMode;slotNeedsRefresh=!1;slotQueue=Promise.resolve();storageCache;storageRead;constructor($){this.deps=$,this.now=$.now??Date.now,this.paths=$.paths??GX;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new Q6({now:this.now,poll:async(X,J)=>{if(await this.readAuthority()!=="local")throw Error("Pi login quota polling is disabled while enrolled");let z=await W$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:I0}),G=A0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new V6({paths:this.paths,now:this.now,...$.readBudgetMs!==void 0?{readBudgetMs:$.readBudgetMs}:{},vaultMode:()=>this.vaultMode(),vaultAuthority:()=>this.readAuthority(),refreshProvider:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local token refresh is disabled while enrolled");let J=await P5({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=v$({id_token:"",access_token:J.access,refresh_token:J.refresh});return{...J,...z?{identity:z}:{}}},pullQuota:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local quota polling is disabled while enrolled");let J=X.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await W$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=A0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new f4({host:"pi",stateDir:F3(this.paths().statePath),reservedRouteIds:()=>this.pool.peek().rows.map((X)=>X.id),fetchImpl:Z,now:this.now})}vaultMode(){return this.vault.enrolled()}readAuthority(){return this.vault.authority()}vaultSlot(){return this.slot??=this.deps.slot??$X(this.paths().statePath),this.slot}withSlot($){let Z=this.slotQueue.then($);return this.slotQueue=Z.catch(()=>{this.slotVaultMode=void 0}),Z}syncVaultSlot($,Z=!1){return this.withSlot(async()=>{if(await this.reconcileSlot(Z),this.slotNeedsRefresh&&$)await $(),this.slotNeedsRefresh=!1})}disconnectVault(){return this.withSlot(async()=>{this.slotVaultMode=void 0;try{let $=await this.vaultSlot().exitVault();return this.slotNeedsRefresh=!0,await this.vault.disconnect(),$}finally{await this.reconcileSlot()}})}async reconcileSlot($=!1){let Z=await this.readAuthority()!=="local";if(Z===this.slotVaultMode&&!$)return;let X=this.slotVaultMode;this.slotVaultMode=void 0;let J=await this.vaultSlot().inspect();if(Z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=Z&&J.slot!=="placeholder"||!Z&&J.slot==="placeholder"||X!==void 0&&Z!==X||this.slotNeedsRefresh;let z=await this.readAuthority()!=="local";if(z!==Z){if(z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=!0}this.slotVaultMode=z}async start(){return await this.readAuthority(),this.vault.start(),this.pool.load().then(()=>{},()=>{})}async storage(){let $=this.paths(),Z;try{let X=MY($.configPath);Z=`${$.configPath}|${X.ino}:${X.size}:${X.mtimeMs}`}catch{Z=`${$.configPath}|-`}if(this.storageCache?.key===Z)return this.storageCache.storage;if(this.storageRead?.key!==Z){let X=A4($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return I3(this.storageRead.promise,this.deps.readBudgetMs??LY,()=>this.storageCache?.storage??null)}accounts($){let Z=[];if(!this.vaultMode())this.localAccounts($,Z);for(let X of this.vault.routes())Z.push({id:X.id,token:void 0,kind:X.kind,vault:!0,...X.identity?{identity:X.identity}:{},...X.quota!==void 0?{quota:X.quota}:{}});return Z}localAccounts($,Z){let X=this.main.currentToken(),J=this.main.currentIdentity(),z=this.vault.identities();if(X&&!(J!==void 0&&z.has(J))){let H=this.main.quotaMap();Z.push({id:I0,token:X,...J?{identity:J}:{},...H?{quota:H}:{}})}let G=this.pool.peek(),B=this.now();if(G.active)for(let H of BX(G.rows,$,B,J,z))Z.push({id:H.id,token:this.pool.usableToken(H,B),...H.identity?{identity:H.identity}:{},...H.quota!==void 0?{quota:H.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===I0)return this.main.requestReading();if(this.vault.owns($))return this.vault.requestReading($);return this.pool.requestReading($)}rememberVaultToken($,Z){this.vaultTokens.delete($),this.vaultTokens.set($,Z);while(this.vaultTokens.size>PY){let X=this.vaultTokens.keys().next().value;if(X===void 0)break;this.vaultTokens.delete(X)}}recordHeaders($,Z,X){let J=new Headers(X),z=E9(J),G=I9(J),B=this.vaultTokens.get(Z);if(B?.id===$)this.vault.recordSnapshot($,z,G,B.receipt);else if($===I0)this.main.record(z,Z,G);else this.pool.recordSnapshot($,z,Z,G)}recordRateLimitFrame($,Z){let X=this.vaultTokens.get($);if(X){this.vault.recordSnapshot(X.id,Z,!0,X.receipt);return}if(this.main.record(Z,$,!0))return;let J=this.pool.rowForToken($);if(J)this.pool.recordSnapshot(J.id,Z,$,!0)}observeWebSocketMessage($,Z){if(!Z.includes("codex.rate_limits"))return;let X=SY($);if(!X)return;let J;try{J=JSON.parse(Z)}catch{return}if(!J||typeof J!=="object"||J.type!=="codex.rate_limits")return;this.recordRateLimitFrame(X,b9(J))}stream($,Z,X){let J=this.deps.createStream(),z=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==X2){J.push(z2($,t7));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(z2($,G.refusal?c5(G.refusal,this.vault.name):TY(G.block)));return}if(G.head)J.push(G.head);if(G.rest)for(;;){let B=await G.rest.next();if(B.done)break;J.push(B.value)}}catch(G){J.push(z2($,O1(G,X?.apiKey).message))}finally{J.end(),z()}})(),J}async route($,Z,X){let J=await this.storage(),z=await this.readAuthority()!=="local";if(z)await I3(this.vault.awaitRequestRoster().then(()=>!0),M3,()=>!1);else this.main.observeToken(X?.apiKey),await this.pool.current(),this.pool.refreshDueTokens(this.pool.peek().rows,J);let G=J?.routing?.mode??"main-first",B=!1,H=0,Q=await(()=>HX({accounts:()=>{let W=this.accounts(J);return H=W.length,W},storage:J,mode:G,mainId:z?O3(this.vault.routes()):void 0,sessionId:X?.sessionId,requestBytes:Buffer.byteLength(JSON.stringify(Z),"utf8"),now:this.now,refreshBackoff:(W)=>this.pool.refreshBackoffFor(W.map((V)=>this.poolRowById(V.id)).filter((V)=>V!==void 0)),requestPull:(W)=>this.requestPull(W),firstReadingWaitMs:this.deps.firstReadingWaitMs??_Y,send:(W)=>W.vault?this.vaultAttempt($,Z,X,W.id).then((V)=>{if(!V)B=!0;return V}):W.token?this.attempt($,Z,X,W.id,W.token):Promise.resolve(void 0),placePin:w7,creditsServing:this.creditsServing,log:{debug:()=>{},info:(W,V)=>OY.info(W,V)}}))();if(Q.kind==="blocked"){if(z&&(H===0||B))return{...Q,refusal:B?"vault-refused":s5(this.vault)};if(z&&Q.block.reason==="no-credential")return{...Q,refusal:"vault-empty"};return Q}return{kind:"sent",...Q.attempt}}async attempt($,Z,X,J,z){let G,B;try{let W=X?.fetch??globalThis.fetch;B=this.deps.streamSimple($,Z,{...X,apiKey:z,fetch:Object.assign(async(V,U)=>{try{return await g7(await W(V,U),z,"event-stream")}catch(K){throw O1(K,z)}},W),onResponse:async(V,U)=>{G=V.status,this.recordHeaders(J,z,V.headers),await X?.onResponse?.(V,U)}})}catch(W){return{head:z2($,O1(W,z).message),rest:void 0}}let H=async function*(){try{for await(let W of B){if(W.type==="error")W.error.errorMessage=L1(W.error.errorMessage??"",z);yield W}}catch(W){yield z2($,O1(W,z).message)}}(),Y=await H.next(),Q=Y.done?void 0:Y.value;return{...G!==void 0?{status:G}:{},head:Q,rest:Y.done||Q?.type==="error"?void 0:H}}async vaultAttempt($,Z,X,J){let z;return await this.vault.send(J,async(B,H)=>{return this.rememberVaultToken(B,{id:J,receipt:{credentialId:H.credentialId,accountIdentitySource:H.accountIdentitySource,...H.accountIdentity!==void 0?{accountIdentity:H.accountIdentity}:{},...H.expectedAccountIdentity!==void 0?{expectedAccountIdentity:H.expectedAccountIdentity}:{}}}),z=await this.attempt($,Z,X,J,B),new Response(null,{status:z.status??200})},{site:"model",...X?.signal?{signal:X.signal}:{}})?z:void 0}commandSupport(){return{vaultMode:()=>this.vaultMode(),readAuthority:()=>this.readAuthority(),syncVaultSlot:($,Z)=>this.syncVaultSlot($,Z),disconnectVault:()=>this.disconnectVault(),observeLogin:async($)=>{if(await this.readAuthority()==="local")this.main.observeToken($)},store:()=>this.pool.poolStore(),mainIdentity:()=>this.main.currentIdentity(),mainQuota:()=>this.main.quotaSnapshot(),reload:()=>this.pool.load(),vault:this.vault,refreshAllQuota:async()=>{let $=await this.readAuthority()==="local"?await this.storage():null;if(await this.readAuthority()!=="local")return(await this.vault.pollStale(0)).map((G)=>({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}}));let[Z,X,J]=await Promise.all([this.main.currentToken()?this.main.pollNow():void 0,this.pool.pollRows($),this.vault.pollStale(0)]),z=[];if(Z)z.push({account:I0,ok:Z.ok,...Z.error?{error:Z.error}:{}});for(let G of[...X,...J])z.push({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}});return z}}}}var B2="https://chatgpt.com/backend-api",WX;class K6 extends Y6{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=WX;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var G2=0,j6;function EY(){let $=globalThis;if(G2===0)j6=$.WebSocket,$.WebSocket=K6;return G2++,()=>{if(G2=Math.max(0,G2-1),G2===0){if($.WebSocket===K6)$.WebSocket=j6;j6=void 0}}}var IY=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:B2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:B2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:B2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:B2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}],bY=5000;function QX($,Z){$.registerProvider("openai-codex",{baseUrl:B2,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:X2}:{},models:IY,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function xY(){return new U6({streamSimple:($,Z,X)=>RY($,Z,X),createStream:AY,installWebSocket:EY})}async function kY($){let Z=xY();WX=(B,H)=>Z.observeWebSocketMessage(B,H);let X,J,z=(B=!0)=>Z.syncVaultSlot(X?async()=>{QX($,Z),await X?.()}:void 0,B),G=()=>{z(!1).catch(()=>{J?.("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error")})};if(ZX($,{pool:Z.commandSupport(),afterApply:z,onContext:(B)=>{X=()=>B.modelRegistry.refresh(),J=(H,Y)=>B.ui.notify(H,Y)}}),await z().catch(()=>{}),QX($,Z),setInterval(G,bY).unref?.(),typeof $.on==="function")$.on("session_start",async(B,H)=>{X=()=>H.modelRegistry.refresh(),J=(Y,Q)=>H.ui.notify(Y,Q),Z.start();try{await z()}catch{J("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error");return}if(Z.vaultMode())return;try{await Z.commandSupport().observeLogin(await H.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{QX as registerPiProvider,EY as installRawCodexWebSocket,kY as default,xY as createPiOpenAIRuntime};
122
+ `)[0]??"",G=J.match(/sec-websocket-accept:\s*(\S+)/i);if(!z.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:z}),this.emit("error",{message:`WS upgrade failed: ${z}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:z}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(X+4),this.log("open",{statusLine:z}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],X=$[1],J=(Z&128)!==0,z=Z&15,G=(X&128)!==0,B=X&127,H=2;if(B===126){if($.length<4)return;B=$[2]<<8|$[3],H=4}else if(B===127){if($.length<10)return;B=0;for(let Q=0;Q<8;Q++)B=B*256+$[2+Q];H=10}if(G)H+=4;if($.length<H+B)return;let Y=$.slice(H,H+B);this.rxBuffer=$.slice(H+B),this.handleFrame(J,z,Y)}}handleFrame($,Z,X){if(Z===9){this.writeFrame(10,X);return}if(Z===10)return;if(Z===8){let z=1005,G="";if(X.length>=2)z=X[0]<<8|X[1],G=Buffer.from(X.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:z,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[X];else if(Z===0)this.fragChunks.push(X);if(!$)return;let J=NY(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let z=Buffer.from(J).toString("utf-8");this.emit("message",{data:z})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let X=Z.length,J=crypto.getRandomValues(new Uint8Array(4)),z;if(X<126)z=[128|$,128|X];else if(X<65536)z=[128|$,254,X>>8&255,X&255];else{z=[128|$,255];for(let H=7;H>=0;H--)z.push(X/2**(8*H)&255)}let G=new Uint8Array(X);for(let H=0;H<X;H++)G[H]=Z[H]^J[H%4];let B=new Uint8Array(z.length+4+X);B.set(z,0),B.set(J,z.length),B.set(G,z.length+4);try{this.socket?.write(B)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function KY($){return $}function DY($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function NY($){let Z=0;for(let z of $)Z+=z.length;let X=new Uint8Array(Z),J=0;for(let z of $)X.set(z,J),J+=z.length;return X}import{statSync as AY}from"node:fs";var qY=15000;function G2($){if(!$)return;let Z=B$($);return Z?H$(Z):void 0}class K4{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=G2($);if(this.token!==void 0&&this.accountKey(this.token,this.identity)!==this.accountKey($,Z))this.quota=void 0,this.snapshot=void 0;this.token=$,this.identity=Z;let X=this.accountKey($,Z);if(this.firstPolledFor!==X)this.firstPolledFor=X,this.pollNow()}currentToken(){return this.token}currentIdentity(){return this.identity}quotaMap(){return this.quota}quotaSnapshot(){let $=K$(this.quota),Z=this.quota?.credits;if(!$&&!this.snapshot&&!Z)return;return{...this.snapshot?.resetCreditsAvailable!==void 0?{resetCreditsAvailable:this.snapshot.resetCreditsAvailable}:{},...this.snapshot?.spendControl?{spendControl:this.snapshot.spendControl}:{},...Z?{credits:{...Z}}:{},...$}}requestReading($=!1){let Z=this.now();if(!$&&this.lastPull!==void 0&&Z-this.lastPull<(this.deps.pullRetryMs??qY))return this.inflight;return this.pollNow()}pending(){return this.inflight}pollNow(){if(this.inflight)return this.inflight;let $=this.token;if(!$)return Promise.resolve({ok:!1,error:"Pi holds no OpenAI login"});let Z=this.identity;this.lastPull=this.now();let X=(async()=>{try{let J=await this.deps.poll($,Z);if(this.accountKey(this.token,this.identity)!==this.accountKey($,Z))return{ok:!0};return this.snapshot=J.snapshot,this.merge(J.observation),{ok:!0}}catch(J){let z=J instanceof Error?J.message:String(J);return this.deps.log?.warn("Pi login quota poll failed",{error:z}),{ok:!1,error:z}}})();return this.inflight=X,X.finally(()=>{if(this.inflight===X)this.inflight=void 0}),X}record($,Z,X){if(!this.owns(Z))return!1;let J=R0($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=G2($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=u0(this.quota,$);if(X0(Z))this.quota=Z}catch(Z){this.deps.log?.warn("Pi login quota observation not merged",{error:Z instanceof Error?Z.message:String(Z)})}}accountKey($,Z){if(Z)return`identity:${Z}`;return $?`token:${$}`:void 0}}import{homedir as FY}from"node:os";import{join as WX}from"node:path";function MY(){return process.env.PI_AGENT_DIR?.trim()||WX(FY(),".pi","agent")}function VX(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||WX(MY(),n2)}function LY($=VX()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||w3($)}function UX($=VX()){return{configPath:$,statePath:LY($)}}function D4($){return $!==void 0&&($.vault===!0||!!$.token)}function jX($,Z,X,J,z=new Set){return $.filter((G)=>{if(!G.candidate||G.type!=="oauth")return!1;if(G.credential?.type!=="oauth")return!1;if(m0(G.credential))return!1;if(G.id===b0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return F6(K$(G.quota),Z,X)})}function x6($,Z){let X=$.now(),J=H7(Z,$.storage,X);return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...X0(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function KX($){let Z=$.accounts(),X=W7(x6($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await OY($,Z,$.sessionId);if(J)return J}return _Y($,Z)}async function _Y($,Z){let X=Q7($.mode),J=x6($,Z),z=U7({...J,placement:X,mainId:$.mainId});if(z.kind==="block")return $.log?.debug("pool admission blocked the request",{reason:z.block.reason}),{kind:"blocked",block:z.block};if(z.lastPath)$.log?.debug("pool admission: every account is exhausted; probing anyway",{order:z.order});let G=new Map(Z.map((W)=>[W.id,W])),B=p5($.storage),H=[],Y=new Set,Q;for(;;){let W=d6(z.order.filter((K)=>!Y.has(K)),H,B);if(W===void 0)break;let V=G.get(W);if(!D4(V)){Y.add(W);continue}let U=await $.send(V);if(!U){Y.add(W);continue}Q={attempt:U,accountId:V.id},H.push({id:V.id,...U.status!==void 0?{status:U.status}:{}})}if(Q)return DX($,J,Q.accountId),{kind:"sent",...Q};return{kind:"blocked",block:{reason:"no-credential"}}}async function OY($,Z,X){let J=$.requestBytes,z=new Map(Z.map((D)=>[D.id,D])),G=x6($,Z),B=cZ(G),H={requestBytes:J,reservePercent:(D)=>M1($.storage,D===b0?void 0:D),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},Y=(D,F,_)=>(R,M)=>{let N=new Set(R);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:D.rows.map((L)=>L.id).filter((L)=>!F.excluded.has(L)),excludeAccountIds:R,quotaCheckedAtByAccount:Object.fromEntries(D.rows.map((L)=>[L.id,F.projections.get(L.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(_.map((L)=>[L.id,L.identity])),select:(L)=>K7(D,H,N,L),persist:M})},Q=Y(G,B,Z),W=Q([],!0);if(!W)return;let V=W.accountId,U=(D)=>{let F=Q([V],!0);if(!F)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:V,toAccountId:F.accountId,reason:D}),V=F.accountId,!0},K=D7(G,H,V);if(K.kind==="none")return;if(K.kind==="move"){if(!U(K.reason)&&K.reason==="killswitch")return}else if(K.kind==="detour"){let D=Q([V],!1);if(!D)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:V,servedAccountId:D.accountId}),V=D.accountId}let j=z.get(V);if(!D4(j))return;let q=await $.send(j);if(!q)return;if(q.status===401||q.status===403||q.status===429){let D=$.accounts();G=x6($,D),B=cZ(G),Q=Y(G,B,D);let F=N7(G,B,V,q.status);if(F.action==="migrate"){let _=V;if(U(F.reason)&&V!==_){let R=D.find((N)=>N.id===V),M=D4(R)?await $.send(R):void 0;if(R&&M)q=M,j=R;else V=_}}}return DX($,G,j.id),{kind:"sent",attempt:q,accountId:j.id}}function DX($,Z,X){let J=$.log,z=J?.info;$.creditsServing?.served(Z,X,J&&z?{info:(G,B)=>z.call(J,G,B)}:void 0)}var PY=500,CY=15000;function k6($,Z,X){return new Promise((J,z)=>{let G=setTimeout(()=>J(X()),Z);G.unref?.(),$.then((B)=>{clearTimeout(G),J(B)},(B)=>{clearTimeout(G),z(B)})})}var TY={info(){},warn(){}};class N4{deps;now;log;snapshot={active:!1,rows:[],key:void 0,readAt:0};inflightRead;store;stores=new Set;disposal;initializing;refreshing=new Map;backoff=new Map;rotated=new Map;pending=new Map;writes=new Map;lastPull=new Map;quotaPulls=new Map;polled=new Set;polledSnapshots=new Map;pollOutcomes=new Map;disposed=!1;constructor($){this.deps=$,this.now=$.now??Date.now,this.log=$.log??TY}peek(){return{active:this.snapshot.active,rows:this.snapshot.rows}}async current(){let $=this.filesKey();if(this.snapshot.key===$)return this.peek();let Z=await k6(this.startRead($),this.deps.readBudgetMs??PY,()=>this.snapshot);return{active:Z.active,rows:Z.rows}}async load(){let $=await this.startRead(this.filesKey());return{active:$.active,rows:$.rows}}poolStore(){return this.storeFor(this.deps.paths())}polledSnapshot($){return this.polledSnapshots.get($)}filesKey(){let $=this.deps.paths();return`${$.configPath}|${X4($.configPath)}|${X4($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=S3({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:m6,coalesceQuota:!0,now:this.now,pull:(X)=>this.coalescedPull(X),onPullFailure:(X,J)=>{this.pollOutcomes.set(X,{id:X,ok:!1,error:J.message}),this.log.warn("pool quota poll failed",{rowId:X,kind:J.kind,error:J.message})},logger:this.log,...this.deps.store,onStep:async(X,J)=>{if(await this.deps.store?.onStep?.(X,J),J.operation!=="updateSettings"&&X.startsWith("before-")&&(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside()))throw Error("Local account writes are disabled while connected to the vault.")}});return this.store={configPath:$.configPath,store:Z},this.stores.add(Z),Z}startRead($){if(this.inflightRead?.key===$)return this.inflightRead.promise;let Z=this.now(),X=this.read($,Z),J={key:$,promise:X};this.inflightRead=J;let z=()=>{if(this.inflightRead===J)this.inflightRead=void 0};return X.then(z,z),X}async read($,Z){let X=this.deps.paths(),J;try{J=await this.storeFor(X).read()}catch(G){return this.log.warn("account pool read failed",{error:G instanceof Error?G.message:String(G)}),this.snapshot}if(J.status==="pending-migration"){if(!this.setAside())this.initialize(X)}else if(J.status==="error")this.log.warn("account pool is unreadable",{file:J.file,reason:J.reason});let z=J.status==="ready"?{active:!0,rows:J.rows,key:$,readAt:Z}:{active:!1,rows:[],key:$,readAt:Z};if(Z>=this.snapshot.readAt)this.snapshot={...z,rows:this.withLocalState(z.rows)};if(this.snapshot.active)this.pollUnseenRows();return this.snapshot}initialize($){if(this.disposed||this.initializing?.configPath===$.configPath)return;let Z=this.storeFor($).initialize().then((X)=>{this.log.info("account pool initialized",{status:X.status})},(X)=>{if(this.log.warn("account pool initialization failed",{error:X instanceof Error?X.message:String(X)}),this.initializing?.promise===Z)this.initializing=void 0});this.initializing={configPath:$.configPath,promise:Z}}withLocalState($){let Z=this.now();return $.map((X)=>{let J=X,z=this.rotated.get(X.id);if(z?.type==="oauth"&&X.credential?.type==="oauth"){let G=X.credential.lastRefreshedAt??0,B=z.lastRefreshedAt??0;if(G>=B)this.rotated.delete(X.id);else J={...J,credential:z}}return y7(J,this.pending,Z)})}replaceRow($,Z){this.snapshot={...this.snapshot,rows:this.snapshot.rows.map((X)=>X.id===$?Z(X):X)}}pollUnseenRows(){if(this.disposed||this.setAside())return;for(let $ of this.snapshot.rows){let Z=$.torn===!0&&$.enabled;if(!($.candidate||Z)||$.type!=="oauth")continue;let X=`${$.id}\x00${$.credentialEpoch??0}\x00${$.identity??""}`;if(this.polled.has(X))continue;this.polled.add(X),this.requestReading($.id,!0)}}requestReading($,Z=!1){if(this.disposed||this.setAside())return;let X=this.now(),J=this.lastPull.get($);if(!Z&&J!==void 0&&X-J<(this.deps.pullRetryMs??CY))return this.storeFor(this.deps.paths()).pullsSettled();this.lastPull.set($,X);let z=this.storeFor(this.deps.paths());return z.requestReading($),z.pullsSettled()}coalescedPull($){let Z=JSON.stringify([this.deps.paths().configPath,$.id,$.credentialEpoch,$.identity]),X=this.quotaPulls.get(Z);if(X)return X;let J=this.pull($).finally(()=>this.quotaPulls.delete(Z));return this.quotaPulls.set(Z,J),J}async pull($){let Z;try{Z=await this.deps.pullQuota($)}catch(J){throw this.pollOutcomes.set($.id,{id:$.id,ok:!1,error:J instanceof Error?J.message:String(J)}),J}this.pollOutcomes.set($.id,{id:$.id,ok:!0}),this.polledSnapshots.set($.id,Z.snapshot);let X=this.snapshot.rows.find((J)=>J.id===$.id);if(X&&X.credentialEpoch===$.credentialEpoch&&X.identity===$.identity)this.applyObservation(X,Z.observation);return Z.observation}applyObservation($,Z){f7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:J4(X.quota,Z),needsFirstReading:!1}))}recordSnapshot($,Z,X,J){if(!this.snapshot.active||this.disposed||this.setAside())return;let z=this.snapshot.rows.find((U)=>U.id===$);if(z?.type!=="oauth")return;let G=G2(X);if(!(G&&z.identity?G===z.identity:p1(z)?.access===X))return;let H=R0(Z,this.now(),J);if(!H)return;if(this.applyObservation(z,H),z.credentialEpoch===void 0)return;let Y={credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Q=this.storeFor(this.deps.paths()),V=(this.writes.get(z.id)??Promise.resolve()).then(async()=>{if(this.deps.vaultAuthority?await this.deps.vaultAuthority()!=="local":this.setAside())return;return Q.recordQuota(z.id,Y,H)}).catch((U)=>{this.log.warn("pool quota not recorded",{rowId:z.id,error:U instanceof Error?U.message:String(U)})});this.writes.set(z.id,V),V.finally(()=>{if(this.writes.get(z.id)===V)this.writes.delete(z.id)})}rowForToken($){let Z=G2($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:p1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=fZ(Z),z=[];for(let G of $){if(!G.candidate)continue;let B=p1(G);if(!B)continue;let H=(B.expires??0)-X;if(!(!B.access||!B.expires||H<=J)||this.refreshBackedOff(G,X))continue;z.push(this.refresh(G.id))}return Promise.all(z).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=p1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===z$(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=p1($);if(!X?.access.trim())return;if(typeof X.expires!=="number"||X.expires<=Z)return;return X.access}refresh($){let Z=this.refreshing.get($);if(Z)return Z;let X=this.runRefresh($).finally(()=>{if(this.refreshing.get($)===X)this.refreshing.delete($)});return this.refreshing.set($,X),X}async runRefresh($){let Z=this.snapshot.rows.find((J)=>J.id===$),X=Z?p1(Z)?.refresh:void 0;try{let J=await this.storeFor(this.deps.paths()).refresh($,this.deps.refreshProvider,{refuse:()=>this.setAside()?"vault-mode":void 0});if(this.setAside())return;if(J.status==="rotated"){this.backoff.delete($),this.rotated.set($,J.credential),this.replaceRow($,(z)=>({...z,credential:J.credential,...J.identity!==void 0&&z.identity===void 0?{identity:J.identity}:{}}));return}if(J.status==="identity-contradicted"){this.backoff.delete($),this.replaceRow($,(z)=>({...z,enabled:!1,candidate:!1})),this.log.warn("pool row disabled: its refresh returned a different account",{rowId:$});return}this.recordRefreshFailure($,X,Error(J.reason))}catch(J){this.recordRefreshFailure($,X,J)}}recordRefreshFailure($,Z,X){if(this.log.warn("pool row refresh failed",{rowId:$,error:X instanceof Error?X.message:String(X)}),!Z)return;this.backoff.set($,g7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return h7($,this.backoff,this.now(),(Z,X)=>this.usableToken(Z,X))}async pollRows($){if(this.setAside())return[];let Z=await this.load();if(!Z.active||this.disposed)return[];let X=Z.rows.filter((J)=>J.candidate&&J.type==="oauth");if(X.length===0)return[];await this.refreshDueTokens(X,$);for(let J of X)this.pollOutcomes.delete(J.id),this.requestReading(J.id,!0);return await this.poolStore().pullsSettled(),X.map((J)=>this.pollOutcomes.get(J.id)??{id:J.id,ok:!1,error:"the quota poll did not run"})}setAside(){return this.deps.vaultMode?.()===!0}dispose(){return this.disposed=!0,this.disposal??=(async()=>{await Promise.allSettled([...this.writes.values()]),await Promise.all([...this.stores].map(($)=>$.close()))})(),this.disposal}async settled(){for(;;){let $=[...this.writes.values(),...this.refreshing.values(),...this.initializing?[this.initializing.promise]:[]];if(await Promise.allSettled($),await this.store?.store.pullsSettled(),this.writes.size===0&&this.refreshing.size===0){await this.disposal;return}}}}var SY=uZ,RY=500,EY=u("routing"),IY=64;function bY(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function B2($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:bY(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function xY($){let Z=$.resetAtMs!==void 0?` It resets at ${new Date($.resetAtMs).toISOString()}.`:"";switch($.reason){case"quota-unknown":return`No OpenAI account has a quota reading yet; one is being taken now. Try again in ${Y7} seconds.`;case"quota-exhausted":return`Every OpenAI account has used up its quota.${Z}`;case"killswitch":return"Every OpenAI account is below its killswitch quota floor (see the Limits section of `/openai`).";case"mid-stream-rate-limit":return`Every OpenAI account is rate-limited.${Z}`;case"no-credential":return"No OpenAI account holds a usable sign-in. Sign in with `/login` or add an account with `/openai`."}}function kY($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class q4{main;pool;vault;deps;creditsServing=new dZ;vaultTokens=new Map;now;paths;slot;slotVaultMode;slotNeedsRefresh=!1;slotQueue=Promise.resolve();storageCache;storageRead;constructor($){this.deps=$,this.now=$.now??Date.now,this.paths=$.paths??UX;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new K4({now:this.now,poll:async(X,J)=>{if(await this.readAuthority()!=="local")throw Error("Pi login quota polling is disabled while enrolled");let z=await W$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:b0}),G=R0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new N4({paths:this.paths,now:this.now,...$.readBudgetMs!==void 0?{readBudgetMs:$.readBudgetMs}:{},vaultMode:()=>this.vaultMode(),vaultAuthority:()=>this.readAuthority(),refreshProvider:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local token refresh is disabled while enrolled");let J=await I5({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=w$({id_token:"",access_token:J.access,refresh_token:J.refresh});return{...J,...z?{identity:z}:{}}},pullQuota:async(X)=>{if(await this.readAuthority()!=="local")throw Error("Local quota polling is disabled while enrolled");let J=X.credential;if(J.type!=="oauth"||!J.access)throw Error("the row holds no access token to poll with");let z=await W$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=R0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new mZ({host:"pi",stateDir:_6(this.paths().statePath),reservedRouteIds:()=>this.pool.peek().rows.map((X)=>X.id),fetchImpl:Z,now:this.now})}vaultMode(){return this.vault.enrolled()}readAuthority(){return this.vault.authority()}vaultSlot(){return this.slot??=this.deps.slot??HX(this.paths().statePath),this.slot}withSlot($){let Z=this.slotQueue.then($);return this.slotQueue=Z.catch(()=>{this.slotVaultMode=void 0}),Z}syncVaultSlot($,Z=!1){return this.withSlot(async()=>{if(await this.reconcileSlot(Z),this.slotNeedsRefresh&&$)await $(),this.slotNeedsRefresh=!1})}disconnectVault(){return this.withSlot(async()=>{this.slotVaultMode=void 0;try{let $=await this.vaultSlot().exitVault();return this.slotNeedsRefresh=!0,await this.vault.disconnect(),$}finally{await this.reconcileSlot()}})}async reconcileSlot($=!1){let Z=await this.readAuthority()!=="local";if(Z===this.slotVaultMode&&!$)return;let X=this.slotVaultMode;this.slotVaultMode=void 0;let J=await this.vaultSlot().inspect();if(Z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=Z&&J.slot!=="placeholder"||!Z&&J.slot==="placeholder"||X!==void 0&&Z!==X||this.slotNeedsRefresh;let z=await this.readAuthority()!=="local";if(z!==Z){if(z)await this.vaultSlot().enterVault();else await this.vaultSlot().exitVault();this.slotNeedsRefresh=!0}this.slotVaultMode=z}async start(){return await this.readAuthority(),this.vault.start(),this.pool.load().then(()=>{},()=>{})}async storage(){let $=this.paths(),Z;try{let X=AY($.configPath);Z=`${$.configPath}|${X.ino}:${X.size}:${X.mtimeMs}`}catch{Z=`${$.configPath}|-`}if(this.storageCache?.key===Z)return this.storageCache.storage;if(this.storageRead?.key!==Z){let X=xZ($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return k6(this.storageRead.promise,this.deps.readBudgetMs??RY,()=>this.storageCache?.storage??null)}accounts($){let Z=[];if(!this.vaultMode())this.localAccounts($,Z);for(let X of this.vault.routes())Z.push({id:X.id,token:void 0,kind:X.kind,vault:!0,...X.identity?{identity:X.identity}:{},...X.quota!==void 0?{quota:X.quota}:{}});return Z}localAccounts($,Z){let X=this.main.currentToken(),J=this.main.currentIdentity(),z=this.vault.identities();if(X&&!(J!==void 0&&z.has(J))){let H=this.main.quotaMap();Z.push({id:b0,token:X,...J?{identity:J}:{},...H?{quota:H}:{}})}let G=this.pool.peek(),B=this.now();if(G.active)for(let H of jX(G.rows,$,B,J,z))Z.push({id:H.id,token:this.pool.usableToken(H,B),...H.identity?{identity:H.identity}:{},...H.quota!==void 0?{quota:H.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===b0)return this.main.requestReading();if(this.vault.owns($))return this.vault.requestReading($);return this.pool.requestReading($)}rememberVaultToken($,Z){this.vaultTokens.delete($),this.vaultTokens.set($,Z);while(this.vaultTokens.size>IY){let X=this.vaultTokens.keys().next().value;if(X===void 0)break;this.vaultTokens.delete(X)}}recordHeaders($,Z,X){let J=new Headers(X),z=y9(J),G=g9(J),B=this.vaultTokens.get(Z);if(B?.id===$)this.vault.recordSnapshot($,z,G,B.receipt);else if($===b0)this.main.record(z,Z,G);else this.pool.recordSnapshot($,z,Z,G)}recordRateLimitFrame($,Z){let X=this.vaultTokens.get($);if(X){this.vault.recordSnapshot(X.id,Z,!0,X.receipt);return}if(this.main.record(Z,$,!0))return;let J=this.pool.rowForToken($);if(J)this.pool.recordSnapshot(J.id,Z,$,!0)}observeWebSocketMessage($,Z){if(!Z.includes("codex.rate_limits"))return;let X=kY($);if(!X)return;let J;try{J=JSON.parse(Z)}catch{return}if(!J||typeof J!=="object"||J.type!=="codex.rate_limits")return;this.recordRateLimitFrame(X,h9(J))}stream($,Z,X){let J=this.deps.createStream(),z=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==z2){J.push(B2($,GX));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(B2($,G.refusal?t5(G.refusal,this.vault.name):xY(G.block)));return}if(G.head)J.push(G.head);if(G.rest)for(;;){let B=await G.rest.next();if(B.done)break;J.push(B.value)}}catch(G){J.push(B2($,P1(G,X?.apiKey).message))}finally{J.end(),z()}})(),J}async route($,Z,X){let J=await this.storage(),z=await this.readAuthority()!=="local";if(z)await k6(this.vault.awaitRequestRoster().then(()=>!0),O6,()=>!1);else this.main.observeToken(X?.apiKey),await this.pool.current(),this.pool.refreshDueTokens(this.pool.peek().rows,J);let G=J?.routing?.mode??"main-first",B=!1,H=0,Q=await(()=>KX({accounts:()=>{let W=this.accounts(J);return H=W.length,W},storage:J,mode:G,mainId:z?T6(this.vault.routes()):void 0,sessionId:X?.sessionId,requestBytes:Buffer.byteLength(JSON.stringify(Z),"utf8"),now:this.now,refreshBackoff:(W)=>this.pool.refreshBackoffFor(W.map((V)=>this.poolRowById(V.id)).filter((V)=>V!==void 0)),requestPull:(W)=>this.requestPull(W),firstReadingWaitMs:this.deps.firstReadingWaitMs??SY,send:(W)=>W.vault?this.vaultAttempt($,Z,X,W.id).then((V)=>{if(!V)B=!0;return V}):W.token?this.attempt($,Z,X,W.id,W.token):Promise.resolve(void 0),placePin:a7,creditsServing:this.creditsServing,log:{debug:()=>{},info:(W,V)=>EY.info(W,V)}}))();if(Q.kind==="blocked"){if(z&&(H===0||B))return{...Q,refusal:B?"vault-refused":e5(this.vault)};if(z&&Q.block.reason==="no-credential")return{...Q,refusal:"vault-empty"};return Q}return{kind:"sent",...Q.attempt}}async attempt($,Z,X,J,z){let G,B;try{let W=X?.fetch??globalThis.fetch;B=this.deps.streamSimple($,Z,{...X,apiKey:z,fetch:Object.assign(async(V,U)=>{try{return await u7(await W(V,U),z,"event-stream")}catch(K){throw P1(K,z)}},W),onResponse:async(V,U)=>{G=V.status,this.recordHeaders(J,z,V.headers),await X?.onResponse?.(V,U)}})}catch(W){return{head:B2($,P1(W,z).message),rest:void 0}}let H=async function*(){try{for await(let W of B){if(W.type==="error")W.error.errorMessage=O1(W.error.errorMessage??"",z);yield W}}catch(W){yield B2($,P1(W,z).message)}}(),Y=await H.next(),Q=Y.done?void 0:Y.value;return{...G!==void 0?{status:G}:{},head:Q,rest:Y.done||Q?.type==="error"?void 0:H}}async vaultAttempt($,Z,X,J){let z;return await this.vault.send(J,async(B,H)=>{return this.rememberVaultToken(B,{id:J,receipt:{credentialId:H.credentialId,accountIdentitySource:H.accountIdentitySource,...H.accountIdentity!==void 0?{accountIdentity:H.accountIdentity}:{},...H.expectedAccountIdentity!==void 0?{expectedAccountIdentity:H.expectedAccountIdentity}:{}}}),z=await this.attempt($,Z,X,J,B),new Response(null,{status:z.status??200})},{site:"model",...X?.signal?{signal:X.signal}:{}})?z:void 0}commandSupport(){return{vaultMode:()=>this.vaultMode(),readAuthority:()=>this.readAuthority(),syncVaultSlot:($,Z)=>this.syncVaultSlot($,Z),disconnectVault:()=>this.disconnectVault(),observeLogin:async($)=>{if(await this.readAuthority()==="local")this.main.observeToken($)},store:()=>this.pool.poolStore(),mainIdentity:()=>this.main.currentIdentity(),mainQuota:()=>this.main.quotaSnapshot(),reload:()=>this.pool.load(),vault:this.vault,refreshAllQuota:async()=>{let $=await this.readAuthority()==="local"?await this.storage():null;if(await this.readAuthority()!=="local")return(await this.vault.pollStale(0)).map((G)=>({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}}));let[Z,X,J]=await Promise.all([this.main.currentToken()?this.main.pollNow():void 0,this.pool.pollRows($),this.vault.pollStale(0)]),z=[];if(Z)z.push({account:b0,ok:Z.ok,...Z.error?{error:Z.error}:{}});for(let G of[...X,...J])z.push({account:G.id,ok:G.ok,...G.error?{error:G.error}:{}});return z}}}}var Y2="https://chatgpt.com/backend-api",qX;class M4 extends j4{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=qX;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var H2=0,F4;function gY(){let $=globalThis;if(H2===0)F4=$.WebSocket,$.WebSocket=M4;return H2++,()=>{if(H2=Math.max(0,H2-1),H2===0){if($.WebSocket===M4)$.WebSocket=F4;F4=void 0}}}var hY=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:Y2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:Y2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:Y2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:Y2,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}],vY=5000;function NX($,Z){$.registerProvider("openai-codex",{baseUrl:Y2,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:z2}:{},models:hY,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function mY(){return new q4({streamSimple:($,Z,X)=>yY($,Z,X),createStream:fY,installWebSocket:gY})}async function wY($){let Z=mY();qX=(H,Y)=>Z.observeWebSocketMessage(H,Y);let X,J,z=(H=!0)=>Z.syncVaultSlot(X?async()=>{NX($,Z),await X?.()}:void 0,H),G=()=>{z(!1).catch(()=>{J?.("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error")})};YX($,{pool:Z.commandSupport(),afterApply:z,onContext:(H)=>{X=()=>H.modelRegistry.refresh(),J=(Y,Q)=>H.ui.notify(Y,Q)}}),await z().catch(()=>{}),NX($,Z);let B=setInterval(G,vY);if(B.unref?.(),typeof $.on==="function")$.on("session_shutdown",async()=>{clearInterval(B),await Z.pool.dispose()}),$.on("session_start",async(H,Y)=>{X=()=>Y.modelRegistry.refresh(),J=(Q,W)=>Y.ui.notify(Q,W),Z.start();try{await z()}catch{J("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error");return}if(Z.vaultMode())return;try{await Z.commandSupport().observeLogin(await Y.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{NX as registerPiProvider,gY as installRawCodexWebSocket,wY as default,mY as createPiOpenAIRuntime};