@cortexkit/pi-openai-auth 1.3.0 → 1.4.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.d.ts +67 -28
- package/dist/index.js +23 -23
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{createRequire as k5}from"node:module";var f5=k5(import.meta.url);import{createAssistantMessageEventStream as IB}from"@earendil-works/pi-ai";import{streamSimple as bB}from"@earendil-works/pi-ai/compat";var s="all",L3=Object.freeze(["primary"]);function e4($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function y1($,Z){return JSON.stringify([$,Z])}function N1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j0($){return typeof $==="number"&&Number.isFinite($)}function t4($){return typeof $==="string"&&$.length>0}function O0($,Z,X){return $[Z]===void 0||X($[Z])}function y5($){return j0($)&&$>0}function F3($){return typeof $==="string"}function g5($){if(!N1($)||!t4($.scope)||!t4($.label))return!1;switch($.kind){case"reading":return j0($.checkedAt)&&j0($.usedPercent)&&O0($,"resetsAt",F3)&&O0($,"windowMinutes",y5);case"retired":return j0($.retiredAt);case"absent":return j0($.checkedAt);default:return!1}}function h5($){if(!N1($)||!j0($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&O0($,"remainingPercent",j0)&&O0($,"usedPercent",j0)&&O0($,"resetsAt",F3)&&O0($,"limit",j0)&&O0($,"used",j0)&&O0($,"remaining",j0)&&O0($,"unit",F3)}function $6($){return N1($)&&j0($.value)&&Number.isInteger($.value)&&$.value>=0&&j0($.checkedAt)}function _3($){return N1($)&&Object.values($).every($6)}function O3($){if(!N1($))return;let Z=Object.entries($).filter(([,X])=>$6(X));return Z.length===0?void 0:Object.fromEntries(Z)}function M1($){if(B0($))return $;if(!N1($))return;let{counters:Z,...X}=$;if(!B0(X))return;let J=O3(Z);return{...X,...J===void 0?{}:{counters:J}}}function B0($){if(!N1($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!g5(X))return!1;let J=y1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return O0($,"budget",h5)&&O0($,"counters",_3)}class X2 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function z2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J2($){return typeof $==="number"&&Number.isFinite($)}function Z6($){return $===void 0||typeof $==="string"&&$!==""}function X6($){return typeof $==="string"&&$!==""}function W$($,Z){return $[Z]===void 0||J2($[Z])}function C3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function v5($){return z2($)&&Z6($.scope)&&X6($.label)&&J2($.usedPercent)&&C3($,"resetsAt")&&($.windowMinutes===void 0||J2($.windowMinutes)&&$.windowMinutes>0)}function m5($){return z2($)&&Z6($.scope)&&X6($.label)}function w5($){if(!z2($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&W$($,"remainingPercent")&&W$($,"usedPercent")&&C3($,"resetsAt")&&W$($,"limit")&&W$($,"used")&&W$($,"remaining")&&C3($,"unit")}function J6($){if(!z2($)||!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(!v5(z))return!1;let G=y1(z.scope??s,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(m5))return!1;return($.budget===void 0||w5($.budget))&&($.counters===void 0||_3($.counters))}function p5($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function u5($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function l5($,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 E0($,Z){let X=$===void 0?void 0:M1($);if($!==void 0&&X===void 0)throw new X2("stored quota map is malformed");if(!J6(Z))throw new X2("quota observation is malformed");let J=X??{limits:[]},z=Z.checkedAt,G=new Map;for(let U of J.limits)G.set(y1(U.scope,U.label),U);let Q=(U)=>{let N=G.get(U);return N===void 0||z>=e4(N)},B=new Set;for(let U of Z.readings??[]){let N=U.scope??s,D=y1(N,U.label);if(B.add(D),!Q(D))continue;G.set(D,{scope:N,label:U.label,kind:"reading",checkedAt:z,usedPercent:U.usedPercent,...U.resetsAt===void 0?{}:{resetsAt:U.resetsAt},...U.windowMinutes===void 0?{}:{windowMinutes:U.windowMinutes}})}for(let U of Z.coverage??[]){let N=U.scope??s,D=y1(N,U.label);if(B.has(D)||!Q(D))continue;let M=G.get(D);G.set(D,M===void 0||M.kind==="absent"?{scope:N,label:U.label,kind:"absent",checkedAt:z}:{scope:N,label:U.label,kind:"retired",retiredAt:z})}let{limits:H,budget:Y,counters:W,...V}=J,j=u5(J.budget,Z.budget,z),K=l5(J.counters,Z.counters);return{...V,limits:[...G.values()].sort(p5),...j===void 0?{}:{budget:j},...K===void 0?{}:{counters:K}}}var P3=Object.freeze({validate:B0,decode:M1,merge:E0});var B6=900000,H6="no quota reading yet",Y6="no limits reported";function W6($){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 V6($){if($%1440===0)return`${$/1440}d`;if($%60===0)return`${$/60}h`;return`${$}m`}function Q2($){if($.scope!==s||$.windowMinutes===void 0)return $.label;return V6($.windowMinutes)}function T3($){return Math.min(100,Math.max(0,$))}function G2($){return Math.round(T3($))}function z6($){return`${G2($)}% left`}function G6($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:W6(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function d5($,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===s)return-1;if(Z.scope===s)return 1;return $.scope<Z.scope?-1:1}return $.label<Z.label?-1:$.label>Z.label?1:0}function U6($,Z){let{windows:X,age:J}=j6($,Z),z=X.map(({part:G})=>G);return J===void 0?{windows:z}:{windows:z,age:J}}function j6($,Z){if(!$)return{windows:[]};let{now:X}=Z,z=$.limits.filter((Q)=>Q.kind==="reading"&&Q.remainingPercent!==void 0).sort(d5).map((Q)=>{let B=T3(Q.remainingPercent??0);return{scope:Q.scope,...Q.windowMinutes===void 0?{}:{windowMinutes:Q.windowMinutes},part:{kind:"window",name:Q2(Q),figure:z6(Q.remainingPercent??0),remainingPercent:B,checkedAt:Q.checkedAt,...G6(Q.resetsAt,Q.checkedAt,X)}}}),G=$.budget;if(G){let Q=G.remainingPercent,B=G.reached?"credits spent":Q!==void 0?`credits ${z6(Q)}`:"credits available";z.push({scope:s,spent:G.reached,part:{kind:"budget",name:"credits",figure:B,...Q===void 0?{}:{remainingPercent:T3(Q)},checkedAt:G.checkedAt,...G6(G.resetsAt,G.checkedAt,X)}})}if(z.length>0){let Q=X-Math.min(...z.map(({part:B})=>B.checkedAt));if(Q>(Z.staleAfterMs??B6))return{windows:z,age:`checked ${W6(Q)} ago`}}return{windows:z}}function Q6($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function K6($){let Z=[...new Set($.map(Q6))],X=new Map(Z.map((z)=>[z,2])),J=(z)=>z.slice(0,X.get(z));for(;;){let z=new Map;for(let Q of Z)z.set(J(Q),[...z.get(J(Q))??[],Q]);let G=!1;for(let Q of z.values()){if(Q.length<2)continue;for(let B of Q){let H=X.get(B)??2;if(H<B.length)X.set(B,H+1),G=!0}}if(!G)break}return new Map($.map((z)=>[z,J(Q6(z))]))}var c5=2;function s5($){let Z=$.map((J)=>J.label.trim()||J.scope),X=K6(Z);return Z.map((J)=>X.get(J)??J)}function i5($,Z){if(!$||$.length===0)return;let X=Z.filter(({part:B})=>B.kind==="window");if(X.some(({scope:B})=>B===s))return;let J=$.flatMap((B,H)=>{let W=X.filter(({scope:V})=>V===B.scope).reduce((V,j)=>V===void 0||(j.part.remainingPercent??0)<(V.part.remainingPercent??0)?j:V,void 0);return W?[{group:B,listed:H,window:W}]:[]});if(J.length===0)return;let z=s5($),G=(B)=>B.window.part.remainingPercent??0,Q=[...J].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,c5).sort((B,H)=>B.listed-H.listed);return Q.map((B,H)=>{let{windowMinutes:Y}=B.window,W=[z[B.listed]??B.group.scope,...Y===void 0?[]:[V6(Y)],`${G2(G(B))}%`].join(" ");return H===Q.length-1?`${W} left`:W})}function a5($,Z){let{windows:X}=j6($,Z),J=i5($?.groups,X);if(J)return J;let z=X.filter(({part:j,scope:K})=>j.kind==="window"&&K===s),G=X.filter(({part:j,scope:K})=>j.kind==="window"&&K!==s),Q=K6(G.map(({scope:j})=>j)),B=X.find(({part:j})=>j.kind==="budget"),H=B?.spent?0:B?.part.remainingPercent,W=[...G.map(({scope:j,part:K})=>({label:Q.get(j)??j,remaining:K.remainingPercent??0})),...H===void 0?[]:[{label:"cr",remaining:H}]].reduce((j,K)=>j===void 0||K.remaining<j.remaining?K:j,void 0),V=z.map(({part:j})=>`${j.name} ${G2(j.remainingPercent??0)}%`);if(W)V.push(`${W.label} ${G2(W.remaining)}%`);if(V.length===0)return X.map(({part:j})=>j.figure);return V.map((j,K)=>K===V.length-1?`${j} left`:j)}function g1($,Z){if(Z.form==="narrow")return a5($,Z);let X=U6($,Z),J=(Z.form??"full")==="full",z=X.windows.map((G)=>{let Q=J&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${Q}`});return X.age===void 0?z:[...z,X.age]}function C0($,Z){let X=g1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?Y6:H6}function n5($){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 r5($,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 o5($){return{checkedAt:$.checkedAt,reached:$.reached,...$.remainingPercent===void 0?{}:{remainingPercent:$.remainingPercent},...$.resetsAt===void 0?{}:{resetsAt:$.resetsAt}}}function i($,Z=s){let X=new Map;for(let Y of $?.limits??[]){if(Y.scope!==Z&&Y.scope!==s)continue;let W=X.get(Y.label);if(W===void 0){X.set(Y.label,Y);continue}let V=Y.scope===s?W:Y,j=Y.scope===s?Y:W;X.set(Y.label,V.kind==="reading"?V:j)}let J=[...X.values()].map(n5).sort(r5),z=J.filter((Y)=>Y.kind==="reading"),G=z.length>0?z:J,Q=G.length>0?Math.min(...G.map((Y)=>Y.checkedAt)):void 0,B=$?.budget?.kind==="reading"?o5($.budget):void 0,H=O3($?.counters);return{scope:Z,limits:J,...Q===void 0?{}:{checkedAt:Q},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H}}}function V$($,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 A3($){return $.kind==="reading"&&typeof $.usedPercent==="number"&&Number.isFinite($.usedPercent)&&$.usedPercent>=100}function B2($,Z){if(typeof $.resetsAt!=="string")return;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X>Z?X:void 0}function D6($,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 t5($,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((Q)=>Q.label===G))return{id:$,stage:1,gate:3,reason:"unknown-window",window:{scope:Z.scope,label:G},pullRequested:!0};let z=Z.limits.filter(A3);for(let G of z)if(B2(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 Q=B2(G,J);if(Q!==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:Q}}return}function h0($){let Z=$.scope??s,X=$.requiredLabels??L3,J=[],z=[],G=[];for(let j of $.rows){let K=D6(j.id,$,$.now);if(K){J.push(K);continue}if(j.kind==="api-key"){G.push({id:j.id,kind:j.kind});continue}let U=i(j.quota,Z),N=t5(j.id,U,X,$.now);if(N){z.push(N);continue}G.push({id:j.id,kind:j.kind,projection:U})}let Q=new Map(G.flatMap((j)=>{let K=V$(j.projection,$.now);return K?[[j.id,K]]:[]})),B=Q.size>0&&Q.size===G.length,H=[];for(let j of G){let K=Q.get(j.id);if(K===void 0)H.push(j);else if(B)H.push({...j,lastPath:!0});else z.push({id:j.id,stage:2,reason:"budget-spent",...K})}let Y=new Map($.rows.map((j,K)=>[j.id,K])),W=(j,K)=>(Y.get(j.id)??0)-(Y.get(K.id)??0);z.sort(W);let V=z.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of V)$.requestPull?.(j);return{admitted:H,refused:z,excluded:J,pulls:V}}var H2="main";function S3($){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 h1($,Z,X=H2){if(Z==="roster"||!$.includes(X))return[...$];let J=$.filter((z)=>z!==X);return Z==="main-first"?[X,...J]:[...J,X]}function R3($){let Z=h0($),X=new Set(Z.admitted.map((z)=>z.id));return{order:h1($.rows.map((z)=>z.id),$.placement??"roster",$.formerMainId).filter((z)=>X.has(z)&&$.killswitch?.get(z)!==!1),admission:Z}}function E3($,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 U$($,Z,X){if(!Z.has($.accountId))return!1;return!(typeof $.wireIdentity==="string"&&typeof X==="string"&&$.wireIdentity!==X)}function I3($,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 k3=900000,N6=0.016666666666666666,b3=0.000001;function Y2($,Z){for(let X of[$?.checkedAt,Z])if(typeof X==="number"&&Number.isFinite(X))return X;return}function M6($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function F6($){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 f3($){let Z=($.classifyStatus??M6)($.status);if(Z==="permanent")return{action:"migrate",reason:"permanent"};if(!$.quota)return{action:"retain",reason:"unknown"};let X=Y2($.quota,$.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||$.now-X>k3)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of F6($.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=V$($.quota,$.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:Z}}function x3($,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,N6);return J/G}function q6($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function e5($,Z){if(!$.quota)return;let X=Y2($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>k3)return;let J=F6($.quota).map((Q)=>x3({remainingPercent:Q.remainingPercent??Number.NaN,...Q.resetsAt===void 0?{}:{resetsAt:Q.resetsAt}},$.reservePercent[Q.label]??0,Z)),z=$.quota.budget;if(z&&typeof z.remainingPercent==="number"&&Number.isFinite(z.remainingPercent))J.push(x3({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 L6($){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)=>e5(z,$.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,Q)=>{let B=(($.pendingBytes.get(G.candidate.accountId)??0)+$.requestBytes)/Math.max(G.weight,b3),H=(($.pendingBytes.get(Q.candidate.accountId)??0)+$.requestBytes)/Math.max(Q.weight,b3);return B-H||G.candidate.configuredOrder-Q.candidate.configuredOrder||q6(G.candidate.accountId,Q.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 Q=(z.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-Q||z.configuredOrder-G.configuredOrder||q6(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:Y2(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function y3($){let Z=h0($),X=new Map(Z.admitted.map((U)=>[U.id,U])),J=new Map(Z.refused.map((U)=>[U.id,U])),z=new Set(Z.excluded.map((U)=>U.id)),G=new Set($.rows.map((U)=>U.id)),Q=$.pin!==void 0&&U$($.pin,G,$.identities?.get($.pin.accountId));if(Q&&$.pin){let U=X.get($.pin.accountId);if(U&&$.killswitch?.get(U.id)!==!1)return{outcome:"dispatch",accountId:U.id,source:"pin",...U.projection?.checkedAt===void 0?{}:{quotaCheckedAt:U.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:Z}}let B=$.pin?J.get($.pin.accountId):void 0,H=Q&&$.pin!==void 0&&$.refusedPinPolicy==="move-on-confirmed-exhaustion"&&($.killswitch?.get($.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Y=(U)=>{return(typeof $.rowReservePercent==="function"?$.rowReservePercent(U):$.rowReservePercent?.get(U.id))??$.reservePercent??{}},W=$.scope,V=$.rows.map((U,N)=>({row:U,configuredOrder:N})).filter(({row:U})=>!z.has(U.id)).map(({row:U,configuredOrder:N})=>{let D=$.killswitch?.get(U.id),M=$.resetCreditsApplicable?.get(U.id);return{accountId:U.id,quota:U.kind==="api-key"?void 0:X.get(U.id)?.projection??i(U.quota,W),reservePercent:Y(U),configuredOrder:N,...M===void 0?{}:{resetCreditsApplicable:M},...D===void 0?{}:{killswitchPasses:D}}}),j=[],K=Q?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(V.length>0){let U=L6({candidates:V,pendingBytes:$.pendingBytes??new Map,requestBytes:$.requestBytes,now:$.now,...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}});if(!U)break;let N=J.get(U.accountId);if(N){j.push(N),V=V.filter((M)=>M.accountId!==U.accountId);continue}let D=$.identities?.get(U.accountId);return{outcome:"dispatch",accountId:U.accountId,source:U.source,...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt},pin:Q&&!H?{action:"retain"}:{action:"assign",pin:{accountId:U.accountId,inputBytes:$.requestBytes,...D===void 0?{}:{wireIdentity:D},...U.quotaCheckedAt===void 0?{}:{quotaCheckedAt:U.quotaCheckedAt}}},refusedSelections:j,admission:Z}}return{outcome:"no-admissible-account",pin:K,refusedSelections:j,admission:Z}}import{appendFileSync as HX,chmodSync as YX,existsSync as m3,renameSync as R6,statSync as WX}from"node:fs";import{open as VX}from"node:fs/promises";import{dirname as UX,resolve as jX}from"node:path";import{randomUUID as $X}from"node:crypto";import{lstat as P6,readFile as T6,rename as ZX,unlink as _6}from"node:fs/promises";import{dirname as i0,resolve as N0}from"node:path";var I=process.platform==="win32",O6=new Set;function g3($){if($?.reason==="io-error"){if($.win32Code===2||$.win32Code===3)return"ENOENT";if($.win32Code===80||$.win32Code===183)return"EEXIST"}return $?.code??"ERR_PRIVATE_FILE"}var C6;function v1(){return C6??=import("@cortexkit/private-files"),C6}class d 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(`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:X});this.path=$,this.stage=Z,this.name="PrivateFileError",this.code=g3(J),this.win32Code=J?.win32Code,this.reason=J?.reason}}async function K0($,Z,X){try{return await X()}catch(J){if(J instanceof d)throw J;throw new d($,Z,J)}}var XX;async function v0($,Z){$=N0($),Z??=XX,await K0($,"safe-parent",async()=>{let X=await(await v1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await P6($);throw new d(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function J0($,Z,X=!1){if($=N0($),Z==="directory")return v0($);await K0($,"verify",async()=>{let J=await v1(),z=await J.verifyOwnerOnly($),G=!1;if(!z.ok){let{reason:Q}=z.refusal;if(Q==="io-error")await J.verifyPrivatePath($,Z);if(X&&[J.EXTRA_ACE,J.NOT_PROTECTED,J.NULL_DACL,J.EMPTY_DACL].includes(Q))await v0(i0($)),await J.securePrivatePath($,Z),G=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:Q,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await J.verifyPrivatePath($,Z),G&&!O6.has($))O6.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function D0($,Z=!1,X){$=N0($),await K0($,"directory",async()=>{let J=await v1();try{return await P6($),await v0($,X)}catch(G){if(g3(G)!=="ENOENT")throw G}let z=i0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await D0(z,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(G){if(g3(G)!=="EEXIST")throw G}await v0($,X)})}async function M0($,Z=!1){if(!I)return T6($,"utf8");return(await h3($,Z)).toString("utf8")}async function h3($,Z=!1){if(!I)return T6($);if($=N0($),Z)await v0(i0($)),await J0($,"file",!0);return K0($,"read",async()=>(await v1()).readOwnerOnly($))}async function m1($,Z){await v0(i0(N0($))),await K0($,"create",async()=>{await(await v1()).createPrivateFile(N0($),Z)})}async function A6($){await v0(i0(N0($))),await K0($,"directory-create",async()=>{await(await v1()).createOwnerOnly(N0($),{kind:"dir"})})}async function v3($,Z,X={}){$=N0($),Z=N0(Z);let J=X.now??(()=>performance.now()),z=J(),G=X.deadline??1/0,Q,B=[0,10,20,40,80,100],H,Y=0;for(let V of B){let j=Math.min(Q??1/0,G);if(J()>=j)break;if(V)await(X.sleep??((U)=>new Promise((N)=>setTimeout(N,U))))(Math.min(V,Math.max(0,j-J())));if(J()>=j)break;let K=J();if(await X.beforeRename?.(),Q!==void 0)Q+=J()-K;if(J()>=G)break;Y++;try{return await(X.rename??ZX)($,Z),{attempts:Y,elapsedMs:J()-z}}catch(U){H??=U;let N=U;if(!(N.win32Code!==void 0?N.win32Code===32||N.win32Code===33:["EBUSY","EPERM","EACCES"].includes(N.code??"")&&!N.reason))break;Q??=J()+500}}let W=new d(Z,"rename",H??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw W.attempts=Y,W.elapsedMs=J()-z,W}async function w1($,Z,X={}){$=N0($),await D0(i0($));try{await J0($,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}let J=N0(X.stagePath??`${$}.${$X()}.tmp`);if(i0(J)!==i0($))throw new d($,"stage-directory",{code:"EXDEV"});let z=!1,G=!1,Q={attempts:0,elapsedMs:0},B="stage-create",H=(Y)=>{try{X.onOutcome?.({path:$,stage:Y?.stage??"published",published:G,fileDurable:G,durabilityConfirmed:!1,attempts:Y?.attempts??Q.attempts,elapsedMs:Y?.elapsedMs??Q.elapsedMs,...Y&&{code:Y.code,win32Code:Y.win32Code}})}catch{}};try{if(await m1(J,Z),z=!0,B="before-rename",Q=await v3(J,$,X),z=!1,G=!0,B="published-callback",X.onRenamed?.(),B="published-verify",await J0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new d($,"directory-sync-unsupported",{code:"ENOTSUP"});H()}catch(Y){let W=Y instanceof d?Y:new d($,B,Y);if(W.published=G,W.fileDurable=G,G)Object.assign(W,Q);if(z){try{await _6(J)}catch{W.orphanPath=J}z=!1}throw H(W),W}finally{if(z)await _6(J).catch(()=>{})}}var JX=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,zX=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function GX($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function I0($={}){let Z=[zX,...$.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function X(G){let Q=G.toLowerCase().replace(/[-_]/g,"");return JX.test(G)||Q.includes("apikey")||Q.endsWith("secret")||Q.endsWith("password")||Q.endsWith("token")&&!Q.endsWith("tokens")||!!$.extraSecretKeys?.(Q)}function J(G){let Q=G,B=[["name",G.name],["message",G.message],["stack",G.stack]];for(let Y of["code","status","cause"])if(Q[Y]!==void 0)B.push([Y,Q[Y]]);let H=new Set(B.map(([Y])=>Y));for(let Y of Object.entries(G))if(!H.has(Y[0]))B.push(Y);return B}function z(G,Q,B,H=0){if(typeof G==="string")return Z.reduce((Y,W)=>Y.replace(W,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(B.has(G))return"[Circular]";B.add(G);try{if(Array.isArray(G))return G.map((V)=>z(V,Q,B,H));let Y=GX(G);if(Y&&H>=8)return"[Truncated]";let W=Y?H+1:H;return Object.fromEntries((Y?J(G):Object.entries(G)).map(([V,j])=>[V,Q&&X(V)?"***REDACTED***":z(j,Q,B,W)]))}finally{B.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var S6=I0(),QX=S6.redact,BX=S6.redactStrings;var W2={error:0,warn:1,info:2,debug:3,trace:4},I6=5242880,b6=3;function w3($){try{YX($,384)}catch{}}function KX($){try{if(!(m3($)&&WX($).size>=I6))return;for(let X=b6-1;X>=1;X--)if(m3(`${$}.${X}`)){let J=`${$}.${X+1}`;R6(`${$}.${X}`,J),w3(J)}let Z=`${$}.1`;R6($,Z),w3(Z)}catch{}}async function m0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await K0(Z,"log-close",()=>X.close())}async function E6($,Z){await D0(UX(Z));try{await J0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await m1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await J0(Z,"file",!0)}}return $.handle=await K0(Z,"log-open",()=>VX(Z,"a")),$.file=Z,$.handle}async function DX($,Z,X){Z=jX(Z);try{if($.file!==Z)await m0($);let J=$.handle??await E6($,Z);if((await K0(Z,"log-stat",()=>J.stat())).size>=I6){await m0($);for(let G=b6-1;G>=0;G--){let Q=G===0?Z:`${Z}.${G}`,B=`${Z}.${G+1}`;try{await J0(Q,"file",!0)}catch(H){if(H.code==="ENOENT")continue;throw H}try{await J0(B,"file",!0)}catch(H){if(H.code!=="ENOENT")throw H}await v3(Q,B),await J0(B,"file")}J=await E6($,Z)}await K0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await m0($).catch(()=>{}),J}}function qX($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function NX($){let Z,X,J,z=I0(),G,Q=[],B,H=Promise.resolve(),Y,W={};function V(q){let L=H.then(q);return H=L.catch((S)=>{Y=S}),L}function j(q){if(I&&q.file!==Z)V(()=>m0(W)).catch(()=>{});Z=q.file,X=q.level,z=I0(q),G=q.captureSink}function K(q){if(q===void 0||q in W2)J=q}function U(){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 W2)return q;return"info"}function D(q=!0){if(B)clearTimeout(B),B=void 0;if(!Q.length){if(I)return V(async()=>{if(q)await m0(W);if(Y)throw Y});return}let L;try{L=U()}catch{if(Q=[],I&&q)return V(()=>m0(W));return}let S=Q.join("");if(Q=[],!L){if(I&&q)return V(()=>m0(W));return}if(I)return V(async()=>{try{await DX(W,L,S)}finally{if(q)await m0(W)}});try{if(KX(L),m3(L))w3(L);HX(L,S,{encoding:"utf8",mode:384})}catch{}}function M(){if(!B)B=setTimeout(()=>{B=void 0;let q=D(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function P(q,L,S,A){if(Z===void 0&&G===void 0)return;try{if(W2[L]>W2[N()])return;let x=z.redactStrings(S),w;try{w=z.redact(A)}catch{w="[unserializable]"}let f=`[${new Date().toISOString()}] ${L.toUpperCase()} [${q}] ${x}`+(A===void 0?"":qX(w))+`
|
|
2
|
-
`;try{G?.({channel:q,level:
|
|
3
|
-
`,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??
|
|
4
|
-
`,"utf8"),await G.chmod(384),X.durable)try{await G.sync()}catch(
|
|
5
|
-
`,{deadline:performance.now()+Math.max(0,t),beforeRename:async()=>{let
|
|
6
|
-
`,"utf8"),await T.chmod(384),await T.close(),T=void 0;let u=await q();if(u?.ownerId!==J||!(Number(u?.expiresAt)>z())||!await h())throw new
|
|
7
|
-
`;if(I)await
|
|
8
|
-
`;if(I)await m1(M,C);else await v6(M,C)}catch(C){if(s3(C))return!1;throw await c(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function f1(){let C;try{C=await g6(D)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if(I)await J0(D,"directory",!0);if(C.mtimeMs+E>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let T=`${D}.${j2()}`;try{await y6(D,T)}catch(b){if(b.code==="ENOENT")return"missing";throw b}if($.onStep)await $.onStep("stale-marker-claimed");return await o(T),"recovered"}async function $2(C){try{if(!await e$())return!1}catch(T){if(T.code==="EEXIST"){if(I){await J0(D,"directory",!0);try{await M0(M,!0)}catch(b){if(b.code!=="ENOENT")throw b}}return!1}throw T}try{await C()}finally{await c()}return!0}async function v(){for(let C=0;C<F;C++){if($.onStep)await $.onStep("relinquish-read");let T;try{T=await q()}catch(b){if(I)throw b;return}if(T?.ownerId!==J)return;try{await K2(Z,{recursive:!0,force:!0});return}catch(b){if(I)throw b;await w()}}}function g0(){if(!$.renew||Q||H)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=SX(()=>{G=null;let T=(async()=>{let b=!Q;try{if(!await $2(async()=>{let t=await q(),Z2=z();if(Q||H){b=!1;return}if(t?.ownerId!==J){K("taken-over",t),b=!1;return}if(!(Number(t?.expiresAt)>Z2)){K("expired",t),b=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q||H){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q||H){b=!1;return}if(!await h())return;if($.onStep)await $.onStep("renewal-write-ready");if(Q||H){b=!1;return}if(await L(),$.onStep)await $.onStep("renewal-write-finished");if(!await h()){K("marker-lost"),b=!1,await v();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(u){if(I&&u instanceof d)U=u,K("renewal-failed"),b=!1;try{let t=await q();if(t?.ownerId!==J)K("taken-over",t);else if(!(Number(t?.expiresAt)>z()))K("expired",t)}catch{K("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(b&&!Q&&!H)g0()}})();N=T,T.finally(()=>{if(N===T)N=null})},C),"unref"in G)G.unref();V("scheduled")}function o4(){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 q1=await x();if(!q1)for(let C=0;C<F;C++){if(q1=await x(),q1)break;let T=await f();if(T.status==="live")return o4();if(T.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await e$()){await w();continue}}catch(b){if(b.code!=="EEXIST")throw b;if(await f1()==="fresh")return null;await w();continue}try{let b=await f();if(b.status==="live")return o4();if(!y(T.identity,b))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(T.identity,u))continue;if(await o(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(q1=await x(),!q1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),q1=!1,null;break}finally{await c()}}if(!q1)return null;return g0(),{ownerId:J,whenLost:()=>W,hasLost:()=>H!==void 0,assertOwned:async()=>{if(U)throw U;let C;try{let T=await q();if(C=T,!Q&&!H&&T?.ownerId===J&&Number(T?.expiresAt)>z())return;K(T?.ownerId!==J?"taken-over":"expired",T)}catch(T){if(K("unreadable"),I&&T instanceof d)throw T}throw new n0({target:$.path,name:$.name,expectedOwnerId:J,...typeof C?.ownerId==="string"?{observedOwnerId:C.ownerId}:{},...typeof C?.expiresAt==="number"?{observedExpiresAt:C.expiresAt}:{}})},release:async()=>{if(I&&B)return;Q=!0,j(),await N;for(let C=0;C<F;C++){try{let T=!1;if(await $2(async()=>{let u;try{u=await q()}catch(t){if(I&&t.code==="ENOENT"){T=!0;return}throw t}if(u?.ownerId!==J){T=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await o(Z),T=!0})){if(I&&!T)throw new d(Z,"release-not-confirmed",{code:"EIO"});B=T;return}await f1()}catch(T){if(I)throw T;return}await w()}if(I)throw new d(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function i3($,Z){return`${$}.${Z}.lock`}class L1 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class n0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function a3($,Z,X){let J=performance.now();for(;;){let z=await $0({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 await X(z)}finally{await z.release()}let G=Z.timeoutMs-(performance.now()-J);if(G<=0)throw new L1({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((Q)=>setTimeout(Q,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as IX}from"node:async_hooks";var w6=new IX;function z0($){if(w6.getStore()!==void 0)throw new V2($)}function b0($,Z){return w6.run($,async()=>await Z())}async function p6($,Z,X,J,z){if(!Z)return;try{await b0($,()=>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 n3=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function bX($,Z,X){let J=(Q)=>{try{let B=X.onLockEvent?.({type:Q,name:$.name,path:$.path});if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}},z={...Z,...xX($)},G=performance.now();for(;;){let Q=await $0({name:$.name,path:$.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(Y)=>X.onRenewalTimer?.({name:$.name,path:$.path},Y)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...X.onLockStep?{onStep:(Y)=>X.onLockStep?.({name:$.name,path:$.path},Y)}:{}});if(Q){J("acquired");let Y={name:$.name,path:$.path,assertOwned:()=>Q.assertOwned(),release:async()=>{await Q.release(),J("released")}};try{await Y.assertOwned()}catch(W){throw await Y.release(),W}return Y}let B=z.timeoutMs-(performance.now()-G);if(B<=0)throw new L1({target:$.path,name:$.name,timeoutMs:z.timeoutMs});let H=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Y)=>setTimeout(Y,Math.min(z.retryMs+H,B)))}}function xX($){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 r0{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await bX($,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 _1($,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 D$}from"node:crypto";var p="commonAuthPool",o0=1,P0="rows",D2="retiredEpochs",q$=1,r3=300000,m=p;function kX($){let Z=JSON.parse(JSON.stringify($)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(O(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X(Z)}function O1($){return D$("sha256").update(kX($)).digest("hex")}function u6($){if(!O($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function fX($){if(!O($)||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 H0="commonAuthProviderState";function O($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var yX=new Set(["__proto__","constructor","prototype"]);function l1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(yX.has($))return"id is a reserved object key";return}function o3($){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 l6($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function t0($){return D$("sha256").update(l6($)).digest("hex")}function x0($){return D$("sha256").update(`credential-stamp\x00${l6($)}`).digest("hex")}function w0($){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 D$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function t3($,Z,X,J={}){return{credentialEpoch:Z,digest:x0($),dispatch:w0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function d1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return D$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function N$($,Z,X,J){if(!Z||X===void 0)return;if(!O($)||!Object.hasOwn($,H0))return;let z=V0($[m]);if(!z||z.providerState===void 0||z.digest!==x0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function Z0($){return Number.isSafeInteger($)&&$>=1}function V0($){if(!O($))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 $?fX($.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(!O(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!o3(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 gX($,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 hX($,Z,X,J){if(!$)return"none";if(!O(J)||!Object.hasOwn(J,m))return"missing";let z=V0(J[m]);if(!z)return"malformed";if(z.digest!==x0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!gX(z.binding,$,X))return"mismatched";if(z.dispatch!==w0($))return"mismatched";return"bound"}function d6($){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(!O(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(!O(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>o0)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${o0}`};if(P0 in X&&!O(X[P0]))return{status:"error",reason:`${p}.${P0} is not an object`};return{status:"ready",exists:!0,config:Z}}function c6($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!O($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!O($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function c1($){return Array.isArray($.accounts)?$.accounts:[]}function s6($){let Z=$[p];if(!O(Z))return{};let X=Z[P0];return O(X)?X:{}}function vX($){return O($.accounts)?$.accounts:{}}function mX($){if(!O($))return"not an object";let Z=l1($.id);if(Z)return Z;if($.type==="api")return o3($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function wX($,Z){if(!O($))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 $&&!u6($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function pX($,Z){if(!O(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 q2($,Z){return c1($).find((X)=>O(X)&&X.id===Z)}function i6($){if(!O($[p]))$[p]={};return $[p]}function e3($){let Z=i6($);if(!O(Z[P0]))Z[P0]={};return Z[P0]}function e0($,Z){let X=s6($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return O(J)?J:void 0}function N2($,Z,X){Object.defineProperty(e3($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function a6($,Z){let X=$[p];if(!O(X))return;let J=X[D2];if(!O(J)||!Object.hasOwn(J,Z))return;let z=J[Z];return Z0(z)?z:void 0}function n6($,Z){let X=e0($,Z)?.credentialEpoch;return Z0(X)?X:void 0}function M2($,Z){return Math.max(a6($,Z)??0,n6($,Z)??0)+1}function r6($,Z){let X=[...Z];if(X.length===0)return;let J=i6($),z=O(J[D2])?J[D2]:{},G={},Q=(B,H)=>Object.defineProperty(G,B,{value:H,enumerable:!0,writable:!0,configurable:!0});for(let[B,H]of Object.entries(z))if(Z0(H))Q(B,H);for(let B of X)Q(B,Math.max(a6($,B)??0,n6($,B)??1));J[D2]=G}function $1($,Z,X,J){let z=s6($),G=vX(Z),Q=new Set,B=[];for(let H of c1($)){let Y=mX(H),W=O(H)&&typeof H.id==="string"?H.id:void 0,V=W===void 0?void 0:z[W],j=O(V)&&Object.hasOwn(V,"staged"),K=j?u6(V.staged):void 0;if(Y||!O(H)||W===void 0||Q.has(W)){if(W!==void 0&&!Q.has(W))Q.add(W);if(W!==void 0)B.push({id:W,type:O(H)&&H.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,W),candidate:!1,invalid:"roster",stamp:"none",...K?{staged:K}:{}});continue}Q.add(W);let U=H.type==="api"?"api":"oauth",N=Object.hasOwn(z,W),D=N?wX(z[W],X):void 0,M=pX(H,G[W]),P=H.enabled!==!1,E=D?D.credentialEpoch:N?void 0:1,F=typeof H.accountId==="string"&&H.accountId?H.accountId:void 0,q={id:W,type:U,enabled:P,needsFirstReading:D?D.needsFirstReading:U==="oauth",hasEntry:N,candidate:!1,...typeof H.label==="string"?{label:H.label}:{},...typeof H.addedAt==="number"?{addedAt:H.addedAt}:{},...F!==void 0?{identity:F}:{},...M?{credential:M,fingerprint:t0(M)}:{},...D?{credentialEpoch:D.credentialEpoch}:{},...K?{staged:K}:{},...D?.disabledReason!==void 0?{disabledReason:D.disabledReason}:{},...D&&"quota"in D?{quota:D.quota}:{},...uX(G[W],M,E,F,J),stamp:hX(M,E,F,G[W])};if(N&&!D)q.invalid="entry";else q.candidate=P&&M!==void 0&&!j;B.push(q)}return B}function uX($,Z,X,J,z){if(!O($)||!Object.hasOwn($,H0))return{};let G=N$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[H0];if(!z?.validate(Q))return{providerStateDropped:"invalid"};if(d1(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function l($){return $.identity??$.id}function M$($,Z){if($===void 0||$>Z+r3)return Z;return Math.max(Z,$+1)}function $Z($,Z){return M$($,Z)>Z+r3}function s1($){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 o6($,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 t6($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function e6($,Z={}){if(!O($))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)&&!o3($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var F2="transition",$8="transitionMark";function lX($){if(!O($))return;let Z=$[F2];if(!O(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 F$($,Z,X){if(X.enabled)j$($,Z);else a0($,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)u1($,z.identity)}function dX($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function cX($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function sX($,Z,X,J={}){let z=O(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of $1($,Z,X)){if(Q.invalid||Q.staged||!Q.credential)continue;let B=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!O(B))continue;let H=V0(B[m]);if(!H?.binding)continue;if(H.digest!==x0(Q.credential))continue;let Y=Q.credentialEpoch??1;if(H.credentialEpoch>Y){if(!cX(H))continue;if(J.requireCredentialStamps){if(H.dispatch===void 0)continue;if(H.dispatch!==w0(dX(Q.credential,H.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...H,binding:H.binding}})}else if(H.credentialEpoch===Y&&H.dispatch!==void 0&&H.dispatch===w0(Q.credential)&&H.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:H.binding.identity});else if(H.credentialEpoch===Y&&H.binding.identity===Q.identity){if(J.requireCredentialStamps&&H.dispatch!==w0(Q.credential))continue;let W=lX(B[m]);if(W&&e0($,Q.id)?.[$8]!==W.mark)G.set(Q.id,{kind:"transition",transition:W})}}return G}function ZZ($,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(p1))delete G.disabledReason;$.setEntry(Z,G);let Q=$.rosterRow(Z);if(!Q)return;if(J.identity!==void 0)Q.accountId=J.identity;else delete Q.accountId;if(J.baseURL!==void 0)Q.baseURL=J.baseURL;if(J.authHeader!==void 0)Q.authHeader=J.authHeader}function XZ($,Z,X,J={}){let z=sX($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>$1(G,Z,X),rosterRow:(B)=>q2(G,B),entry:(B)=>e0(G,B),setEntry:(B,H)=>N2(G,B,H)};for(let[B,H]of z)if(H.kind==="replace")ZZ(Q,B,H.stamp.credentialEpoch,H.stamp.binding);for(let[B,H]of z)if(H.kind==="identity")F1(Q,B,H.identity);else if(H.kind==="transition")F$(Q,B,H.transition);else if(H.stamp.binding.identity!==void 0)u1(Q,H.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function JZ($,Z,X,J={}){let{config:z,torn:G}=XZ($,Z,X,J),Q=$1(z,Z,X,J.providerState);for(let B of Q){if(G.includes(B.id))B.torn=!0,B.candidate=!1;if(J.requireCredentialStamps&&B.stamp!=="bound")B.unbound=!0,B.candidate=!1}return Q}async function zZ($){try{return await M0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function Z8($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function Y0($){for(let Z=0;Z<3;Z++){let X=await zZ($.configPath),J=await zZ($.statePath),z=await zZ($.configPath);if(X!==z){if(Z<2)await iX(2+Math.floor(Math.random()*4));continue}let G=d6(Z8(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=c6(Z8(J));if(Q.status==="error")return{status:"error",file:"state",reason:Q.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:Q.exists,config:G.config,state:Q.state,rows:JZ(G.config,Q.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 X8{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 JZ(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 O(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){_1(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),q2(this.config,$)}dropRosterRows($){let Z=this.roster(),X=Z.filter((J)=>!(O(J)&&J.id===$));return this.config.accounts=X,Z.length-X.length}entries(){return e3(this.config)}entry($){return this.entries(),e0(this.config,$)}setEntry($,Z){N2(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=XZ(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=O(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn(Z,$)?Z[$]:void 0;return O(X)?X:void 0}dropStateAccount($){if(O(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!O(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 H of Z)if(O(H)&&typeof H.id==="string")X.add(H.id);let J=new Set;for(let H of c1(this.snapshot.config))if(O(H)&&typeof H.id==="string"&&!X.has(H.id))J.add(H.id);for(let H of Object.keys(this.entries()))if(!X.has(H))J.add(H);r6(this.config,J);let z=this.entries(),G={};for(let[H,Y]of Object.entries(z))if(X.has(H))Object.defineProperty(G,H,{value:Y,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[p],B={...this.config,version:q$,accounts:Z,[p]:{...Q,schemaVersion:o0,[P0]:G}};await this.write(this.ctx.configPath,B,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let H of J)this.ctx.removedIds.add(H);this.config=B}),this.config=B}async commitState($,Z={}){let X={...this.state,version:q$,accounts:O(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 d3(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 d3(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await l3($,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 J8($,Z){let X=new r0($.lockDefaults,$.lockEnv),J={writes:0};try{for(let B of $.storeLocks)await X.acquire(B);let z=await Y0($);if(z.status==="error")throw T0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[B,H]of Object.entries(z.config))if(!Z.includes(B))G[B]=H;G.version=q$,G[p]={schemaVersion:o0,[P0]:{}};let Q={operation:"initialize",rowId:void 0};return await F0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",Q),await X.assertAll()}}),J.writes++,await $.onStep?.("after-config-write",Q),"initialized"}catch(z){throw i1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function r($,Z,X,J,z,G={}){let Q=Z.held.length;try{for(let Y of $.storeLocks)await Z.acquire(Y);let B=await Y0($);if(B.status!=="ready")throw T0(B,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let H=new X8($,B,Z,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))H.assertNotStaged(J.rowId);if(G.completeTorn??!0)await H.completeTorn();return await z(H)}finally{await Z.releaseTo(Q)}}function i1($,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 K$)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 Q={operation:Z,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof n0)return new g({...Q,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 L1)return new g({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new g({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function G0($,Z,X,J,z){let G=new r0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(B){let H=i1(B,Z,X,Q);if(H.kind!=="after-persist-hook")await p6(Z,J,X,H,$.logger);throw H}finally{await G.releaseAll()}}function q0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(l(Z))}`,path:$.ctx.statePath}}async function p0($,Z,X){let J=await Y0($.ctx);if(J.status!=="ready")throw T0(J,Z,X);let z=J.rows.find((Y)=>Y.id===X),G=e0(J.config,X),Q=J.state.accounts,B=O(Q)&&Object.hasOwn(Q,X)?Q[X]:void 0,H=O(B)?B[m]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))_1(Z,X,G.staged);if(!z&&O(H)&&Object.hasOwn(H,"staged"))_1(Z,X,H.staged);if(!z)throw A0(Z,X);return{result:J,row:z}}function A0($,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 W0($,Z){if(Z.unbound)throw _($,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 _($,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 L2($,Z,X,J){let{ctx:z}=$,G=new r0(z.lockDefaults,z.lockEnv),Q={writes:0};try{if(!Z0(X?.credentialEpoch))throw _("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await r(z,G,Q,{operation:"pull",rowId:Z},async(B)=>{B.assertNotStaged(Z);let H=B.row(Z);if(!H)throw A0("pull",Z);if(H.invalid)throw _("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!H.credential)throw _("pull",Z,"no-credential",`row ${Z} holds no credential`);W0("pull",H);let Y=B.entry(Z);if(H.torn||!Y||Y.credentialEpoch!==X.credentialEpoch||H.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(Y.quota,J);if(!z.codec.validate(W))throw _("pull",Z,"invalid-quota","the quota codec rejected the merged map");B.setEntry(Z,{...Y,quota:W,needsFirstReading:!1}),await B.commitConfig()},{completeTorn:!1})}catch(B){throw i1(B,"pull",Z,Q)}finally{await G.releaseAll()}}function u0($,Z,X,J,z="the provider state"){if(!$)throw _(Z,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(J);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw _(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw _(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function L$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:u0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function z8($,Z,X,J,z){let G=$?.onReplace,Q=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(Q===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:Q};return{kind:"set",value:u0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function G8($,Z,X,J,z){if(Z.kind==="set")return d1($,Z.value);if(Z.kind==="clear")return;return N$(X,J?.credential,z,J?.identity)}async function Q8($,Z,X,J,z={}){z0("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return G0(G,Q,Z,z.onFailure,async(B,H)=>{let Y=G.providerState;if(!Y)throw _(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw _(Q,Z,"invalid-input","a mutator is required");let W=O(X)?X.credentialEpoch:void 0;if(!Z0(W))throw _(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await p0($,Q,Z);await B.acquire(q0($,V));for(let j of z.extraLocks??[])await B.acquire(j);return r(G,B,H,{operation:Q,rowId:Z},async(j)=>{let K=j.row(Z);if(!K)throw A0(Q,Z);if(l(K)!==l(V))throw _(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(K.invalid)throw _(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!K.credential)throw _(Q,Z,"no-credential",`row ${Z} holds no credential`);if(W0(Q,K),(K.credentialEpoch??1)!==W||K.identity!==X.identity)throw _(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let N=await GZ(j,Y,Q,K,J);if(N.kind!=="changed")return{id:Z,outcome:"unchanged",...N.kind==="unchanged"&&N.value!==void 0?{providerState:N.value}:{}};return j.setStateAccount(Z,N.account),await j.commitState(),N.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:N.value}})})}var B8=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function GZ($,Z,X,J,z,G=!1){let{id:Q,credential:B}=J;if(!B)throw _(X,Q,"no-credential",`row ${Q} holds no credential`);let H=J.credentialEpoch??1,Y=$.stateAccount(Q),W=Y?.[m],V=V0(W);if(!O(W)||!V?.binding||V.digest!==x0(B)||V.credentialEpoch!==H||V.binding.identity!==J.identity)throw _(X,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let j=J.providerState===void 0?void 0:structuredClone(J.providerState),K=await b0(X,()=>z(j,J));if(G&&K===B8)return{kind:"declined"};let U=K===void 0?void 0:u0(Z,X,Q,K,"the provider state the mutator returned"),N=Y!==void 0&&Object.hasOwn(Y,H0);if(U===void 0?!N:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let D={...Y};if(U===void 0){delete D[H0];let M={...W};delete M.providerState,D[m]=M}else{D[H0]=U;let M=d1(Z,U);if(V.providerState!==M)D[m]={...W,providerState:M}}return{kind:"changed",...U!==void 0?{value:U}:{},account:D}}import{randomUUID as H8}from"node:crypto";async function P2($,Z,X){if(!X)return;let J=$.rows().map((G)=>{let{id:Q,type:B,label:H,enabled:Y,disabledReason:W,identity:V,credentialEpoch:j,stamp:K,staged:U,torn:N,invalid:D}=G;return{id:Q,type:B,label:H,enabled:Y,disabledReason:W,identity:V,credentialEpoch:j,stamp:K,staged:U,torn:N,invalid:D}}),z=await b0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw _($.info.operation,Z,"row-protected",z)}var aX=["access","refresh","expires","lastRefreshedAt","apiKey"];function nX($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function rX($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!O(J)){if(X.baseURL===void 0)throw _($.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"}:nX(J),Q=X.baseURL?.trim()??G.baseURL,B=X.authHeader??G.authHeader;if(Q!==G.baseURL||B!==G.authHeader)throw _($.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:Q,authHeader:B}}function Y8($,Z,X,J){let z=$.rosterRow(Z),G=$.row(Z),Q=J??(G?G.identity:O(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function _2($,Z,X,J,z={}){let G=rX(Z,X,J),Q=Z.stateAccount(X),B=z.providerState??{kind:"keep"},H=Z.row(X)?.credentialEpoch??Z.entry(X)?.credentialEpoch,Y=typeof H==="number"?H:1,W=G8($.ctx.providerState,B,Q,Q&&Object.hasOwn(Q,H0)?Z.row(X):void 0,Y),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??M$(V,$.ctx.now()):void 0,K={...Q??{}};for(let D of aX)delete K[D];if(z.clearErrors)delete K.lastRefreshError,delete K.lastQuotaRefreshError,delete K.quota;if(B.kind==="clear")delete K[H0];else if(B.kind==="set")K[H0]=B.value;let U=t6(G,j),N={...K,...o6(G,j),[m]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[F2]:z.transition}:{},...t3(U,Y,z.binding??Y8(Z,X,U,z.identity),{replace:z.binding!==void 0,...W!==void 0?{providerState:W}:{}})}};return{stored:U,account:N}}async function O2($,Z,X){return $.setStateAccount(Z,X.account),await $.commitState(X.stored),X.stored}async function T2($,Z,X,J,z={}){return O2(Z,X,_2($,Z,X,J,z))}async function oX($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=N$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:t3(Z.credential,Z.credentialEpoch??1,Y8($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function BZ($,Z,X){let J=$==="add"?l1(Z):void 0;if(J)throw _($,Z,"invalid-input",J);let z=e6(X,{baseURLOptional:$==="rotate"});if(z)throw _($,Z,"invalid-input",z)}function A2($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw _($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function n1($,Z,X){if(X!==void 0&&!Z0(O(X)?X.credentialEpoch:void 0))throw _($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function S2($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw _($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw _($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function C2($,Z){return _($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function _$($,Z){return _($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function tX($,Z,X,J){let{id:z,credential:G,identity:Q}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!a1(Z.state,z))return;let B=()=>{throw _("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},H=Z.stateAccount(z),Y=V0(H?.[m]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return B();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return B();let W=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[V]=$1({accounts:[s1({id:z,credential:W,identity:Y.binding.identity,addedAt:0})],[p]:{rows:{[z]:{credentialEpoch:M2(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return B();if(Q!==void 0&&Q!==V.identity)return B();if(x0(G)!==Y.digest)return B();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return B();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return B()}else if(w0(G)!==Y.dispatch)return B();if(Y.providerState!==void 0&&V.providerState===void 0)return B();if(J!==void 0&&d1($.ctx.providerState,J)!==Y.providerState)return B();return V}function eX($,Z,X,J){let{id:z,credential:G,identity:Q,label:B}=X,H=Z.rosterRow(z),Y=()=>{throw _("add",z,H?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},W=Z.stateAccount(z),V=V0(W?.[m]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return Y();if(H&&(H.type!==G.type||H.label!==B||H.accountId!==Q))return Y();if(j.reservation!==X.stage?.reservation||j.label!==B||j.disabledReason!==X.disabled?.reason||V.binding.identity!==Q)return Y();let K=J===void 0?void 0:O1(J),U=W?.[H0],N=U===void 0?void 0:O1(U);if(j.providerState!==K||j.providerState!==N)return Y();if(x0(G)!==V.digest||w0(G)!==V.dispatch)return Y();let D=H?Z.config:{accounts:[{...s1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[p]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},M=$1(D,Z.state,$.ctx.codec,$.ctx.providerState).find((P)=>P.id===z);if(!M?.credential||M.invalid||M.stamp!=="bound"||M.type!==G.type||M.enabled||M.label!==j.label||M.identity!==V.binding.identity||M.disabledReason!==j.disabledReason||M.staged?.reservation!==j.reservation)return Y();if(H)return{id:z,outcome:"exists",credential:M.credential,credentialEpoch:V.credentialEpoch};if(M2(Z.config,z)!==V.credentialEpoch)return Y();return Z.roster().push({...s1({id:z,credential:G,identity:Q,label:B,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:M.credential,credentialEpoch:V.credentialEpoch}))}async function W8($,Z,X={}){z0("add");let{ctx:J}=$,{id:z,credential:G,identity:Q,label:B}=Z,H=Z.stage!==void 0||Z.disabled!==void 0,Y=await G0(J,"add",z,X.onFailure,async(W,V)=>{BZ("add",z,G);let j=X.onExisting??"rotate";if(Z.stage!==void 0&&j==="rotate")throw _("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||Z.stage!==void 0&&(B!==void 0&&typeof B!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!O(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!O(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||j==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw _("add",z,"invalid-input","staging requires a reservation and a disabled reason");let K=Z.providerState===void 0?void 0:u0(J.providerState,"add",z,Z.providerState);if(await W.acquire(q0($,{id:z,identity:Q})),G.type==="oauth")await W.acquire(X.providerLock??$.providerLock);for(let U of X.extraLocks??[])await W.acquire(U);return r(J,W,V,{operation:"add",rowId:z},async(U)=>{await P2(U,z,X.protect);let N=O(U.state.accounts)?U.state.accounts:{},D=Object.entries(N).find(([f,y])=>{if(f===z||U.rosterRow(f)||!O(y))return!1;let h=y[m];if(!O(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 _("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 _("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&j!=="rotate"&&(U.rosterRow(z)||a1(U.state,z)))return eX($,U,Z,K);if(j==="rotate"){U.assertNotStaged(z);let f=U.rows().find((y)=>y.fingerprint===t0(G));if(f)U.assertNotStaged(f.id)}if(j==="refuse"){let f=U.rows().find((c)=>c.fingerprint===t0(G)||c.id===z&&c.credential),y=O(U.state.accounts)?U.state.accounts:{},h=Object.entries(y).find(([,c])=>{if(!O(c))return!1;if(G.type==="oauth")return c.refresh===G.refresh;return typeof c.apiKey==="string"&&c.apiKey.trim()===G.apiKey.trim()})?.[0],o=f?.id??h??z;if(f||h!==void 0||a1(U.state,z))throw _("add",o,"credential-exists",`row ${o} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||a1(U.state,z)))throw _("add",z,"id-exists",`row ${z} already exists`);let M=tX($,U,Z,K),P=U.rows(),E=t0(G),F=j==="rotate"&&!M&&P.find((f)=>f.invalid===void 0&&f.fingerprint===E);if(F){if(U.assertNotStaged(F.id),W0("add",F),Q!==void 0&&F.identity!==void 0&&Q!==F.identity)throw C2("add",F.id);let f=_2($,U,F.id,G,{...K!==void 0?{providerState:L$(J.providerState,"add",F.id,F.providerState,K)}:{}});await U.completeTorn(),U.assertNotStaged(F.id);let y=await O2(U,F.id,f);return{id:F.id,outcome:"rotated",credential:y,credentialEpoch:F.credentialEpoch??1}}let q=P.find((f)=>f.id===z);if(q){if(q.invalid)throw _("add",z,"invalid-row",`row ${z} is invalid`);if(q.credential)throw _("add",z,"id-exists",`row ${z} already holds a credential`);if(W0("add",q),q.type!==G.type)throw _("add",z,"type-mismatch",`row ${z} is a ${q.type} row`);if(Q!==void 0&&q.identity!==void 0&&Q!==q.identity)throw C2("add",z);if(!q.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let f=_2($,U,z,G,{clearErrors:!0,...K!==void 0?{providerState:{kind:"set",value:K}}:{}});await U.completeTorn();let y=await O2(U,z,f);if(!q.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:y,credentialEpoch:q.credentialEpoch??1}}let L=M2(U.config,z);if(!Z0(L))throw _("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let S=M?.identity??Q;U.roster().push(s1({id:z,credential:G,...S!==void 0?{identity:S}:{},...B!==void 0?{label:B}:{},addedAt:J.now()})),U.setEntry(z,{credentialEpoch:L,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let A="added";if(Z.disabled)a0(U,z,Z.disabled.reason),A="added-disabled";if(!Z.disabled&&S!==void 0&&G.type==="oauth"){if(P.find((y)=>y.invalid===void 0&&y.type==="oauth"&&y.enabled&&y.identity===S))a0(U,z,p3),A="added-disabled"}if(M?.credential)return await U.commitConfig(),{id:z,outcome:A,credential:M.credential,credentialEpoch:M.credentialEpoch??L};U.dropStateAccount(z);let x=_2($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...B!==void 0?{label:B}:{},...K!==void 0?{providerState:O1(K)}:{}}}:{},...K!==void 0?{providerState:{kind:"set",value:K}}:{}});if(j==="rotate")await U.completeTorn();let w=await O2(U,z,x);return await U.commitConfig(),{id:z,outcome:A,credential:w,credentialEpoch:L}},{completeTorn:!1})});if(!H&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))$.firePull(Y.id,"add");return Y}async function V8($,Z,X,J={},z={}){z0("replace");let{ctx:G}=$,Q=await G0(G,"replace",Z,z.onFailure,async(B,H)=>{BZ("replace",Z,X),n1("replace",Z,z.attribution);let Y=J.providerState===void 0?void 0:u0(G.providerState,"replace",Z,J.providerState),{row:W}=await p0($,"replace",Z);if(await B.acquire(q0($,W)),X.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await B.acquire(V);return r(G,B,H,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)S2("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let j=A2("replace",Z,V.row(Z),X);if(l(j)!==l(W))throw _$("replace",Z);let K=V.entry(Z)?.credentialEpoch,U=(typeof K==="number"?K:1)+1;if(!Z0(U))throw _("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=z8(G.providerState,j,U,J.identity,Y),D={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(ZZ(V,Z,U,D),J.identity!==void 0)u1(V,J.identity);let M=await T2($,V,Z,X,{clearErrors:!0,binding:D,providerState:N});return await V.commitConfig(),{id:Z,credential:M,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return Q}async function U8($,Z,X,J={},z={}){z0("rotate");let{ctx:G}=$;return G0(G,"rotate",Z,z.onFailure,async(Q,B)=>{BZ("rotate",Z,X),n1("rotate",Z,z.attribution);let H=J.providerState===void 0?void 0:u0(G.providerState,"rotate",Z,J.providerState),{row:Y}=await p0($,"rotate",Z);if(await Q.acquire(q0($,Y)),J.identity!==void 0&&X.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await Q.acquire(W);return r(G,Q,B,{operation:"rotate",rowId:Z},async(W)=>{if(z.attribution!==void 0)S2("rotate",Z,W.row(Z),z.attribution),await W.completeTorn();let V=A2("rotate",Z,W.row(Z),X);if(l(V)!==l(Y))throw _$("rotate",Z);if(W0("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw C2("rotate",Z);let j=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,K=await T2($,W,Z,X,{identity:j,...H!==void 0?{providerState:L$(G.providerState,"rotate",Z,V.providerState,H)}:{}}),U=!1;if(!V.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(J.identity!==void 0&&V.identity!==J.identity)F1(W,Z,J.identity),U=!0;if(U)await W.commitConfig();return{id:Z,credential:K}},{completeTorn:z.attribution===void 0})})}async function j8($,Z,X,J,z){z0(Z);let{ctx:G}=$,Q=G.providerState,B=z.attribution,H=z.providerState;return G0(G,Z,X,z.onFailure,async(Y,W)=>{if(n1(Z,X,B),H!==void 0){if(typeof H!=="function")throw _(Z,X,"invalid-input","the provider-state mutator must be a function");if(B===void 0)throw _(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw _(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await p0($,Z,X);await Y.acquire(q0($,V));for(let j of z.extraLocks??[])await Y.acquire(j);return r(G,Y,W,{operation:Z,rowId:X},async(j)=>{await P2(j,X,z.protect),j.assertNotStaged(X);let K=j.row(X),U=J.enabled?A2("enable",X,K):K;if(!U||!j.rosterRow(X))throw A0(Z,X);if(l(U)!==l(V))throw _$(Z,X);if(B!==void 0)S2(Z,X,U,B);if(J.enabled&&U.disabledReason?.startsWith(p1))throw _("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let N=!J.enabled||!U.enabled||U.disabledReason!==void 0;if(J.enabled&&N&&U.type==="oauth"){let F=U.identity===void 0?void 0:j.rows().find((q)=>q.id!==X&&q.invalid===void 0&&q.type==="oauth"&&q.enabled&&q.identity===U.identity);if(F)throw _("enable",X,"duplicate-identity",`row ${F.id} is enabled with the same identity as row ${X}`)}if(H===void 0||Q===void 0){if(await j.completeTorn(),!N)return{id:X};if(J.enabled)j$(j,X);else a0(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!U.credential)throw _(Z,X,"no-credential",`row ${X} holds no credential`);W0(Z,U);let D=await GZ(j,Q,Z,U,H,!0);if(D.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let M={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)j$(j,X);else a0(j,X,J.reason);await j.commitConfig()}return M}if(!N)return j.setStateAccount(X,D.account),await j.commitState(),M;let P=J.enabled?{mark:H8(),enabled:!0}:{mark:H8(),enabled:!1,reason:J.reason},E=D.account[m];return j.setStateAccount(X,{...D.account,[m]:{...E,[F2]:P}}),await j.commitState(),F$(j,X,P),await j.commitConfig(),M},{completeTorn:!1})})}function K8($,Z,X,J={}){return j8($,"disable",Z,{enabled:!1,reason:X},J)}function D8($,Z,X={}){return j8($,"enable",Z,{enabled:!0},X)}async function q8($,Z,X={}){z0("remove");let{ctx:J}=$;return G0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw _("remove",Z,"invalid-input","id must be non-empty");let Q=X.attribution;if(n1("remove",Z,Q),X.staged!==void 0&&(!O(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw _("remove",Z,"invalid-input","a staged removal needs a reservation");let B=await Y0(J);if(B.status!=="ready")throw T0(B,"remove",Z);let H=B.rows.find((W)=>W.id===Z);if(!H&&!a1(B.state,Z))throw A0("remove",Z);let Y=l(H??{id:Z});await z.acquire(q0($,H??{id:Z}));for(let W of X.extraLocks??[])await z.acquire(W);return r(J,z,G,{operation:"remove",rowId:Z},async(W)=>{let V=W.reservation(Z);if(V!==void 0){if(!O(V)||!X.staged||V.reservation!==X.staged.reservation)throw _("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw _("remove",Z,"attribution",`row ${Z} is no longer reserved`);let j=W.row(Z),K=a1(W.state,Z);if(!j&&!K)throw A0("remove",Z);if(l(j??{id:Z})!==Y)throw _$("remove",Z);if(Q!==void 0)if(j)R2(Z,j,Q);else $J($,W,Z,Q);let U=X.protect;if(U){let N={row:j,config:W.snapshot.config,state:W.snapshot.state},D=await b0("remove",()=>U(Z,N));if(D!==void 0)throw _("remove",Z,"row-protected",D)}if(j){if(Q===void 0)await W.completeTorn();W.dropRosterRows(Z),await W.commitConfig()}if(K)W.dropStateAccount(Z),await W.commitState();return{id:Z,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function R2($,Z,X,J="remove"){if(S2(J,$,Z,X),Z.torn)throw _(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw _(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function $J($,Z,X,J){let z=()=>_("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),Q=V0(G?.[m]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let B;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();B={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")B={type:"oauth",refresh:G.refresh};else throw z();let[H]=$1({accounts:[s1({id:X,credential:B,identity:Q.binding.identity,addedAt:0})],[p]:{rows:{[X]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!H?.credential||H.invalid||H.stamp!=="bound")throw z();if(Q.credentialEpoch!==J.credentialEpoch||Q.binding.identity!==J.identity)throw _("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function a1($,Z){let X=$.accounts;return O(X)&&Object.hasOwn(X,Z)}function QZ($){return O($)&&typeof $.id==="string"?$.id:void 0}function ZJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let Q=QZ(G);if(Q!==void 0)X.add(Q)}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 XJ($,Z){let X=new Map;for(let G of $){let Q=QZ(G);if(Q===void 0)continue;let B=X.get(Q);if(B)B.push(G);else X.set(Q,[G])}let J=Z.flatMap((G)=>X.get(G)??[]),z=0;return $.map((G)=>QZ(G)===void 0?G:J[z++])}async function N8($,Z,X={}){z0("reorder");let{ctx:J}=$,z=X.onFailure;return G0(J,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of X.extraLocks??[])await G.acquire(B);return r(J,G,Q,{operation:"reorder",rowId:void 0},async(B)=>{let H=B.roster(),Y=ZJ(H,Z);if(Y)throw new g({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let W=[...Z],V=XJ(H,W);if(V.every((j,K)=>j===H[K]))return{ids:W,outcome:"unchanged"};return B.config.accounts=V,await B.commitConfig(),{ids:W,outcome:"reordered"}},{completeTorn:!1})})}async function M8($,Z,X,J,z={}){return z0("recordIdentity"),G0($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof X!=="string"||X.length===0)throw _("recordIdentity",Z,"invalid-input","identity must be non-empty");let B=O(J)?J.credentialEpoch:void 0;if(!Z0(B))throw _("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:H}=await p0($,"recordIdentity",Z);await G.acquire(q0($,H)),await G.acquire(z.providerLock??$.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return r($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(Y)=>{let W=A2("recordIdentity",Z,Y.row(Z));if(l(W)!==l(H))throw _$("recordIdentity",Z);if(W0("recordIdentity",W),(W.credentialEpoch??1)!==B)throw _("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 C2("recordIdentity",Z);if(W.identity===void 0)await oX(Y,W,X);let V=F1(Y,Z,X);return await Y.commitConfig(),{id:Z,disabled:V}})})}function L8($){let Z=$[p];return O(Z)&&O(Z.publications)?Z.publications:{}}function _8($,Z){let X=L8($);if(!Object.hasOwn(X,Z))return;let J=X[Z];if(!O(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)=>!O(z)||typeof z.id!=="string"||!Z0(z.credentialEpoch))||J.finalized.some((z)=>!O(z)||typeof z.id!=="string"||!Z0(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw _("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function O8($,Z){let X=await Y0($.ctx);if(X.status!=="ready")throw T0(X,"publishRoster",Z);return _8(X.config,Z)}function JJ($,Z){let X=()=>{throw _("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!O(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(!O(z)||typeof z.id!=="string"||l1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),n1("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"||l1(z))||new Set(Z.order).size!==Z.order.length)X()}function C8($,Z){$.entries();let X=$.config[p],J={...L8($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function zJ($,Z,X){let J=new Set;for(let Q of c1($.config)){if(!O(Q)||typeof Q.id!=="string")continue;if(J.has(Q.id))throw _("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(Q.id)}let z=new Set(Z.remove.map((Q)=>Q.id)),G=X.filter((Q)=>Q.invalid!=="roster"&&!z.has(Q.id));if(G.length!==Z.order.length||Z.order.some((Q)=>!G.some((B)=>B.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw _("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function F8($,Z){await $.assertAll();for(let J of Z.removed)if(V0($.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=V0(z?.[m]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let Q={...z[m]};delete Q.staged,$.setStateAccount(J.id,{...z,[m]:Q})}}await $.commitState(void 0,{durable:!0});let X={...Z,phase:"cleaned"};return C8($,X),await $.commitConfig({durable:!0}),X}async function P8($,Z,X={}){return z0("publishRoster"),G0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!O(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw _("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=O1(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((B)=>O(B)&&typeof B.id==="string");for(let B=0;;B++){let H=await Y0($.ctx);if(H.status!=="ready")throw T0(H,"publishRoster",Z.operationId);let Y=new Map(Q.map(({id:V})=>[V,l(H.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(Y.values())].sort())await J.acquire(q0($,{id:V}));await J.acquire(X.providerLock??$.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let W=await r($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let j=V.rows();if(Q.some(({id:q})=>l(j.find((L)=>L.id===q)??{id:q})!==Y.get(q)))return;let K=_8(V.config,Z.operationId);if(K){if(K.planDigest!==G)throw _("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 F8(V,K)}}JJ($,Z);let U=zJ(V,Z,j),N=[];for(let q of Z.remove){V.assertNotStaged(q.id);let L=j.find((S)=>S.id===q.id);if(!L)throw _("publishRoster",q.id,"attribution","the removed row no longer exists");if(R2(q.id,L,q.attribution,"publishRoster"),!L.credential||q.fingerprint!==void 0&&t0(L.credential)!==q.fingerprint)throw _("publishRoster",q.id,"attribution","the removed secret no longer matches");N.push(L)}let D=[];for(let q of Z.finalize){let L=j.find((y)=>y.id===q.id),S=V0(V.stateAccount(q.id)?.[m]);if(!L||L.staged?.reservation!==q.reservation||S?.staged?.reservation!==q.reservation||L.enabled)throw _("publishRoster",q.id,"row-staged","the finalized row is not disabled under this reservation");let A=V.stateAccount(q.id),x=V.rosterRow(q.id),w=A?.[H0],f=w===void 0?void 0:O1(w);if(!S?.staged||S.staged.label!==x?.label||S.staged.disabledReason!==L.disabledReason||S.staged.providerState!==f)throw _("publishRoster",q.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");R2(q.id,L,q.attribution,"publishRoster"),D.push(L)}let M=U.find((q)=>q.torn);if(M)throw _("publishRoster",Z.operationId,"attribution",`Row ${M.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let P=new Set;for(let q of U){if(!(Z.finalize.find((S)=>S.id===q.id)?.enabled??q.enabled)||q.type!=="oauth"||q.identity===void 0)continue;if(P.has(q.identity))throw _("publishRoster",q.id,"invalid-input","the final enabled roster repeats a known identity");P.add(q.identity)}for(let q of U)if(q.identity!==void 0&&q.fingerprint!==void 0&&U.some((L)=>L.id!==q.id&&L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("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((L)=>L.identity!==void 0&&L.identity!==q.identity&&L.fingerprint===q.fingerprint))throw _("publishRoster",q.id,"attribution","the staged secret belonged to a different known identity");await P2(V,Z.operationId,X.protect);let E={operationId:Z.operationId,planDigest:G,phase:"committed",removed:N.map((q)=>({id:q.id,credentialEpoch:q.credentialEpoch??1})),finalized:Z.finalize.map((q,L)=>({id:q.id,credentialEpoch:D[L]?.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 L=V.rosterRow(q.id);L.enabled=q.enabled;let S={...V.entry(q.id)};if(delete S.staged,q.enabled)delete S.disabledReason;else S.disabledReason=q.disabledReason;V.setEntry(q.id,S)}let F=V.roster().filter((q)=>!O(q)||typeof q.id!=="string"||j.find((L)=>L.id===q.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((q)=>V.rosterRow(q)),...F],C8(V,E),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await F8(V,E)}},{completeTorn:!1});if(W)return W;if(await J.releaseAll(),B>=1)throw _("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class HZ{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 r0(J.lockDefaults,J.lockEnv),G={writes:0};try{let Q=await r(J,z,G,{operation:"pull",rowId:$},async(H)=>{if(H.reservation($)!==void 0)return;await H.completeTorn();let Y=H.row($);if(Y?.unbound&&Y.enabled&&Y.type==="oauth"&&Y.credential&&!Y.invalid)W0("pull",Y);if(!Y?.candidate||Y.type!=="oauth")return;if(!Y.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await H.commitConfig();let W=H.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(),!Q){this.firedAtLoad.delete($);return}await J.hold?.("pull-before-request",$);let B;try{B=await this.hook?.(Q)}catch(H){throw new g({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:H})}await L2(X,$,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(Q){this.firedAtLoad.delete($);let B=i1(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,B)}catch(H){this.logger?.warn("pull failure hook threw",{rowId:$,error:H instanceof Error?H.message:String(H)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:B.kind})}finally{await z.releaseAll()}}}import{randomUUID as GJ}from"node:crypto";function YZ($,Z){if(_1("refresh",$,Z?.staged),!Z)throw _("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw _("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw _("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw _("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function T8($){return _("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 A8($,Z,X,J={}){z0("refresh");let{ctx:z}=$;return G0(z,"refresh",Z,J.onFailure,async(G,Q)=>{let{row:B}=await p0($,"refresh",Z);YZ(Z,B);let H=await J.refuse?.(B);if(H!==void 0)return{status:"refused",rowId:Z,reason:H};let Y=l(B),W;for(let U=0;;U++){await G.acquire(q0($,{id:Z,identity:Y===Z?void 0:Y})),await G.acquire(J.providerLock??$.providerLock);for(let M of J.extraLocks??[])await G.acquire(M);let D=await r(z,G,{writes:0},{operation:"refresh",rowId:Z},async(M)=>{let P=YZ(Z,M.row(Z));if(W0("refresh",P),!P.hasEntry)M.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await M.commitConfig(),P=YZ(Z,M.row(Z));if(l(P)!==Y)return{keyNow:l(P)};let E=await J.refuse?.(P);if(E!==void 0)return{refused:E};return{row:P,credential:P.credential,credentialEpoch:P.credentialEpoch,identity:P.identity}});if("refused"in D)return{status:"refused",rowId:Z,reason:D.refused};if("keyNow"in D){if(await G.releaseAll(),U>=1)throw _("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Y=D.keyNow;continue}W=D;break}if($Z(W.credential.lastRefreshedAt,z.now()))throw T8(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await X(W.credential,W.row)}catch(U){throw new g({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw _("refresh",Z,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:u0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),K=await r(z,G,Q,{operation:"refresh",rowId:Z},async(U)=>{let N=U.row(Z),D=U.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`});W0("refresh",N);let M=await J.refuse?.(N);if(M!==void 0)return{refused:M};let P=z.now(),E=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if($Z(E,P))throw T8(Z);let F={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,L=q?{mark:GJ(),enabled:!1,reason:`${p1}${JSON.stringify(q)}`}:void 0,S=N.identity===void 0&&V.identity?V.identity:void 0,A=await T2($,U,Z,F,{stamp:M$(E,P),transition:L,identity:S,...j!==void 0?{providerState:L$(z.providerState,"refresh",Z,N.providerState,j)}:{}});if(L!==void 0)F$(U,Z,L),await U.commitConfig();let x=N.identity;if(S!==void 0)F1(U,Z,S),x=S,await U.commitConfig();return{stored:A,identity:x,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 U=J.onPersisted;await b0("refresh",()=>U(Z,K.stored))}catch(U){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:U})}return{status:"rotated",rowId:Z,credential:K.stored,...K.identity!==void 0?{identity:K.identity}:{}}})}import{isDeepStrictEqual as QJ}from"node:util";var I2=Object.freeze(["version","accounts",p]);function WZ($){let Z={};for(let[X,J]of Object.entries($))if(!I2.includes(X))E2(Z,X,J);return Z}function E2($,Z,X){Object.defineProperty($,Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function BJ($,Z){let X={};for(let[J,z]of Object.entries($))if(I2.includes(J))E2(X,J,z);else if(Object.hasOwn(Z,J))E2(X,J,Z[J]);for(let[J,z]of Object.entries(Z))if(!Object.hasOwn($,J))E2(X,J,z);return X}function S8($){return new g({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function R8($){let Z=await Y0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:WZ(Z.config)}}async function E8($,Z,X={}){z0("updateSettings");let{ctx:J}=$,z=X.onFailure;return G0(J,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let H of X.extraLocks??[])await G.acquire(H);let B=G.held.length;try{for(let D of J.storeLocks)await G.acquire(D);let H=await Y0(J);if(H.status!=="ready")throw T0(H,"updateSettings",void 0);let Y=WZ(H.config),W=structuredClone(Y),V=await b0("updateSettings",()=>Z(W)),j=V===void 0?W:V;if(!O(j))throw S8("the settings mutator must produce an object");let K=I2.filter((D)=>Object.hasOwn(j,D));if(K.length>0)throw S8(`settings cannot set the pool-owned key(s) ${K.join(", ")}`);if(QJ(j,Y))return{settings:Y,outcome:"unchanged"};let U=BJ(H.config,j),N={operation:"updateSettings",rowId:void 0};return await F0(J.configPath,U,{beforeRename:async()=>{await J.onStep?.("before-config-write",N),await G.assertAll()}}),Q.writes++,await J.onStep?.("after-config-write",N),{settings:WZ(U),outcome:"updated"}}finally{await G.releaseTo(B)}})}var I8=new Map;function HJ($){let Z=I8.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},I8.set($,Z);return Z}function b8($){if($.status==="ready")return{status:"ready",schemaVersion:o0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function VZ($){let Z=HJ($.configPath),X={...n3,...$.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 HZ(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:J,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Q,B)=>z.fire(Q,B)};return{async load(){let Q=await Y0(J);if(Q.status==="ready"){for(let B of Q.rows)if((B.candidate||B.torn&&B.enabled)&&B.type==="oauth"&&B.needsFirstReading)z.fire(B.id,"load")}return b8(Q)},async read(){return b8(await Y0(J))},async initialize(Q={}){return{status:await J8(J,Q.dropKeys??[])}},add:(Q,B)=>W8(G,Q,B),publishRoster:(Q,B)=>P8(G,Q,B),publication:(Q)=>O8(G,Q),replace:(Q,B,H,Y)=>V8(G,Q,B,H,Y),rotate:(Q,B,H,Y)=>U8(G,Q,B,H,Y),updateProviderState:(Q,B,H,Y)=>Q8(G,Q,B,H,Y),disable:(Q,B,H)=>K8(G,Q,B,H),enable:(Q,B)=>D8(G,Q,B),remove:(Q,B)=>q8(G,Q,B),reorder:(Q,B)=>N8(G,Q,B),readSettings:()=>R8(G),updateSettings:(Q,B)=>E8(G,Q,B),recordIdentity:(Q,B,H,Y)=>M8(G,Q,B,H,Y),refresh:(Q,B,H)=>A8(G,Q,B,H),recordQuota:(Q,B,H)=>L2(G,Q,B,H),requestReading:(Q)=>z.fire(Q,"admission"),pullsSettled:()=>z.settled()}}var YJ=[/\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 KZ($={}){let{redactStrings:Z}=I0({...$,extraValuePatterns:[...YJ,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class Q0 extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var x8=/^[a-z][a-z0-9-]{0,63}$/,UZ={code:"action-failed",text:"That action failed."},WJ=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 O$($){if($ instanceof Q0)return{code:x8.test($.code)?$.code:UZ.code,text:$.message};if($ instanceof g)return{code:`pool-${$.kind}`,text:WJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return UZ}var k8="This cannot be undone. Continue?",VJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function UJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return VJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function jJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function jZ($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>jZ(z,`${Z}[${G}]`,X));if(!jJ($))return $;let J={};for(let[z,G]of Object.entries($)){if(UJ(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:jZ(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function f8($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=jZ($,"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 KJ($){return{value:String($.value),label:String($.label)}}function DJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(KJ),...$.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 DZ($){if($.irreversible===!0)return{message:$.confirm||k8,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function y8($){let Z=DZ($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(DJ),...Z?{confirm:Z}:{}}}function qJ($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function NJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:qJ($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(y8)}}function MJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(NJ),actions:(Z.actions??[]).map(y8),...Z.facts!==void 0?{facts:Z.facts}:{}}}function g8($,Z,X){return{command:$,title:Z,sections:X.map(MJ)}}function h8($,Z,X,J){return f8({command:$,menu:g8($,Z,X)},$,J)}function v8($,Z,X,J,z){return f8({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:x8.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:g8($,Z,X)},$,z)}var p8="disabled from the command menu";function FJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function l0($){return FJ($)?{...$}:{}}function LJ($){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 _J($,Z){return $.label??Z??$.id}function b2($,Z){return B0($.quota)?i($.quota,Z):void 0}function u8($,Z){return`${$} ${Z}${$===1?"":"s"}`}var C$="Actions";function OJ($){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 m8($,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 w8($){return O$($).text}async function CJ($){let Z=await $.read(),X=await $.readSettings();return{load:Z,rows:LJ(Z),settings:X.status==="error"?{}:X.settings}}function x2($,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:_J($,X)}}function PJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((V)=>V.id),Q=OJ(Z.load),B=Z.rows.filter((V)=>V.enabled).length,H=Z.rows.map((V,j)=>{let{account:K,name:U}=x2(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",M=[];if(!V.invalid&&V.enabled)M.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,p8,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)M.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${U}.`}});if(G.length>1)M.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((P,E)=>({value:String(E+1),label:String(E+1)})),value:String(j+1)}],run:async({values:P})=>{let E=Number(P.position),F=G.filter((L)=>L!==V.id);return F.splice(E-1,0,V.id),(await X.reorder(F,z)).outcome==="unchanged"?`${U} is already at position ${E}.`:`Moved ${U} to position ${E}.`}});return M.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:N,group:"Accounts",status:D,account:K,actions:M}}),Y=$.accounts?.login,W=[];if(Y&&!Q)W.push({id:"add",label:Y.label??"Add account",group:C$,knobs:Y.knobs??[],run:async({values:V,invocation:j})=>{let K=await Y.run(V,j);if(K.status==="cancelled")return{ok:!1,text:K.message??"Login cancelled."};if(K.status==="ready"){let U=await X.add(K.account,z);return m8(K.account.label??U.id,U)}return K.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let N=await X.add(U,z);j.notify(m8(U.label??N.id,N))},(U)=>{j.notify(`Adding the account failed: ${w8(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${w8(U)}`,"error")}),K.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${u8(Z.rows.length,"account")}, ${B} enabled`],items:Q?[]:H,actions:W}}}function TJ($,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 j of W)$.store.requestReading(j);await $.store.pullsSettled()}},Q=Z.rows.filter((W)=>W.candidate),B=Q.map((W)=>{let{account:V,name:j}=x2(W,$),K=b2(W,X);return{id:W.id,label:j,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:U})=>{return await G([W.id],U),`Checked quota for ${j}.`}}]}}),H=Z.rows.filter((W)=>!W.candidate).map((W)=>{let{name:V}=x2(W,$),j=W.invalid?"invalid":!W.enabled?"disabled":W.credential===void 0?"no credential":"unavailable",K=C0(b2(W,X),{now:J,form:"compact"});return`${V} (${j}): ${K}`}),Y=[];if(Q.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:C$,run:async({invocation:W})=>{let V=Q.map((j)=>j.id);return await G(V,W),`Checked quota for ${u8(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:H,items:B,actions:Y}}}function AJ($,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"}],Q=l0(Z.settings.routing).mode,B=typeof Q==="string"&&G.some((U)=>U.value===Q)?Q:"ordered",H=S3(B),Y=Z.rows.map((U)=>U.id),W=h1(Y,H.placement,$.routing?.formerMainId??H2),j=[`Mode: ${G.find((U)=>U.value===B)?.label??B}`];if(Y.length>0)j.push(`Roster order: ${Y.join(", ")}`);if(H.mode==="ordered"&&W.join()!==Y.join())j.push(`Tried in order: ${W.join(", ")}`);let K=[{id:"mode",label:"Change mode",group:C$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:B}],run:async({values:U})=>{let N=String(U.mode);return await X.updateSettings((D)=>{D.routing={...l0(D.routing),mode:N};return},z),`Routing mode set to ${G.find((D)=>D.value===N)?.label??N}.`}}];if(Y.length>1)K.push({id:"order",label:"Set order",group:C$,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:Y.join(", "),required:!0}],run:async({values:U})=>{let N=String(U.order).split(/[\s,]+/).filter((M)=>M.length>0),D=await X.reorder(N,z);return D.outcome==="unchanged"?"The order is unchanged.":`Order set to ${D.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:K}}}function SJ($,Z){if($.limits?.labels)return[...$.limits.labels];let X=$.quota?.scope??"all",J=[];for(let z of Z.rows)for(let G of b2(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function RJ($,Z){let X=$.quota?.scope??"all",J=new Map;for(let z of Z.rows)for(let G of b2(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,Q2(G));return(z)=>J.get(z)??z}function EJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=l0(Z.settings.killswitch),Q=G.enabled===!0,B=l0(G.accounts),H=SJ($,Z),Y=RJ($,Z),W=Q?"on":"off",V=Z.rows.map((j)=>{let{account:K,name:U}=x2(j,$),N=l0(B[j.id]),D=H.filter((M)=>typeof N[M]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${W}`,status:D.length===0?"no floors":D.map((M)=>`${Y(M)} ≥${N[M]}%`).join(" · "),account:K,actions:[{id:"floors",label:"Set floors",knobs:H.map((M)=>({kind:"number",id:M,label:`Minimum % left for ${Y(M)}`,min:0,max:100,...typeof N[M]==="number"?{value:N[M]}:{}})),run:async({values:M})=>{return await X.updateSettings((P)=>{let E=l0(P.killswitch),F=l0(E.accounts),q=l0(F[j.id]);for(let L of H){let S=M[L];if(typeof S==="number")q[L]=S;else if(S===null)delete q[L]}if(Object.keys(q).length>0)F[j.id]=q;else delete F[j.id];if(Object.keys(F).length>0)E.accounts=F;else delete E.accounts;P.killswitch=E;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${W}`],items:V,actions:[{id:"killswitch",label:Q?"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:C$,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!Q}],run:async({values:j})=>{let K=j.enabled===!0;return await X.updateSettings((U)=>{U.killswitch={...l0(U.killswitch),enabled:K};return},z),`Killswitch ${K?"on":"off"}.`}}]}}}async function l8($){let Z=await CJ($.store);return[PJ($,Z),TJ($,Z),AJ($,Z),EJ($,Z)]}var IJ=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),qZ=["accounts","quota","routing","limits"];function d8($,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 bJ($,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 xJ($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=bJ(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function kJ($,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 C1($){let Z=$.logger??n("commands"),X=KZ($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},B=qZ.filter((j)=>!Q[j]);for(let j of qZ)if(Q[j]&&$[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let H=$.store;if(B.length>0&&!H)throw Error(`a store is required for the built-in ${B.join(", ")} section${B.length>1?"s":""}`);let Y=new Set;for(let j of G){if(IJ.has(j.id)||Y.has(j.id))throw Error(`extra section id ${j.id} is taken`);Y.add(j.id)}async function W(j,K,U,N){try{return{id:j,slot:K,title:U.title,content:await U.build(N)}}catch(D){return Z.warn("command menu section failed to build",{command:$.command,section:j,error:X(D instanceof Error?D.message:String(D))}),{id:j,slot:K,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let K=H&&B.length>0?await l8({store:H,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let N of qZ){let D=Q[N];if(D)U.push(await W(N,N,D,j));else{let M=K.find((P)=>P.slot===N);if(M)U.push(M)}}if($.cache)U.push(await W("cache","cache",$.cache,j));if($.diagnostics)U.push(await W("diagnostics","diagnostics",$.diagnostics,j));for(let N of G)U.push(await W(N.id,"extra",N,j));return U}return{command:$.command,async open(j){let K=d8(j,X);return h8($.command,$.title,await V(K),J)},async apply(j,K){let U=d8(K,X),N=async(F)=>v8($.command,$.title,await V(U),F,J),D=j.command===$.command?kJ(await V(U),j):void 0;if(!D)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let M=DZ(D);if(M&&j.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:M.message,needsConfirmation:!0});let P=xJ(D.knobs??[],j.values);if("problem"in P)return N({ok:!1,code:"invalid-input",text:P.problem});let E;try{let F=await D.run({values:P.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});E=typeof F==="string"?{ok:!0,text:F}:{ok:F.ok,text:F.text,...F.ok?{}:{code:F.code??"refused"}}}catch(F){let q=O$(F);Z.warn("command menu action failed",{command:$.command,section:j.sectionId,action:j.actionId,code:q.code,error:X(F instanceof Error?F.message:String(F))}),E={ok:!1,...q}}return N(E)}}}async function P$($,Z,X){let J=new Map,z=[];for(let Q of X){let B=Q.label;for(let H=2;J.has(B);H++)B=`${Q.label} (${H})`;J.set(B,Q.value),z.push(B)}let G=await $.select(Z,z);return G===void 0?void 0:J.get(G)}function c8($,Z){return Z.length>0?`${$}
|
|
1
|
+
import{createRequire as zX}from"node:module";var GX=zX(import.meta.url);import{createAssistantMessageEventStream as UY}from"@earendil-works/pi-ai";import{streamSimple as jY}from"@earendil-works/pi-ai/compat";var c="all",x3=Object.freeze(["primary"]);function U6($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function w1($,Z){return JSON.stringify([$,Z])}function r0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Y0($){return typeof $==="number"&&Number.isFinite($)}function V6($){return typeof $==="string"&&$.length>0}function U0($,Z,X){return $[Z]===void 0||X($[Z])}function BX($){return Y0($)&&$>0}function b3($){return typeof $==="string"}function HX($){if(!r0($)||!V6($.scope)||!V6($.label))return!1;switch($.kind){case"reading":return Y0($.checkedAt)&&Y0($.usedPercent)&&U0($,"resetsAt",b3)&&U0($,"windowMinutes",BX);case"retired":return Y0($.retiredAt);case"absent":return Y0($.checkedAt);default:return!1}}function YX($){if(!r0($)||!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 j6($){return r0($)&&Y0($.value)&&Number.isInteger($.value)&&$.value>=0&&Y0($.checkedAt)}function k3($){return r0($)&&Object.values($).every(j6)}function QX($){return typeof $==="boolean"}function h0($){return r0($)&&typeof $.hasCredits==="boolean"&&typeof $.unlimited==="boolean"&&U0($,"balance",Y0)&&U0($,"overageLimitReached",QX)&&Y0($.checkedAt)}function f3($){if(!r0($))return;let Z=Object.entries($).filter(([,X])=>j6(X));return Z.length===0?void 0:Object.fromEntries(Z)}function P1($){if($0($))return $;if(!r0($))return;let{counters:Z,credits:X,...J}=$;if(!$0(J))return;let z=f3(Z),G=h0(X)?X:void 0;return{...J,...z===void 0?{}:{counters:z},...G===void 0?{}:{credits:G}}}function $0($){if(!r0($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let X of $.limits){if(!HX(X))return!1;let J=w1(X.scope,X.label);if(Z.has(J))return!1;Z.add(J)}return U0($,"budget",YX)&&U0($,"counters",k3)&&U0($,"credits",h0)}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 K6($){return $===void 0||typeof $==="string"&&$!==""}function D6($){return typeof $==="string"&&$!==""}function N$($,Z){return $[Z]===void 0||V2($[Z])}function y3($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function WX($){return U2($)&&K6($.scope)&&D6($.label)&&V2($.usedPercent)&&y3($,"resetsAt")&&($.windowMinutes===void 0||V2($.windowMinutes)&&$.windowMinutes>0)}function VX($){return U2($)&&K6($.scope)&&D6($.label)}function UX($){if(!U2($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&N$($,"remainingPercent")&&N$($,"usedPercent")&&y3($,"resetsAt")&&N$($,"limit")&&N$($,"used")&&N$($,"remaining")&&y3($,"unit")}function p1($){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(!WX(z))return!1;let G=w1(z.scope??c,z.label);if(J.has(G))return!1;J.add(G)}if(!X.every(VX))return!1;return($.budget===void 0||UX($.budget))&&($.counters===void 0||k3($.counters))&&($.credits===void 0||h0($.credits))}function jX($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function KX($,Z,X){if(Z===void 0)return $;if($!==void 0&&X<$.checkedAt)return $;return{...Z,checkedAt:X}}function DX($,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 qX($,Z){if(Z===void 0)return $;if($!==void 0&&Z.checkedAt<$.checkedAt)return $;return{...Z}}function v0($,Z){let X=$===void 0?void 0:P1($);if($!==void 0&&X===void 0)throw new W2("stored quota map is malformed");if(!p1(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(w1(D.scope,D.label),D);let B=(D)=>{let M=G.get(D);return M===void 0||z>=U6(M)},H=new Set;for(let D of Z.readings??[]){let M=D.scope??c,O=w1(M,D.label);if(H.add(O),!B(O))continue;G.set(O,{scope:M,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 M=D.scope??c,O=w1(M,D.label);if(H.has(O)||!B(O))continue;let R=G.get(O);G.set(O,R===void 0||R.kind==="absent"?{scope:M,label:D.label,kind:"absent",checkedAt:z}:{scope:M,label:D.label,kind:"retired",retiredAt:z})}let{limits:Y,budget:Q,counters:V,credits:W,...U}=J,K=KX(J.budget,Z.budget,z),j=DX(J.counters,Z.counters),N=qX(J.credits,Z.credits);return{...U,limits:[...G.values()].sort(jX),...K===void 0?{}:{budget:K},...j===void 0?{}:{counters:j},...N===void 0?{}:{credits:N}}}var g3=Object.freeze({validate:$0,decode:P1,merge:v0});var F6=900000,_6="no quota reading yet",L6="no limits reported";function O6($){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 P6($){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 P6($.windowMinutes)}function h3($){return Math.min(100,Math.max(0,$))}function j2($){return Math.round(h3($))}function q6($){return`${j2($)}% left`}function N6($,Z,X){let J=$===void 0?Number.NaN:Date.parse($);return{...Number.isFinite(J)&&J>X?{resetIn:O6(J-X)}:{},resetSinceReading:Number.isFinite(J)&&J>Z&&J<=X}}function NX($,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 C6($,Z){let{windows:X,age:J}=T6($,Z),z=X.map(({part:G})=>G);return J===void 0?{windows:z}:{windows:z,age:J}}function MX($){let Z=A6($.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 T6($,Z){if(!$)return{windows:[]};let{now:X}=Z,z=$.limits.filter((B)=>B.kind==="reading"&&B.remainingPercent!==void 0).sort(NX).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:q6(B.remainingPercent??0),remainingPercent:H,checkedAt:B.checkedAt,...N6(B.resetsAt,B.checkedAt,X)}}}),G=$.budget;if(G){let B=G.remainingPercent,H=G.reached?"credits spent":B!==void 0?`credits ${q6(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,...N6(G.resetsAt,G.checkedAt,X)}})}if(MX(z),z.length>0){let B=X-Math.min(...z.map(({part:H})=>H.checkedAt));if(B>(Z.staleAfterMs??F6))return{windows:z,age:`checked ${O6(B)} ago`}}return{windows:z}}function M6($){let Z=$.slice($.indexOf(":")+1);return Z.charAt(0).toUpperCase()+Z.slice(1)}function A6($){let Z=[...new Set($.map(M6))],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(M6(z))]))}var FX=2;function _X($){let Z=$.map((J)=>J.label.trim()||J.scope),X=A6(Z);return Z.map((J)=>X.get(J)??J)}function LX($,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 V=X.filter(({scope:W})=>W===H.scope).reduce((W,U)=>W===void 0||(U.part.remainingPercent??0)<(W.part.remainingPercent??0)?U:W,void 0);return V?[{group:H,listed:Y,window:V}]:[]});if(J.length===0)return;let z=_X($),G=(H)=>H.window.part.remainingPercent??0,B=[...J].sort((H,Y)=>G(H)-G(Y)||H.listed-Y.listed).slice(0,FX).sort((H,Y)=>H.listed-Y.listed);return B.map((H,Y)=>{let{windowMinutes:Q}=H.window,V=[z[H.listed]??H.group.scope,...Q===void 0?[]:[P6(Q)],`${j2(G(H))}%`].join(" ");return Y===B.length-1?`${V} left`:V})}function OX($,Z){let{windows:X}=T6($,Z),J=LX($?.groups,X);if(J)return J;let z=X.filter(({part:W,scope:U})=>W.kind==="window"&&U===c),G=X.filter(({part:W,scope:U})=>W.kind==="window"&&U!==c),B=X.find(({part:W})=>W.kind==="budget"),H=B?.spent?0:B?.part.remainingPercent,Q=[...G.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...H===void 0||B===void 0?[]:[{label:B.part.short,remaining:H}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),V=z.map(({part:W})=>`${W.name} ${j2(W.remainingPercent??0)}%`);if(Q)V.push(`${Q.label} ${j2(Q.remaining)}%`);if(V.length===0)return X.map(({part:W})=>W.figure);return V.map((W,U)=>U===V.length-1?`${W} left`:W)}function u1($,Z){if(Z.form==="narrow")return OX($,Z);let X=C6($,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=u1($,Z);if(X.length>0)return X.join(" · ");return $&&$.limits.length>0?L6:_6}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 PX($){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 CX($,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 TX($){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 V of $?.limits??[]){if(V.scope!==Z&&V.scope!==c)continue;let W=X.get(V.label);if(W===void 0){X.set(V.label,V);continue}let U=V.scope===c?W:V,K=V.scope===c?V:W;X.set(V.label,U.kind==="reading"?U:K)}let J=[...X.values()].map(PX).sort(CX),z=J.filter((V)=>V.kind==="reading"),G=z.length>0?z:J,B=G.length>0?Math.min(...G.map((V)=>V.checkedAt)):void 0,H=$?.budget?.kind==="reading"?TX($.budget):void 0,Y=f3($?.counters),Q=h0($?.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 C1($,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 S6($,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 AX($,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 I0($){let Z=$.scope??c,X=$.requiredLabels??x3,J=[],z=[],G=[];for(let U of $.rows){let K=S6(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=AX(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=C1(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])),V=(U,K)=>(Q.get(U.id)??0)-(Q.get(K.id)??0);z.sort(V);let W=z.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of W)$.requestPull?.(U);return{admitted:Y,refused:z,excluded:J,pulls:W}}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 l1($,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=I0($),X=new Set(Z.admitted.map((z)=>z.id));return{order:l1($.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 F$($,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 _$=900000,E6=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 I6($){if($===401||$===403)return"permanent";if($===void 0||$===0||!Number.isFinite($)||$>=500&&$<=599||$===429)return"transient";return"healthy"}function b6($){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??I6)($.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>_$)return{action:"retain",reason:"stale"};if($.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of b6($.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=C1($.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,E6);return J/G}function R6($,Z){if($<Z)return-1;if($>Z)return 1;return 0}function SX($,Z){if(!$.quota)return;let X=N2($.quota,$.quotaCheckedAt);if(X===void 0||Z-X>_$)return;let J=b6($.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 x6($){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)=>SX(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||R6(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||R6(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=I0($),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&&F$($.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??{}},V=$.scope,W=$.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),M=$.resetCreditsApplicable?.get(j.id);return{accountId:j.id,quota:j.kind==="api-key"?void 0:X.get(j.id)?.projection??s(j.quota,V),reservePercent:Q(j),configuredOrder:N,...M===void 0?{}:{resetCreditsApplicable:M},...D===void 0?{}:{killswitchPasses:D}}}),U=[],K=B?{action:"retain"}:$.pin?{action:"clear"}:{action:"none"};while(W.length>0){let j=x6({candidates:W,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),W=W.filter((M)=>M.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 gX,chmodSync as hX,existsSync as r3,renameSync as w6,statSync as vX}from"node:fs";import{open as mX}from"node:fs/promises";import{dirname as wX,resolve as pX}from"node:path";import{randomUUID as RX}from"node:crypto";import{lstat as g6,readFile as h6,rename as EX,unlink as k6}from"node:fs/promises";import{dirname as o0,resolve as F0}from"node:path";var I=process.platform==="win32",f6=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 y6;function d1(){return y6??=import("@cortexkit/private-files"),y6}class a 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(`Private file refused at ${Z}: ${$} (${J?.reason??J?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem 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 D0($,Z,X){try{return await X()}catch(J){if(J instanceof a)throw J;throw new a($,Z,J)}}var IX;async function m0($,Z){$=F0($),Z??=IX,await D0($,"safe-parent",async()=>{let X=await(await d1()).verifySafeParent($,Z);if(X.ok===!1){if(X.reason==="io-error"||X.reason==="wrong-kind")await g6($);throw new a(X.level??X.path,"safe-parent",{...X,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function z0($,Z,X=!1){if($=F0($),Z==="directory")return m0($);await D0($,"verify",async()=>{let J=await d1(),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 m0(o0($)),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&&!f6.has($))f6.add($),process.emitWarning(`Private permissions tightened: ${$}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function q0($,Z=!1,X){$=F0($),await D0($,"directory",async()=>{let J=await d1();try{return await g6($),await m0($,X)}catch(G){if(a3(G)!=="ENOENT")throw G}let z=o0($);if(z===$)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await q0(z,!1,X);try{await J.createOwnerOnly($,{kind:"dir"})}catch(G){if(a3(G)!=="EEXIST")throw G}await m0($,X)})}async function _0($,Z=!1){if(!I)return h6($,"utf8");return(await i3($,Z)).toString("utf8")}async function i3($,Z=!1){if(!I)return h6($);if($=F0($),Z)await m0(o0($)),await z0($,"file",!0);return D0($,"read",async()=>(await d1()).readOwnerOnly($))}async function c1($,Z){await m0(o0(F0($))),await D0($,"create",async()=>{await(await d1()).createPrivateFile(F0($),Z)})}async function v6($){await m0(o0(F0($))),await D0($,"directory-create",async()=>{await(await d1()).createOwnerOnly(F0($),{kind:"dir"})})}async function n3($,Z,X={}){$=F0($),Z=F0(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 W of H){let U=Math.min(B??1/0,G);if(J()>=U)break;if(W)await(X.sleep??((j)=>new Promise((N)=>setTimeout(N,j))))(Math.min(W,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??EX)($,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 V=new a(Z,"rename",Y??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw V.attempts=Q,V.elapsedMs=J()-z,V}async function s1($,Z,X={}){$=F0($),await q0(o0($));try{await z0($,"file",!0)}catch(Q){if(Q.code!=="ENOENT")throw Q}let J=F0(X.stagePath??`${$}.${RX()}.tmp`);if(o0(J)!==o0($))throw new a($,"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 c1(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 z0($,"file"),X.durable&&X.durability!=="file-only-on-windows")throw new a($,"directory-sync-unsupported",{code:"ENOTSUP"});Y()}catch(Q){let V=Q instanceof a?Q:new a($,H,Q);if(V.published=G,V.fileDurable=G,G)Object.assign(V,B);if(z){try{await k6(J)}catch{V.orphanPath=J}z=!1}throw Y(V),V}finally{if(z)await k6(J).catch(()=>{})}}var bX=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,xX=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function kX($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function b0($={}){let Z=[xX,...$.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 bX.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,V)=>Q.replace(V,"***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((W)=>z(W,B,H,Y));let Q=kX(G);if(Q&&Y>=8)return"[Truncated]";let V=Q?Y+1:Y;return Object.fromEntries((Q?J(G):Object.entries(G)).map(([W,U])=>[W,B&&X(W)?"***REDACTED***":z(U,B,H,V)]))}finally{H.delete(G)}}return{redact:(G)=>z(G,!0,new WeakSet),redactStrings:(G)=>z(G,!1,new WeakSet)}}var m6=b0(),fX=m6.redact,yX=m6.redactStrings;var M2={error:0,warn:1,info:2,debug:3,trace:4},u6=5242880,l6=3;function o3($){try{hX($,384)}catch{}}function uX($){try{if(!(r3($)&&vX($).size>=u6))return;for(let X=l6-1;X>=1;X--)if(r3(`${$}.${X}`)){let J=`${$}.${X+1}`;w6(`${$}.${X}`,J),o3(J)}let Z=`${$}.1`;w6($,Z),o3(Z)}catch{}}async function w0($){let{file:Z,handle:X}=$;if($.file=void 0,$.handle=void 0,Z&&X)await D0(Z,"log-close",()=>X.close())}async function p6($,Z){await q0(wX(Z));try{await z0(Z,"file",!0)}catch(X){if(X.code!=="ENOENT")throw X;try{await c1(Z,"")}catch(J){if(J.code!=="EEXIST")throw J;await z0(Z,"file",!0)}}return $.handle=await D0(Z,"log-open",()=>mX(Z,"a")),$.file=Z,$.handle}async function lX($,Z,X){Z=pX(Z);try{if($.file!==Z)await w0($);let J=$.handle??await p6($,Z);if((await D0(Z,"log-stat",()=>J.stat())).size>=u6){await w0($);for(let G=l6-1;G>=0;G--){let B=G===0?Z:`${Z}.${G}`,H=`${Z}.${G+1}`;try{await z0(B,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await z0(H,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await n3(B,H),await z0(H,"file")}J=await p6($,Z)}await D0(Z,"log-append",()=>J.appendFile(X,"utf8"))}catch(J){throw await w0($).catch(()=>{}),J}}function dX($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function cX($){let Z,X,J,z=b0(),G,B=[],H,Y=Promise.resolve(),Q,V={};function W(q){let _=Y.then(q);return Y=_.catch((S)=>{Q=S}),_}function U(q){if(I&&q.file!==Z)W(()=>w0(V)).catch(()=>{});Z=q.file,X=q.level,z=b0(q),G=q.captureSink}function K(q){if(q===void 0||q in M2)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 M2)return q;return"info"}function D(q=!0){if(H)clearTimeout(H),H=void 0;if(!B.length){if(I)return W(async()=>{if(q)await w0(V);if(Q)throw Q});return}let _;try{_=j()}catch{if(B=[],I&&q)return W(()=>w0(V));return}let S=B.join("");if(B=[],!_){if(I&&q)return W(()=>w0(V));return}if(I)return W(async()=>{try{await lX(V,_,S)}finally{if(q)await w0(V)}});try{if(uX(_),r3(_))o3(_);gX(_,S,{encoding:"utf8",mode:384})}catch{}}function M(){if(!H)H=setTimeout(()=>{H=void 0;let q=D(!1);if(q instanceof Promise)q.catch(()=>{})},500)}function O(q,_,S,A){if(Z===void 0&&G===void 0)return;try{if(M2[_]>M2[N()])return;let b=z.redactStrings(S),w;try{w=z.redact(A)}catch{w="[unserializable]"}let f=`[${new Date().toISOString()}] ${_.toUpperCase()} [${q}] ${b}`+(A===void 0?"":dX(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 M()}catch{}}function R(q){return{error:(_,S)=>O(q,"error",_,S),warn:(_,S)=>O(q,"warn",_,S),info:(_,S)=>O(q,"info",_,S),debug:(_,S)=>O(q,"debug",_,S),trace:(_,S)=>O(q,"trace",_,S)}}function F(){if(I)W(()=>w0(V)).catch(()=>{});if(Q=void 0,B=[],H)clearTimeout(H),H=void 0;Z=void 0,X=void 0,J=void 0,z=b0(),G=void 0}if($)U($);return{configure:U,createLogger:R,setLogLevel:K,flushLogs:D,reset:F}}var sX=cX();function d($){return sX.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 F2 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 a1="identity-contradicted: ",t3="duplicate-identity";function t0($,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 L$($,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 i1($,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))t0($,z.id,"duplicate-identity"),J.push(z.id);return J}function T1($,Z,X){let J=$.rosterRow(Z);if(!J)return[];return J.accountId=X,i1($,X)}import{setTimeout as LJ}from"node:timers/promises";import{randomUUID as d6}from"node:crypto";import{mkdir as tX,open as _2,rename as eX,rm as $J}from"node:fs/promises";import{dirname as e3}from"node:path";class O$ extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function L0($,Z,X={}){await $4($,Z,X)}async function $4($,Z,X,J){if(I)return s1($,X.serialize?X.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
3
|
+
`,{beforeRename:X.beforeRename,stagePath:`${$}.${(X.stageName??d6)()}.tmp`,onRenamed:J,durable:X.durable,durability:X.durability,onOutcome:X.onOutcome});await tX(e3($),{recursive:!0});let z=`${$}.${(X.stageName??d6)()}.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 O$(H)}if(await G.close(),G=void 0,await X.beforeRename?.(),await eX(z,$),B=!1,J?.(),X.durable){let H=await _2(e3($),"r");try{await H.sync()}catch(Y){throw new O$(Y)}finally{await H.close()}}}finally{if(await G?.close().catch(()=>{}),B)await $J(z,{force:!0}).catch(()=>{})}}async function Z4($){if(I){await z0($,"file");let J=new a($,"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 c6,open as o6,readFile as s6,rename as a6,rm as O2,stat as i6}from"node:fs/promises";import{dirname as X4,join as n6}from"node:path";async function r6($,Z){let X=await o6($,"wx",384);try{await X.writeFile(Z,"utf8")}finally{await X.close()}}var ZJ=globalThis.setTimeout.bind(globalThis),XJ=globalThis.clearTimeout.bind(globalThis);function J4($){let Z=$?.code;return Z==="ENOENT"||!I&&(Z==="EINVAL"||Z==="ENOTDIR")}function Z0($){return JJ({...$,now:Date.now})}async function JJ($){let Z=z4($.path,$.name),X=n6(Z,"owner.json"),J=L2(),z=$.now??Date.now,G=null,B=!1,H=!1,Y,Q,V=new Promise((C)=>{Q=C});function W(C){try{let T=$.onRenewalTimer?.(C);if(T&&(typeof T==="object"||typeof T==="function")&&"then"in T&&typeof T.then==="function")Promise.resolve(T).catch(()=>{})}catch{}}function U(){if(!G)return;XJ(G),G=null,W("cancelled")}function K(C,T){if(Y||B)return;Y=Object.freeze({reason:C,expectedOwnerId:J,...typeof T?.ownerId==="string"?{observedOwnerId:T.ownerId}:{},...typeof T?.expiresAt==="number"?{observedExpiresAt:T.expiresAt}:{}}),U(),Q(Y)}let j,N=null,D=`${Z}.evicting`,M=n6(D,"owner.json"),O=L2(),R=5000,F=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 z0(Z,"directory",!0),JSON.parse(await _0(X,!0))}try{return JSON.parse(await s6(Z,"utf8"))}catch(C){if(C.code!=="EISDIR")throw C;return JSON.parse(await s6(X,"utf8"))}}async function _(){if(I){let u=await q(),t=Number(u?.expiresAt)-z();await s1(Z,`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
|
|
5
|
+
`,{deadline:performance.now()+Math.max(0,t),beforeRename:async()=>{let Q2=await q();if(Q2?.ownerId!==J||!(Number(Q2?.expiresAt)>z())||!await h())throw new e0({target:$.path,name:$.name})}});return}let C=`${Z}.${L2()}.tmp`,T,x=!1;try{T=await o6(C,"wx",384),x=!0,await T.writeFile(`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
|
|
6
|
+
`,"utf8"),await T.chmod(384),await T.close(),T=void 0;let u=await q();if(u?.ownerId!==J||!(Number(u?.expiresAt)>z())||!await h())throw new e0({target:$.path,name:$.name});await a6(C,Z),x=!1}finally{if(await T?.close().catch(()=>{}),x)await O2(C,{force:!0}).catch(()=>{})}}async function S(){let C=`${JSON.stringify({ownerId:J,expiresAt:z()+$.ttlMs})}
|
|
7
|
+
`;if(I)await c1(Z,C);else await r6(Z,C)}async function A(C){let T=C.code;if(T==="EEXIST"){if(I)await q();return!0}if(T==="EISDIR"){if(I)await z0(Z,"directory",!0),await _0(X,!0);return!0}return!1}async function b(){if(I)await q0(X4(Z));try{return await S(),!0}catch(C){let T=C.code;if(await A(C))return!1;if(T==="ENOENT"){if(I)await q0(X4(Z));else await c6(X4(Z),{recursive:!0});try{return await S(),!0}catch(x){if(await A(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 T;try{T=await q()}catch(u){if(I&&u.code!=="ENOENT")throw u}let x=Number(T?.expiresAt);if(Number.isFinite(x)&&x>z())return{status:"live"};if(typeof T?.ownerId==="string"&&Number.isFinite(x))return{status:"stale",identity:{kind:"owner",ownerId:T.ownerId,expiresAt:x}};try{let u=await i6(Z),t=Number.isFinite(x)?x:u.mtimeMs+$.ttlMs;if(t>z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:u.dev,ino:u.ino,mtimeMs:u.mtimeMs,expiresAt:t}}}catch(u){if(u.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw u}}function y(C,T){if(T.status!=="stale")return!1;let x=T.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(M,I))?.ownerId===O}catch(C){if(I&&C.code!=="ENOENT")throw C;return!1}}async function o(C){if(I)await D0(C,"remove",()=>O2(C,{recursive:!0,force:!0}));else await O2(C,{recursive:!0,force:!0}).catch(()=>{})}async function i(){if(await h())await o(D)}async function H2(){if(I)await v6(D);else await c6(D);try{let C=`${JSON.stringify({ownerId:O,createdAt:z()})}
|
|
8
|
+
`;if(I)await c1(M,C);else await r6(M,C)}catch(C){if(J4(C))return!1;throw await i(),C}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function m1(){let C;try{C=await i6(D)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if(I)await z0(D,"directory",!0);if(C.mtimeMs+R>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let T=`${D}.${L2()}`;try{await a6(D,T)}catch(x){if(x.code==="ENOENT")return"missing";throw x}if($.onStep)await $.onStep("stale-marker-claimed");return await o(T),"recovered"}async function Y2(C){try{if(!await H2())return!1}catch(T){if(T.code==="EEXIST"){if(I){await z0(D,"directory",!0);try{await _0(M,!0)}catch(x){if(x.code!=="ENOENT")throw x}}return!1}throw T}try{await C()}finally{await i()}return!0}async function v(){for(let C=0;C<F;C++){if($.onStep)await $.onStep("relinquish-read");let T;try{T=await q()}catch(x){if(I)throw x;return}if(T?.ownerId!==J)return;try{await O2(Z,{recursive:!0,force:!0});return}catch(x){if(I)throw x;await w()}}}function g0(){if(!$.renew||B||Y)return;let C=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=ZJ(()=>{G=null;let T=(async()=>{let x=!B;try{if(!await Y2(async()=>{let t=await q(),Q2=z();if(B||Y){x=!1;return}if(t?.ownerId!==J){K("taken-over",t),x=!1;return}if(!(Number(t?.expiresAt)>Q2)){K("expired",t),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 a)j=u,K("renewal-failed"),x=!1;try{let t=await q();if(t?.ownerId!==J)K("taken-over",t);else if(!(Number(t?.expiresAt)>z()))K("expired",t)}catch{K("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(x&&!B&&!Y)g0()}})();N=T,T.finally(()=>{if(N===T)N=null})},C),"unref"in G)G.unref();W("scheduled")}function W6(){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 O1=await b();if(!O1)for(let C=0;C<F;C++){if(O1=await b(),O1)break;let T=await f();if(T.status==="live")return W6();if(T.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 m1()==="fresh")return null;await w();continue}try{let x=await f();if(x.status==="live")return W6();if(!y(T.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(T.identity,u))continue;if(await o(Z),!await h())return null;if($.onStep)await $.onStep("stale-lock-removed");if(O1=await b(),!O1)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await h())return await v(),O1=!1,null;break}finally{await i()}}if(!O1)return null;return g0(),{ownerId:J,whenLost:()=>V,hasLost:()=>Y!==void 0,assertOwned:async()=>{if(j)throw j;let C;try{let T=await q();if(C=T,!B&&!Y&&T?.ownerId===J&&Number(T?.expiresAt)>z())return;K(T?.ownerId!==J?"taken-over":"expired",T)}catch(T){if(K("unreadable"),I&&T instanceof a)throw T}throw new e0({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<F;C++){try{let T=!1;if(await Y2(async()=>{let u;try{u=await q()}catch(t){if(I&&t.code==="ENOENT"){T=!0;return}throw t}if(u?.ownerId!==J){T=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await h())return;await o(Z),T=!0})){if(I&&!T)throw new a(Z,"release-not-confirmed",{code:"EIO"});H=T;return}await m1()}catch(T){if(I)throw T;return}await w()}if(I)throw new a(Z,"release-not-confirmed",{code:"ETIMEDOUT"})}}}function z4($,Z){return`${$}.${Z}.lock`}class p0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class e0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function G4($,Z,X){let J=performance.now();for(;;){Z.signal?.throwIfAborted();let z=await Z0({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 p0({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((B)=>setTimeout(B,Math.min(25,Math.ceil(G))))}}import{AsyncLocalStorage as zJ}from"node:async_hooks";var t6=new zJ;function G0($){if(t6.getStore()!==void 0)throw new F2($)}function x0($,Z){return t6.run($,async()=>await Z())}async function e6($,Z,X,J,z){if(!Z)return;try{await x0($,()=>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 B4=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function GJ($,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,...BJ($)},G=performance.now();for(;;){let B=await Z0({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(V){throw await Q.release(),V}return Q}let H=z.timeoutMs-(performance.now()-G);if(H<=0)throw new p0({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 BJ($){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 $1{defaults;env;held=[];constructor($,Z){this.defaults=$,this.env=Z}async acquire($){let Z=await GJ($,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 P$}from"node:crypto";var p="commonAuthPool",Z1=1,C0="rows",P2="retiredEpochs",C$=1,H4=300000,m=p;function HJ($){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 S1($){return P$("sha256").update(HJ($)).digest("hex")}function $8($){if(!P($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function YJ($){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 QJ=new Set(["__proto__","constructor","prototype"]);function n1($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(QJ.has($))return"id is a reserved object key";return}function Y4($){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 Z8($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function X1($){return P$("sha256").update(Z8($)).digest("hex")}function k0($){return P$("sha256").update(`credential-stamp\x00${Z8($)}`).digest("hex")}function u0($){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 P$("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function Q4($,Z,X,J={}){return{credentialEpoch:Z,digest:k0($),dispatch:u0($),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function r1($,Z){let X=$?.credentialBound?$.credentialBound(Z):Z;return P$("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function T$($,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!==k0(Z)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function X0($){return Number.isSafeInteger($)&&$>=1}function j0($){if(!P($))return;let Z=$.credentialEpoch;if(!X0(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 $?YJ($.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&&!Y4(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 WJ($,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 VJ($,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!==k0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!WJ(z.binding,$,X))return"mismatched";if(z.dispatch!==u0($))return"mismatched";return"bound"}function X8($){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>Z1)return{status:"error",reason:`${p}.schemaVersion ${J} is newer than ${Z1}`};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 J8($){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 o1($){return Array.isArray($.accounts)?$.accounts:[]}function z8($){let Z=$[p];if(!P(Z))return{};let X=Z[C0];return P(X)?X:{}}function UJ($){return P($.accounts)?$.accounts:{}}function jJ($){if(!P($))return"not an object";let Z=n1($.id);if(Z)return Z;if($.type==="api")return Y4($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function KJ($,Z){if(!P($))return;let X=$.credentialEpoch;if(!X0(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 $&&!$8($.staged))return;return{credentialEpoch:X,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:J}:{}}}function DJ($,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 o1($).find((X)=>P(X)&&X.id===Z)}function G8($){if(!P($[p]))$[p]={};return $[p]}function W4($){let Z=G8($);if(!P(Z[C0]))Z[C0]={};return Z[C0]}function J1($,Z){let X=z8($),J=Object.hasOwn(X,Z)?X[Z]:void 0;return P(J)?J:void 0}function T2($,Z,X){Object.defineProperty(W4($),Z,{value:X,enumerable:!0,writable:!0,configurable:!0})}function B8($,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 X0(z)?z:void 0}function H8($,Z){let X=J1($,Z)?.credentialEpoch;return X0(X)?X:void 0}function A2($,Z){return Math.max(B8($,Z)??0,H8($,Z)??0)+1}function Y8($,Z){let X=[...Z];if(X.length===0)return;let J=G8($),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(X0(Y))B(H,Y);for(let H of X)B(H,Math.max(B8($,H)??0,H8($,H)??1));J[P2]=G}function z1($,Z,X,J){let z=z8($),G=UJ(Z),B=new Set,H=[];for(let Y of o1($)){let Q=jJ(Y),V=P(Y)&&typeof Y.id==="string"?Y.id:void 0,W=V===void 0?void 0:z[V],U=P(W)&&Object.hasOwn(W,"staged"),K=U?$8(W.staged):void 0;if(Q||!P(Y)||V===void 0||B.has(V)){if(V!==void 0&&!B.has(V))B.add(V);if(V!==void 0)H.push({id:V,type:P(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...K?{staged:K}:{}});continue}B.add(V);let j=Y.type==="api"?"api":"oauth",N=Object.hasOwn(z,V),D=N?KJ(z[V],X):void 0,M=DJ(Y,G[V]),O=Y.enabled!==!1,R=D?D.credentialEpoch:N?void 0:1,F=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,q={id:V,type:j,enabled:O,needsFirstReading:D?D.needsFirstReading:j==="oauth",hasEntry:N,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...F!==void 0?{identity:F}:{},...M?{credential:M,fingerprint:X1(M)}:{},...D?{credentialEpoch:D.credentialEpoch}:{},...K?{staged:K}:{},...D?.disabledReason!==void 0?{disabledReason:D.disabledReason}:{},...D&&"quota"in D?{quota:D.quota}:{},...qJ(G[V],M,R,F,J),stamp:VJ(M,R,F,G[V])};if(N&&!D)q.invalid="entry";else q.candidate=O&&M!==void 0&&!U;H.push(q)}return H}function qJ($,Z,X,J,z){if(!P($)||!Object.hasOwn($,Q0))return{};let G=T$($,Z,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let B=$[Q0];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(r1(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function l($){return $.identity??$.id}function A$($,Z){if($===void 0||$>Z+H4)return Z;return Math.max(Z,$+1)}function V4($,Z){return A$($,Z)>Z+H4}function t1($){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 Q8($,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 W8($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function V8($,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)&&!Y4($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var S2="transition",U8="transitionMark";function NJ($){if(!P($))return;let Z=$[S2];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 S$($,Z,X){if(X.enabled)L$($,Z);else t0($,Z,X.reason??"");if(!$.rosterRow(Z))return;let J=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...J,[U8]:X.mark}),!X.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)i1($,z.identity)}function MJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function FJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function _J($,Z,X,J={}){let z=P(Z.accounts)?Z.accounts:{},G=new Map;for(let B of z1($,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!==k0(B.credential))continue;let Q=B.credentialEpoch??1;if(Y.credentialEpoch>Q){if(!FJ(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==u0(MJ(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===u0(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!==u0(B.credential))continue;let V=NJ(H[m]);if(V&&J1($,B.id)?.[U8]!==V.mark)G.set(B.id,{kind:"transition",transition:V})}}return G}function U4($,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(a1))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 j4($,Z,X,J={}){let z=_J($,Z,X,J);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),B={rows:()=>z1(G,Z,X),rosterRow:(H)=>C2(G,H),entry:(H)=>J1(G,H),setEntry:(H,Y)=>T2(G,H,Y)};for(let[H,Y]of z)if(Y.kind==="replace")U4(B,H,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[H,Y]of z)if(Y.kind==="identity")T1(B,H,Y.identity);else if(Y.kind==="transition")S$(B,H,Y.transition);else if(Y.stamp.binding.identity!==void 0)i1(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function K4($,Z,X,J={}){let{config:z,torn:G}=j4($,Z,X,J),B=z1(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 D4($){try{return await _0($,I)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}function j8($){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 D4($.configPath),J=await D4($.statePath),z=await D4($.configPath);if(X!==z){if(Z<2)await LJ(2+Math.floor(Math.random()*4));continue}let G=X8(j8(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=J8(j8(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:K4(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 K8{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 K4(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 W4(this.config)}entry($){return this.entries(),J1(this.config,$)}setEntry($,Z){T2(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=j4(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 o1(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);Y8(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:C$,accounts:Z,[p]:{...B,schemaVersion:Z1,[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:C$,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 Z4(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 Z4(this.ctx.configPath)}async write($,Z,X,J=!0,z=!1,G){await $4($,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 D8($,Z){let X=new $1($.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=C$,G[p]={schemaVersion:Z1,[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 e1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function r($,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 K8($,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 e1($,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 O$)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 e0)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 p0)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 B0($,Z,X,J,z){let G=new $1($.lockDefaults,$.lockEnv),B={writes:0};try{return await z(G,B)}catch(H){let Y=e1(H,Z,X,B);if(Y.kind!=="after-persist-hook")await e6(Z,J,X,Y,$.logger);throw Y}finally{await G.releaseAll()}}function N0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(l(Z))}`,path:$.ctx.statePath}}async function l0($,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=J1(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 A0(Z,X);return{result:J,row:z}}function A0($,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 L($,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 L($,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 $1(z.lockDefaults,z.lockEnv),B={writes:0};try{if(!X0(X?.credentialEpoch))throw L("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await r(z,G,B,{operation:"pull",rowId:Z},async(H)=>{H.assertNotStaged(Z);let Y=H.row(Z);if(!Y)throw A0("pull",Z);if(Y.invalid)throw L("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!Y.credential)throw L("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 V=z.codec.merge(Q.quota,J);if(!z.codec.validate(V))throw L("pull",Z,"invalid-quota","the quota codec rejected the merged map");H.setEntry(Z,{...Q,quota:V,needsFirstReading:!1}),await H.commitConfig()},{completeTorn:!1})}catch(H){throw e1(H,"pull",Z,B)}finally{await G.releaseAll()}}function d0($,Z,X,J,z="the provider state"){if(!$)throw L(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 L(Z,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!$.validate(G))throw L(Z,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function R$($,Z,X,J,z){if(J===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:d0($,Z,X,$.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function q8($,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:d0($,"replace",Z.id,B,"the provider state onReplace returned")}}function N8($,Z,X,J,z){if(Z.kind==="set")return r1($,Z.value);if(Z.kind==="clear")return;return T$(X,J?.credential,z,J?.identity)}async function M8($,Z,X,J,z={}){G0("updateProviderState");let{ctx:G}=$,B="updateProviderState";return B0(G,B,Z,z.onFailure,async(H,Y)=>{let Q=G.providerState;if(!Q)throw L(B,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw L(B,Z,"invalid-input","a mutator is required");let V=P(X)?X.credentialEpoch:void 0;if(!X0(V))throw L(B,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:W}=await l0($,B,Z);await H.acquire(N0($,W));for(let U of z.extraLocks??[])await H.acquire(U);return r(G,H,Y,{operation:B,rowId:Z},async(U)=>{let K=U.row(Z);if(!K)throw A0(B,Z);if(l(K)!==l(W))throw L(B,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(K.invalid)throw L(B,Z,"invalid-row",`row ${Z} failed validation`);if(!K.credential)throw L(B,Z,"no-credential",`row ${Z} holds no credential`);if(V0(B,K),(K.credentialEpoch??1)!==V||K.identity!==X.identity)throw L(B,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let N=await q4(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 F8=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function q4($,Z,X,J,z,G=!1){let{id:B,credential:H}=J;if(!H)throw L(X,B,"no-credential",`row ${B} holds no credential`);let Y=J.credentialEpoch??1,Q=$.stateAccount(B),V=Q?.[m],W=j0(V);if(!P(V)||!W?.binding||W.digest!==k0(H)||W.credentialEpoch!==Y||W.binding.identity!==J.identity)throw L(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 x0(X,()=>z(U,J));if(G&&K===F8)return{kind:"declined"};let j=K===void 0?void 0:d0(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 M={...V};delete M.providerState,D[m]=M}else{D[Q0]=j;let M=r1(Z,j);if(W.providerState!==M)D[m]={...V,providerState:M}}return{kind:"changed",...j!==void 0?{value:j}:{},account:D}}import{randomUUID as _8}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:V,identity:W,credentialEpoch:U,stamp:K,staged:j,torn:N,invalid:D}=G;return{id:B,type:H,label:Y,enabled:Q,disabledReason:V,identity:W,credentialEpoch:U,stamp:K,staged:j,torn:N,invalid:D}}),z=await x0($.info.operation,()=>X({id:Z,row:J.find((G)=>G.id===Z),rows:J,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw L($.info.operation,Z,"row-protected",z)}var OJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function PJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function CJ($,Z,X){if(X.type!=="api")return X;let J=$.rosterRow(Z);if(!P(J)){if(X.baseURL===void 0)throw L($.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"}:PJ(J),B=X.baseURL?.trim()??G.baseURL,H=X.authHeader??G.authHeader;if(B!==G.baseURL||H!==G.authHeader)throw L($.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 L8($,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=CJ(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,V=N8($.ctx.providerState,H,B,B&&Object.hasOwn(B,Q0)?Z.row(X):void 0,Q),W=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??A$(W,$.ctx.now()):void 0,K={...B??{}};for(let D of OJ)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=W8(G,U),N={...K,...Q8(G,U),[m]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[S2]:z.transition}:{},...Q4(j,Q,z.binding??L8(Z,X,j,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};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 TJ($,Z,X){if(!Z.credential||Z.stamp!=="bound")return;let J=$.stateAccount(Z.id),z=T$(J,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...J??{},[m]:Q4(Z.credential,Z.credentialEpoch??1,L8($,Z.id,Z.credential,X),z!==void 0?{providerState:z}:{})}),await $.commitState()}function M4($,Z,X){let J=$==="add"?n1(Z):void 0;if(J)throw L($,Z,"invalid-input",J);let z=V8(X,{baseURLOptional:$==="rotate"});if(z)throw L($,Z,"invalid-input",z)}function f2($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw L($,Z,"invalid-row",`row ${Z} failed validation`);if(J&&J.type!==X.type)throw L($,Z,"type-mismatch",`row ${Z} holds a ${X.type} credential`);return X}function Z$($,Z,X){if(X!==void 0&&!X0(P(X)?X.credentialEpoch:void 0))throw L($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function y2($,Z,X,J){if(!X)throw A0($,Z);if(X.invalid)throw L($,Z,"invalid-row",`row ${Z} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw L($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function b2($,Z){return L($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function E$($,Z){return L($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function AJ($,Z,X,J){let{id:z,credential:G,identity:B}=X;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!$$(Z.state,z))return;let H=()=>{throw L("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 V=G.type==="api"?{...G,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}:G,[W]=z1({accounts:[t1({id:z,credential:V,identity:Q.binding.identity,addedAt:0})],[p]:{rows:{[z]:{credentialEpoch:A2(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!W?.credential||W.invalid||W.stamp!=="bound")return H();if(B!==void 0&&B!==W.identity)return H();if(k0(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(u0(G)!==Q.dispatch)return H();if(Q.providerState!==void 0&&W.providerState===void 0)return H();if(J!==void 0&&r1($.ctx.providerState,J)!==Q.providerState)return H();return W}function SJ($,Z,X,J){let{id:z,credential:G,identity:B,label:H}=X,Y=Z.rosterRow(z),Q=()=>{throw L("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),W=j0(V?.[m]),U=W?.staged;if(!W?.binding||!U||W.replace||W.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||W.binding.identity!==B)return Q();let K=J===void 0?void 0:S1(J),j=V?.[Q0],N=j===void 0?void 0:S1(j);if(U.providerState!==K||U.providerState!==N)return Q();if(k0(G)!==W.digest||u0(G)!==W.dispatch)return Q();let D=Y?Z.config:{accounts:[{...t1({id:z,credential:G.type==="api"?{...G,baseURL:W.binding.baseURL??"",authHeader:W.binding.authHeader}:G,identity:W.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[p]:{rows:{[z]:{credentialEpoch:W.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},M=z1(D,Z.state,$.ctx.codec,$.ctx.providerState).find((O)=>O.id===z);if(!M?.credential||M.invalid||M.stamp!=="bound"||M.type!==G.type||M.enabled||M.label!==U.label||M.identity!==W.binding.identity||M.disabledReason!==U.disabledReason||M.staged?.reservation!==U.reservation)return Q();if(Y)return{id:z,outcome:"exists",credential:M.credential,credentialEpoch:W.credentialEpoch};if(A2(Z.config,z)!==W.credentialEpoch)return Q();return Z.roster().push({...t1({id:z,credential:G,identity:B,label:H,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:W.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:M.credential,credentialEpoch:W.credentialEpoch}))}async function O8($,Z,X={}){G0("add");let{ctx:J}=$,{id:z,credential:G,identity:B,label:H}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,Q=await B0(J,"add",z,X.onFailure,async(V,W)=>{M4("add",z,G);let U=X.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw L("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 L("add",z,"invalid-input","staging requires a reservation and a disabled reason");let K=Z.providerState===void 0?void 0:d0(J.providerState,"add",z,Z.providerState);if(await V.acquire(N0($,{id:z,identity:B})),G.type==="oauth")await V.acquire(X.providerLock??$.providerLock);for(let j of X.extraLocks??[])await V.acquire(j);return r(J,V,W,{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 L("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 L("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)||$$(j.state,z)))return SJ($,j,Z,K);if(U==="rotate"){j.assertNotStaged(z);let f=j.rows().find((y)=>y.fingerprint===X1(G));if(f)j.assertNotStaged(f.id)}if(U==="refuse"){let f=j.rows().find((i)=>i.fingerprint===X1(G)||i.id===z&&i.credential),y=P(j.state.accounts)?j.state.accounts:{},h=Object.entries(y).find(([,i])=>{if(!P(i))return!1;if(G.type==="oauth")return i.refresh===G.refresh;return typeof i.apiKey==="string"&&i.apiKey.trim()===G.apiKey.trim()})?.[0],o=f?.id??h??z;if(f||h!==void 0||$$(j.state,z))throw L("add",o,"credential-exists",`row ${o} already holds this secret or id`)}if(U==="stage-duplicate"&&(j.rosterRow(z)||$$(j.state,z)))throw L("add",z,"id-exists",`row ${z} already exists`);let M=AJ($,j,Z,K),O=j.rows(),R=X1(G),F=U==="rotate"&&!M&&O.find((f)=>f.invalid===void 0&&f.fingerprint===R);if(F){if(j.assertNotStaged(F.id),V0("add",F),B!==void 0&&F.identity!==void 0&&B!==F.identity)throw b2("add",F.id);let f=E2($,j,F.id,G,{...K!==void 0?{providerState:R$(J.providerState,"add",F.id,F.providerState,K)}:{}});await j.completeTorn(),j.assertNotStaged(F.id);let y=await I2(j,F.id,f);return{id:F.id,outcome:"rotated",credential:y,credentialEpoch:F.credentialEpoch??1}}let q=O.find((f)=>f.id===z);if(q){if(q.invalid)throw L("add",z,"invalid-row",`row ${z} is invalid`);if(q.credential)throw L("add",z,"id-exists",`row ${z} already holds a credential`);if(V0("add",q),q.type!==G.type)throw L("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 _=A2(j.config,z);if(!X0(_))throw L("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let S=M?.identity??B;j.roster().push(t1({id:z,credential:G,...S!==void 0?{identity:S}:{},...H!==void 0?{label:H}:{},addedAt:J.now()})),j.setEntry(z,{credentialEpoch:_,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let A="added";if(Z.disabled)t0(j,z,Z.disabled.reason),A="added-disabled";if(!Z.disabled&&S!==void 0&&G.type==="oauth"){if(O.find((y)=>y.invalid===void 0&&y.type==="oauth"&&y.enabled&&y.identity===S))t0(j,z,t3),A="added-disabled"}if(M?.credential)return await j.commitConfig(),{id:z,outcome:A,credential:M.credential,credentialEpoch:M.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:S1(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:A,credential:w,credentialEpoch:_}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(Q.outcome==="added"||Q.outcome==="completed"))$.firePull(Q.id,"add");return Q}async function P8($,Z,X,J={},z={}){G0("replace");let{ctx:G}=$,B=await B0(G,"replace",Z,z.onFailure,async(H,Y)=>{M4("replace",Z,X),Z$("replace",Z,z.attribution);let Q=J.providerState===void 0?void 0:d0(G.providerState,"replace",Z,J.providerState),{row:V}=await l0($,"replace",Z);if(await H.acquire(N0($,V)),X.type==="oauth")await H.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await H.acquire(W);return r(G,H,Y,{operation:"replace",rowId:Z},async(W)=>{if(z.attribution!==void 0)y2("replace",Z,W.row(Z),z.attribution),await W.completeTorn();let U=f2("replace",Z,W.row(Z),X);if(l(U)!==l(V))throw E$("replace",Z);let K=W.entry(Z)?.credentialEpoch,j=(typeof K==="number"?K:1)+1;if(!X0(j))throw L("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=q8(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(U4(W,Z,j,D),J.identity!==void 0)i1(W,J.identity);let M=await k2($,W,Z,X,{clearErrors:!0,binding:D,providerState:N});return await W.commitConfig(),{id:Z,credential:M,credentialEpoch:j}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")$.firePull(Z,"replace");return B}async function C8($,Z,X,J={},z={}){G0("rotate");let{ctx:G}=$;return B0(G,"rotate",Z,z.onFailure,async(B,H)=>{M4("rotate",Z,X),Z$("rotate",Z,z.attribution);let Y=J.providerState===void 0?void 0:d0(G.providerState,"rotate",Z,J.providerState),{row:Q}=await l0($,"rotate",Z);if(await B.acquire(N0($,Q)),J.identity!==void 0&&X.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await B.acquire(V);return r(G,B,H,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)y2("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let W=f2("rotate",Z,V.row(Z),X);if(l(W)!==l(Q))throw E$("rotate",Z);if(V0("rotate",W),J.identity!==void 0&&W.identity!==void 0&&J.identity!==W.identity)throw b2("rotate",Z);let U=J.identity!==void 0&&W.identity===void 0?J.identity:void 0,K=await k2($,V,Z,X,{identity:U,...Y!==void 0?{providerState:R$(G.providerState,"rotate",Z,W.providerState,Y)}:{}}),j=!1;if(!W.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:W.type==="oauth"}),j=!0;if(J.identity!==void 0&&W.identity!==J.identity)T1(V,Z,J.identity),j=!0;if(j)await V.commitConfig();return{id:Z,credential:K}},{completeTorn:z.attribution===void 0})})}async function T8($,Z,X,J,z){G0(Z);let{ctx:G}=$,B=G.providerState,H=z.attribution,Y=z.providerState;return B0(G,Z,X,z.onFailure,async(Q,V)=>{if(Z$(Z,X,H),Y!==void 0){if(typeof Y!=="function")throw L(Z,X,"invalid-input","the provider-state mutator must be a function");if(H===void 0)throw L(Z,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw L(Z,X,"invalid-input","the store was opened without a provider-state codec")}let{row:W}=await l0($,Z,X);await Q.acquire(N0($,W));for(let U of z.extraLocks??[])await Q.acquire(U);return r(G,Q,V,{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 A0(Z,X);if(l(j)!==l(W))throw E$(Z,X);if(H!==void 0)y2(Z,X,j,H);if(J.enabled&&j.disabledReason?.startsWith(a1))throw L("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 F=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(F)throw L("enable",X,"duplicate-identity",`row ${F.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)L$(U,X);else t0(U,X,J.reason);return await U.commitConfig(),{id:X}}if(!j.credential)throw L(Z,X,"no-credential",`row ${X} holds no credential`);V0(Z,j);let D=await q4(U,B,Z,j,Y,!0);if(D.kind==="declined")return{id:X,declined:!0};await U.completeTorn();let M={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)L$(U,X);else t0(U,X,J.reason);await U.commitConfig()}return M}if(!N)return U.setStateAccount(X,D.account),await U.commitState(),M;let O=J.enabled?{mark:_8(),enabled:!0}:{mark:_8(),enabled:!1,reason:J.reason},R=D.account[m];return U.setStateAccount(X,{...D.account,[m]:{...R,[S2]:O}}),await U.commitState(),S$(U,X,O),await U.commitConfig(),M},{completeTorn:!1})})}function A8($,Z,X,J={}){return T8($,"disable",Z,{enabled:!1,reason:X},J)}function S8($,Z,X={}){return T8($,"enable",Z,{enabled:!0},X)}async function R8($,Z,X={}){G0("remove");let{ctx:J}=$;return B0(J,"remove",Z,X.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw L("remove",Z,"invalid-input","id must be non-empty");let B=X.attribution;if(Z$("remove",Z,B),X.staged!==void 0&&(!P(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw L("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((V)=>V.id===Z);if(!Y&&!$$(H.state,Z))throw A0("remove",Z);let Q=l(Y??{id:Z});await z.acquire(N0($,Y??{id:Z}));for(let V of X.extraLocks??[])await z.acquire(V);return r(J,z,G,{operation:"remove",rowId:Z},async(V)=>{let W=V.reservation(Z);if(W!==void 0){if(!P(W)||!X.staged||W.reservation!==X.staged.reservation)throw L("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(X.staged)throw L("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=V.row(Z),K=$$(V.state,Z);if(!U&&!K)throw A0("remove",Z);if(l(U??{id:Z})!==Q)throw E$("remove",Z);if(B!==void 0)if(U)g2(Z,U,B);else RJ($,V,Z,B);let j=X.protect;if(j){let N={row:U,config:V.snapshot.config,state:V.snapshot.state},D=await x0("remove",()=>j(Z,N));if(D!==void 0)throw L("remove",Z,"row-protected",D)}if(U){if(B===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(K)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function g2($,Z,X,J="remove"){if(y2(J,$,Z,X),Z.torn)throw L(J,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw L(J,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function RJ($,Z,X,J){let z=()=>L("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]=z1({accounts:[t1({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 L("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function $$($,Z){let X=$.accounts;return P(X)&&Object.hasOwn(X,Z)}function N4($){return P($)&&typeof $.id==="string"?$.id:void 0}function EJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let X=new Set;for(let G of $){let B=N4(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 IJ($,Z){let X=new Map;for(let G of $){let B=N4(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)=>N4(G)===void 0?G:J[z++])}async function E8($,Z,X={}){G0("reorder");let{ctx:J}=$,z=X.onFailure;return B0(J,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let H of X.extraLocks??[])await G.acquire(H);return r(J,G,B,{operation:"reorder",rowId:void 0},async(H)=>{let Y=H.roster(),Q=EJ(Y,Z);if(Q)throw new g({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Q});let V=[...Z],W=IJ(Y,V);if(W.every((U,K)=>U===Y[K]))return{ids:V,outcome:"unchanged"};return H.config.accounts=W,await H.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function I8($,Z,X,J,z={}){return G0("recordIdentity"),B0($.ctx,"recordIdentity",Z,z.onFailure,async(G,B)=>{if(typeof X!=="string"||X.length===0)throw L("recordIdentity",Z,"invalid-input","identity must be non-empty");let H=P(J)?J.credentialEpoch:void 0;if(!X0(H))throw L("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await l0($,"recordIdentity",Z);await G.acquire(N0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let Q of z.extraLocks??[])await G.acquire(Q);return r($.ctx,G,B,{operation:"recordIdentity",rowId:Z},async(Q)=>{let V=f2("recordIdentity",Z,Q.row(Z));if(l(V)!==l(Y))throw E$("recordIdentity",Z);if(V0("recordIdentity",V),(V.credentialEpoch??1)!==H)throw L("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==X)throw b2("recordIdentity",Z);if(V.identity===void 0)await TJ(Q,V,X);let W=T1(Q,Z,X);return await Q.commitConfig(),{id:Z,disabled:W}})})}function x8($){let Z=$[p];return P(Z)&&P(Z.publications)?Z.publications:{}}function k8($,Z){let X=x8($);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"||!X0(z.credentialEpoch))||J.finalized.some((z)=>!P(z)||typeof z.id!=="string"||!X0(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw L("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function f8($,Z){let X=await W0($.ctx);if(X.status!=="ready")throw T0(X,"publishRoster",Z);return k8(X.config,Z)}function bJ($,Z){let X=()=>{throw L("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"||n1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),Z$("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"||n1(z))||new Set(Z.order).size!==Z.order.length)X()}function y8($,Z){$.entries();let X=$.config[p],J={...x8($.config)};Object.defineProperty(J,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function xJ($,Z,X){let J=new Set;for(let B of o1($.config)){if(!P(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw L("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 L("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function b8($,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 y8($,X),await $.commitConfig({durable:!0}),X}async function g8($,Z,X={}){return G0("publishRoster"),B0($.ctx,"publishRoster",Z?.operationId??"",X.onFailure,async(J,z)=>{if(!P(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw L("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=S1(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:W})=>[W,l(Y.rows.find((U)=>U.id===W)??{id:W})]));for(let W of[...new Set(Q.values())].sort())await J.acquire(N0($,{id:W}));await J.acquire(X.providerLock??$.providerLock);for(let W of X.extraLocks??[])await J.acquire(W);let V=await r($.ctx,J,z,{operation:"publishRoster",rowId:Z.operationId},async(W)=>{let U=W.rows();if(B.some(({id:q})=>l(U.find((_)=>_.id===q)??{id:q})!==Q.get(q)))return;let K=k8(W.config,Z.operationId);if(K){if(K.planDigest!==G)throw L("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 W.markPublicationDecision(),await W.syncConfig(),{outcome:"cleaned",receipt:await b8(W,K)}}bJ($,Z);let j=xJ(W,Z,U),N=[];for(let q of Z.remove){W.assertNotStaged(q.id);let _=U.find((S)=>S.id===q.id);if(!_)throw L("publishRoster",q.id,"attribution","the removed row no longer exists");if(g2(q.id,_,q.attribution,"publishRoster"),!_.credential||q.fingerprint!==void 0&&X1(_.credential)!==q.fingerprint)throw L("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),S=j0(W.stateAccount(q.id)?.[m]);if(!_||_.staged?.reservation!==q.reservation||S?.staged?.reservation!==q.reservation||_.enabled)throw L("publishRoster",q.id,"row-staged","the finalized row is not disabled under this reservation");let A=W.stateAccount(q.id),b=W.rosterRow(q.id),w=A?.[Q0],f=w===void 0?void 0:S1(w);if(!S?.staged||S.staged.label!==b?.label||S.staged.disabledReason!==_.disabledReason||S.staged.providerState!==f)throw L("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 M=j.find((q)=>q.torn);if(M)throw L("publishRoster",Z.operationId,"attribution",`Row ${M.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let O=new Set;for(let q of j){if(!(Z.finalize.find((S)=>S.id===q.id)?.enabled??q.enabled)||q.type!=="oauth"||q.identity===void 0)continue;if(O.has(q.identity))throw L("publishRoster",q.id,"invalid-input","the final enabled roster repeats a known identity");O.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 L("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 L("publishRoster",q.id,"attribution","the staged secret belonged to a different known identity");await x2(W,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)W.dropRosterRows(q.id);for(let q of Z.finalize){let _=W.rosterRow(q.id);_.enabled=q.enabled;let S={...W.entry(q.id)};if(delete S.staged,q.enabled)delete S.disabledReason;else S.disabledReason=q.disabledReason;W.setEntry(q.id,S)}let F=W.roster().filter((q)=>!P(q)||typeof q.id!=="string"||U.find((_)=>_.id===q.id)?.invalid==="roster");return W.config.accounts=[...Z.order.map((q)=>W.rosterRow(q)),...F],y8(W,R),await W.syncState(),await W.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await b8(W,R)}},{completeTorn:!1});if(V)return V;if(await J.releaseAll(),H>=1)throw L("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class F4{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 $1(J.lockDefaults,J.lockEnv),G={writes:0};try{let B=await r(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 V=Y.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(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=e1(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 kJ}from"node:crypto";function _4($,Z){if(A1("refresh",$,Z?.staged),!Z)throw L("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw L("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw L("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw L("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function h8($){return L("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 v8($,Z,X,J={}){G0("refresh");let{ctx:z}=$;return B0(z,"refresh",Z,J.onFailure,async(G,B)=>{let{row:H}=await l0($,"refresh",Z);_4(Z,H);let Y=await J.refuse?.(H);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let Q=l(H),V;for(let j=0;;j++){await G.acquire(N0($,{id:Z,identity:Q===Z?void 0:Q})),await G.acquire(J.providerLock??$.providerLock);for(let M of J.extraLocks??[])await G.acquire(M);let D=await r(z,G,{writes:0},{operation:"refresh",rowId:Z},async(M)=>{let O=_4(Z,M.row(Z));if(V0("refresh",O),!O.hasEntry)M.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await M.commitConfig(),O=_4(Z,M.row(Z));if(l(O)!==Q)return{keyNow:l(O)};let R=await J.refuse?.(O);if(R!==void 0)return{refused:R};return{row:O,credential:O.credential,credentialEpoch:O.credentialEpoch,identity:O.identity}});if("refused"in D)return{status:"refused",rowId:Z,reason:D.refused};if("keyNow"in D){if(await G.releaseAll(),j>=1)throw L("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Q=D.keyNow;continue}V=D;break}if(V4(V.credential.lastRefreshedAt,z.now()))throw h8(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let W;try{W=await X(V.credential,V.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 W?.refresh!=="string"||!W.refresh.trim())throw L("refresh",Z,"provider","the provider returned no refresh token",!0);let U=W.providerState===void 0?void 0:d0(z.providerState,"refresh",Z,W.providerState,"the provider state the provider returned"),K=await r(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!==V.credentialEpoch||N.identity!==V.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 M=await J.refuse?.(N);if(M!==void 0)return{refused:M};let O=z.now(),R=N.credential?.type==="oauth"?N.credential.lastRefreshedAt:void 0;if(V4(R,O))throw h8(Z);let F={type:"oauth",access:W.access,refresh:W.refresh,expires:W.expires},q=N.identity!==void 0&&W.identity!==void 0&&N.identity!==W.identity?{expectedIdentity:N.identity,returnedIdentity:W.identity}:void 0,_=q?{mark:kJ(),enabled:!1,reason:`${a1}${JSON.stringify(q)}`}:void 0,S=N.identity===void 0&&W.identity?W.identity:void 0,A=await k2($,j,Z,F,{stamp:A$(R,O),transition:_,identity:S,...U!==void 0?{providerState:R$(z.providerState,"refresh",Z,N.providerState,U)}:{}});if(_!==void 0)S$(j,Z,_),await j.commitConfig();let b=N.identity;if(S!==void 0)T1(j,Z,S),b=S,await j.commitConfig();return{stored:A,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 x0("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 fJ}from"node:util";var v2=Object.freeze(["version","accounts",p]);function L4($){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 yJ($,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 m8($){return new g({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}async function w8($){let Z=await W0($.ctx);if(Z.status==="error")return Z;return{status:Z.status,settings:L4(Z.config)}}async function p8($,Z,X={}){G0("updateSettings");let{ctx:J}=$,z=X.onFailure;return B0(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=L4(Y.config),V=structuredClone(Q),W=await x0("updateSettings",()=>Z(V)),U=W===void 0?V:W;if(!P(U))throw m8("the settings mutator must produce an object");let K=v2.filter((D)=>Object.hasOwn(U,D));if(K.length>0)throw m8(`settings cannot set the pool-owned key(s) ${K.join(", ")}`);if(fJ(U,Q))return{settings:Q,outcome:"unchanged"};let j=yJ(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:L4(j),outcome:"updated"}}finally{await G.releaseTo(H)}})}var u8=new Map;function gJ($){let Z=u8.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},u8.set($,Z);return Z}function l8($){if($.status==="ready")return{status:"ready",schemaVersion:Z1,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function O4($){let Z=gJ($.configPath),X={...B4,...$.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 F4(()=>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 l8(B)},async read(){return l8(await W0(J))},async initialize(B={}){return{status:await D8(J,B.dropKeys??[])}},add:(B,H)=>O8(G,B,H),publishRoster:(B,H)=>g8(G,B,H),publication:(B)=>f8(G,B),replace:(B,H,Y,Q)=>P8(G,B,H,Y,Q),rotate:(B,H,Y,Q)=>C8(G,B,H,Y,Q),updateProviderState:(B,H,Y,Q)=>M8(G,B,H,Y,Q),disable:(B,H,Y)=>A8(G,B,H,Y),enable:(B,H)=>S8(G,B,H),remove:(B,H)=>R8(G,B,H),reorder:(B,H)=>E8(G,B,H),readSettings:()=>w8(G),updateSettings:(B,H)=>p8(G,B,H),recordIdentity:(B,H,Y,Q)=>I8(G,B,H,Y,Q),refresh:(B,H,Y)=>v8(G,B,H,Y),recordQuota:(B,H,Y)=>R2(G,B,H,Y),requestReading:(B)=>z.fire(B,"admission"),pullsSettled:()=>z.settled()}}var hJ=[/\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 T4($={}){let{redactStrings:Z}=b0({...$,extraValuePatterns:[...hJ,...$.extraValuePatterns??[]]});return(X)=>Z(X)}class H0 extends Error{code;constructor($,Z,X){super(Z,X);this.name="CommandError",this.code=$}}var d8=/^[a-z][a-z0-9-]{0,63}$/,P4={code:"action-failed",text:"That action failed."},vJ=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 I$($){if($ instanceof H0)return{code:d8.test($.code)?$.code:P4.code,text:$.message};if($ instanceof g)return{code:`pool-${$.kind}`,text:vJ.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return P4}var c8="This cannot be undone. Continue?",mJ=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function wJ($){let Z=$.toLowerCase().replace(/[-_]/g,"");return mJ.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function pJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C4($,Z,X){if(typeof $==="string"){let z=X.redact($);if(z!==$)X.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>C4(z,`${Z}[${G}]`,X));if(!pJ($))return $;let J={};for(let[z,G]of Object.entries($)){if(wJ(z)){X.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(J,z,{value:C4(G,`${Z}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function s8($,Z,X){let J={redact:X.redact,dropped:[],redacted:[]},z=C4($,"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 uJ($){return{value:String($.value),label:String($.label)}}function lJ($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(uJ),...$.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 A4($){if($.irreversible===!0)return{message:$.confirm||c8,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function a8($){let Z=A4($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(lJ),...Z?{confirm:Z}:{}}}function dJ($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function cJ($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:dJ($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(a8)}}function sJ($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(cJ),actions:(Z.actions??[]).map(a8),...Z.facts!==void 0?{facts:Z.facts}:{}}}function i8($,Z,X){return{command:$,title:Z,sections:X.map(sJ)}}function n8($,Z,X,J){return s8({command:$,menu:i8($,Z,X)},$,J)}function r8($,Z,X,J,z){return s8({command:$,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:d8.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:i8($,Z,X)},$,z)}var e8="disabled from the command menu";function aJ($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function c0($){return aJ($)?{...$}:{}}function iJ($){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 nJ($,Z){return $.label??Z??$.id}function m2($,Z){return $0($.quota)?s($.quota,Z):void 0}function $9($,Z){return`${$} ${Z}${$===1?"":"s"}`}var b$="Actions";function rJ($){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 o8($,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 t8($){return I$($).text}async function oJ($){let Z=await $.read(),X=await $.readSettings();return{load:Z,rows:iJ(Z),settings:X.status==="error"?{}:X.settings}}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:nJ($,X)}}function tJ($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=Z.rows.map((W)=>W.id),B=rJ(Z.load),H=Z.rows.filter((W)=>W.enabled).length,Y=Z.rows.map((W,U)=>{let{account:K,name:j}=w2(W,$),N=[W.type==="api"?"API key":"OAuth",...K.identity!==void 0?[K.identity]:[],...!W.invalid&&!W.enabled&&W.disabledReason?[`disabled: ${W.disabledReason}`]:[]].join(" · "),D=W.invalid?"invalid":W.enabled?"enabled":"disabled",M=[];if(!W.invalid&&W.enabled)M.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(W.id,e8,z),`Disabled ${j}.`}});if(!W.invalid&&!W.enabled)M.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(W.id,z),`Enabled ${j}.`}});if(G.length>1)M.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((O,R)=>({value:String(R+1),label:String(R+1)})),value:String(U+1)}],run:async({values:O})=>{let R=Number(O.position),F=G.filter((_)=>_!==W.id);return F.splice(R-1,0,W.id),(await X.reorder(F,z)).outcome==="unchanged"?`${j} is already at position ${R}.`:`Moved ${j} to position ${R}.`}});return M.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${j}? Its stored credential is deleted.`,run:async()=>{return await X.remove(W.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${j}.`}}),{id:W.id,label:j,detail:N,group:"Accounts",status:D,account:K,actions:M}}),Q=$.accounts?.login,V=[];if(Q&&!B)V.push({id:"add",label:Q.label??"Add account",group:b$,knobs:Q.knobs??[],run:async({values:W,invocation:U})=>{let K=await Q.run(W,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 o8(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(o8(j.label??N.id,N))},(j)=>{U.notify(`Adding the account failed: ${t8(j)}`,"error")}).catch((j)=>{U.notify(`Adding the account failed: ${t8(j)}`,"error")}),K.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[Z.rows.length===0?"No accounts yet":`${$9(Z.rows.length,"account")}, ${H} enabled`],items:B?[]:Y,actions:V}}}function eJ($,Z){let X=$.quota?.scope??"all",J=$.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(V,W)=>{if($.quota?.check)await $.quota.check(V,W);else{for(let U of V)$.store.requestReading(U);await $.store.pullsSettled()}},B=Z.rows.filter((V)=>V.candidate),H=B.map((V)=>{let{account:W,name:U}=w2(V,$),K=m2(V,X);return{id:V.id,label:U,group:z,status:P0(K,{now:J,form:"compact"}),detail:P0(K,{now:J,form:"full"}),account:W,actions:[{id:"check",label:"Check this account",run:async({invocation:j})=>{return await G([V.id],j),`Checked quota for ${U}.`}}]}}),Y=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:W}=w2(V,$),U=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",K=P0(m2(V,X),{now:J,form:"compact"});return`${W} (${U}): ${K}`}),Q=[];if(B.length>0)Q.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:b$,run:async({invocation:V})=>{let W=B.map((U)=>U.id);return await G(W,V),`Checked quota for ${$9(W.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:H,actions:Q}}}function $z($,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=c0(Z.settings.routing).mode,H=typeof B==="string"&&G.some((j)=>j.value===B)?B:"ordered",Y=m3(H),Q=Z.rows.map((j)=>j.id),V=l1(Q,Y.placement,$.routing?.formerMainId??q2),U=[`Mode: ${G.find((j)=>j.value===H)?.label??H}`];if(Q.length>0)U.push(`Roster order: ${Q.join(", ")}`);if(Y.mode==="ordered"&&V.join()!==Q.join())U.push(`Tried in order: ${V.join(", ")}`);let K=[{id:"mode",label:"Change mode",group:b$,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:H}],run:async({values:j})=>{let N=String(j.mode);return await X.updateSettings((D)=>{D.routing={...c0(D.routing),mode:N};return},z),`Routing mode set to ${G.find((D)=>D.value===N)?.label??N}.`}}];if(Q.length>1)K.push({id:"order",label:"Set order",group:b$,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:Q.join(", "),required:!0}],run:async({values:j})=>{let N=String(j.order).split(/[\s,]+/).filter((M)=>M.length>0),D=await X.reorder(N,z);return D.outcome==="unchanged"?"The order is unchanged.":`Order set to ${D.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:K}}}function Zz($,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 Xz($,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 Jz($,Z){let{store:X,extraLocks:J}=$,z=J?{extraLocks:J}:{},G=c0(Z.settings.killswitch),B=G.enabled===!0,H=c0(G.accounts),Y=Zz($,Z),Q=Xz($,Z),V=B?"on":"off",W=Z.rows.map((U)=>{let{account:K,name:j}=w2(U,$),N=c0(H[U.id]),D=Y.filter((M)=>typeof N[M]==="number");return{id:U.id,label:j,group:`Floors · killswitch ${V}`,status:D.length===0?"no floors":D.map((M)=>`${Q(M)} ≥${N[M]}%`).join(" · "),account:K,actions:[{id:"floors",label:"Set floors",knobs:Y.map((M)=>({kind:"number",id:M,label:`Minimum % left for ${Q(M)}`,min:0,max:100,...typeof N[M]==="number"?{value:N[M]}:{}})),run:async({values:M})=>{return await X.updateSettings((O)=>{let R=c0(O.killswitch),F=c0(R.accounts),q=c0(F[U.id]);for(let _ of Y){let S=M[_];if(typeof S==="number")q[_]=S;else if(S===null)delete q[_]}if(Object.keys(q).length>0)F[U.id]=q;else delete F[U.id];if(Object.keys(F).length>0)R.accounts=F;else delete R.accounts;O.killswitch=R;return},z),`Floors updated for ${j}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${V}`],items:W,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:b$,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={...c0(j.killswitch),enabled:K};return},z),`Killswitch ${K?"on":"off"}.`}}]}}}async function Z9($){let Z=await oJ($.store);return[tJ($,Z),eJ($,Z),$z($,Z),Jz($,Z)]}var zz=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),S4=["accounts","quota","routing","limits"];function X9($,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 Gz($,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 Bz($,Z){let X={};for(let J of $){let z=Z&&Object.hasOwn(Z,J.id)?Z[J.id]:void 0,G=Gz(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function Hz($,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 R1($){let Z=$.logger??d("commands"),X=T4($.redaction),J={logger:Z,redact:X},z=$.now??Date.now,G=$.extras??[],B=$.replace??{},H=S4.filter((U)=>!B[U]);for(let U of S4)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(zz.has(U.id)||Q.has(U.id))throw Error(`extra section id ${U.id} is taken`);Q.add(U.id)}async function V(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 W(U){let K=Y&&H.length>0?await Z9({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],j=[];for(let N of S4){let D=B[N];if(D)j.push(await V(N,N,D,U));else{let M=K.find((O)=>O.slot===N);if(M)j.push(M)}}if($.cache)j.push(await V("cache","cache",$.cache,U));if($.diagnostics)j.push(await V("diagnostics","diagnostics",$.diagnostics,U));for(let N of G)j.push(await V(N.id,"extra",N,U));return j}return{command:$.command,async open(U){let K=X9(U,X);return n8($.command,$.title,await W(K),J)},async apply(U,K){let j=X9(K,X),N=async(F)=>r8($.command,$.title,await W(j),F,J),D=U.command===$.command?Hz(await W(j),U):void 0;if(!D)return N({ok:!1,code:"unavailable",text:"That action is no longer available."});let M=A4(D);if(M&&U.confirmed!==!0)return N({ok:!1,code:"needs-confirmation",text:M.message,needsConfirmation:!0});let O=Bz(D.knobs??[],U.values);if("problem"in O)return N({ok:!1,code:"invalid-input",text:O.problem});let R;try{let F=await D.run({values:O.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:j});R=typeof F==="string"?{ok:!0,text:F}:{ok:F.ok,text:F.text,...F.ok?{}:{code:F.code??"refused"}}}catch(F){let q=I$(F);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:q.code,error:X(F instanceof Error?F.message:String(F))}),R={ok:!1,...q}}return N(R)}}}async function x$($,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 J9($,Z){return Z.length>0?`${$}
|
|
9
9
|
${Z.join(`
|
|
10
|
-
`)}`:$}function
|
|
10
|
+
`)}`:$}function p2($){return $.status?`${$.label} · ${$.status}`:$.label}function Yz($){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 Qz($){let Z=$.detail?[$.detail]:[];for(let[X,J]of Object.entries($.facts??{}))Z.push(`${X}: ${String(J)}`);return J9(p2($),Z)}async function Wz($,Z){switch(Z.kind){case"choice":{let X=await x$($,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 x$($,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 Vz($,Z){let X={};for(let J of Z.knobs){let z=await Wz($,J);if(!z)return;X[J.id]=z.value}return X}async function R4($,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 x$(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=Yz(B);if(H.length===0&&Y.length===0){Z.notify("Nothing to do here.");break}let Q=await x$(Z,J9(B.title,Y),[...H,{label:"Back",value:{kind:"back"}}]);if(!Q||Q.kind==="back")break;let V,W;if(Q.kind==="item"){if(W=Q.item,V=await x$(Z,Qz(W),W.actions.map((j)=>({label:j.label,value:j}))),!V)continue}else V=Q.action;let U=await Vz(Z,V);if(!U)continue;if(V.confirm){if(!await Z.confirm(V.label,V.confirm.message)){Z.notify("Cancelled.");continue}}let K=await $.apply({command:z.command,sectionId:B.id,...W?{itemId:W.id}:{},actionId:V.id,values:U,...V.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 mG,randomUUID as wG}from"node:crypto";import{setTimeout as pG}from"node:timers/promises";var Uz=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 jz}from"node:crypto";var Kz=86400000,Dz=300000,qz=3600000,Nz=60000,Mz=900000,Fz=300000;function E4($){return $ instanceof Error?$.message:String($)}function I4($){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 b4($){let Z=E4($),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 X$($){return jz("sha256").update($).digest("hex")}function u2($){let Z=X$($.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(I4($.error))z=Math.min(qz,Dz*2**Math.min(J-1,6));else z=Kz;return{message:E4($.error),checkedAt:$.now,nextRetryAt:$.now+z,retryCount:J,tokenHash:Z}}function G1($,Z,X){if(!$?.nextRetryAt||$.nextRetryAt<=X)return!1;if(!Z)return!0;return $.tokenHash===X$(Z)}function k$($,Z){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil((($.nextRetryAt??Z)-Z)/1000))}s after: ${$.message}`}function f$($){let X=($.previous?.retryCount??0)+1,J,z=$.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(b4($.error))J=Math.min(Mz,Nz*2**Math.min(X-1,6));else J=Fz;return{message:E4($.error),checkedAt:$.now,nextRetryAt:$.now+J,retryCount:X}}function J$($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function x4($){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 _z($){return $==="chatgptaccountid"||$==="email"||$==="orgname"||$==="organizationname"}var z9=b0({extraSecretKeys:_z}),JU=z9.redact,G9=z9.redactStrings;import{createServer as B9}from"node:http";import{setTimeout as Lz}from"node:timers/promises";var c2="app_EMoamEEZ73f0CkXaXp7hrann",b1="https://auth.openai.com",g$=1455,Oz=3000,Pz="cortexkit-opencode-openai-auth";function Y9($){return`${Pz}/${$}`}var Q9="main",Cz=`"${Q9}" is a reserved account id; choose a different label.`;function W9($){let Z=new Uint8Array($),X=String.fromCharCode(...Z);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Tz(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=W9(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:X}}function z$($){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 G$($){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 h$($){if($.id_token){let Z=z$($.id_token),X=Z&&G$(Z);if(X)return X}if($.access_token){let Z=z$($.access_token);return Z?G$(Z):void 0}return}function Az($){return typeof $==="string"&&$.toLowerCase()===Q9}function k4($){if(Az($))throw Error(Cz);return $}function Sz($,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`${b1}/oauth/authorize?${J.toString()}`}async function Rz($,Z,X){let J=await fetch(`${b1}/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 Ez($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var Iz=`<!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>`,
|
|
50
|
+
</html>`,l2=($)=>`<!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">${
|
|
93
|
+
<div class="error">${Ez($)}</div>
|
|
94
94
|
</div>
|
|
95
95
|
</body>
|
|
96
|
-
</html>`,g2=[],S$,d0=new Map;function n8($,Z){return new Promise((X,J)=>{let z=(Q)=>{$.off("listening",G),J(Q)},G=()=>{$.off("error",z),X()};$.once("error",z),$.once("listening",G),$.listen(R$,Z)})}function e8($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function P1(){return d0.size}function S1($){if(d0.delete($),P1()===0)T1()}async function Jz(){let $=`http://localhost:${R$}/auth/callback`;if(g2.length>0)return{port:R$,redirectUri:$};if(S$)return S$;S$=(async()=>{let Z=(G,Q)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${R$}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),Y=B.searchParams.get("state"),W=B.searchParams.get("error"),V=B.searchParams.get("error_description");if(W){let K=V||W;if(Y){let U=d0.get(Y);if(U)U.reject(Error(K)),S1(Y);else if(P1()===0)T1()}else if(P1()===0)T1();Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(y2(K));return}if(!Y){if(P1()===0)T1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(y2("Missing state parameter"));return}if(!H){if(P1()===0)T1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(y2("Missing authorization code"));return}let j=d0.get(Y);if(!j){if(P1()===0)T1();Q.writeHead(400,{"Content-Type":"text/html"}),Q.end(y2("Unknown state — authorization may have expired"));return}S1(Y),$z(H,$,j.pkce).then((K)=>j.resolve(K)).catch((K)=>j.reject(K)),Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(Xz);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Y=H?[H]:[...d0.keys()];Q.writeHead(200),Q.end("Login cancelled");for(let W of Y){let V=d0.get(W);if(!V)continue;V.reject(Error("Login cancelled")),S1(W)}if(P1()===0)T1();return}Q.writeHead(404),Q.end("Not found")},X=a8(Z);await n8(X,"127.0.0.1");let J=[X],z=a8(Z);try{await n8(z,"::1"),J.push(z)}catch(G){let Q=G.code;if(Q!=="EADDRNOTAVAIL"&&Q!=="EAFNOSUPPORT")throw e8(X),G}return g2=J,{port:R$,redirectUri:$}})();try{return await S$}finally{S$=void 0}}function T1(){let $=g2;g2=[];for(let Z of $)e8(Z)}function zz($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){S1(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if(d0.get(Z))S1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),B=()=>{if(clearTimeout(Q),d0.get(Z))S1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",B);d0.set(Z,{pkce:$,state:Z,resolve:(H)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",B);z(H)},reject:(H)=>{if(clearTimeout(Q),J)J.removeEventListener("abort",B);G(H)}})})}async function Gz($){let Z=await fetch(`${A1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":r8($)},body:JSON.stringify({client_id:h2})});if(!Z.ok)throw Error("Failed to initiate device authorization");let X=await Z.json();return{deviceData:X,url:`${A1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function Qz($,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,Q=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let B=await fetch(`${A1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":r8(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(B.ok){let W=await B.json(),V=await fetch(`${A1}/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:`${A1}/deviceauth/callback`,client_id:h2,code_verifier:W.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=G-(Date.now()-Q);if(H<=0)throw Error("Device authorization expired");let Y=Math.min(J+aJ,H);try{await iJ(Y,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(OZ(Z),X){let{deviceData:W,url:V,instructions:j}=await Gz(z),K=(async()=>{let U=await Qz(W,z,J),N=Date.now(),D=E$(U);return{id:OZ(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:N+(U.expires_in??3600)*1000,enabled:!0,addedAt:N,lastUsed:N,lastRefreshedAt:N,accountId:D}})();return{url:V,instructions:j,completion:K}}let{redirectUri:G}=await Jz(),Q=await oJ(),B=t8(crypto.getRandomValues(new Uint8Array(32)).buffer),H=eJ(G,Q,B),Y=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let W=await zz(Q,B,void 0,J),V=Date.now(),j=E$(W);return{id:OZ(Z||j||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:j}}finally{S1(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}import{basename as Bz,dirname as Hz,join as Yz}from"node:path";var v2="openai-auth.json",Z9="openai-auth-state.json";function CZ($){return Bz($)===v2?Yz(Hz($),Z9):`${$}.state.json`}function m2($){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 PZ($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function X9($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function J9($,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=PZ($.get(`${z}-window-minutes`)),Q=m2($.get(`${z}-reset-at`)??void 0);if(J===0&&$.get(`${z}-window-minutes`)==="0"&&!Q)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:Q,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var Q9=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function B9($,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 H9($){if(Q9.some((z)=>B9($,z)==="invalid"))return{};let Z={},X=J9($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=J9($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;return Z}function Y9($){let Z=Q9.map((X)=>B9($,X));return Z.includes("valid")&&!Z.includes("invalid")}function z9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=PZ($.window_minutes),X=m2($.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 W9($){let Z={},X=z9($.rate_limits?.primary);if(X)Z.primary=X;let J=z9($.rate_limits?.secondary);if(J)Z.secondary=J;return Z}function $$($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function G9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=PZ($.limit_window_seconds),X=m2($.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=G9($.rate_limit?.primary_window);if(X)Z.primary=X;let J=G9($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=X9($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=X9($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let Q=$.spend_control?.individual_limit;if($.spend_control===null||Q===null)Z.spendControlCleared=!0;if(Q&&typeof $.spend_control?.reached==="boolean"){let H=$$(Q.limit),Y=$$(Q.used),W=$$(Q.remaining),V=$$(Q.used_percent),j=$$(Q.remaining_percent);if(H!==void 0&&Y!==void 0&&W!==void 0&&V!==void 0&&j!==void 0)Z.spendControl={limit:H,used:Y,remaining:W,usedPercent:V,remainingPercent:j,resetsAt:m2(Q.reset_at),unit:Q.unit,source:Q.source,reached:$.spend_control.reached}}let B=$.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=$$(B.balance);Z.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{}}}return Z}import{ClaustrumClient as sz}from"@cortexkit/claustrum-client";import{resolve as U9}from"node:path";import{storeIdentity as Kz}from"@cortexkit/claustrum-client";import{SubcClient as j9}from"@cortexkit/subc-client";import{ClaustrumCredentialError as Wz}from"@cortexkit/claustrum-client";import{SocketClosedError as Vz,SocketTimeoutError as Uz,SubcCallError as jz}from"@cortexkit/subc-client";class R extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var TZ=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 R1 extends R{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function X1($){if($ instanceof R1||$ instanceof Vz||$ instanceof Uz)return"unreachable";let Z=$ instanceof Wz||$ instanceof jz?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(TZ,Z))return"answered";return TZ[Z]}var AZ=300000,w2=300000,SZ=1000;class I${#$;#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 p2{#$;#Z;#z;#X=!1;constructor($,Z){this.#$=$,this.#Z=Z}get running(){return this.#z}request(){if(this.#z)return this.#X=!0,this.#z;return this.#z=(async()=>{do{this.#X=!1;try{await this.#$()}catch($){this.#Z($)}}while(this.#X)})().finally(()=>{this.#z=void 0}),this.#z}}class u2{#$;#Z=new I$;#z;#X="polling";#Y;#W;#J=!1;#G;#H=!1;#Q=0;constructor($){this.#$=$,this.#z=new p2(async()=>{let Z=this.#H;if(this.#H=!1,Z||this.#G!==this.#$.view())await this.#$.discover()},(Z)=>{if(!this.#J)this.#$.onError?.(Z)})}get mode(){return this.#X}start(){if(this.#J||this.#Y||this.#W)return;if(typeof this.#$.client.watchScoped!=="function"){this.#D("fallback","client-without-watch");return}this.#j(!1)}stop(){if(this.#J)return;if(this.#J=!0,this.#W)(this.#$.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0;let $=this.#Y;this.#Y=void 0,$?.handle.stop()}#D($,Z){if(this.#X===$)return;this.#X=$,this.#$.logger?.debug("claustrum vault watch",{mode:$,reason:Z}),this.#$.onMode?.($)}#V($,Z){this.#W=(this.#$.setTimeoutImpl??setTimeout)(()=>{if(this.#W=void 0,!this.#J)Z()},$),this.#W.unref?.()}async#j($){let Z;try{Z=await this.#$.enrollmentToken()}catch(Q){if(this.#J)return;this.#$.onError?.(Q),this.#q("token-unreadable");return}let X=this.#$.client.watchScoped;if(this.#J||this.#Y||!X)return;this.#Z.restart(),this.#H=$;let J,z;try{z=X.call(this.#$.client,(Q)=>{if(this.#J||!J||this.#Y!==J)return;if(J.notices++,J.notices===1)this.#$.onReachable?.(),J.acceptedAt=(this.#$.now??Date.now)(),this.#D("watching","accepted");if(!this.#Z.continuous(Q))this.#H=!0;this.#G=Q.view,this.#z.request()},{enrollmentToken:Z})}catch(Q){this.#$.onError?.(Q),this.#q("watch-failed");return}J={handle:z,notices:0},this.#Y=J,this.#D("polling",$?"resubscribing":"opening");let G=J;z.closed.then((Q)=>this.#U(G,Q),(Q)=>this.#U(G,{kind:"transport_lost",error:Q}))}#U($,Z){if(this.#J||this.#Y!==$)return;if(this.#Y=void 0,Z.kind==="stopped")return;if(Z.kind==="transport_lost")this.#$.onTransportLost?.();if(Z.kind==="unsupported"){this.#D("fallback","vault-without-watch");return}if(Z.kind==="refused"){this.#q("refused");try{this.#$.onRefused(Z.error)}catch(X){this.#$.onError?.(X)}return}if($.notices>0){let X=(this.#$.now??Date.now)();if($.acceptedAt!==void 0&&X-$.acceptedAt>=300000)this.#Q=0;let J=Math.min(1000*2**Math.min(this.#Q,16),300000);this.#Q++,this.#D("polling","resubscribing"),this.#V(J,()=>void this.#j(!0));return}this.#q(Z.kind)}#q($){this.#D("fallback",$),this.#V(300000,()=>void this.#j(!1))}}function K9($){let Z=$.identity??Kz($.projectRoot??process.cwd(),$.storagePath??process.cwd());return{connectionFile:$.connectionFile,async getUsage(){let X,J=!1,z,G=new Promise((B,H)=>{z=setTimeout(()=>H(Error("insula usage timeout")),3000),z.unref?.()}),Q=(async()=>{if(X=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}):await j9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:Math.min($.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let B=await X.routeOpen({kind:"management_surface",module_id:"insula"},Z);return await X.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([Q,G])}finally{J=!0,clearTimeout(z),X?.close()}},watchUsage(X){let J,z,G=!1,Q=(async()=>{let B,H=new Promise((W,V)=>{B=setTimeout(()=>V(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Y=(async()=>{let W=Math.min($.handshakeTimeoutMs??3000,3000),V=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:W}):await j9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:W});if(J=V,G){V.close();return}let j=await V.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){V.close();return}z=V.subscribe(j,{method:"usage.watch"},X)})();try{await Promise.race([Y,H])}catch(W){throw G=!0,W}finally{clearTimeout(B)}if(z)await z.closed})().finally(()=>{G=!0,J?.close()});return{stop(){if(G)return;G=!0,z?.unsubscribe(),J?.close()},closed:Q}}}}var EZ=60000,Dz=4*EZ,RZ=new Map,l2=new Map;function d2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function qz($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!d2(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 Nz($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class D9{transport;key;#$=[];#Z=new p2(async()=>{try{let $=await this.transport.getUsage();if(!d2($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>d2(Z)&&typeof Z.provider==="string")}catch{this.#$=[]}},()=>{});#z=new I$;#X="polling";#Y=0;#W=0;#J=new Map;#G;#H;#Q={};#D=0;constructor($,Z){this.transport=$,this.key=Z}refresh($){if(this.#Z.running)return this.#Z.running;if(this.#X==="watching")return Promise.resolve();for(let[X,J]of l2)if($-J>=EZ)l2.delete(X);let Z=l2.get(this.key);if(Z!==void 0&&$-Z<EZ)return Promise.resolve();return l2.set(this.key,$),this.#Z.request()}watchMode(){return this.#X}watch($={}){this.#Y++;let Z=$.provider;if(Z===void 0)this.#W++;else this.#J.set(Z,(this.#J.get(Z)??0)+1);if(this.#Y===1)this.#Q=$,this.#U();let X=!1;return()=>{if(X)return;if(X=!0,Z===void 0)this.#W--;else{let J=(this.#J.get(Z)??1)-1;if(J>0)this.#J.set(Z,J);else this.#J.delete(Z)}if(--this.#Y===0)this.#V()}}#V(){if(this.#H)(this.#Q.clearTimeoutImpl??clearTimeout)(this.#H);this.#H=void 0;let $=this.#G;this.#G=void 0,$?.handle?.stop(),this.#X="polling"}#j($){this.#H=(this.#Q.setTimeoutImpl??setTimeout)(()=>{if(this.#H=void 0,this.#Y>0&&!this.#G)this.#U()},$),this.#H.unref?.()}#U(){let $=this.transport.watchUsage;if(!$){this.#X="fallback";return}this.#X="polling",this.#z.restart();let Z={notices:0};this.#G=Z;let X;try{X=$.call(this.transport,(J)=>this.#q(Z,J))}catch(J){this.#B(Z,J);return}Z.handle=X,X.closed.then(()=>this.#B(Z,void 0),(J)=>this.#B(Z,J))}#q($,Z){if(this.#G!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#D=0;let X=qz(Z);if(!X)this.#z.restart();if(!(X?this.#z.continuous(X):!1)||X?.provider===void 0||this.#W>0||this.#J.has(X.provider))this.#Z.request()}#B($,Z){if(this.#G!==$)return;this.#G=void 0;let X=Nz(Z);if(X==="unknown_method"||X==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let J=Math.min(SZ*2**Math.min(this.#D,16),w2);this.#D++,this.#X="polling",this.#j(J);return}if(this.#X="fallback",this.#Z.request(),Z===void 0||X1(Z)==="unreachable")this.#j(w2)}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||!d2(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=Dz)continue;return{entry:J,context:{fetchedAt:z,...typeof J.source==="string"&&{source:J.source}}}}return}}function IZ($,Z){let X=JSON.stringify([U9($.connectionFile),U9(Z)]),J=RZ.get(X);if(!J)J={source:new D9($,X),refs:0},RZ.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)RZ.delete(X)}}}import{ClaustrumCredentialError as xU}from"@cortexkit/claustrum-client";function bZ($){let Z=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:B,listener:H}of X)B.removeEventListener("abort",H);X.length=0},G=(B)=>{if(J||Z.signal.aborted)return;Z.abort(B),z()},Q=$.find((B)=>B.aborted);if(Q)return Z.abort(Q.reason),{signal:Z.signal,dispose:z};for(let B of $){if(Z.signal.aborted)break;let H=()=>G(B.reason);if(X.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:Z.signal,dispose:z}}import{ClaustrumCredentialError as h9}from"@cortexkit/claustrum-client";import{createHash as Mz,randomBytes as Fz,randomUUID as Lz}from"node:crypto";import{constants as q9}from"node:fs";import{chmod as _z,mkdir as Oz,open as _9,readFile as xZ,realpath as Cz,rename as Pz,stat as O9,unlink as C9}from"node:fs/promises";import{basename as P9,dirname as z1,extname as N9,isAbsolute as M9,join as fZ,resolve as Tz}from"node:path";import{ClaustrumCredentialError as Az,ClaustrumClient as Sz,writeEnrollmentTokenFile as Rz}from"@cortexkit/claustrum-client";var Ez=1,s2=16384,T9=30000,yZ=/^[0-9a-f]{64}$/,A9=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),S9=new Set(["pending_queue_full"]);function kZ($){if(!($ instanceof Az))return;if(A9.has($.code))return{code:$.code,disposition:"terminal"};if(S9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function gZ($,Z){if(!/^[a-z0-9][a-z0-9-]*$/.test($)||!/^[a-z0-9][a-z0-9-]*$/.test(Z))throw new R("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${$}-${Z}`}function hZ($){return Sz.connect($)}function R9($){let Z=N9($)||".json",X=P9($,N9($));return{statePath:fZ(z1($),`${X}-state${Z}`),tokenPath:$}}function vZ($){let Z=$.override?.trim();if(Z&&!M9(Z)&&!$.cwd)throw new R("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?M9(Z)?Z:Tz($.cwd,Z):fZ($.stateDir,`${$.host}-enrollment.json`);return R9(X)}function E9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function c2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function I9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function b$(){return new R("invalid-state","invalid Claustrum enrollment state")}function a2($){if(!E9($)||$.version!==Ez||typeof $.proposedName!=="string"||$.proposedName.length===0)throw b$();if($.phase==="pending"){if(!yZ.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!c2($.createdAt)||!c2($.updatedAt))throw b$();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)||!I9($.tokenGeneration)||!c2($.updatedAt))throw b$();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"||!c2($.updatedAt))throw b$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw b$()}function mZ($){if(!E9($)||!yZ.test(String($.token??""))||!I9($.token_generation))throw new R("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function Iz($){if(!$.isFile())throw new R("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new R("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new R("unsafe-file","Claustrum enrollment file must be owned by the current user")}function F9($){try{return JSON.parse($)}catch{throw new R("invalid-state","Claustrum enrollment file is not valid JSON")}}async function G1($){if(I)try{await D0(z1($));let X=await M0($,!0);if(Buffer.byteLength(X)>s2)throw new R("unsafe-file","Claustrum enrollment file is too large");return F9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await _9($,q9.O_RDONLY|q9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new R("unsafe-file","Claustrum enrollment file could not be opened safely")}try{Iz(await Z.stat());let X=Buffer.alloc(s2+1),{bytesRead:J}=await Z.read(X,0,X.byteLength,0);if(J>s2)throw new R("unsafe-file","Claustrum enrollment file is too large");return F9(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function L9($,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
|
|
98
|
-
`;if(Buffer.byteLength(z)>s2)throw new R("invalid-state","Claustrum enrollment state is too large");if(I)return w1($,z);let G=fZ(J,`.${P9($)}.${process.pid}.${Lz()}.tmp`),Q,B=!1;try{Q=await _9(G,"wx",384),B=!0,await Q.writeFile(z,"utf8"),await Q.chmod(384),await Q.sync(),await Q.close(),Q=void 0,await Pz(G,$),B=!1}finally{if(await Q?.close().catch(()=>{}),B)await C9(G).catch(()=>{})}}async function x$($,Z){let X=await G1($.tokenPath),J=X===void 0?void 0:mZ(X),z=await G1($.statePath),G=z===void 0?void 0:a2(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 J1(G)}async function wZ($,Z){let X;try{X=await x$($,Z)}catch(J){if(!(J instanceof R)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await G1($.statePath);if(z===void 0)return"unreadable";let G=a2(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 Q1($){let Z=await G1($);if(Z===void 0)throw new R("not-enrolled","Claustrum enrollment is not configured");return mZ(Z)}function J1($){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 k9(){return new R("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class n2{#$;#Z;#z;#X;#Y;#W;#J;constructor($){this.#J=$.ancestorOptions??{},this.#$=$.client,this.#Z=$.paths,this.#z=$.proposedName,this.#X=$.now??Date.now,this.#Y=$.mintSecret??(()=>Fz(32).toString("hex")),this.#W=$.writeTokenFile??Rz}async status(){return x$(this.#Z,this.#z)}async resetTerminal(){return f9(this.#Z,this.#z)}async#G($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#X()};return await E1(this.#Z.statePath,X,this.#J),J1(X)}async reconcile(){await i2(z1(this.#Z.statePath),this.#J);let $=await $0({name:"ceremony",path:this.#Z.statePath,ttlMs:T9,renew:!0});if(!$)return{state:"busy"};try{let Z=await G1(this.#Z.tokenPath),X=Z===void 0?void 0:mZ(Z),J=await G1(this.#Z.statePath),z=J===void 0?void 0:a2(J);if(z&&z.proposedName!==this.#z)throw k9();if(X){if(!z||z.phase==="pending"){let Q={version:1,phase:"approved",proposedName:z?.proposedName??this.#z,tokenGeneration:X.token_generation,updatedAt:this.#X()};await E1(this.#Z.statePath,Q,this.#J),z=Q}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 Q={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await E1(this.#Z.statePath,Q,this.#J),J1(Q)}if(z&&z.phase!=="pending")return J1(z);if(!z){let Q=this.#X();if(z={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#Y(),createdAt:Q,updatedAt:Q},!yZ.test(z.requestSecret))throw new R("invalid-state","invalid minted Claustrum enrollment secret");await E1(this.#Z.statePath,z,this.#J)}if(!z.requestId)try{let Q=Mz("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),B=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:Q});z={...z,requestId:B.requestId,updatedAt:this.#X()},await E1(this.#Z.statePath,z,this.#J)}catch(Q){let B=kZ(Q);if(!B)throw Q;if(B.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:B.code};return this.#G(z,B.code)}let G=z.requestId;if(!G)return J1(z);try{let Q=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(Q.status==="pending")return J1(z);if(Q.status==="denied"){let H={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#X()};return await E1(this.#Z.statePath,H,this.#J),J1(H)}await i2(z1(this.#Z.tokenPath),this.#J),await x9(z1(this.#Z.tokenPath),this.#J),await this.#W(this.#Z.tokenPath,{token:Q.token,token_generation:Q.tokenGeneration});let B={version:1,phase:"approved",proposedName:z.proposedName,approvedName:Q.name,tokenGeneration:Q.tokenGeneration,updatedAt:this.#X()};return await E1(this.#Z.statePath,B,this.#J),J1(B)}catch(Q){let B=kZ(Q);if(!B)throw Q;if(B.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:B.code};return this.#G(z,B.code)}}finally{await $.release()}}}async function f9($,Z){await i2(z1($.statePath));let X=await $0({name:"ceremony",path:$.statePath,ttlMs:T9,renew:!0});if(!X)return"busy";try{if(await G1($.tokenPath)!==void 0)return"refused-approved";let J=await G1($.statePath);if(J===void 0)return"idle";let z=a2(J);if(z.proposedName!==Z)throw k9();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await C9($.statePath),"reset"}finally{await X.release()}}var k$="claustrum-tombstone:v1:";function r2($){return`${k$}${$}`}function pZ($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function o2($){return typeof $==="string"&&$.startsWith(k$)}function y9($,Z){if(!pZ($)||$.type!=="oauth")return!1;return $.refresh===r2(Z)}function g9($,Z){if(y9($,Z))return"placeholder";if(pZ($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!o2($.refresh))return"login";if(pZ($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function uZ($){let Z=g9($.auth,$.provider);if($.mode==="custody"&&Z==="login")throw new R("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 R("host-slot-placeholder",`${$.provider} host slot holds the vault placeholder; sign in to use local accounts`);return Z}function v9($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function xz($,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 dZ=n("claustrum");function sZ($,Z,X,J=dZ){let z=v9(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:xz(Z,X)}),z}var cZ=300000,m9=60000;function lZ(){return new R("invalid-material","Claustrum returned invalid credential material")}function kz($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw lZ()}if(!X||typeof X!=="object")throw lZ();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(k$))throw lZ();return Z}function fz($,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 yz($){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 t2{#$;#Z;#z;#X;#Y;#W;#J;#G=new WeakMap;#H=new WeakMap;#Q=new Map;#D=new WeakMap;#V;#j;#U=!1;#q=new R1;#B;#N=!1;#F=-1/0;#L=2000;#K=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>Q1(Z);else throw new R("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#X=$.family,this.#Y=$.parseIdentity,this.#W=$.requireAssertion??!1,this.#z=$.now??Date.now,this.#J=$.logger??dZ,this.#V=$.setTimeoutImpl??setTimeout,this.#j=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#K||this.#U)return;this.#U=!0,this.#q=$ instanceof h9?$:new R1,this.#J.warn("serving kept vault receipt",{reason:"unreachable"}),this.#_()}reachable(){if(this.#K||!this.#U)return;if(this.#U=!1,this.#B)this.#j(this.#B);this.#B=void 0,this.#L=2000;for(let $ of this.#Q.values())$.since=null;(this.#J.info??dZ.info)("vault receipt serving resumed",{reason:"reachable"})}#_(){if(this.#K||!this.#U||this.#B||this.#N)return;this.#B=this.#V(()=>{this.#B=void 0,this.#O(!0)},this.#L),this.#B.unref?.()}#O($=!1){if(this.#K||!this.#U||this.#N)return;if(this.#z()-this.#F<1000){this.#_();return}this.#F=this.#z(),this.#N=!0,this.discover().catch(()=>{if($&&this.#U)this.#L=Math.min(this.#L*2,30000)}).finally(()=>{this.#N=!1,this.#_()})}#M($){if(this.#K)throw new R("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#C($){this.#M($);let Z=await this.#Z();if(this.#M($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new R("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#P($,Z){this.#M(Z);let X,J;try{let z=$();X=Z?await Promise.race([z,new Promise((G,Q)=>{let B=()=>Q(Z.reason);if(Z.addEventListener("abort",B,{once:!0}),J=()=>Z.removeEventListener("abort",B),Z.aborted)B()})]):await z}catch(z){if(this.#M(Z),X1(z)==="unreachable")this.transportLost(z);else this.reachable();if(z instanceof h9)throw z;if(X1(z)==="unreachable")throw new R1;throw new R("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#M(Z),this.reachable(),X}async discover($){let Z,X;try{X=await this.#C($)}catch(H){throw this.#Q.clear(),H}try{Z=await this.#P(()=>this.#$.listScoped(X),$)}catch(H){throw this.listFailed(H),H}let J=[],z=[],G=new Map;for(let H of Z.rows){let Y=fz(H,this.#X);if(!Y)continue;z.push({row:H,type:Y}),G.set(H.id,(G.get(H.id)??0)+1)}let Q=[];for(let{row:H,type:Y}of z){let W;if(!H.id.trim())W="empty credential id";else if((G.get(H.id)??0)>1)W="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())W="blank account identity";else if(!H.state.trim())W="empty state";if(W){J.push({...H.id.trim()&&{credentialId:H.id},reason:W});continue}Q.push(Object.freeze({credentialId:H.id,credentialType:Y,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of J)this.#J.warn("skipped malformed vault record",H);let B=yz(Z);return{view:Z.view,credentials:Object.freeze(Q),skipped:Object.freeze(J),...B&&{grantReach:B}}}listFailed($){if(X1($)==="unreachable")this.transportLost($);else this.reachable(),this.#Q.clear()}forget($){this.#Q.delete($)}retain($){let Z=new Map($.map((X)=>[X.credentialId,X]));for(let[X,J]of this.#Q){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.#Q){if(!this.#T(X.attempt)){this.forget(Z);continue}if(X.since!==null)$=Math.min($??X.since,X.since)}return Object.freeze({active:$!==null,since:$})}#T($){return $.expiresAtMs===null?$.credentialType==="api_key":$.expiresAtMs-this.#z()>m9}async authorize($,Z,X="vault"){this.#M(Z);let{credentialId:J,credentialType:z,accountIdentity:G}=$,Q=this.#Q.get(J);if(Q&&(Q.attempt.credentialType!==z||Q.attempt.expectedAccountIdentity!==G))this.forget(J),Q=void 0;let B;try{B=await this.#C(Z)}catch(H){throw this.#Q.clear(),H}if(this.#U&&Q)return this.#O(),this.#A(J,Q,B,X);try{let H=await this.#S({credentialId:J,credentialType:z,accountIdentity:G},B,Z);return this.#Q.set(J,{attempt:H,routeId:X,since:null}),H}catch(H){if(this.#M(Z),X1(H)!=="unreachable")throw this.forget(J),H;return this.#A(J,Q,B,X,H)}}#A($,Z,X,J,z=this.#q){if(!Z||this.#Q.get($)!==Z||!this.#T(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.#G.set(G,X),this.#D.set(G,J),G}async#S($,Z,X){if(!$.credentialId)throw new R("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:z,accountIdentity:G}=$;if(this.#W&&G===void 0)throw new R("identity-unasserted","Claustrum dispatch requires a known account identity");let Q=await this.#P(()=>this.#$.getScoped({credentialId:J,enrollmentToken:Z,...z==="oauth"&&{minTtlMs:cZ}}),X);if(Q.credentialId!==void 0&&Q.credentialId!==J)throw new R("identity-changed","Claustrum served credential identity changed");let B=Q.expiresAtMs;if(!Number.isSafeInteger(Q.recordVersion)||Q.recordVersion<0||B===null&&z==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#z()<cZ))throw new R("insufficient-validity","Claustrum served credential has insufficient validity");let H=kz(Q.material),Y=Q.accountId?.trim()?Q.accountId:void 0;if(this.#W&&(Q.credentialId===void 0||Y===void 0))throw new R("identity-unasserted","Claustrum served credential did not assert its identity");let W=Y===void 0?this.#Y?.(H):void 0,V=Y??W;if(G!==void 0&&V!==void 0&&V!==G)throw new R("identity-changed","Claustrum served credential identity changed");let j=V??G,U=Object.freeze(Object.defineProperty({credentialId:J,credentialType:z,...j!==void 0&&{accountIdentity:j},accountIdentitySource:Y!==void 0?"asserted":W!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...Q.credentialId!==void 0&&{assertedCredentialId:Q.credentialId},...Y!==void 0&&{assertedAccountIdentity:Y},...Q.projectId!==void 0&&{projectId:Q.projectId},recordVersion:Q.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#G.set(U,Z),U}async reportFailure($,Z,X){if(Z!==401)return;this.#M();let J=this.#G.get($);if(!J)throw new R("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#D.get($);if(z!==void 0){this.forget($.credentialId),this.#J.debug("scoped 401 not reported",{routeId:z,reason:"kept-receipt"});return}let G=this.#Q.get($.credentialId);if(G&&G.attempt.recordVersion===$.recordVersion)this.forget($.credentialId);let Q=this.#H.get($);if(Q)return Q;let B=this.#P(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:$.recordVersion,reporterSource:X}));this.#H.set($,B);try{await B,this.#J.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:X})}catch(H){throw this.#H.delete($),H}}close(){if(this.#K)return;if(this.#K=!0,this.#B)this.#j(this.#B);this.#B=void 0,this.#Q.clear(),this.#$.close()}}import{createHash as gz}from"node:crypto";function w9($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function iZ($,Z,X){return $.some((J)=>w9(J,Z,X))}function aZ($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function nZ($,Z,X){return $.filter((J)=>!Z.some((z)=>w9(J,z,X)))}var u9="vault:";function hz($){return gz("sha256").update($).digest("hex")}function vz($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function mz($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function B1($){return[$.credentialId,...$.aliases??[]]}function l9($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??u9,G=X.reservedRouteIds??new Set,Q=$?.rows??[],B=[...$?.declined??[]],H=Z.skipped.length===0,Y=new Set(Z.credentials.map((F)=>F.credentialId)),W=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),V=Z.skipped.some((F)=>F.credentialId===void 0),j=(F)=>!Y.has(F)&&(W.has(F)||V),K=new Map;for(let F of Q){if(F.accountIdentity===void 0)continue;for(let q of B1(F))if(!K.has(q))K.set(q,F.accountIdentity)}let U=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:K.get(F.credentialId),claimed:!1},L=mz(q),S=U.get(L)??[];S.push(q),U.set(L,S)}let N=new Set,D=new Set(G),M=[],P=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),E=[...U.values()].map((F)=>F.toSorted(P)).sort((F,q)=>F[0]&&q[0]?P(F[0],q[0]):0);for(let F of E){let q=F[0]?.identity,L=F.filter((v)=>v.credential.state==="active"),S=L.length?L:F,A=S.filter((v)=>v.claimed),x=A.length?A:S,w=new Set(F.map((v)=>v.credential.credentialId)),f=Q.find((v)=>!N.has(v)&&B1(v).some((g0)=>w.has(g0))&&(v.accountIdentity===void 0||v.accountIdentity===q)),y=x.find((v)=>v.credential.credentialId===f?.credentialId)??x[0];if(!y)continue;let h=y.credential,o=f??(q===void 0?void 0:Q.find((v)=>!N.has(v)&&v.accountIdentity===q));if(o)N.add(o);let c=o?.routeId;if(!c||G.has(c)){let v=`${z}${h.credentialId}${q===void 0?"":`~${hz(q).slice(0,10)}`}`;c=v;for(let g0=2;D.has(c);g0++)c=`${v}~${g0}`}D.add(c);let e$=o?B1(o).filter(j):[],f1=[...new Set([...F.map((v)=>v.credential.credentialId),...e$])].filter((v)=>v!==h.credentialId).sort((v,g0)=>v.localeCompare(g0)),$2=X.mapAccount?.(h)??{};M.push({previousIndex:o?Q.indexOf(o):1/0,row:{routeId:c,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...f1.length&&{aliases:f1},state:h.state,label:$2.label?.trim()||vz(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...f1].some((v)=>iZ(B,v,q)),addedAt:o?.addedAt??J,...o?.quota!==void 0&&{quota:o.quota},...!y.claimed&&q!==void 0&&{unclaimed:!0}}})}return Q.forEach((F,q)=>{if(N.has(F)||!B1(F).some(j))return;if(D.has(F.routeId))return;let[L,...S]=B1(F).filter((w)=>!Y.has(w));if(L===void 0)return;D.add(F.routeId);let{aliases:A,...x}=F;M.push({previousIndex:q,row:{...x,credentialId:L,...S.length&&{aliases:S},stale:!0}})}),M.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:H,...!H&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:M.map((F)=>F.row),declined:B}}function rZ($){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 f$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Z$($){return $===void 0||typeof $==="string"}function wz($){let Z=f$($)?M1($.quota):void 0;if(!f$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!Z$($.accountIdentity)||!Z$($.email)||!Z$($.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 pz=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function p9($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!f$(X)||!Z$(X.credentialId)||typeof X.reason!=="string"||!pz.has(X.reason))return;Z.push(X)}return Z}function uz($){if(!f$($)||$.version!==1||!Z$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!p9($.rejected))throw new R("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=wz(z);if(!G)throw new R("invalid-state","Claustrum roster file is not valid");Z.push(G)}let X=[];for(let z of $.declined){if(!f$(z)||typeof z.credentialId!=="string"||!Z$(z.accountIdentity))throw new R("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=p9($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function L0($){let Z;try{Z=await M0($,I)}catch(J){if(J.code==="ENOENT")return;throw J}let X;try{X=JSON.parse(Z)}catch{throw new R("invalid-state","Claustrum roster file is not valid")}return uz(X)}var lz={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},dz={name:"claustrum-roster",ttlMs:30000};async function X$($,Z,X={}){return a3($,lz,async(J)=>{let z=await L0($),{next:G,result:Q}=await Z(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await F0($,G,{beforeRename:async()=>{await X.beforePublish?.(),await J.assertOwned()}});return Q})}function oZ($,Z){return X$($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z);if(!X||!J)throw new R("route-unavailable","Claustrum route is not in the roster");let z=aZ(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 tZ($,Z){return X$($,(X)=>{let J=X?.rows.find((z)=>z.routeId===Z);if(!X||!J)throw new R("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:nZ(X.declined,B1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function cz($,Z){if(!B1($).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")&&B1($).length===1)return"bind";return"refuse"}function eZ($,Z){return X$($,(X)=>{let J=X?.rows.find((B)=>B.routeId===Z.routeId),z=!X||!J?"refuse":cz(J,Z);if(!X||!J||z==="refuse")return{result:!1};let G=E0(J.quota,Z.observation),Q=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...X,rows:X.rows.map((B)=>B===J?{...B,...Q,quota:G}:B)},result:!0}})}function $4($,Z){return X$($,(X)=>{let J=X?.rows.find((G)=>G.routeId===Z.routeId);if(!X||!J||J.accountIdentity===void 0||J.accountIdentity!==Z.accountIdentity)return{result:!1};let z=E0(J.quota,Z.observation);return{next:{...X,rows:X.rows.map((G)=>G===J?{...G,quota:z}:G)},result:!0}})}async function Z4($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let X=await $0({...dz,path:$.path,renew:!0});if(!X){let J=await L0($.path);if($.signal?.throwIfAborted(),!J?.view)throw new R("roster-busy","Claustrum account discovery is already in progress");return J}try{let J=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await X$($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let G=typeof $.projection==="function"?$.projection():$.projection,Q=l9(z,J,G);return{...JSON.stringify(z)!==JSON.stringify(Q)&&{next:Q},result:Q}})}finally{await X.release()}}class e2{#$;#Z=new AbortController;#z;#X;#Y;#W;#J;#G;#H;#Q;#D=!1;#V;#j;#U;#q;constructor($){this.#$=$,this.#z=$.logger??n("claustrum")}#B($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#N(){return await this.#$.isCustodyActive?.()??!0}#F($,Z){let X=bZ([this.#Z.signal,...Z?[Z]:[]]);return new Promise((J,z)=>{let G=()=>{X.signal.removeEventListener("abort",Q),X.dispose()},Q=()=>{G(),z(X.signal.reason)};if(X.signal.addEventListener("abort",Q,{once:!0}),$.then((B)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(B)},(B)=>{G(),z(B)}),X.signal.aborted)Q()})}async#L(){if(this.#B(),this.#X)return this.#X;if(!this.#W)this.#W=this.#$.connect().then(($)=>{if(this.#Z.signal.aborted)$.close(),this.#B();if(this.#Y=$,this.#X=new t2({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.#V=IZ($.insula,this.#$.tokenPath);return this.#X}).finally(()=>{this.#W=void 0});return this.#F(this.#W)}snapshot(){return this.#G}grantReach(){let $=this.#H;return $&&this.#G?.view===$.view?$.reach:void 0}watchState(){return Object.freeze({vault:this.#j?.mode??"polling",...this.#$.insula&&{insula:this.#V?.source.watchMode()??"polling"}})}#K(){this.#j?.stop(),this.#j=void 0,this.#Y=void 0,this.#U?.(),this.#U=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return rZ(this.#G)}refresh(){if(this.#B(),this.#J)return this.#J;return this.#J=(async()=>{if(!await this.#N()){this.#G=void 0,this.#H=void 0,this.#K(),this.#X?.close(),this.#X=void 0,this.#V?.release(),this.#V=void 0;return}let $=await this.#L(),Z,X=await Z4({path:this.#$.rosterPath,custody:{discover:async(z)=>{return Z=await $.discover(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.#B();let J=X?.view!==this.#G?.view;if(this.#G=X,$.retain(X?.rows??[]),Z&&X?.view!==void 0)this.#H=Z.grantReach?{view:X.view,reach:Z.grantReach}:void 0;if(X&&J)this.#$.onRoster?.(X);return this.#q=(this.#$.now??Date.now)(),X})().finally(()=>{this.#J=void 0}),this.#J}start(){if(this.#D)return;this.#B(),this.#D=!0;let $=async()=>{try{if(await this.#_())await this.refresh();await this.refreshInsulaQuota(),this.#O()}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#_(){if(this.#j?.mode!=="watching")return!0;let $=(this.#$.now??Date.now)();if(this.#q===void 0||$-this.#q>=AZ)return!0;return!await this.#N()}#O(){let $=this.#Y;if(this.#Z.signal.aborted||!$||!this.#X)return;if(!this.#j){let Z=new u2({client:$,enrollmentToken:async()=>(await Q1(this.#$.tokenPath)).token,view:()=>this.#G?.view,discover:async()=>{while(this.#J)await this.#J.catch(()=>{});await this.refresh()},onRefused:(X)=>{this.#X?.listFailed(X),this.#$.onError?.(X)},onTransportLost:()=>this.#X?.transportLost(),onReachable:()=>this.#X?.reachable(),onError:(X)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(X)},logger:this.#z,now:this.#$.now,setTimeoutImpl:this.#$.setTimeoutImpl,clearTimeoutImpl:this.#$.clearTimeoutImpl});this.#j=Z,Z.start()}if(this.#$.insula&&this.#V&&!this.#U)this.#U=this.#V.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 Q1(this.#$.tokenPath),await this.#L(),await this.#V?.source.refresh((this.#$.now??Date.now)())}catch{}}async cachedInsulaQuota($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{return await Q1(this.#$.tokenPath),this.#M($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{await Q1(this.#$.tokenPath);let X=(await L0(this.#$.rosterPath))?.rows.find((J)=>J.routeId===$);return this.#M(X?.accountIdentity)}catch{return}}#M($){if(!this.#$.insula||!$)return;let Z=this.#V?.source.current(this.#$.insula.provider,$,(this.#$.now??Date.now)());return Z?this.#$.insula.normalize(Z.entry,Z.context):void 0}async authorize($,Z){this.#B(Z);let X=this.#G??await this.#F(this.refresh(),Z);if(!X||!await this.#N())throw this.#X?.close(),this.#X=void 0,this.#K(),this.#V?.release(),this.#V=void 0,new R("not-active","Claustrum scoped custody is not active");let J=await L0(this.#$.rosterPath);this.#B(Z);let z=X.rows.find((H)=>H.routeId===$),G=J?.rows.find((H)=>H.routeId===$);if(G&&!G.enabled){if(z)this.#X?.forget(z.credentialId);throw new R("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.#X?.forget(z.credentialId);throw new R("route-unavailable","Claustrum route is disabled, removed or changed")}let Q=await this.#F(this.#L(),Z),B=bZ([this.#Z.signal,...Z?[Z]:[]]);try{return await Q.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,$)}finally{B.dispose()}}async reportFailure($,Z,X){if(this.#B(),!this.#X)throw new R("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.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 Q;try{Q=await this.authorize($,J)}catch{}if(sZ(X.site,z,Q,this.#z))await G.body?.cancel().catch(()=>{}),z=Q,G=await Z(Q,J)}if(G.status===401)await this.reportFailure(z,401,X.reporterSource??"direct").catch((Q)=>this.#$.onError?.(Q)),Promise.resolve().then(()=>this.refresh()).catch((Q)=>{if(!this.#Z.signal.aborted)this.#$.onError?.(Q)});return G}async decline($){this.#B(),await oZ(this.#$.rosterPath,$),this.#G=await L0(this.#$.rosterPath),this.#X?.retain(this.#G?.rows??[])}async accept($){this.#B(),await tZ(this.#$.rosterPath,$),this.#G=await L0(this.#$.rosterPath)}async recordQuota($,Z,X){this.#B();let J=await eZ(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}});if(J)this.#G=await L0(this.#$.rosterPath);return J}async recordAccountQuota($,Z,X){this.#B();let J=await $4(this.#$.rosterPath,{routeId:$,accountIdentity:Z,observation:X});if(J)this.#G=await L0(this.#$.rosterPath);return J}close(){if(this.#Z.signal.aborted)return;if(this.#Z.abort(new R("closed","Claustrum consumer is closed")),this.#Q)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#K(),this.#X?.close(),this.#V?.release(),this.#V=void 0,this.#G=void 0,this.#H=void 0}}async function d9($){let Z=await sz.connect($);return Object.assign(Z,{insula:K9($)})}var iz=r2("openai");function c9($){return o2($)}function k0($){if(!$||$.corrupt===!0)return!1;return c9($.refresh)}class y$ 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 $3($){if(c9($))throw new y$}function c0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var az=n("quota");var nz="app_EMoamEEZ73f0CkXaXp7hrann",rz="https://auth.openai.com";async function s9($){$3($.refreshToken);let Z=await $.fetchImpl(`${rz}/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:nz}).toString()});if(!Z.ok){let z=_Z(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 oz="https://chatgpt.com/backend-api/wham/usage";async function J$($){let Z=$.logger??az,X=$.accountKey??"unknown",J=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await $.fetchImpl(oz,{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 Q=_Z(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:Q})}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:c0(z)}),z}}import{createHash as $G}from"node:crypto";var ZG=globalThis.setTimeout,XG=5;function g$($){let Z=$?.quota?.checkIntervalMinutes??XG;return Math.max(1,Z)*60000}function JG($){return $?.quota?.enabled!==!1}function J4($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function zG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function i9($,Z,X){if(!JG(Z))return X+g$(Z);let J=zG(Z),z=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=J[G])continue;let B=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=X)return X+g$(Z);z.push(B)}if(!z.length)return X+g$(Z);return Math.min(...z)+60000}function GG($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function QG($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function _0($){return $G("sha256").update($).digest("hex").slice(0,16)}class H1{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!==_0($))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($)!==_0(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return X}getAllFallbacks(){return this.fallbacks}setMain($,Z,X,J=!1){if(!J&&!a9(Z.quota))return;if(this.mainTokenFp=_0($),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=Z,X4(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&&!a9(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(z&&G&&z!==G)this.clearRateLimited($);let Q=z??G;if(this.fallbacks.set($,{...Z,accountId:Q}),X)this.fallbackTokenFps.set($,_0(X));else this.fallbackTokenFps.delete($);if(X4(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=_0($);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=H1.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(k0(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=_0($);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=QG(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=GG($);if(!X)return;let J=Z?_0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:i9(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&&o1(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=g$(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 o1(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==_0(Z))return!1}return o1(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,_0(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<H1.API_CALL_GAP_MS)await new Promise((z)=>{let G=ZG(z,H1.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=_0($);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 $0({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=_0($),this.main={quota:z,refreshAfter:i9(z,this.storage,G),checkedAt:G},X4(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 $0({name:H1.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+g$(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(H1.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(H1.isAuthError($))return;this.mainLastApiError=A$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(H1.isAuthError(X))return;let J=_0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,A$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function a9($){return Boolean($.primary||$.secondary)}function X4($){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 OG}from"node:fs/promises";var I1=n("refresh"),Q4=n("accounts"),WG=1e4,VG=15000,z4=50;function Y1($){return $.type==="oauth"&&$.corrupt!==!0}function UG($){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 G$="floors-v1";class X3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var jG=[401,403,429],n9={primary:0,secondary:0},KG=!1,W1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var DG=new Set(["__proto__","constructor","prototype"]);function W4($){return $.length>0&&!DG.has($)}function qG($){return $ instanceof X3||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function Z3($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():HG(),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 r9($){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 NG($){if(!k($))return;let Z={};for(let z of["primary","secondary"]){let G=$[z];if(!k(G))continue;let Q=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Y=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[z]={usedPercent:Q,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Y)&&Y>0?{windowMinutes:Y}:{}}}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),Q=Number(X.remaining),B=Number(X.usedPercent),H=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof X.reached==="boolean")Z.spendControl={limit:z,used:G,remaining:Q,usedPercent:B,remainingPercent:H,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let J=$.credits;if(k(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&typeof J.overageLimitReached==="boolean"){let z=Number(J.balance);Z.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,overageLimitReached:J.overageLimitReached,...Number.isFinite(z)?{balance:z}:{}}}return Object.keys(Z).length?Z:void 0}function MG($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!UG(Z))return null;let J=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...Z3($),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{...Z3($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...Z3($),type:"oauth",corrupt:!0}}return{...Z3($),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:r9($.lastRefreshError),lastQuotaRefreshError:r9($.lastQuotaRefreshError),quota:NG($.quota)}}function FG($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!W4(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 o9=new Set;function LG($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(o9.has(Z))return;o9.add(Z),Q4.warn("account load-dropped, preserved on disk",{droppedIds:$})}function _G($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(MG).filter((J)=>J!=null);if(X.length<Z.length){let J=new Set;for(let Q of Z)if(k(Q)&&typeof Q.id==="string"&&Q.id.trim())J.add(Q.id.trim());let z=new Set(X.map((Q)=>Q.id)),G=[];for(let Q of J)if(!z.has(Q))G.push(Q);LG(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:FG($.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 J3($){try{return{exists:!0,value:JSON.parse(await OG($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function z3($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function CG($){let Z;try{Z=(await J3($)).value}catch{return null}return kG(Z)}function PG($,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:{},Q=k($.refresh)?$.refresh:{},B=J??G,H=J??Q,W=Q.mainRefreshLeaseId!==void 0?{id:Q.mainRefreshLeaseId,until:Q.mainRefreshLeaseUntil,tokenHash:Q.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},j=Array.isArray($.accounts)?$.accounts.map((K)=>{if(!k(K))return K;let U=typeof K.id==="string"&&k(z[K.id])?z[K.id]:{};return{...K,...U}}):void 0;return TG({...$,refresh:z3({...Q,mainLastRefreshError:Q.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:W.id,mainRefreshLeaseUntil:W.until,mainRefreshLeaseTokenHash:W.tokenHash}),quota:z3({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:j})}async function V4($){let Z=await J3($.configPath);if(!Z.exists)return null;let X=await J3($.statePath);return _G(PG(Z.value,X.value))}function TG($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function AG($){if($.type==="api")return z3({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return z3({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function G3($){return Math.max($?.primary?.checkedAt??0,$?.secondary?.checkedAt??0)}function h$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function SG($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function RG($,Z){if(!SG($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var EG=300000;function t9($,Z){if($===void 0)return 0;return $>Z+EG?0:$}function IG($,Z,X){let J=Date.now(),z=t9(Z.lastRefreshedAt,J),G=t9(X.lastRefreshedAt,J),Q=Z.expires??0,B=X.expires??0,H=G>z?X:z>G?Z:B>Q?X:Q>B?Z:RG(Z,X);h$($,H,"access"),h$($,H,"refresh"),h$($,H,"expires"),h$($,H,"lastRefreshedAt"),h$($,H,"lastRefreshError")}function bG($,Z){if(!k($))return Z;let X=$,J=G3(X.quota),z=G3(Z.quota),G=J>z,Q=G?{...X,...Z,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...Z};if(!G&&!("lastQuotaRefreshError"in Z))delete Q.lastQuotaRefreshError;if(!("lastRefreshError"in Z))delete Q.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof Z.lastUsed!=="number"||X.lastUsed>Z.lastUsed))Q.lastUsed=X.lastUsed;return IG(Q,X,Z),Q}async function xG($,Z=!1){let X=Date.now(),J=X+VG,z=0;while(Date.now()<=J){z++;let B=await $0({name:"save",ttlMs:WG,path:$,renew:Z});if(B)return B;let H=J-Date.now();if(H<=0)break;await YG(Math.min(z4+G7(z4),H))}let G=Date.now()-X,Q=Math.round(G/Math.max(1,z));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${z} attempts, ~${Q}ms apart; retry interval is ${z4}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 kG($){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 fG($,Z){$.main=$.main??{};let X=typeof $.main.quotaCheckedAt==="number"?$.main.quotaCheckedAt:G3($.main.quota),J=typeof Z.quota?.mainQuotaCheckedAt==="number"?Z.quota.mainQuotaCheckedAt:G3(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 yG($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function B4($){if(Array.isArray($))return $.map(B4);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,B4(X)]))}async function gG($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await xG(z);try{let Q=(await J3(z)).value,B=k(Q)?{...Q,version:1}:{version:1};if(X.mainQuota)fG(B,$);if(X.mainRefresh)yG(B,$);if(X.accounts){let H=X.accounts===!0?null:new Set(X.accounts),Y=await CG(Z.configPath);B.accounts={...k(B.accounts)?B.accounts:{}};for(let W of $.accounts){if(H&&!H.has(W.id))continue;if(Y&&!Y.has(W.id))continue;B.accounts[W.id]=bG(B.accounts[W.id],AG(W))}if(H){for(let W of H)if(!$.accounts.some((V)=>V.id===W))delete B.accounts[W]}if(Y){for(let W of Object.keys(B.accounts))if(!Y.has(W))delete B.accounts[W]}}if(J&&!J())return;await F0(z,B4(B))}finally{await G.release()}}function J7($){return $?.fallbackOn?.length?$.fallbackOn:jG}function hG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??n9.primary,secondary:Z.secondary??Z["1w"]??n9.secondary}}function H4($){return $?.quota?.enabled!==!1}function m$($){return $?.quota?.failClosedOnUnknownQuota??KG}function Q3($,Z,X=Date.now()){if(!H4(Z))return!0;if(!$)return!m$(Z);let J=hG(Z),z=m$(Z);for(let G of["primary","secondary"]){let Q=$[G];if(!Q)continue;if(J4(Q,X)){if(z)return!1;continue}if(Q.remainingPercent<J[G])return!1}return!0}function U4($){return $?.killswitch?.enabled===!0}function e9($){return{primary:$?.primary??$?.["5h"]??W1.primary,secondary:$?.secondary??$?.["1w"]??W1.secondary}}function $7($){return typeof $==="number"&&Number.isFinite($)?$:0}function V1($,Z){if(!$?.killswitch)return W1;if($.killswitch.schema===G$){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:$7(G?.primary),secondary:$7(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return e9($.killswitch.accounts[Z]);return e9($.killswitch.main)}function z7($,Z,X,J=Date.now()){if(!U4(Z))return!0;if(!$)return!m$(Z);let z=V1(Z,X),G=m$(Z);for(let Q of["primary","secondary"]){let B=$[Q];if(!B)continue;if(J4(B,J)){if(G)return!1;continue}if(B.remainingPercent<z[Q])return!1}return!0}function vG($){return $?.refresh?.enabled!==!1}function j4($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function G7($){return Math.floor(Math.random()*($+1))}function b1($,Z,X){return!$.access||!$.expires||$.expires-X<=j4(Z)}function mG($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function z$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class Q7 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 U0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function v$($){return $ instanceof Error?$.message:String($)}function Y4($,Z,X){if(Z instanceof y$)return;$.lastRefreshError=f2({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function G4($,Z,X){if(Z instanceof y$)return;if($.lastQuotaRefreshError=A$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)Y4($,Z,X)}function Z7($,Z){if(!$)return!1;if(!$.resetsAt)return!0;let X=Date.parse($.resetsAt);return Number.isFinite(X)?X>Z:!0}function wG($,Z){if(!$)return!1;return Z7($.primary,Z)||Z7($.secondary,Z)}function pG($,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 X7($,Z,X){return!pG($.quota,Z,X)}function uG($,Z,X,J){return LZ(X)&&Q3($.quota,Z,J)&&wG($.quota,J)}function lG($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var dG=60000,cG=60000,sG=600000;function iG($){return`fallback-oauth-refresh-${BG("sha256").update($).digest("base64url").slice(0,16)}`}var aG=1e4,nG=100;class rG{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($)$3($.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+lG(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return V4(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await gG($,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(()=>{})},dG+G7(cG)),"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||!Y1(z))continue;if(z$(Z,z))continue;if(k0(z))continue;let G=!1,Q=z;try{if(b1(Q,Z,this.now())){let B=Q.lastRefreshError;if(B&&Z1(B,Q.refresh,this.now()))throw G=!0,Error(T$(B,this.now()));try{Q=await this.refreshAccount(Q,Z),J=!0}catch(H){if(qG(H))continue;G=!0;let Y=Z.accounts.find((W)=>W.id===z.id&&Y1(W));if(Y&&!Z1(Y.lastRefreshError,Y.refresh,this.now()))Y4(Y,H,this.now()),U0(Z,Y),J=!0;throw H}}if(this.seedFallbackQuota(Q,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(Q),Z))X.push(Q)}catch(B){let H=mG(Q,this.now());if(G){if(!H)continue}else if(!H)continue;if(uG(Q,Z,B,this.now()))I1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:Q.id,error:v$(B)}),X.push(Q);else if(!m$(Z))X.push(Q)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{Q4.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:v$(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){Q4.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:v$(Z)})}}accountPassesQuotaPolicy($,Z){return Q3($.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(!$||!vG($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!Y1(X))continue;if(z$($,X))continue;if(k0(X))continue;if(!b1(X,$,this.now()))continue;if(Z1(X.lastRefreshError,X.refresh,this.now()))continue;try{I1.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){I1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:v$(J)}),Y4(X,J,this.now()),U0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!H4($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!Y1(X))continue;if(z$($,X))continue;if(k0(X))continue;let J=X;try{if(b1(J,$,this.now())){if(Z1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(o1(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):X7(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){G4(X,z,this.now()),U0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!H4(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||!Y1(G))continue;if(z$(Z,G))continue;if(k0(G))continue;let Q=G;try{if(b1(Q,Z,this.now())){let B=Q.lastRefreshError;if(B&&Z1(B,Q.refresh,this.now()))throw Error(T$(B,this.now()));Q=await this.refreshAccount(Q,Z),z=!0}if(!J&&!X7(Q,Z,this.now())){if(Q.lastQuotaRefreshError)Q.lastQuotaRefreshError=void 0,U0(Z,Q),z=!0;continue}await this.refreshAccountQuota(Q,Z),z=!0}catch(B){G4(G,B,this.now()),U0(Z,G),z=!0,X.push({accountId:G.id,message:v$(B)})}}if(z)await this.save(Z);return{storage:Z,errors:X}}async refreshAccount($,Z,X={}){let J=this.refreshPromises.get($.id);if(J){let Q=await J;return U0(Z,Q),Q}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return U0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+aG;while(Date.now()<z){await new Promise((Y)=>setTimeout(Y,nG));let G=await this.load(),Q=G?.accounts.find((Y)=>Y.id===$.id&&Y1(Y));if(!Q)continue;if(this.assertNotTombstoned(Q),(Q.access!==X.access||Q.refresh!==X.refresh||(Q.expires??0)>(X.expires??0)+60000)&&(J.force||!b1(Q,G,this.now())))return U0(Z,Q),I1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:Q.id,expiresInMs:Q.expires?Q.expires-this.now():void 0}),Q;let H=Q.lastRefreshError;if(H&&Z1(H,Q.refresh,this.now()))throw U0(Z,Q),Error(T$(H,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(z$($,Z))throw new Q7(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((B)=>B.id===$.id&&Y1(B));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!b1(z,J,this.now()))return U0(Z,z),z;let G=z??$,Q=await $0({name:iG(G.id),ttlMs:sG,path:this.paths.configPath,renew:!0});if(!Q){I1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh($,Z,G,X);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((W)=>W.id===$.id&&Y1(W)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!b1(z,J,this.now()))return U0(Z,z),z;if(!z)throw new X3($.id);G=z;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});I1.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 H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,U0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((W)=>W.id===$.id))throw new X3($.id);return I1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await Q.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,U0(Z,X),await this.save(Z)}catch(G){throw G4($,G,this.now()),U0(Z,$),G}}}var B7="/backend-api/wham/rate-limit-reset-credits",Nj=`https://chatgpt.com${B7}`,oG=`${B7}/consume`,Mj=`https://chatgpt.com${oG}`;function X0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as ZQ}from"node:fs";import{rm as U7}from"node:fs/promises";import{dirname as XQ,join as j7}from"node:path";import{resolveClaustrumConnectionPath as JQ}from"@cortexkit/claustrum-client";function H7($,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 Y7($){if(!X0($)||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 tG($){let Z=Y7($.total),X=Y7($.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},...X0($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function W7($,Z){let X=H7($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=H7($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((B)=>X0(B)&&B.id==="individual_limit"):void 0,G=X0(z)?tG(z):void 0,Q=X0($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof Q==="number"&&Number.isFinite(Q)&&Q>=0&&{resetCreditsAvailable:Q},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var V7=["primary","secondary"];function K4($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function w$($){return typeof $==="number"&&Number.isFinite($)}function eG($,Z){if(!K4(Z))return;let X=Z.usedPercent;if(!w$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...w$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function $Q($){let Z=$.spendControl;if(K4(Z)&&typeof Z.reached==="boolean"){let X=(J)=>w$(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 S0($,Z,X){if(!K4($)||!w$(Z))return;let J=[],z=[];for(let H of V7){let Y=eG(H,$[H]);if(Y)J.push(Y);else if(X)z.push({label:H})}let G=$Q($),Q=$.resetCreditsAvailable,B=typeof Q==="number"&&Number.isSafeInteger(Q)&&Q>=0?{resetCredits:{value:Q,checkedAt:Z}}:void 0;if(J.length===0&&z.length===0&&!G&&!B)return;return{checkedAt:Z,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{},...B?{counters:B}:{}}}function Q$($){if(!B0($))return;let Z=i($),X={};for(let J of V7){let z=Z.limits.find((Q)=>Q.label===J&&Q.kind==="reading");if(!z||!w$(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 D4($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var q4="ck auth reclassify --from-registry";function B3($,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 \`${D4($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${q4}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var f0=n("vault"),zQ="openai-auth",K7={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},GQ={opencode:"OpenCode",pi:"Pi"};function QQ($){return gZ(zQ,$)}function H3($){return j7(XQ($),"openai-auth-vault")}function BQ($,Z){return{...vZ({stateDir:$,host:Z}),rosterPath:j7($,`${Z}-roster.json`)}}var Y3=2000;var HQ={"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 ${q4} 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 D7($,Z){if($!=="vault-no-grant")return HQ[$];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: ${D4(Z)}`}function q7($){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 YQ($){let Z=t1($);return Z?e1(Z):void 0}class N7 extends e2{#$;constructor($,Z){super($);this.#$=Z}refresh(){let $=super.refresh();return this.#$($),$}}class N4{host;name;paths;#$;#Z;#z=new Map;#X=new Map;#Y=new Map;#W;#J;#G;#H;#Q=!1;#D=!1;#V=Promise.withResolvers();#j="unknown";#U;constructor($){this.#$=$,this.host=$.host,this.name=QQ($.host),this.paths=BQ($.stateDir,$.host),this.#Z=new N7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:K7,connect:()=>this.#N(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:YQ,insula:{provider:"codex",normalize:W7},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onError:(Z)=>this.#K("vault roster refresh failed",Z),logger:f0},(Z)=>this.#M(Z))}#q(){return(this.#$.connectionFile??JQ)()}#B(){return{connectionFile:this.#q(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>f0.debug("vault transport error",{errorClass:$})}}#N(){return(this.#$.connectScoped?.()??d9(this.#B())).then(($)=>{return this.#W=$.insula!==void 0,$})}#F($,Z,X){if(this.#Y.get($)===Z)return;this.#Y.set($,Z),f0.info("vault background quota source changed",{routeId:$,source:Z,reason:X})}#L(){return this.#$.connectEnrollment?.()??hZ(this.#B())}#K($,Z){this.#J=c0(Z),f0.warn($,{host:this.host,error:this.#J})}#_(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=ZQ($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#_(),Z=await wZ(this.paths,this.name);if($===this.#_())return this.#j=Z,this.#U=$,Z;return"unreadable"}enrolled(){return this.#U!==this.#_()||this.#j!=="local"}async#O(){if(this.#U!==this.#_())await this.authority();return this.enrolled()}start(){if(this.#Q||this.#D)return;this.#Q=!0,this.#Z.start()}#M($){if(this.#H===$)return;this.#H=$,$.finally(()=>{if(this.#H===$)this.#H=void 0;this.#V.resolve()}).catch(()=>{})}#C(){return this.#Z.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let $=this.#H;if($)await $.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#H??this.#C()).catch((X)=>{this.#K("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let $=this.#H;if($)await $.catch(()=>{return});let Z=await this.#C();return this.#J=void 0,Z}catch($){return this.#K("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.#K("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#Z.authorize($,Z.signal)}catch(X){this.#K("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.#K("vault failure report failed",X)}await this.refresh()}recordSnapshot($,Z,X,J){let z=S0(Z,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota($,z,J).then(()=>{},(G)=>this.#K("vault quota write failed",G))}pollQuota($,Z=!0){let X=this.#X.get($);if(X)return X;let J=this.#P($,Z).finally(()=>{this.#X.delete($)});return this.#X.set($,J),J}async#P($,Z){if(Z){await this.authority(),await this.#Z.refreshInsulaQuota();let G=(await L0(this.paths.rosterPath))?.rows.find((B)=>B.routeId===$),Q=await this.#Z.cachedInsulaQuotaForRoute($);if(Q!==void 0&&G?.accountIdentity){let B=S0(Q,Q.primary.checkedAt,!0);if(!B)return this.#F($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota($,G.accountIdentity,B))return this.#F($,"insula",null),{ok:!0};return this.#F($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}this.#F($,"fallback",this.#W===!1?"insula-not-configured":"no-insula-reading")}let X,J=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let B=Z?void 0:await this.#Z.cachedInsulaQuota(Q);if(B!==void 0){let Y=S0(B,B.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#Z.recordQuota($,Y,Q),new Response(null,{status:200})}let H=await J$({accessToken:G,fetchImpl:J,now:this.#$.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:f0});return await this.recordSnapshot($,H,!0,Q),X=void 0,new Response(null,{status:200})}catch(B){X=c0(B);let H=B?.status;if(typeof H==="number")return new Response(null,{status:H});throw B}},{site:"quota"}).catch((G)=>{X=c0(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)=>{f0.warn("vault quota poll failed",{routeId:$,error:c0(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=WQ(J.quota);if(z!==void 0&&Z-z<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async decline($){await this.#Z.decline($),f0.info("vault account declined",{routeId:$})}async accept($){await this.#Z.accept($),f0.info("vault account accepted",{routeId:$})}async status(){await this.authority();let $;try{$=await x$(this.paths,this.name)}catch(Z){this.#K("vault enrollment state unreadable",Z),$={state:"blocked",proposedName:this.name,code:Z instanceof R?Z.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:$,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let $=await this.#L().catch((Z)=>{throw new Q0("vault-unreachable",`Could not reach the Claustrum vault (${this.#q()}): ${c0(Z)}. Is the vault running?`)});try{let Z=new n2({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(f0.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#J=void 0,await this.refresh();return J}finally{$.close()}}waitForApproval($={}){return this.#G??=(async()=>{let Z=$.sleep??((G)=>new Promise((Q)=>setTimeout(Q,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.#G=void 0}),this.#G}async disconnect(){await U7(this.paths.tokenPath,{force:!0}),await U7(this.paths.statePath,{force:!0}),await this.authority(),this.#J=void 0,f0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())uZ({mode:"custody",auth:$,provider:"openai"})}close(){this.#D=!0,this.#V.resolve(),this.#Z.close()}}function WQ($){if(!$)return;let Z=i($).limits.map((X)=>X.checkedAt);return Z.length>0?Math.max(...Z):void 0}function W3($,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 ${K7.category} --operation read`]}function M7($,Z,X){let J=`${GQ[$]} (${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 M4($,Z){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?`. ${B3($.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}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...W3($.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 F7=`${String.fromCharCode(27)}\\[[0-9;]*m`,lj=new RegExp(F7,"g"),dj=new RegExp(`^${F7}`);function B$($){return $.authority!=="local"}async function s0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function O7($){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."),Y3)})])}finally{clearTimeout(Z)}}function U1($){return $.email||$.label||$.routeId}var L4="Accounts are managed in the vault with ck. Disconnect to use local accounts.",p$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var R0="main";function V3($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function P7($,Z,X){let J=new Map;if(U4(Z))for(let z of $)J.set(z.id,z7(Q$(z.quota),Z,z.id===R0?void 0:z.id,X));return J}var T7=5,_4=5000;function A7($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function S7($,Z=_4){let X=$.rows.filter((Q)=>Q.kind==="oauth"&&$.killswitch.get(Q.id)!==!1&&i(Q.quota).limits.length===0);if(X.length===0)return;if(h0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((Q)=>$.killswitch.get(Q.id)!==!1))return;let z=[];if(h0({rows:X,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:(Q)=>{let B=$.requestPull(Q);if(B)z.push(B.catch(()=>{}))}}),z.length===0)return;let G;return Promise.race([Promise.all(z),new Promise((Q)=>{G=setTimeout(Q,Z)})]).then(()=>{}).finally(()=>clearTimeout(G))}function O4($){return $.reason==="exhausted"||$.reason==="budget-spent"}function R7($,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 C7($,Z,X){if(Z.refused.find((z)=>!O4(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return R7($[0],Z,X)}function E7($){let Z=$.replayable!==!1,X=$.mainId===void 0?R0:$.mainId??"",J=Z?$.placement:"main-first",z=R3({rows:$.rows,placement:J,formerMainId:X,killswitch:$.killswitch,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),G=h1($.rows.map((H)=>H.id),J,X),Q=new Set(z.admission.refused.filter((H)=>O4(H)&&$.killswitch.get(H.id)!==!1).map((H)=>H.id)),B=G.filter((H)=>Q.has(H));if(!Z){let H=G.includes(X),Y=H?X:z.order[0]??B[0];if(Y!==void 0&&z.order.includes(Y))return{kind:"send",order:[Y],lastPath:!1};if(Y!==void 0&&Q.has(Y))return{kind:"send",order:[Y],lastPath:!0};return{kind:"block",block:H?R7(X,z.admission,$.killswitch):C7(G,z.admission,$.killswitch)}}if(z.order.length>0)return{kind:"send",order:z.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:C7(G,z.admission,$.killswitch)}}function C4($){let Z=h0({rows:$.rows,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,now:$.now,requestPull:$.requestPull}),X=new Map;for(let J of $.rows)X.set(J.id,i(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 I7($,Z,X){let J=X.exclude,z=J?$.rows.filter((Q)=>!J.has(Q.id)):$.rows,G=new Map;for(let Q of z){let B=Z.resetCredits(Q.id);if(B!==void 0)G.set(Q.id,B)}return y3({rows:z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:$.requestPull,killswitch:$.killswitch,requestBytes:Z.requestBytes,...X.pendingBytes?{pendingBytes:X.pendingBytes}:{},rowReservePercent:(Q)=>Z.reservePercent(Q.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...X.pin===void 0?{}:{pin:{accountId:X.pin}},...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}})}function b7($,Z,X,J){let z=I7($,Z,{exclude:X,pendingBytes:J});if(z.outcome!=="dispatch"||z.source==="pin")return;return{accountId:z.accountId,source:z.source,...z.quotaCheckedAt===void 0?{}:{quotaCheckedAt:z.quotaCheckedAt}}}function x7($,Z,X){let J=$.killswitch.get(X)===!1,z=I7($,Z,{pin:X});if(z.outcome==="dispatch"){if(z.pin.action==="assign")return{kind:"move",reason:J?"killswitch":"exhausted"};return z.accountId===X?{kind:"serve"}:{kind:"detour"}}let G=z.admission.refused.find((Q)=>Q.id===X);if(!J&&G&&O4(G))return{kind:"last-path"};return{kind:"none"}}function k7($,Z,X,J){let z=$.killswitch.get(X);return f3({quota:Z.projections.get(X),now:$.now,...J===void 0?{}:{status:J},...z===void 0?{}:{killswitchPasses:z}})}function f7($){return X0($)?{...$}:{}}function U3($,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:Q})=>{let B=await $.apply({command:$.command,sectionId:Z,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},Q);return{ok:B.ok,text:B.text,...B.code?{code:B.code}:{}}}}}function P4($,Z){return new Proxy($,{get(X,J){if(J==="read")return async()=>{let G=await X.read();if(G.status!=="ready")return G;let Q={...G,rows:G.rows.map((Y)=>({...Y,label:Y.label??Y.id}))};if(!Z)return Q;let B=await s0(Z);if(!B$(B))return Q;let H=[...B.status.accounts.map((Y)=>({id:Y.routeId,label:U1(Y),type:"oauth",enabled:Y.enabled,identity:Y.accountIdentity,quota:Y.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:H}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!Z)return G;let Q=await s0(Z),B=f7(G.settings.killswitch);if(!B$(Q)||!G.settings.killswitch)return G;let H=f7(B.accounts);for(let Y of Q.status.accounts)H[Y.routeId]=V1({version:1,accounts:[],...G.settings},Y.routeId);return{...G,settings:{...G.settings,killswitch:{...B,accounts:H}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function T4($,Z,X={}){let J=C1($),z=(Y)=>C1({command:$.command,title:$.title,store:P4($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Y??""},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Y,W)=>{let V=await s0(Z),j=B$(V),K=V3(V.status.accounts.map((A)=>({id:A.routeId,credentialId:A.credentialId}))),U=j?z(K):J,D=(await U.open(W)).menu.sections.find((A)=>A.id===Y);if(!D)throw new Q0("unavailable","The account menu is unavailable.");if(!j)return{lines:D.lines,items:D.items.map((A)=>({...A,actions:A.actions.map((x)=>U3(U,Y,x,A.id))})),actions:D.actions.map((A)=>U3(U,Y,A))};let M=new Map(V.status.accounts.map((A)=>[A.routeId,A])),P=($.now??Date.now)(),E=(A)=>({id:"check",label:A?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await s0(Z)).routes].filter((f)=>!A||f===A);if(A&&w.length===0)throw new Q0("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 Q0("quota-check-failed",`${f}: ${y.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(Y==="quota"){let A=(x,w)=>C0(i(x.quota,$.quota?.scope),{now:P,form:w});return{lines:V.status.accounts.filter((x)=>!V.routes.has(x.routeId)).map((x)=>`${U1(x)} (${x.enabled?x.state:"disabled"}): ${A(x,"compact")}`),items:V.status.accounts.filter((x)=>V.routes.has(x.routeId)).map((x)=>({id:x.routeId,label:U1(x),group:"Accounts",status:A(x,"compact"),detail:A(x,"full"),actions:[E(x.routeId)]})),actions:V.routes.size>0?[E()]:[]}}let F=D.items.map((A)=>{let x=M.get(A.id),w=x&&Y==="accounts"?`Vault · ${x.credentialType==="oauth"?"login":"API key"} · ${x.state} · ${x.enabled?"enabled":"declined"}`:A.detail;return{id:A.id,label:A.label,detail:w,group:A.group,status:x&&Y==="accounts"?x.enabled?x.state:"disabled":A.status,...A.facts?{facts:A.facts}:{},actions:x&&Y!=="limits"?[]:A.actions.map((f)=>U3(U,Y,f,A.id))}}),q=D.actions.filter((A)=>Y==="limits"||Y==="routing"&&A.id==="mode").map((A)=>U3(U,Y,A)),L=D.actions.find((A)=>A.id==="mode")?.knobs.find((A)=>A.id==="mode"),S=Y==="routing"&&K===null&&L?.kind==="choice"&&(L.value==="main-first"||L.value==="fallback-first");return{lines:Y==="accounts"?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`,L4]:[...D.lines,...S?["No default vault account, so this mode orders like Ordered"]:[]],items:F,actions:q}},Q=C1({...$,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Y)=>G("accounts",Y)},quota:{title:"Quota",build:(Y)=>G("quota",Y)},routing:{title:"Routing",build:(Y)=>G("routing",Y)},limits:{title:"Limits",build:(Y)=>G("limits",Y)}},extras:$.extras?.map((Y)=>Y.id!=="reset"?Y:{...Y,build:async(W)=>{let V=await s0(Z);if(B$(V))return{lines:[L4]};return Y.build(W)}})}),B=async()=>{if(!B$(await s0(Z)))return{menu:J,error:void 0};let Y=X.refresh===!1?void 0:await O7(Z);return{menu:Q,error:Y}},H=async(Y,W)=>{let V=await Y.menu.open(W);if(Y.error)V.menu.sections.find((K)=>K.id==="vault")?.lines.push(`Last error: ${Y.error}`);return V};return{command:$.command,open:async(Y)=>H(await B(),Y),apply:async(Y,W)=>{let V=await B(),{menu:j}=V;if(j===Q&&(Y.sectionId==="accounts"||Y.sectionId==="routing"&&Y.actionId==="order"||Y.sectionId==="reset"||Y.sectionId==="quota"&&(await s0(Z)).routes.size===0||Y.sectionId==="limits"&&Y.itemId!==void 0&&!(await s0(Z)).status.accounts.some((K)=>K.routeId===Y.itemId)))return{...await H(V,W),ok:!1,code:"vault-local-action",text:p$};if(X.refuseApply)return{...await H(V,W),ok:!1,...X.refuseApply};return j.apply(Y,W)}}}var j1="openai",E4="OpenAI accounts",x1="main",g7="that account is already your main account, so it was not added again",u$=n("commands"),h7=new Set(["__proto__","constructor","prototype"]);function v7($,Z){let X={version:1,accounts:[],killswitch:$},J=X0($.accounts)?Object.keys($.accounts):[],z={};for(let B of new Set([x1,...Z,...J])){if(h7.has(B))continue;let H=V1(X,B===x1?void 0:B);z[B]={primary:H.primary,secondary:H.secondary}}let G=V1(X,void 0),Q={...$};return delete Q.main,Q.accounts=z,Q.defaults={primary:G.primary,secondary:G.secondary},Q.schema=G$,Q}function m7($,Z){let X=X0($.accounts)?{...$.accounts}:{};for(let z of new Set([x1,...Z])){if(h7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:W1.primary,secondary:W1.secondary}}let J=X0($.defaults)?$.defaults:{primary:W1.primary,secondary:W1.secondary};return{...$,accounts:X,defaults:J,schema:G$}}function A4($,Z){let X=!1;if(X0($.cachekeep))$.cacheKeep={...$.cachekeep,...X0($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(X0(J)&&J.schema!==G$)$.killswitch=v7(J,Z),X=!0;return X}async function y7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function w7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return A4(z,await y7($)),{...J,settings:z}},X=async(J,z)=>{let G=await y7($);return $.updateSettings(async(Q)=>{A4(Q,G);let B=await J(Q)??Q;if(X0(B.killswitch)&&B.killswitch.schema!==G$)B.killswitch=m7(B.killswitch,G);return B},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 p7($,Z){let X=(H,Y)=>Z.rowLocks?Z.rowLocks(H):Y,J=(H,Y)=>{let W=X(H,Y?.extraLocks);return{...Y??{},...W?{extraLocks:W}:{}}},z=(H,Y,W,V)=>$.replace(H,Y,W,J(H,V)),B={add:async(H,Y)=>{let W=await $.read(),j=(W.status==="ready"?W.rows:[]).filter((D)=>D.type==="oauth"&&!D.invalid),K=H.identity?j.find((D)=>D.identity===H.identity):void 0;if(K?.id===x1)throw new Q0("main-account",g7);let U=K??j.find((D)=>D.id===H.id&&D.id!==x1);if(!U||H.credential.type!=="oauth")return $.add(H,Y);let N=await z(U.id,H.credential,H.identity!==void 0?{identity:H.identity}:{},Y?.extraLocks?{extraLocks:Y.extraLocks}:void 0);return u$.info("account signed in again",{id:U.id}),{id:N.id,outcome:"rotated",credential:N.credential,credentialEpoch:N.credentialEpoch}},replace:z,enable:(H,Y)=>$.enable(H,J(H,Y)),disable:(H,Y,W)=>$.disable(H,Y,J(H,W)),remove:(H,Y)=>$.remove(H,J(H,Y))};return new Proxy($,{get(H,Y){if(Object.hasOwn(B,Y))return B[Y];let W=Reflect.get(H,Y,H);return typeof W==="function"?W.bind(H):W}})}var u7="migration";function S4($){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:j1,title:E4,sections:[{id:u7,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 R4(X)}var LQ=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function _Q($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(LQ.has(Z))return!0;return Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function j3($,Z,X){if(Array.isArray($))return $.map((z,G)=>j3(z,`${Z}[${G}]`,X));if(!X0($))return $;let J={};for(let[z,G]of Object.entries($)){if(_Q(z)){X.push(`${Z}.${z}`);continue}J[z]=j3(G,`${Z}.${z}`,X)}return J}function R4($){let Z=[],X=j3($,"menu",Z);if(Z.length>0)u$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function l7($){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 d7($,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}),Q=z?`Open this verification URL:
|
|
96
|
+
</html>`,d2=[],y$,s0=new Map;function H9($,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(g$,Z)})}function V9($){$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}function E1(){return s0.size}function x1($){if(s0.delete($),E1()===0)I1()}async function bz(){let $=`http://localhost:${g$}/auth/callback`;if(d2.length>0)return{port:g$,redirectUri:$};if(y$)return y$;y$=(async()=>{let Z=(G,B)=>{let H=new URL(G.url||"/",`http://127.0.0.1:${g$}`);if(H.pathname==="/auth/callback"){let Y=H.searchParams.get("code"),Q=H.searchParams.get("state"),V=H.searchParams.get("error"),W=H.searchParams.get("error_description");if(V){let K=W||V;if(Q){let j=s0.get(Q);if(j)j.reject(Error(K)),x1(Q);else if(E1()===0)I1()}else if(E1()===0)I1();B.writeHead(200,{"Content-Type":"text/html"}),B.end(l2(K));return}if(!Q){if(E1()===0)I1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Missing state parameter"));return}if(!Y){if(E1()===0)I1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Missing authorization code"));return}let U=s0.get(Q);if(!U){if(E1()===0)I1();B.writeHead(400,{"Content-Type":"text/html"}),B.end(l2("Unknown state — authorization may have expired"));return}x1(Q),Rz(Y,$,U.pkce).then((K)=>U.resolve(K)).catch((K)=>U.reject(K)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(Iz);return}if(H.pathname==="/cancel"){let Y=H.searchParams.get("state"),Q=Y?[Y]:[...s0.keys()];B.writeHead(200),B.end("Login cancelled");for(let V of Q){let W=s0.get(V);if(!W)continue;W.reject(Error("Login cancelled")),x1(V)}if(E1()===0)I1();return}B.writeHead(404),B.end("Not found")},X=B9(Z);await H9(X,"127.0.0.1");let J=[X],z=B9(Z);try{await H9(z,"::1"),J.push(z)}catch(G){let B=G.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw V9(X),G}return d2=J,{port:g$,redirectUri:$}})();try{return await y$}finally{y$=void 0}}function I1(){let $=d2;d2=[];for(let Z of $)V9(Z)}function xz($,Z,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){x1(Z),G(Error("Login cancelled"));return}let B=setTimeout(()=>{if(s0.get(Z))x1(Z),G(Error("OAuth callback timeout — authorization took too long"))},X),H=()=>{if(clearTimeout(B),s0.get(Z))x1(Z),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",H);s0.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 kz($){let Z=await fetch(`${b1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Y9($)},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:`${b1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function fz($,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(`${b1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":Y9(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(H.ok){let V=await H.json(),W=await fetch(`${b1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:V.authorization_code,redirect_uri:`${b1}/deviceauth/callback`,client_id:c2,code_verifier:V.code_verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.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+Oz,Y);try{await Lz(Q,void 0,{signal:X})}catch(V){if(V instanceof Error&&V.name==="AbortError")throw Error("Device authorization cancelled");throw V}}}async function U9($){let{label:Z,headless:X=!1,signal:J,version:z}=$;if(k4(Z),X){let{deviceData:V,url:W,instructions:U}=await kz(z),K=(async()=>{let j=await fz(V,z,J),N=Date.now(),D=h$(j);return{id:k4(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:W,instructions:U,completion:K}}let{redirectUri:G}=await bz(),B=await Tz(),H=W9(crypto.getRandomValues(new Uint8Array(32)).buffer),Y=Sz(G,B,H),Q=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let V=await xz(B,H,void 0,J),W=Date.now(),U=h$(V);return{id:k4(Z||U||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:W+(V.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:U}}finally{x1(H)}})();return{url:Y,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}import{basename as yz,dirname as gz,join as hz}from"node:path";var s2="openai-auth.json",j9="openai-auth-state.json";function f4($){return yz($)===s2?hz(gz($),j9):`${$}.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 y4($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function K9($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function D9($,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=y4($.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 F9=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function _9($,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 L9($){if(F9.some((G)=>_9($,G)==="invalid"))return{};let Z={},X=D9($,"x-codex-primary-used-percent");if(X)Z.primary=X;let J=D9($,"x-codex-secondary-used-percent");if(J)Z.secondary=J;let z=vz($);if(z)Z.credits=z;return Z}function q9($,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 vz($){let Z=q9($,"x-codex-credits-has-credits"),X=q9($,"x-codex-credits-unlimited");if(Z===void 0||X===void 0)return;let J=B1($.get("x-codex-credits-balance")?.trim());return{hasCredits:Z,unlimited:X,...J!==void 0?{balance:J}:{},checkedAt:Date.now()}}function O9($){let Z=F9.map((X)=>_9($,X));return Z.includes("valid")&&!Z.includes("invalid")}function N9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=y4($.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 P9($){let Z={},X=N9($.rate_limits?.primary);if(X)Z.primary=X;let J=N9($.rate_limits?.secondary);if(J)Z.secondary=J;let z=mz($.credits);if(z)Z.credits=z;return Z}function mz($){if($===null||typeof $!=="object")return;let Z=$;if(typeof Z.has_credits!=="boolean"||typeof Z.unlimited!=="boolean")return;let X=B1(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 B1($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function M9($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=y4($.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 C9($){let Z={},X=M9($.rate_limit?.primary_window);if(X)Z.primary=X;let J=M9($.rate_limit?.secondary_window);if(J)Z.secondary=J;let z=K9($.rate_limit_reset_credits?.available_count);if(z!==void 0)Z.resetCreditsAvailable=z;let G=K9($.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=B1(B.limit),Q=B1(B.used),V=B1(B.remaining),W=B1(B.used_percent),U=B1(B.remaining_percent);if(Y!==void 0&&Q!==void 0&&V!==void 0&&W!==void 0&&U!==void 0)Z.spendControl={limit:Y,used:Q,remaining:V,usedPercent:W,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=B1(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 T9}from"node:path";import{storeIdentity as dz}from"@cortexkit/claustrum-client";import{SubcClient as A9}from"@cortexkit/subc-client";import{ClaustrumCredentialError as wz}from"@cortexkit/claustrum-client";import{SocketClosedError as pz,SocketTimeoutError as uz,SubcCallError as lz}from"@cortexkit/subc-client";class E extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var g4=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 k1 extends E{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function H1($){if($ instanceof k1||$ instanceof pz||$ instanceof uz)return"unreachable";let Z=$ instanceof wz||$ instanceof lz?$.code:$ instanceof Error&&("code"in $)?$.code:void 0;if(typeof Z!=="string"||!Object.hasOwn(g4,Z))return"answered";return g4[Z]}var h4=300000,i2=300000,v4=1000;class v${#$;#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 v$;#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.#M("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.#M("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.#M("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.#M(Z.kind)}#M($){this.#G("fallback",$),this.#V(300000,()=>void this.#K(!1))}}function R9($){let Z=$.identity??dz($.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 A9.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((V,W)=>{H=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),H.unref?.()}),Q=(async()=>{let V=Math.min($.handshakeTimeoutMs??3000,3000),W=$.connector?await $.connector({connectionFile:$.connectionFile,handshakeTimeoutMs:V}):await A9.connect({connectionFile:$.connectionFile,handshakeTimeoutMs:V});if(J=W,G){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},Z);if(G){W.close();return}z=W.subscribe(U,{method:"usage.watch"},X)})();try{await Promise.race([Q,Y])}catch(V){throw G=!0,V}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,S9=4*t2,cz=2*t2,m4=new Map,o2=new Map;function m$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function sz($){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode($))}catch{return}if(!m$(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 az($){return $ instanceof Error&&"code"in $&&typeof $.code==="string"?$.code:void 0}class E9{transport;key;#$=[];#Z=!1;#z=new Set;#J=new Map;#Y=new n2(async()=>{try{let $=await this.transport.getUsage();if(!m$($)||!Array.isArray($.result)||$.error!==void 0)throw Error("unavailable insula usage");this.#$=$.result.filter((Z)=>m$(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 v$;#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.#M()}}#M(){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.#F(Z,J);return}Z.handle=X,X.closed.then(()=>this.#F(Z,void 0),(J)=>this.#F(Z,J))}#N($,Z){if(this.#G!==$)return;if($.notices++,$.notices===1)this.#X="watching";if($.notices===2)this.#U=0;let X=sz(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()}#F($,Z){if(this.#G!==$)return;this.#G=void 0;let X=az(Z);if(X==="unknown_method"||X==="usage_watch_limit"){this.#X="fallback";return}if($.notices>0){let J=Math.min(v4*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||H1(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||!m$(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=S9)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(!m$(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+S9||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>=cz?"unreachable":"cold"}}}function w4($,Z){let X=JSON.stringify([T9($.connectionFile),T9(Z)]),J=m4.get(X);if(!J)J={source:new E9($,X),refs:0},m4.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)m4.delete(X)}}}import{ClaustrumCredentialError as Cj}from"@cortexkit/claustrum-client";function p4($){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 o9}from"@cortexkit/claustrum-client";import{createHash as iz,randomBytes as nz,randomUUID as rz}from"node:crypto";import{constants as I9}from"node:fs";import{chmod as oz,mkdir as tz,open as y9,readFile as u4,realpath as ez,rename as $G,stat as g9,unlink as h9}from"node:fs/promises";import{basename as v9,dirname as Q1,extname as b9,isAbsolute as x9,join as d4,resolve as ZG}from"node:path";import{ClaustrumCredentialError as XG,ClaustrumClient as JG,writeEnrollmentTokenFile as zG}from"@cortexkit/claustrum-client";var GG=1,$3=16384,m9=30000,c4=/^[0-9a-f]{64}$/,w9=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),p9=new Set(["pending_queue_full"]);function l4($){if(!($ instanceof XG))return;if(w9.has($.code))return{code:$.code,disposition:"terminal"};if(p9.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function s4($,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 a4($){return JG.connect($)}function u9($){let Z=b9($)||".json",X=v9($,b9($));return{statePath:d4(Q1($),`${X}-state${Z}`),tokenPath:$}}function i4($){let Z=$.override?.trim();if(Z&&!x9(Z)&&!$.cwd)throw new E("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=Z?x9(Z)?Z:ZG($.cwd,Z):d4($.stateDir,`${$.host}-enrollment.json`);return u9(X)}function l9($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e2($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function d9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function w$(){return new E("invalid-state","invalid Claustrum enrollment state")}function X3($){if(!l9($)||$.version!==GG||typeof $.proposedName!=="string"||$.proposedName.length===0)throw w$();if($.phase==="pending"){if(!c4.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!e2($.createdAt)||!e2($.updatedAt))throw w$();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)||!d9($.tokenGeneration)||!e2($.updatedAt))throw w$();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 w$();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw w$()}function n4($){if(!l9($)||!c4.test(String($.token??""))||!d9($.token_generation))throw new E("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function BG($){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 k9($){try{return JSON.parse($)}catch{throw new E("invalid-state","Claustrum enrollment file is not valid JSON")}}async function W1($){if(I)try{await q0(Q1($));let X=await _0($,!0);if(Buffer.byteLength(X)>$3)throw new E("unsafe-file","Claustrum enrollment file is too large");return k9(X)}catch(X){if(X.code==="ENOENT")return;throw X}let Z;try{Z=await y9($,I9.O_RDONLY|I9.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new E("unsafe-file","Claustrum enrollment file could not be opened safely")}try{BG(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 k9(X.subarray(0,J).toString("utf8"))}finally{await Z.close()}}function f9($,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 HG($,Z,X){try{let[J,z]=await Promise.all([u4(X.passwdPath??"/etc/passwd","utf8"),u4(X.groupPath??"/etc/group","utf8")]),G=f9(J,7),B=f9(z,4);if(!G||!B)return!1;let H=G.filter((W)=>Number(W[2])===$),Y=B.filter((W)=>Number(W[2])===Z);if(H.length!==1||Y.length!==1)return!1;let Q=H[0]?.[0],V=Y[0]?.[3]??"";return(V===""||V.split(",").every((W)=>W===Q))&&!G.some((W)=>Number(W[2])!==$&&Number(W[3])===Z)}catch{return!1}}function c9($){if(!$.passwdPath&&!$.groupPath)return;return{fs:{readFile:(Z)=>u4(Z==="/etc/passwd"?$.passwdPath??Z:Z==="/etc/group"?$.groupPath??Z:Z)}}}async function s9($,Z={}){if(!I){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await ez($)}catch{return}let G;for(;;){let B=await g9(z).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(G===void 0)G=J!==void 0&&await HG(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=Q1(z);if(H===z)return;z=H}}try{await m0($,c9(Z))}catch(X){if(!(X instanceof a))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 q0($,!1,c9(Z));return}await tz($,{recursive:!0,mode:448});let X=await g9($),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 oz($,448)}async function f1($,Z,X={}){let J=Q1($);await Z3(J,X),await s9(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 s1($,z);let G=d4(J,`.${v9($)}.${process.pid}.${rz()}.tmp`),B,H=!1;try{B=await y9(G,"wx",384),H=!0,await B.writeFile(z,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await $G(G,$),H=!1}finally{if(await B?.close().catch(()=>{}),H)await h9(G).catch(()=>{})}}async function p$($,Z){let X=await W1($.tokenPath),J=X===void 0?void 0:n4(X),z=await W1($.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 Y1(G)}async function r4($,Z){let X;try{X=await p$($,Z)}catch(J){if(!(J instanceof E)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await W1($.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 V1($){let Z=await W1($);if(Z===void 0)throw new E("not-enrolled","Claustrum enrollment is not configured");return n4(Z)}function Y1($){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 a9(){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??(()=>nz(32).toString("hex")),this.#B=$.writeTokenFile??zG}async status(){return p$(this.#Z,this.#z)}async resetTerminal(){return i9(this.#Z,this.#z)}async#W($,Z){let X={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#J()};return await f1(this.#Z.statePath,X,this.#X),Y1(X)}async reconcile(){await Z3(Q1(this.#Z.statePath),this.#X);let $=await Z0({name:"ceremony",path:this.#Z.statePath,ttlMs:m9,renew:!0});if(!$)return{state:"busy"};try{let Z=await W1(this.#Z.tokenPath),X=Z===void 0?void 0:n4(Z),J=await W1(this.#Z.statePath),z=J===void 0?void 0:X3(J);if(z&&z.proposedName!==this.#z)throw a9();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 f1(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 f1(this.#Z.statePath,B,this.#X),Y1(B)}if(z&&z.phase!=="pending")return Y1(z);if(!z){let B=this.#J();if(z={version:1,phase:"pending",proposedName:this.#z,requestSecret:this.#Y(),createdAt:B,updatedAt:B},!c4.test(z.requestSecret))throw new E("invalid-state","invalid minted Claustrum enrollment secret");await f1(this.#Z.statePath,z,this.#X)}if(!z.requestId)try{let B=iz("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 f1(this.#Z.statePath,z,this.#X)}catch(B){let H=l4(B);if(!H)throw B;if(H.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:H.code};return this.#W(z,H.code)}let G=z.requestId;if(!G)return Y1(z);try{let B=await this.#$.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(B.status==="pending")return Y1(z);if(B.status==="denied"){let Y={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#J()};return await f1(this.#Z.statePath,Y,this.#X),Y1(Y)}await Z3(Q1(this.#Z.tokenPath),this.#X),await s9(Q1(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 f1(this.#Z.statePath,H,this.#X),Y1(H)}catch(B){let H=l4(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 i9($,Z){await Z3(Q1($.statePath));let X=await Z0({name:"ceremony",path:$.statePath,ttlMs:m9,renew:!0});if(!X)return"busy";try{if(await W1($.tokenPath)!==void 0)return"refused-approved";let J=await W1($.statePath);if(J===void 0)return"idle";let z=X3(J);if(z.proposedName!==Z)throw a9();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await h9($.statePath),"reset"}finally{await X.release()}}var u$="claustrum-tombstone:v1:";function z3($){return`${u$}${$}`}function o4($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function G3($){return typeof $==="string"&&$.startsWith(u$)}function n9($,Z){if(!o4($)||$.type!=="oauth")return!1;return $.refresh===z3(Z)}function r9($,Z){if(n9($,Z))return"placeholder";if(o4($)&&$.type==="oauth"&&typeof $.refresh==="string"&&$.refresh.length>0&&!G3($.refresh))return"login";if(o4($)&&$.type==="api"&&typeof $.key==="string"&&$.key.length>0)return"login";return"empty"}function t4($){let Z=r9($.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 t9($,Z){return Z!==void 0&&!Z.fromKeptReceipt&&!$.fromKeptReceipt&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function YG($,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 $Z=d("claustrum");function XZ($,Z,X,J=$Z){let z=t9(Z,X);return J.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:YG(Z,X)}),z}var ZZ=300000,e9=60000;function e4(){return new E("invalid-material","Claustrum returned invalid credential material")}function QG($){let Z=$.trim();if(Z.startsWith("{")){let X;try{X=JSON.parse(Z)}catch{throw e4()}if(!X||typeof X!=="object")throw e4();let J=X,z=J.access_token??J.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(u$))throw e4();return Z}function WG($,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 VG($){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;#M=new k1;#D;#j=!1;#N=-1/0;#F=2000;#q=!1;#_;#O=new Set;constructor($){let Z=$.tokenPath;if($.readToken)this.#Z=$.readToken;else if(Z)this.#Z=()=>V1(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??$Z,this.#V=$.setTimeoutImpl??setTimeout,this.#K=$.clearTimeoutImpl??clearTimeout}transportLost($){if(this.#q||this.#U)return;this.#U=!0,this.#M=$ instanceof o9?$:new k1,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.#F=2000;for(let $ of this.#H.values())$.since=null;(this.#X.info??$Z.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.#F),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.#S().catch(()=>{if($&&this.#U)this.#F=Math.min(this.#F*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#A($,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),H1(z)==="unreachable")this.transportLost(z);else this.reachable();if(z instanceof o9)throw z;if(H1(z)==="unreachable")throw new k1;throw new E("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#L(Z),this.reachable(),X}async discover($){let Z=await this.#S($);return this.#_=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=WG(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 V;if(!Y.id.trim())V="empty credential id";else if((G.get(Y.id)??0)>1)V="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())V="blank account identity";else if(!Y.state.trim())V="empty state";if(V){J.push({...Y.id.trim()&&{credentialId:Y.id},reason:V});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=VG(Z);return{view:Z.view,credentials:Object.freeze(B),skipped:Object.freeze(J),...H&&{grantReach:H}}}listFailed($){if(H1($)==="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()>e9}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),H1(Y)!=="unreachable")throw this.forget(J),Y;return this.#E(J,B,H,X,Y)}}#E($,Z,X,J,z=this.#M){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:ZZ}}),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()<ZZ))throw new E("insufficient-validity","Claustrum served credential has insufficient validity");let Y=QG(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 V=Q===void 0?this.#Y?.(Y):void 0,W=Q??V;if(G!==void 0&&W!==void 0&&W!==G)throw new E("identity-changed","Claustrum served credential identity changed");let U=W??G,j=Object.freeze(Object.defineProperty({credentialId:J,credentialType:z,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":V!==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.#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.#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 KZ}from"node:path";import{createHash as UG}from"node:crypto";import{resolve as X5}from"node:path";function $5($,Z,X){if($.accountIdentity!==void 0&&X!==void 0)return $.accountIdentity===X;return $.credentialId===Z}function JZ($,Z,X){return $.some((J)=>$5(J,Z,X))}function zZ($,Z,X){let J={credentialId:Z,...X!==void 0&&{accountIdentity:X}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==X),J]}function GZ($,Z,X){return $.filter((J)=>!Z.some((z)=>$5(J,z,X)))}var J5="vault:";function jG($){return UG("sha256").update($).digest("hex")}function KG($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function DG($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function U1($){return[$.credentialId,...$.aliases??[]]}function z5($,Z,X={}){let J=X.now??Date.now(),z=X.routePrefix??J5,G=X.reservedRouteIds??new Set,B=$?.rows??[],H=[...$?.declined??[]],Y=Z.skipped.length===0,Q=new Set(Z.credentials.map((F)=>F.credentialId)),V=new Set(Z.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),W=Z.skipped.some((F)=>F.credentialId===void 0),U=(F)=>!Q.has(F)&&(V.has(F)||W),K=new Map;for(let F of B){if(F.accountIdentity===void 0)continue;for(let q of U1(F))if(!K.has(q))K.set(q,F.accountIdentity)}let j=new Map;for(let F of Z.credentials){let q=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:K.get(F.credentialId),claimed:!1},_=DG(q),S=j.get(_)??[];S.push(q),j.set(_,S)}let N=new Set,D=new Set(G),M=[],O=(F,q)=>F.credential.credentialId.localeCompare(q.credential.credentialId),R=[...j.values()].map((F)=>F.toSorted(O)).sort((F,q)=>F[0]&&q[0]?O(F[0],q[0]):0);for(let F of R){let q=F[0]?.identity,_=F.filter((v)=>v.credential.state==="active"),S=_.length?_:F,A=S.filter((v)=>v.claimed),b=A.length?A:S,w=new Set(F.map((v)=>v.credential.credentialId)),f=B.find((v)=>!N.has(v)&&U1(v).some((g0)=>w.has(g0))&&(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,o=f??(q===void 0?void 0:B.find((v)=>!N.has(v)&&v.accountIdentity===q));if(o)N.add(o);let i=o?.routeId;if(!i||G.has(i)){let v=`${z}${h.credentialId}${q===void 0?"":`~${jG(q).slice(0,10)}`}`;i=v;for(let g0=2;D.has(i);g0++)i=`${v}~${g0}`}D.add(i);let H2=o?U1(o).filter(U):[],m1=[...new Set([...F.map((v)=>v.credential.credentialId),...H2])].filter((v)=>v!==h.credentialId).sort((v,g0)=>v.localeCompare(g0)),Y2=X.mapAccount?.(h)??{};M.push({previousIndex:o?B.indexOf(o):1/0,row:{routeId:i,credentialId:h.credentialId,credentialType:h.credentialType,...q!==void 0&&{accountIdentity:q},...m1.length&&{aliases:m1},state:h.state,label:Y2.label?.trim()||KG(h),...h.email!==void 0&&{email:h.email},...h.orgName!==void 0&&{orgName:h.orgName},enabled:![h.credentialId,...m1].some((v)=>JZ(H,v,q)),addedAt:o?.addedAt??J,...o?.quota!==void 0&&{quota:o.quota},...!y.claimed&&q!==void 0&&{unclaimed:!0}}})}return B.forEach((F,q)=>{if(N.has(F)||!U1(F).some(U))return;if(D.has(F.routeId))return;let[_,...S]=U1(F).filter((w)=>!Q.has(w));if(_===void 0)return;D.add(F.routeId);let{aliases:A,...b}=F;M.push({previousIndex:q,row:{...b,credentialId:_,...S.length&&{aliases:S},stale:!0}})}),M.sort((F,q)=>F.previousIndex===q.previousIndex?F.row.credentialId.localeCompare(q.row.credentialId):F.previousIndex-q.previousIndex),{version:1,view:Z.view,complete:Y,...!Y&&{rejected:Z.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:M.map((F)=>F.row),declined:H}}function BZ($){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 l$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function B$($){return $===void 0||typeof $==="string"}function qG($){let Z=l$($)?P1($.quota):void 0;if(!l$($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!B$($.accountIdentity)||!B$($.email)||!B$($.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 NG=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function Z5($){if(!Array.isArray($))return;let Z=[];for(let X of $){if(!l$(X)||!B$(X.credentialId)||typeof X.reason!=="string"||!NG.has(X.reason))return;Z.push(X)}return Z}function MG($){if(!l$($)||$.version!==1||!B$($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!Z5($.rejected))throw new E("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let G=qG(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(!l$(z)||typeof z.credentialId!=="string"||!B$(z.accountIdentity))throw new E("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=Z5($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...J&&{rejected:J},rows:Z,declined:X}}async function M0($){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 MG(X)}var FG={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},_G={name:"claustrum-roster",ttlMs:30000};async function H$($,Z,X={}){return G4($,{...FG,signal:X.signal},async(J)=>{let z=await M0($),{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 HZ($,Z){return H$($,(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=zZ(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 YZ($,Z){return H$($,(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:GZ(X.declined,U1(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function LG($,Z){if(!U1($).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")&&U1($).length===1)return"bind";return"refuse"}async function QZ($,Z){let{routeId:X,observation:J,...z}=Z;return G5($,{routeId:X,observation:J,accountIdentity:z.accountIdentity,receipt:z})}async function G5($,Z){if(!p1(Z.observation))return!1;let X=a0($,await M0($));if(!j1(X,Z).kept)return!1;return B5($,Z)}function WZ($,Z){return G5($,Z)}function j1($,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=v0(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 VZ($){H3.delete(X5($))}async function UZ($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z()){VZ($.path);return}let X=await Z0({..._G,path:$.path,renew:!0});if(!X){let G=await M0($.path);if($.signal?.throwIfAborted(),!G?.view)throw new E("roster-busy","Claustrum account discovery is already in progress");return G}let J=X5($.path),z;try{let G=await M0($.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 H$($.path,async(Y)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await X.assertOwned();let Q=typeof $.projection==="function"?$.projection():$.projection,V=z5(Y,H,Q);return{...JSON.stringify(Y)!==JSON.stringify(V)&&{next:V},result:V}},{beforePublish:async()=>{$.signal?.throwIfAborted(),await X.assertOwned()}})}catch(G){if(G instanceof p0&&z&&!$.signal?.aborted&&await Z())H3.set(J,z);throw G}finally{await X.release()}}var Y$=new Map,OG=d("claustrum"),H5=100;function Y5($){let Z=KZ($),X=Y$.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},Y$.set(Z,X);return X}function Q5($,Z){let X=Y5($);X.listeners.add(Z);let J;return()=>J??=(()=>{return X.listeners.delete(Z),X.listeners.size?Promise.resolve():jZ($)})()}function PG($){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 B5($,Z){if(!p1(Z.observation))return Promise.resolve(!1);let X=Y5($),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 PG(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 V5(X,H5),Promise.resolve(!0)}function W5($){return[...$.values()].flatMap((Z)=>[...Z.values()]).sort((Z,X)=>Z.order-X.order)}function a0($,Z){let X=Y$.get(KZ($));if(X)for(let J of W5(X.pending)){if(J.priorReading)Z=j1(Z,J.priorReading).roster;Z=j1(Z,J.publication).roster}return Z}function V5($,Z){if($.running||$.timer||!$.pending.size||$.abort.signal.aborted)return;if($.timer=setTimeout(()=>{$.timer=void 0,U5($)},Z),!$.draining)$.timer.unref?.()}function U5($){if($.running||$.abort.signal.aborted)return;let Z=new Map([...$.pending].map(([X,J])=>[X,new Map(J)]));$.running=(async()=>{try{await H$($.path,(X)=>{let J=X;for(let z of W5(Z)){if(z.priorReading)J=j1(J,z.priorReading).roster;J=j1(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)OG.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()):H5;V5($,X)}})()}async function jZ($,Z=1000){let X=KZ($),J=Y$.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)U5(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(),Y$.get(X)===J)Y$.delete(X)}}}class Y3{#$;#Z=new AbortController;#z;#J;#Y;#B;#X;#W;#Q;#H=!1;#G;#V;#K;#U=new Map;#M;#D;constructor($){this.#$=$,this.#z=$.logger??d("claustrum"),this.#D=Q5($.rosterPath,(Z)=>{this.#X=j1(this.#X,Z).roster})}#j($){this.#Z.signal.throwIfAborted(),$?.throwIfAborted()}async#N(){return await this.#$.isCustodyActive?.()??!0}#F($,Z){let X=p4([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=w4($.insula,this.#$.tokenPath);return this.#J}).finally(()=>{this.#Y=void 0});return this.#F(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 BZ(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 UZ({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=a0(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.#M=(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.#M===void 0||$-this.#M>=h4)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 V1(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 V1(this.#$.tokenPath),this.#P($.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute($){if(!this.#$.insula||this.#Z.signal.aborted||!await this.#N())return;try{await V1(this.#$.tokenPath);let X=a0(this.#$.rosterPath,await M0(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 V1(this.#$.tokenPath);let J=a0(this.#$.rosterPath,await M0(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.#F(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=a0(this.#$.rosterPath,await M0(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.#F(this.#q(),Z),H=p4([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)}catch{}if(XZ(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 HZ(this.#$.rosterPath,$),this.#X=a0(this.#$.rosterPath,await M0(this.#$.rosterPath)),this.#J?.retain(this.#X?.rows??[])}async accept($){this.#j(),await YZ(this.#$.rosterPath,$),this.#X=a0(this.#$.rosterPath,await M0(this.#$.rosterPath))}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(),WZ(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(),VZ(this.#$.rosterPath)}async dispose(){this.close(),await this.#D()}}async function j5($){let Z=await CG.connect($);return Object.assign(Z,{insula:R9($)})}var TG=z3("openai");function K5($){return G3($)}function f0($){if(!$||$.corrupt===!0)return!1;return K5($.refresh)}class d$ 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(K5($))throw new d$}function i0($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var AG=d("quota");var SG="app_EMoamEEZ73f0CkXaXp7hrann",RG="https://auth.openai.com";async function D5($){Q3($.refreshToken);let Z=await $.fetchImpl(`${RG}/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:SG}).toString()});if(!Z.ok){let z=x4(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 EG="https://chatgpt.com/backend-api/wham/usage";async function Q$($){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(EG,{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=x4(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:B})}let G=C9(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:i0(z)}),z}}import{createHash as xG}from"node:crypto";var kG=globalThis.setTimeout,fG=5;function c$($){let Z=$?.quota?.checkIntervalMinutes??fG;return Math.max(1,Z)*60000}function yG($){return $?.quota?.enabled!==!1}function qZ($,Z){if(!$?.resetsAt)return!1;let X=Date.parse($.resetsAt);return Number.isFinite(X)&&X<=Z}function gG($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function q5($,Z,X){if(!yG(Z))return X+c$(Z);let J=gG(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+c$(Z);z.push(H)}if(!z.length)return X+c$(Z);return Math.min(...z)+60000}function hG($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function vG($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function O0($){return xG("sha256").update($).digest("hex").slice(0,16)}class K1{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&&!N5(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,DZ(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&&!N5(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(DZ(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=K1.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(f0(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=vG(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=hG($);if(!X)return;let J=Z?O0(Z):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:q5(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&&J$(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=c$(this.storage);for(let X of $){if(X.enabled===!1)continue;if(!X.quota)continue;let 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 J$(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==O0(Z))return!1}return J$(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<K1.API_CALL_GAP_MS)await new Promise((z)=>{let G=kG(z,K1.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 Z0({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:q5(z,this.storage,G),checkedAt:G},DZ(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 Z0({name:K1.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+c$(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(K1.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(K1.isAuthError($))return;this.mainLastApiError=f$({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,X){if(K1.isAuthError(X))return;let J=O0(Z),z=this.fallbackErrorTokenFps.get($)===J?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,f$({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set($,J)}}function N5($){return Boolean($.primary||$.secondary)}function DZ($){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 y1=d("refresh"),FZ=d("accounts"),uG=1e4,lG=15000,NZ=50;function D1($){return $.type==="oauth"&&$.corrupt!==!0}function dG($){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 V$="floors-v1";class V3 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor($){super(`Fallback account ${$} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var cG=[401,403,429],M5={primary:0,secondary:0},sG=!1,q1={primary:5,secondary:10};function k($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var aG=new Set(["__proto__","constructor","prototype"]);function PZ($){return $.length>0&&!aG.has($)}function iG($){return $ instanceof V3||k($)&&$.name==="AccountRemovedDuringRefreshError"&&$.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function W3($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():wG(),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 nG($){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 rG($){if(!k($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!dG(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:F5($.lastRefreshError),lastQuotaRefreshError:F5($.lastQuotaRefreshError),quota:nG($.quota)}}function oG($){if(!k($))return;let Z=Object.create(null);for(let[X,J]of Object.entries($)){if(!PZ(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 _5=new Set;function tG($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(_5.has(Z))return;_5.add(Z),FZ.warn("account load-dropped, preserved on disk",{droppedIds:$})}function eG($){if(!k($)||!Array.isArray($.accounts))return null;let Z=$.accounts,X=Z.map(rG).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);tG(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:oG($.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 $B($,"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 ZB($){let Z;try{Z=(await U3($)).value}catch{return null}return VB(Z)}function XB($,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,V=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 JB({...$,refresh:j3({...B,mainLastRefreshError:B.mainLastRefreshError??Y.lastRefreshError,mainRefreshLeaseId:V.id,mainRefreshLeaseUntil:V.until,mainRefreshLeaseTokenHash:V.tokenHash}),quota:j3({...G,mainQuota:H.quota,mainQuotaCheckedAt:H.quotaCheckedAt,mainQuotaToken:H.quotaToken,mainLastQuotaApiError:H.lastQuotaApiError}),accounts:U})}async function CZ($){let Z=await U3($.configPath);if(!Z.exists)return null;let X=await U3($.statePath);return eG(XB(Z.value,X.value))}function JB($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function zB($){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 s$($,Z,X){if(X in Z)$[X]=Z[X];else delete $[X]}function GB($,Z){return $.access===Z.access&&$.refresh===Z.refresh&&$.expires===Z.expires&&$.lastRefreshedAt===Z.lastRefreshedAt}function BB($,Z){if(!GB($,Z))return Z;if(!("lastRefreshError"in Z))return $;if(!("lastRefreshError"in $))return Z;return(Z.lastRefreshError?.checkedAt??0)>($.lastRefreshError?.checkedAt??0)?Z:$}var HB=300000;function L5($,Z){if($===void 0)return 0;return $>Z+HB?0:$}function YB($,Z,X){let J=Date.now(),z=L5(Z.lastRefreshedAt,J),G=L5(X.lastRefreshedAt,J),B=Z.expires??0,H=X.expires??0,Y=G>z?X:z>G?Z:H>B?X:B>H?Z:BB(Z,X);s$($,Y,"access"),s$($,Y,"refresh"),s$($,Y,"expires"),s$($,Y,"lastRefreshedAt"),s$($,Y,"lastRefreshError")}function QB($,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 YB(B,X,Z),B}async function WB($,Z=!1){let X=Date.now(),J=X+lG,z=0;while(Date.now()<=J){z++;let H=await Z0({name:"save",ttlMs:uG,path:$,renew:Z});if(H)return H;let Y=J-Date.now();if(Y<=0)break;await pG(Math.min(NZ+R5(NZ),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 ${NZ}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 VB($){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 UB($,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 jB($,Z){$.main=$.main??{},$.main.lastRefreshError=Z.refresh?.mainLastRefreshError,$.main.refreshLeaseId=Z.refresh?.mainRefreshLeaseId,$.main.refreshLeaseUntil=Z.refresh?.mainRefreshLeaseUntil,$.main.refreshLeaseTokenHash=Z.refresh?.mainRefreshLeaseTokenHash}function _Z($){if(Array.isArray($))return $.map(_Z);if(!k($))return $;return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0).map(([Z,X])=>[Z,_Z(X)]))}async function KB($,Z,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=Z.statePath,G=await WB(z);try{let B=(await U3(z)).value,H=k(B)?{...B,version:1}:{version:1};if(X.mainQuota)UB(H,$);if(X.mainRefresh)jB(H,$);if(X.accounts){let Y=X.accounts===!0?null:new Set(X.accounts),Q=await ZB(Z.configPath);H.accounts={...k(H.accounts)?H.accounts:{}};for(let V of $.accounts){if(Y&&!Y.has(V.id))continue;if(Q&&!Q.has(V.id))continue;H.accounts[V.id]=QB(H.accounts[V.id],zB(V))}if(Y){for(let V of Y)if(!$.accounts.some((W)=>W.id===V))delete H.accounts[V]}if(Q){for(let V of Object.keys(H.accounts))if(!Q.has(V))delete H.accounts[V]}}if(J&&!J())return;await L0(z,_Z(H))}finally{await G.release()}}function A5($){return $?.fallbackOn?.length?$.fallbackOn:cG}function DB($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??M5.primary,secondary:Z.secondary??Z["1w"]??M5.secondary}}function LZ($){return $?.quota?.enabled!==!1}function i$($){return $?.quota?.failClosedOnUnknownQuota??sG}function D3($,Z,X=Date.now()){if(!LZ(Z))return!0;if(!$)return!i$(Z);let J=DB(Z),z=i$(Z);for(let G of["primary","secondary"]){let B=$[G];if(!B)continue;if(qZ(B,X)){if(z)return!1;continue}if(B.remainingPercent<J[G])return!1}return!0}function TZ($){return $?.killswitch?.enabled===!0}function O5($){return{primary:$?.primary??$?.["5h"]??q1.primary,secondary:$?.secondary??$?.["1w"]??q1.secondary}}function P5($){return typeof $==="number"&&Number.isFinite($)?$:0}function N1($,Z){if(!$?.killswitch)return q1;if($.killswitch.schema===V$){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:P5(G?.primary),secondary:P5(G?.secondary)}}if(Z&&$.killswitch.accounts?.[Z])return O5($.killswitch.accounts[Z]);return O5($.killswitch.main)}function S5($,Z,X,J=Date.now()){if(!TZ(Z))return!0;if(!$)return!i$(Z);let z=N1(Z,X),G=i$(Z);for(let B of["primary","secondary"]){let H=$[B];if(!H)continue;if(qZ(H,J)){if(G)return!1;continue}if(H.remainingPercent<z[B])return!1}return!0}function qB($){return $?.refresh?.enabled!==!1}function AZ($){return($?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function R5($){return Math.floor(Math.random()*($+1))}function g1($,Z,X){return!$.access||!$.expires||$.expires-X<=AZ(Z)}function NB($,Z){return Boolean($.access&&typeof $.expires==="number"&&$.expires>Z)}function W$($,Z){return Boolean($?.mainAccountId&&Z.accountId&&Z.accountId===$.mainAccountId)}class E5 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 K0($,Z){let X=$.accounts.findIndex((J)=>J.id===Z.id);if(X!==-1)$.accounts[X]=Z}function a$($){return $ instanceof Error?$.message:String($)}function OZ($,Z,X){if(Z instanceof d$)return;$.lastRefreshError=u2({error:Z,now:X,refreshToken:$.refresh,previous:$.lastRefreshError})}function MZ($,Z,X){if(Z instanceof d$)return;if($.lastQuotaRefreshError=f$({error:Z,now:X,previous:$.lastQuotaRefreshError}),Z?.isRefreshError===!0)OZ($,Z,X)}function C5($,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 C5($.primary,Z)||C5($.secondary,Z)}function FB($,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 T5($,Z,X){return!FB($.quota,Z,X)}function _B($,Z,X,J){return b4(X)&&D3($.quota,Z,J)&&MB($.quota,J)}function LB($){let Z=$?.quota?.checkIntervalMinutes??5;return Math.max(1,Z)*60000}var OB=60000,PB=60000,CB=600000;function TB($){return`fallback-oauth-refresh-${mG("sha256").update($).digest("base64url").slice(0,16)}`}var AB=1e4,SB=100;class RB{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+LB(Z),checkedAt:X},$.access,!1,$.accountId)}async load(){return CZ(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save($,Z){await KB($,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(()=>{})},OB+R5(PB)),"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||!D1(z))continue;if(W$(Z,z))continue;if(f0(z))continue;let G=!1,B=z;try{if(g1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&G1(H,B.refresh,this.now()))throw G=!0,Error(k$(H,this.now()));try{B=await this.refreshAccount(B,Z),J=!0}catch(Y){if(iG(Y))continue;G=!0;let Q=Z.accounts.find((V)=>V.id===z.id&&D1(V));if(Q&&!G1(Q.lastRefreshError,Q.refresh,this.now()))OZ(Q,Y,this.now()),K0(Z,Q),J=!0;throw Y}}if(this.seedFallbackQuota(B,Z),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),Z))X.push(B)}catch(H){let Y=NB(B,this.now());if(G){if(!Y)continue}else if(!Y)continue;if(_B(B,Z,H,this.now()))y1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:a$(H)}),X.push(B);else if(!i$(Z))X.push(B)}}if(J){let z=structuredClone(Z);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{FZ.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:a$(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){FZ.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:$.id,error:a$(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(!$||!qB($))return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!D1(X))continue;if(W$($,X))continue;if(f0(X))continue;if(!g1(X,$,this.now()))continue;if(G1(X.lastRefreshError,X.refresh,this.now()))continue;try{y1.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){y1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:a$(J)}),OZ(X,J,this.now()),K0($,X),Z=!0}}if(Z)await this.save($)}async refreshQuotaForDueAccounts(){let $=await this.load();if(!$||!LZ($))return;if(!this.options.fetchQuotaFn)return;let Z=!1;for(let X of $.accounts){if(X.enabled===!1||!D1(X))continue;if(W$($,X))continue;if(f0(X))continue;let J=X;try{if(g1(J,$,this.now())){if(G1(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,$),Z=!0}if(J$(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,$),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):T5(J,$,this.now())))continue;await this.refreshAccountQuota(J,$),Z=!0}catch(z){MZ(X,z,this.now()),K0($,X),Z=!0}}if(Z)await this.save($),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts($={}){let Z=await this.load(),X=[];if(!Z||!LZ(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||!D1(G))continue;if(W$(Z,G))continue;if(f0(G))continue;let B=G;try{if(g1(B,Z,this.now())){let H=B.lastRefreshError;if(H&&G1(H,B.refresh,this.now()))throw Error(k$(H,this.now()));B=await this.refreshAccount(B,Z),z=!0}if(!J&&!T5(B,Z,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,K0(Z,B),z=!0;continue}await this.refreshAccountQuota(B,Z),z=!0}catch(H){MZ(G,H,this.now()),K0(Z,G),z=!0,X.push({accountId:G.id,message:a$(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 K0(Z,B),B}let z=this.refreshAccountNow($,Z,X).finally(()=>{this.refreshPromises.delete($.id)});this.refreshPromises.set($.id,z);let G=await z;return K0(Z,G),G}async waitForConcurrentFallbackRefresh($,Z,X,J){let z=Date.now()+AB;while(Date.now()<z){await new Promise((Q)=>setTimeout(Q,SB));let G=await this.load(),B=G?.accounts.find((Q)=>Q.id===$.id&&D1(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||!g1(B,G,this.now())))return K0(Z,B),y1.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&&G1(Y,B.refresh,this.now()))throw K0(Z,B),Error(k$(Y,this.now()))}return null}assertNotShieldedMainRow($,Z,X){if(X.asPoolMain||!Z)return;if(W$($,Z))throw new E5(Z.id)}async refreshAccountNow($,Z,X){let J=await this.load(),z=J?.accounts.find((H)=>H.id===$.id&&D1(H));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!g1(z,J,this.now()))return K0(Z,z),z;let G=z??$,B=await Z0({name:TB(G.id),ttlMs:CB,path:this.paths.configPath,renew:!0});if(!B){y1.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((V)=>V.id===$.id&&D1(V)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!g1(z,J,this.now()))return K0(Z,z),z;if(!z)throw new V3($.id);G=z;let H=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});y1.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,K0(Z,G),await this.save(Z),!(await this.load())?.accounts.some((V)=>V.id===$.id))throw new V3($.id);return y1.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,K0(Z,X),await this.save(Z)}catch(G){throw MZ($,G,this.now()),K0(Z,$),G}}}var I5="/backend-api/wham/rate-limit-reset-credits",WK=`https://chatgpt.com${I5}`,EB=`${I5}/consume`,VK=`https://chatgpt.com${EB}`;function J0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as fB}from"node:fs";import{rm as y5}from"node:fs/promises";import{dirname as yB,join as g5}from"node:path";import{resolveClaustrumConnectionPath as gB}from"@cortexkit/claustrum-client";function b5($,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 x5($){if(!J0($)||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 IB($){let Z=x5($.total),X=x5($.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},...J0($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function k5($,Z){let X=b5($.usage?.primary,Z.fetchedAt);if(!X||!Number.isFinite(Z.fetchedAt))return;let J=b5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((H)=>J0(H)&&H.id==="individual_limit"):void 0,G=J0(z)?IB(z):void 0,B=J0($.savedResets)?$.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var f5=["primary","secondary"];function q3($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function U$($){return typeof $==="number"&&Number.isFinite($)}function bB($,Z){if(!q3(Z))return;let X=Z.usedPercent;if(!U$(X)||X<0||X>100)return;return{label:$,usedPercent:X,...typeof Z.resetsAt==="string"?{resetsAt:Z.resetsAt}:{},...U$(Z.windowMinutes)&&Z.windowMinutes>0?{windowMinutes:Z.windowMinutes}:{}}}function xB($){let Z=$.spendControl;if(q3(Z)&&typeof Z.reached==="boolean"){let X=(J)=>U$(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 kB($,Z){if(!q3($)||typeof $.hasCredits!=="boolean"||typeof $.unlimited!=="boolean")return;return{hasCredits:$.hasCredits,unlimited:$.unlimited,...U$($.balance)&&$.balance>=0?{balance:$.balance}:{},...typeof $.overageLimitReached==="boolean"?{overageLimitReached:$.overageLimitReached}:{},checkedAt:Z}}function S0($,Z,X){if(!q3($)||!U$(Z))return;let J=[],z=[];for(let Q of f5){let V=bB(Q,$[Q]);if(V)J.push(V);else if(X)z.push({label:Q})}let G=xB($),B=$.resetCreditsAvailable,H=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:Z}}:void 0,Y=kB($.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 j$($){if(!$0($))return;let Z=s($),X={};for(let J of f5){let z=Z.limits.find((B)=>B.label===J&&B.kind==="reading");if(!z||!U$(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 SZ($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var RZ="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 \`${SZ($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${RZ}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var R0=d("vault"),hB="openai-auth",h5={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},vB={opencode:"OpenCode",pi:"Pi"};function mB($){return s4(hB,$)}function M3($){return g5(yB($),"openai-auth-vault")}function wB($,Z){return{...i4({stateDir:$,host:Z}),rosterPath:g5($,`${Z}-roster.json`)}}var F3=2000;var pB={"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 ${RZ} 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 v5($,Z){if($!=="vault-no-grant")return pB[$];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: ${SZ(Z)}`}function m5($){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 uB($){let Z=z$($);return Z?G$(Z):void 0}class w5 extends Y3{#$;constructor($,Z){super($);this.#$=Z}refresh(){let $=super.refresh();return this.#$($),$}}class EZ{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=mB($.host),this.paths=wB($.stateDir,$.host),this.#Z=new w5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:h5,connect:()=>this.#j(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:uB,insula:{provider:"codex",normalize:k5},...$.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))}#M(){return(this.#$.connectionFile??gB)()}#D(){return{connectionFile:this.#M(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>R0.debug("vault transport error",{errorClass:$})}}#j(){return(this.#$.connectScoped?.()??j5(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})}#F(){return this.#$.connectEnrollment?.()??a4(this.#D())}#q($,Z){this.#X=i0(Z),R0.warn($,{host:this.host,error:this.#X})}#_(){return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=fB($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#_(),Z=await r4(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=S0(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 M0(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=S0(z,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=S0(H,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 Q$({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=i0(H);let Y=H?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw H}},{site:"quota"}).catch((G)=>{X=i0(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:i0(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=lB(J.quota);if(z!==void 0&&Z-z<$)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}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 p$(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.#F().catch((Z)=>{throw new H0("vault-unreachable",`Could not reach the Claustrum vault (${this.#M()}): ${i0(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 y5(this.paths.tokenPath,{force:!0}),await y5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,R0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())t4({mode:"custody",auth:$,provider:"openai"})}close(){this.#G=!0,this.#V.resolve(),this.#Z.close()}}function lB($){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 ${h5.category} --operation read`]}function p5($,Z,X){let J=`${vB[$]} (${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 IZ($,Z){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}). Run Connect again to send a new request.`};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 u5=`${String.fromCharCode(27)}\\[[0-9;]*m`,gK=new RegExp(u5,"g"),hK=new RegExp(`^${u5}`);function K$($){return $.authority!=="local"}async function n0($){return{authority:await $.authority(),status:await $.status(),identities:$.identities(),routes:new Set($.routes().map((Z)=>Z.id))}}async function c5($){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."),F3)})])}finally{clearTimeout(Z)}}function M1($){return $.email||$.label||$.routeId}var xZ="Accounts are managed in the vault with ck. Disconnect to use local accounts.",n$="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";var E0="main";function O3($){return $.find((Z)=>Z.id.startsWith("vault:")&&Z.credentialId==="chatgpt:openai")?.id??null}function a5($,Z,X){let J=new Map;if(TZ(Z))for(let z of $)J.set(z.id,S5(j$(z.quota),Z,z.id===E0?void 0:z.id,X));return J}var i5=5,kZ=5000;function n5($){if($==="ordered")return"roster";return $==="fallback-first"?"fallback-first":"main-first"}function r5($,Z=kZ){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(I0({rows:$.rows,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}}).admitted.some((B)=>$.killswitch.get(B.id)!==!1))return;let z=[];if(I0({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 eB($,Z){if(!h0($))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 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(C1(Y,Z.now))return!1;return eB(Y.credits,Z.now)}).map((H)=>H.id);return{free:z,credits:B}}function $H($,Z=$.rows){return I0({rows:Z,now:$.now,rateLimitMarks:$.rateLimitMarks,refreshBackoff:$.refreshBackoff,requestPull:()=>{}})}class fZ{#$=new Set;served($,Z,X){let J=$H($),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 o5($,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 s5($,Z,X){if(Z.refused.find((z)=>!L3(z)&&X.get(z.id)!==!1))return{reason:"quota-unknown"};return o5($[0],Z,X)}function t5($){let Z=$.replayable!==!1,X=$.mainId===void 0?E0:$.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=l1($.rows.map((W)=>W.id),J,X),B=new Set(z.admission.refused.filter((W)=>L3(W)&&$.killswitch.get(W.id)!==!1).map((W)=>W.id)),H=G.filter((W)=>B.has(W)),Y=P3($.rows,$,z.admission),Q=z.order.filter((W)=>Y.free.has(W)),V=G.filter((W)=>Y.credits.includes(W));if(!Z){let W=G.includes(X),U=W?X:Q[0]??V[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&&V.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:W?o5(X,z.admission,$.killswitch):s5(G,z.admission,$.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(V.length>0){let W=z.order.length>0?z.order:H;return{kind:"send",order:[...V,...W.filter((U)=>!V.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:s5(G,z.admission,$.killswitch)}}function yZ($){let Z=I0({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 e5($,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 $7($,Z,X,J){let z=e5($,Z,{exclude:X,pendingBytes:J}),G=$.rows.filter((V)=>!X.has(V.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((V)=>V.id===Y)?.quota).checkedAt;return{accountId:Y,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function Z7($,Z,X){let J=$.killswitch.get(X)===!1,z={kind:"move",reason:J?"killswitch":"exhausted"},G=e5($,Z,{pin:X}),B=P3($.rows,$,G.admission),H=B.credits.includes(X),Y=B.credits.some((W)=>W!==X);if(G.outcome==="dispatch"){let W=!B.free.has(G.accountId);if(G.pin.action==="assign"){if(W&&H)return{kind:"serve"};return z}if(G.accountId!==X)return{kind:"detour"};if(W&&Y)return z;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===X),V=J||Q!==void 0&&L3(Q);if(H)return{kind:"serve"};if(Y)return V?z:{kind:"detour"};if(!J&&Q&&L3(Q))return{kind:"last-path"};return{kind:"none"}}function X7($,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 J7($){return J0($)?{...$}:{}}function gZ($,Z){let X=$0(Z)?M$(Z.credits):void 0;return X?`${$} · prepaid ${X}`:$}function z7($,Z){return{...$,sections:$.sections.map((X)=>X.id!=="quota"?X:{...X,items:X.items.map((J)=>J.detail===void 0?J:{...J,detail:gZ(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 hZ($,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 n0(Z);if(!K$(H))return B;let Y=[...H.status.accounts.map((Q)=>({id:Q.routeId,label:M1(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 n0(Z),H=J7(G.settings.killswitch);if(!K$(B)||!G.settings.killswitch)return G;let Y=J7(H.accounts);for(let Q of B.status.accounts)Y[Q.routeId]=N1({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 vZ($,Z,X={}){let J=R1($),z=(Q)=>R1({command:$.command,title:$.title,store:hZ($.store,Z),accounts:$.accounts,quota:$.quota,limits:$.limits,routing:{...$.routing,formerMainId:Q??""},...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.now?{now:$.now}:{}}),G=async(Q,V)=>{let W=await n0(Z),U=K$(W),K=O3(W.status.accounts.map((A)=>({id:A.routeId,credentialId:A.credentialId}))),j=U?z(K):J,D=(await j.open(V)).menu.sections.find((A)=>A.id===Q);if(!D)throw new H0("unavailable","The account menu is unavailable.");if(!U)return{lines:D.lines,items:D.items.map((A)=>({...A,actions:A.actions.map((b)=>C3(j,Q,b,A.id))})),actions:D.actions.map((A)=>C3(j,Q,A))};let M=new Map(W.status.accounts.map((A)=>[A.routeId,A])),O=($.now??Date.now)(),R=(A)=>({id:"check",label:A?"Check this account":"Check now",group:"Actions",run:async()=>{let w=[...(await n0(Z)).routes].filter((f)=>!A||f===A);if(A&&w.length===0)throw new H0("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 H0("quota-check-failed",`${f}: ${y.error??"vault unavailable"}`)}return`Checked quota for ${w.length} account${w.length===1?"":"s"}.`}});if(Q==="quota"){let A=(b,w)=>P0(s(b.quota,$.quota?.scope),{now:O,form:w});return{lines:W.status.accounts.filter((b)=>!W.routes.has(b.routeId)).map((b)=>`${M1(b)} (${b.enabled?b.state:"disabled"}): ${gZ(A(b,"compact"),b.quota)}`),items:W.status.accounts.filter((b)=>W.routes.has(b.routeId)).map((b)=>({id:b.routeId,label:M1(b),group:"Accounts",status:A(b,"compact"),detail:gZ(A(b,"full"),b.quota),actions:[R(b.routeId)]})),actions:W.routes.size>0?[R()]:[]}}let F=D.items.map((A)=>{let b=M.get(A.id),w=b&&Q==="accounts"?`Vault · ${b.credentialType==="oauth"?"login":"API key"} · ${b.state} · ${b.enabled?"enabled":"declined"}`:A.detail;return{id:A.id,label:A.label,detail:w,group:A.group,status:b&&Q==="accounts"?b.enabled?b.state:"disabled":A.status,...A.facts?{facts:A.facts}:{},actions:b&&Q!=="limits"?[]:A.actions.map((f)=>C3(j,Q,f,A.id))}}),q=D.actions.filter((A)=>Q==="limits"||Q==="routing"&&A.id==="mode").map((A)=>C3(j,Q,A)),_=D.actions.find((A)=>A.id==="mode")?.knobs.find((A)=>A.id==="mode"),S=Q==="routing"&&K===null&&_?.kind==="choice"&&(_.value==="main-first"||_.value==="fallback-first");return{lines:Q==="accounts"?[`${W.status.accounts.length} vault account${W.status.accounts.length===1?"":"s"}`,`${W.routes.size} can route`,xZ]:[...D.lines,...S?["No default vault account, so this mode orders like Ordered"]:[]],items:F,actions:q}},B=R1({...$,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(V)=>{let W=await n0(Z);if(K$(W))return{lines:[xZ]};return Q.build(V)}})}),H=async()=>{if(!K$(await n0(Z)))return{menu:J,error:void 0};let Q=X.refresh===!1?void 0:await c5(Z);return{menu:B,error:Q}},Y=async(Q,V)=>{let W=await Q.menu.open(V);if(Q.error)W.menu.sections.find((K)=>K.id==="vault")?.lines.push(`Last error: ${Q.error}`);return W};return{command:$.command,open:async(Q)=>Y(await H(),Q),apply:async(Q,V)=>{let W=await H(),{menu:U}=W;if(U===B&&(Q.sectionId==="accounts"||Q.sectionId==="routing"&&Q.actionId==="order"||Q.sectionId==="reset"||Q.sectionId==="quota"&&(await n0(Z)).routes.size===0||Q.sectionId==="limits"&&Q.itemId!==void 0&&!(await n0(Z)).status.accounts.some((K)=>K.routeId===Q.itemId)))return{...await Y(W,V),ok:!1,code:"vault-local-action",text:n$};if(X.refuseApply)return{...await Y(W,V),ok:!1,...X.refuseApply};return U.apply(Q,V)}}}var F1="openai",uZ="OpenAI accounts",h1="main",B7="that account is already your main account, so it was not added again",r$=d("commands"),H7=new Set(["__proto__","constructor","prototype"]);function Y7($,Z){let X={version:1,accounts:[],killswitch:$},J=J0($.accounts)?Object.keys($.accounts):[],z={};for(let H of new Set([h1,...Z,...J])){if(H7.has(H))continue;let Y=N1(X,H===h1?void 0:H);z[H]={primary:Y.primary,secondary:Y.secondary}}let G=N1(X,void 0),B={...$};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=V$,B}function Q7($,Z){let X=J0($.accounts)?{...$.accounts}:{};for(let z of new Set([h1,...Z])){if(H7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:q1.primary,secondary:q1.secondary}}let J=J0($.defaults)?$.defaults:{primary:q1.primary,secondary:q1.secondary};return{...$,accounts:X,defaults:J,schema:V$}}function mZ($,Z){let X=!1;if(J0($.cachekeep))$.cacheKeep={...$.cachekeep,...J0($.cacheKeep)?$.cacheKeep:{}},delete $.cachekeep,X=!0;let J=$.killswitch;if(J0(J)&&J.schema!==V$)$.killswitch=Y7(J,Z),X=!0;return X}async function G7($){let Z=await $.read();return Z.status==="ready"?Z.rows.map((X)=>X.id):[]}function W7($){let Z=async()=>{let J=await $.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return mZ(z,await G7($)),{...J,settings:z}},X=async(J,z)=>{let G=await G7($);return $.updateSettings(async(B)=>{mZ(B,G);let H=await J(B)??B;if(J0(H.killswitch)&&H.killswitch.schema!==V$)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 V7($,Z){let X=(Y,Q)=>Z.rowLocks?Z.rowLocks(Y):Q,J=(Y,Q)=>{let V=X(Y,Q?.extraLocks);return{...Q??{},...V?{extraLocks:V}:{}}},z=(Y,Q,V,W)=>$.replace(Y,Q,V,J(Y,W)),H={add:async(Y,Q)=>{let V=await $.read(),U=(V.status==="ready"?V.rows:[]).filter((D)=>D.type==="oauth"&&!D.invalid),K=Y.identity?U.find((D)=>D.identity===Y.identity):void 0;if(K?.id===h1)throw new H0("main-account",B7);let j=K??U.find((D)=>D.id===Y.id&&D.id!==h1);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,V)=>$.disable(Y,Q,J(Y,V)),remove:(Y,Q)=>$.remove(Y,J(Y,Q))};return new Proxy($,{get(Y,Q){if(Object.hasOwn(H,Q))return H[Q];let V=Reflect.get(Y,Q,Y);return typeof V==="function"?V.bind(Y):V}})}var U7="migration";function wZ($){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:F1,title:uZ,sections:[{id:U7,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 pZ(X)}var ZH=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function XH($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(ZH.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(!J0($))return $;let J={};for(let[z,G]of Object.entries($)){if(XH(z)){X.push(`${Z}.${z}`);continue}J[z]=T3(G,`${Z}.${z}`,X)}return J}function pZ($){let Z=[],X=T3($,"menu",Z);if(Z.length>0)r$.warn("credential-shaped field stripped before RPC",{fields:Z});return X}function j7($){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 K7($,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.`,
|
|
112
|
-
`)}}}]}}}}var
|
|
113
|
-
`,r:"\r",t:"\t"}[J]??J??Z})}function RQ($,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 H=0;H<X.length;H++){let Y=X[H]??"";if(!/\s/.test(Y))G.push(H)}let Q=[],B=0;for(let H=z.indexOf(J);H>=0;H=z.indexOf(J,H+J.length)){let Y=G[H]??B,W=(G[H+J.length-1]??Y)+1;Q.push(X.slice(B,Y),"[credential]"),B=W}return Q.length?Q.join("")+X.slice(B):X}function $5($,Z){let X=RQ($,Z);return i8(X).replaceAll("***REDACTED***","[credential]")}function K1($,Z){let X=$5($,Z),J=J5(X),z=$5(J,Z);return z===J?X:z}function Z5($){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 Q=Z[4]??"0",B=Q.startsWith("-")||Q.startsWith("+")?1:0;while(Q[B]==="0")B++;let H=Q.slice(B)||"0";if(H.length>16)return;let Y=BigInt((Q.startsWith("-")?"-":"")+H)-BigInt(X.length)+BigInt(J.length-G);return`${Z[1]}${J.slice(z,G)}e${Y}`}function z5($,Z){let X=Z?Z5(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&&Z5(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let z=J5(J.slice(1,-1)),G=K1(z,Z);return G===z?J:JSON.stringify(G)})}function y4($,Z){let X=z5($,Z);try{return JSON.parse($),X}catch{return K1(X,Z)}}var EQ=16384,IQ=65536,bQ=[/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 xQ($){try{let Z=e(JSON.parse($),"request_id");if(typeof Z==="string")return Z;if(typeof Z!=="number")return;let X=0,J,z=!0,G=!1,Q;for(let B of $.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let H=B[0];if(H==="{"||H==="["){X++;continue}if(H==="}"||H==="]"){X--;continue}if(X!==1)continue;if(H===","){z=!0,G=!1,J=void 0;continue}if(H===":"){G=!0;continue}if(z&&H.startsWith('"')){J=JSON.parse(H),z=!1;continue}if(G&&J==="request_id"&&!H.startsWith('"'))Q=H;G=!1}return Q}catch{return}}function kQ($,Z){let X=y4($,Z);if(Buffer.byteLength(X,"utf8")<=IQ)return X;let J=bQ.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(e(G,"type")==="error")z.type="error";let Q=e(G,"error"),B={};for(let Y of["code","type"]){let W=e(Q,Y);if(typeof W==="string")B[Y]=W.slice(0,256)}if(Object.keys(B).length)z.error=B;let H={};for(let Y of["workspace","limitName"]){let W=e(e(G,"metadata"),Y);if(typeof W==="string")H[Y]=W.slice(0,256)}if(Object.keys(H).length)z.metadata=H}catch{}return JSON.stringify(z)}function K3($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(TQ.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function e($,Z){if(!K3($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function l$($,Z){return K1($,Z).slice(0,EQ)}function H$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var fQ=H$(DOMException.prototype,"message"),yQ=H$(DOMException.prototype,"name");function D1($,Z){let X=e($,"message"),J=e($,"name");if(K3($)&&$ instanceof DOMException)try{X=fQ.call($),J=yQ.call($)}catch{}let z=Error(l$(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"?l$(J,Z):"Error",configurable:!0,writable:!0});let G=(V,j,K)=>{let U=e(V,K);if(typeof U==="string"||typeof U==="number"&&Number.isFinite(U)||typeof U==="boolean")Object.defineProperty(j,K,{value:typeof U==="string"?l$(U,Z):U,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=e($,V);if(typeof j==="number"&&Number.isFinite(j))G($,z,V)}for(let V of["code","type","isRetryable"])G($,z,V);for(let V of["error","data"]){let j=e($,V),K=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])G(j,K,N);let U=e(j,"error");if(K3(U)){let N=Object.create(null);for(let D of["type","code","message","resets_at","resets_in_seconds"])G(U,N,D);K.error=N}if(Object.keys(K).length)Object.defineProperty(z,V,{value:K,enumerable:!0})}let Q=e($,"responseHeaders");if(Q&&typeof Q==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let K=e(Q,j);if(typeof K==="string")V[j]=l$(K,Z)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let B=e($,"responseBody");if(typeof B==="string")Object.defineProperty(z,"responseBody",{value:kQ(B,Z),enumerable:!0});let H=e($,"request_id"),Y=e(Q,"x-request-id"),W=typeof H==="string"?H:typeof Y==="string"?Y:typeof B==="string"?xQ(y4(B,Z)):void 0;if(typeof W==="string")Object.defineProperty(z,"request_id",{value:l$(W,Z),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(e($,j)===!0)Object.defineProperty(z,j,{value:!0})}return z}function gQ($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!AQ.test($)&&!SQ.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return z5($,Z);return $}var hQ=H$(Response.prototype,"status"),vQ=H$(Response.prototype,"statusText"),mQ=H$(Response.prototype,"headers"),wQ=H$(Response.prototype,"body"),pQ=Response.prototype.text,X5=Headers.prototype.entries;async function G5($,Z,X="http"){try{let K=function(U){let N=j&&U.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,N+U.slice(N.length).replace(/^data: ?([^\r\n]*)/gm,(D,M)=>D.slice(0,D.length-M.length)+gQ(M,Z))};if(!K3($))throw Error("Invalid provider response");let J=hQ.call($),z=mQ.call($),G=wQ.call($),Q=new Headers;for(let[U,N]of X5.call(z))Q.append(U,N);let B={status:J,statusText:K1(vQ.call($),Z),headers:Q};if(J<200||J>299){for(let[N,D]of X5.call(z)){if(K1(N,Z?.toLowerCase())!==N){B.headers.delete(N);continue}try{B.headers.set(N,K1(D,Z))}catch{B.headers.delete(N)}}B.headers.delete("content-length");let U=await pQ.call($);return new Response(y4(U,Z),B)}if(!G||X==="http")return $;B.headers.delete("content-length");let H=ReadableStream.prototype.getReader.call(G),Y=new TextDecoder("utf-8",{ignoreBOM:!0}),W=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(U){try{for(;;){let N=await H.read();V+=Y.decode(N.value,{stream:!N.done});let D=!1;for(;;){let M=/\r?\n\r?\n/.exec(V);if(!M)break;let P=M.index+M[0].length;U.enqueue(W.encode(K(V.slice(0,P)))),V=V.slice(P),D=!0}if(N.done){if(V)U.enqueue(W.encode(K(V)));U.close();return}if(D)return}}catch(N){U.error(D1(N,Z))}},async cancel(U){try{await H.cancel(U)}catch(N){throw D1(N,Z)}finally{H.releaseLock()}}}),B)}catch(J){throw D1(J,Z)}}var Q5={name:"@cortexkit/pi-openai-auth",version:"1.3.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.21.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.12.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 D3=new Map;function B5($){return D3.get($)?.accountId}function H5($){return D3.delete($)}function Y5($){return i7(D3,$,(Z,X)=>D3.set(Z,X))}import{join as L5}from"node:path";import{createHash as rQ}from"node:crypto";import{constants as j5}from"node:fs";import{lstat as M5,mkdir as K5,open as F5,unlink as oQ}from"node:fs/promises";import{dirname as Y$,resolve as D5}from"node:path";import{setTimeout as tQ}from"node:timers/promises";import{rmdirSync as lQ,statSync as V5,utimesSync as dQ}from"node:fs";import{mkdir as cQ,rmdir as sQ,stat as g4,utimes as iQ}from"node:fs/promises";var aQ=30000,q3=1e4,nQ=3000,h4,d$=new Map;process.once("exit",()=>{for(let[$,Z]of d$)try{if(Z.renewedAt+q3<Date.now())continue;let X=V5($);if(v4(X,Z)&&X.mtime.getTime()===Z.mtime)lQ($)}catch{}});function v4($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function c$($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function W5(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function m4($){try{await sQ($)}catch(Z){if(c$(Z)!=="ENOENT")throw Z}}async function w4($,Z){try{await cQ($)}catch(X){if(c$(X)!=="EEXIST")throw X;if(Z<=0)throw W5();let J;try{J=(await g4($)).mtime.getTime()}catch(z){if(c$(z)==="ENOENT")return w4($,0);throw z}if(!(J<Date.now()-Z))throw W5();return await m4($),w4($,0)}try{if(!h4){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await iQ($,z,z)}let X=await g4($),J=X.mtime.getTime();return h4??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await m4($).catch(()=>{}),X}}async function U5($,Z,X){let J=`${$}.lock`,z=await w4(J,aQ),G=z.mtime,Q=Date.now(),B=!1,H;d$.set(J,{...z,renewedAt:Q});function Y(){if(B=!0,H)clearTimeout(H);d$.delete(J),Z()}function W(){if(!B&&Q+q3<Date.now())Y()}function V(U=nQ){if(B)return;H=setTimeout(()=>{K()},U),H.unref()}function j(U){if(B)return;if(c$(U)==="ENOENT"||Q+q3<Date.now())Y();else V(1000)}async function K(){if(W(),B)return;let U;try{U=V5(J)}catch(D){j(D);return}if(W(),B)return;if(!v4(U,z)||U.mtime.getTime()!==G){Y();return}let N=new Date(h4==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{dQ(J,N,N)}catch(D){j(D);return}if(W(),B)return;G=N.getTime(),Q=Date.now(),d$.set(J,{...z,mtime:G,renewedAt:Q}),V()}return X?.(async()=>{if(H)clearTimeout(H);await K()}),V(),{assertFresh:W,async release(){if(B)return;if(B=!0,H)clearTimeout(H);d$.delete(J);let U=()=>Q+q3<Date.now();if(U()){Y();return}let N;try{N=await g4(J)}catch(D){if(c$(D)!=="ENOENT")throw D;Y();return}if(U()||!v4(N,z)||G!==N.mtime.getTime()){Y();return}await m4(J)}}}class a extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function eQ($){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 Q=JSON.parse($.slice(G,Z));J(),Z++,J();let B=Z,H=0;while(Z<$.length){let W=$[Z];if(W==='"'){z();continue}if(W==="{"||W==="[")H++;if(W==="}"||W==="]"){if(H===0)break;H--}if(W===","&&H===0)break;Z++}let Y=Z;while(/\s/.test($[Y-1]??""))Y--;if(X.children.push({key:Q,offset:G,length:Y-G,value:{offset:B,length:Y-B}}),J(),$[Z]==="}")break;Z++,J()}return X}function i$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function u4($){if(Array.isArray($))return`[${$.map(u4).join(",")}]`;if(i$($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${u4($[Z])}`).join(",")}}`;return JSON.stringify($)}function y0($){return rQ("sha256").update(u4($)).digest("hex")}function s$($){return i$($)?$.code:void 0}async function q5($,Z=!1,X){if(I)try{await X?.($);let z=await h3($,!0),G=z.toString("utf8");if(!z.equals(Buffer.from(G)))throw new a(Z?"invalid-stash":"invalid-auth");return G}catch(z){if(s$(z)==="ENOENT")return;throw z}let J;try{J=await F5($,j5.O_RDONLY|j5.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new a("unsafe-path");await X?.($);let G=await M5($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new a("unsafe-path");let Q=await J.readFile(),B=Q.toString("utf8");if(!Q.equals(Buffer.from(B)))throw new a(Z?"invalid-stash":"invalid-auth");return B}catch(z){if(s$(z)==="ENOENT"&&!J)return;if(s$(z)==="ELOOP"||s$(z)==="ENOENT")throw new a("unsafe-path");throw z}finally{await J?.close()}}function $B($,Z){try{let X=JSON.parse($);if(!i$(X))throw Error();let J=eQ($),z=J.children,G=z.map((H)=>H.key);if(new Set(G).size!==G.length)throw Error();let Q=z.find((H)=>H.key===Z),B=Q?X[Z]:null;if(B!==null&&!i$(B))throw Error();if(Q&&B===null)throw Error();return{text:$,root:J,property:Q,entry:B}}catch{throw new a("invalid-auth")}}function ZB($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function N5($,Z,X){let{text:J,root:z,property:G}=$,Q=z.children??[];if(G){let Y=G.value;if(!Y)throw new a("invalid-auth");if(X!==null)return J.slice(0,Y.offset)+X+J.slice(Y.offset+Y.length);let W=Q.indexOf(G),V=Q[W-1],j=Q[W+1],K=V?V.offset+V.length:G.offset,U=!V&&j?j.offset:G.offset+G.length;return J.slice(0,K)+J.slice(U)}if(X===null)return J;let B=Q.at(-1),H=B?B.offset+B.length:z.offset+1;return`${J.slice(0,H)}${B?",":""}${JSON.stringify(Z)}:${X}${J.slice(H)}`}async function XB($){if(I)return;let Z=await F5($,"r");try{await Z.sync()}finally{await Z.close()}}async function p4($,Z,X,J){await F0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function l4($){return JB($)}function JB($,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 a("invalid-options");let Q=D5($.authPath),B=D5($.stashPath);if(Q===B||B===`${Q}.lock`)throw new a("invalid-options");let H=y0(Q),Y=y0(z),W={type:"api_key",key:z},V=(D)=>y0(D)===y0(W);async function j(){let D=await q5(B,!0,X?.afterReadCheck);if(D===void 0)return;try{let M=JSON.parse(D);if(M.version!==1||M.provider!==J||M.authIdentity!==H||M.placeholderIdentity!==Y||M.entry!==null&&!i$(M.entry)||M.sha256!==y0(M.entry)||(M.entry===null?M.entryJson!==null:typeof M.entryJson!=="string"||y0(JSON.parse(M.entryJson))!==M.sha256))throw Error();return M}catch{throw new a("invalid-stash")}}async function K(D){let M,P,E=!1,F=()=>{if(P?.(),E)throw new a("lock-compromised")};try{if(I)await D0(Y$(Q));else await K5(Y$(Q),{recursive:!0,mode:448});let q=Date.now()+G,L=0;while(!M)try{let A=await U5(Q,()=>{E=!0},X?.onRenew);M=A.release,P=A.assertFresh}catch(A){if(s$(A)!=="ELOCKED")throw A;let x=q-Date.now();if(x<=0)throw new a("lock-timeout");await tQ(Math.min(Math.round(Math.min(10*2**L++,1000)*(1+Math.random())),x))}F();let S=await D(F);return F(),S}catch(q){if(q instanceof a||q instanceof d)throw q;throw new a("io")}finally{await M?.().catch(()=>{}),F()}}async function U(){let D=$B(await q5(Q,!1,X?.afterReadCheck)??"{}",J),M=await j();return{auth:D,stash:M}}async function N(D){D(),await oQ(B),await XB(Y$(B)),Z?.("stash-deleted")}return{inspect:()=>K(async()=>{let{auth:D,stash:M}=await U();return{slot:V(D.entry)?"placeholder":D.entry===null?"empty":!M||y0(D.entry)===M.sha256?"original":"foreign",stash:M?"valid":"missing"}}),enterVault:()=>K(async(D)=>{let{auth:M,stash:P}=await U();if(V(M.entry)){if(!P)throw new a("missing-stash");return}if(P&&y0(M.entry)!==P.sha256)throw new a("conflict");if(!P){if(I)await D0(Y$(B));else{await K5(Y$(B),{recursive:!0,mode:448});let F=await M5(Y$(B));if(!F.isDirectory()||(F.mode&511)!==448)throw new a("unsafe-path")}let E={version:1,provider:J,authIdentity:H,placeholderIdentity:Y,entry:M.entry,entryJson:ZB(M),sha256:y0(M.entry)};await p4(B,JSON.stringify(E),D,X?.beforeRename),Z?.("stash-written")}await p4(Q,N5(M,J,JSON.stringify(W)),D,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>K(async(D)=>{let{auth:M,stash:P}=await U();if(!P){if(V(M.entry))throw new a("missing-stash");return"nothing-to-do"}if(V(M.entry))await p4(Q,N5(M,J,P.entryJson),D,X?.beforeRename),Z?.("auth-written");else if(y0(M.entry)!==P.sha256)return"conflict";return await N(D),"restored"})}}import{getAgentDir as zB}from"@earendil-works/pi-coding-agent";var a$="openai-auth-vault-mode-not-a-credential",_5="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.",O5="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function C5($){return l4({authPath:L5(zB(),"auth.json"),provider:"openai-codex",stashPath:L5(H3($),"pi-openai-codex-login.json"),placeholderKey:a$})}function GB($){return{id:"pi-login",title:"Pi login",build:()=>{let Z=$(),X=Date.now(),J=i({limits:["primary","secondary"].flatMap((G)=>{let Q=Z?.[G];return Q?[{...Q,kind:"reading",scope:"all",label:G,checkedAt:Q.checkedAt??X}]:[]}),...Z?.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:X}}:{}}),z=g1(J,{now:X});return{lines:["Managed by Pi /login",...z.length>0?z:[C0(J,{now:X})]]}}}}function QB($,Z={}){let X=Z.beginAccountLogin??$9,J=Z.packageVersion??Q5.version,z=b4({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=x4({store:$.store(),vault:$.vault,login:{begin:(Q)=>X({...Q,version:J}),mainIdentity:async()=>$.mainIdentity()},quotaCheck:async(Q)=>{if(Q.length===1){let H=$.store();for(let Y of Q)await H.requestReading(Y);await H.pullsSettled();return}let B=(await $.refreshAllQuota()).filter((H)=>!H.ok);if(B.length>0)throw new Q0("quota-check-failed",B.map((H)=>`${H.account}: ${H.error??"quota check failed"}`).join(`
|
|
114
|
-
`))},extras:[
|
|
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.`,...
|
|
116
|
-
`)}},
|
|
111
|
+
The account is added when you finish.`,H=G.completion.then(async(Y)=>{if(Z&&await Z.authority()!=="local")throw new H0("vault-local-action",n$);let Q=await $.mainIdentity?.();if(Y.id===h1||Y.accountId&&Q&&Y.accountId===Q)throw r$.warn("account add rejected (main identity)",{id:Y.id}),new H0("main-account",B7);return r$.info("account added",{id:Y.id}),j7(Y)});return{status:"pending",message:B,completion:H}}}}function lZ($){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 dZ($){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}`,p5(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:M1(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?.(),`${M1(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await Z.accept(G.routeId),await $.changed?.(),`${M1(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?.(),IZ(Z,B);return Z.waitForApproval($.wait).then(async(H)=>{await $.changed?.();let Y=IZ(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 D7=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],q7=["primary","secondary"];function cZ($){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")},V=J.findIndex((W)=>W.id==="reset");if(V<0)J.unshift(Q);else J[V]=Q}let z={command:F1,title:uZ,store:hZ(W7(V7($.store,{...$.rowLocks?{rowLocks:$.rowLocks}:{}}))),...$.extraLocks?{extraLocks:$.extraLocks}:{},accounts:{...$.login?{login:K7($.login,$.vault)}:{},...$.protect?{protect:$.protect}:{},...$.describeIdentity?{describeIdentity:$.describeIdentity}:{}},quota:$.quotaCheck?{check:$.quotaCheck}:{},routing:{orderedVariants:D7,formerMainId:h1},limits:{labels:q7},...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?vZ(z,$.vault,{refresh:!$.readOnly,...$.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):R1(z),B=$.vault?vZ(z,$.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,H=(Q)=>{let{sessionId:V}=Q,W=Q.notify.bind(Q);return{...V!==void 0?{sessionId:V}:{},notify:W}},Y=async(Q)=>{if($.vault&&await $.vault.authority()!=="local")return Q;let V=await $.store.read().catch(()=>{return});if(V?.status!=="ready")return Q;return{...Q,menu:z7(Q.menu,new Map(V.rows.map((W)=>[W.id,W.quota])))}};return{command:F1,async open(Q){let V=H(Q),W=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(W&&!W.migrated)return{command:F1,menu:wZ(W.blockers)};let U=await G.open(V);return Y({...U,menu:pZ(U.menu)})},async apply(Q,V){let W=H(V),U=$.vault&&await $.vault.authority()!=="local"?void 0:await $.migration?.();if(U&&!U.migrated)return{command:F1,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:wZ(U.blockers)};if($.readOnly&&$.vault)return G.apply(Q,W);if($.readOnly||$.allowAction&&!$.allowAction(Q)||Z.has(Q.sectionId)){if(B)return B.apply(Q,W);return{...await G.open(W),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let K=await G.apply(Q,W);if(K.ok)await $.afterApply?.();return Y({...K,menu:pZ(K.menu)})}}}function N7($,Z,X){let J=$.get(Z.sessionId),z=new Set(Z.validPinnedAccountIds);if(J&&!Z.excludeAccountIds.includes(J.accountId)&&F$(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 JH}from"node:fs";var M7=30000,zH=8,GH=1800000;function F7($){return $.identity?`identity:${$.identity}`:`row:${$.id}`}function sZ($){try{let Z=JH($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}`}catch{return"-"}}function v1($){let Z=$.credential;if(Z?.type!=="oauth")return;return{access:Z.access??"",expires:Z.expires,refresh:Z.refresh}}function aZ($,Z){try{return v0($,Z)}catch{return $}}function _7($,Z,X){let J=F7(Z);$.set(J,[...$.get(J)??[],{credentialEpoch:Z.credentialEpoch,identity:Z.identity,observation:X}].slice(-zH))}function L7($,Z,X){let J=$;for(let z of Z.get(F7($))??[]){if(!(X-z.observation.checkedAt<=GH)||z.credentialEpoch!==$.credentialEpoch||z.identity!==$.identity)continue;J={...J,quota:aZ(J.quota,z.observation)}}return J}function O7($,Z,X,J){let z=X$($);if(typeof Z?.status==="number"||I4(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+M7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function P7($,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+M7)}return z}var hq=d("quota");import{types as BH}from"node:util";var HH=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,YH=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function S7($){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 QH($,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,V=(G[Y+J.length-1]??Q)+1;B.push(X.slice(H,Q),"[credential]"),H=V}return B.length?B.join("")+X.slice(H):X}function C7($,Z){let X=QH($,Z);return G9(X).replaceAll("***REDACTED***","[credential]")}function _1($,Z){let X=C7($,Z),J=S7(X),z=C7(J,Z);return z===J?X:z}function T7($){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 R7($,Z){let X=Z?T7(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&&T7(J)===X||(Z==="Infinity"||Z==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===Z)?'"[credential]"':J;let z=S7(J.slice(1,-1)),G=_1(z,Z);return G===z?J:JSON.stringify(G)})}function iZ($,Z){let X=R7($,Z);try{return JSON.parse($),X}catch{return _1(X,Z)}}var WH=16384,VH=65536,UH=[/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 jH($){try{let Z=e(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 KH($,Z){let X=iZ($,Z);if(Buffer.byteLength(X,"utf8")<=VH)return X;let J=UH.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(e(G,"type")==="error")z.type="error";let B=e(G,"error"),H={};for(let Q of["code","type"]){let V=e(B,Q);if(typeof V==="string")H[Q]=V.slice(0,256)}if(Object.keys(H).length)z.error=H;let Y={};for(let Q of["workspace","limitName"]){let V=e(e(G,"metadata"),Q);if(typeof V==="string")Y[Q]=V.slice(0,256)}if(Object.keys(Y).length)z.metadata=Y}catch{}return JSON.stringify(z)}function A3($){if(!$||typeof $!=="object")return!1;let Z=$;for(let X=0;Z&&X<16;X++){if(BH.isProxy(Z))return!1;Z=Object.getPrototypeOf(Z)}return Z===null}function e($,Z){if(!A3($))return;let X=Object.getOwnPropertyDescriptor($,Z);return X&&"value"in X?X.value:void 0}function o$($,Z){return _1($,Z).slice(0,WH)}function D$($,Z){let X=Object.getOwnPropertyDescriptor($,Z)?.get;if(!X)throw Error(`Missing native ${Z} accessor`);return X}var DH=D$(DOMException.prototype,"message"),qH=D$(DOMException.prototype,"name");function L1($,Z){let X=e($,"message"),J=e($,"name");if(A3($)&&$ instanceof DOMException)try{X=DH.call($),J=qH.call($)}catch{}let z=Error(o$(typeof X==="string"?X:typeof $==="string"?$:"Provider request failed",Z));for(let W of Object.getOwnPropertyNames(z))if(W!=="message")Reflect.deleteProperty(z,W);Object.defineProperty(z,"name",{value:typeof J==="string"?o$(J,Z):"Error",configurable:!0,writable:!0});let G=(W,U,K)=>{let j=e(W,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 W of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let U=e($,W);if(typeof U==="number"&&Number.isFinite(U))G($,z,W)}for(let W of["code","type","isRetryable"])G($,z,W);for(let W of["error","data"]){let U=e($,W),K=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])G(U,K,N);let j=e(U,"error");if(A3(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,W,{value:K,enumerable:!0})}let B=e($,"responseHeaders");if(B&&typeof B==="object"){let W={};for(let U of["retry-after-ms","retry-after"]){let K=e(B,U);if(typeof K==="string")W[U]=o$(K,Z)}Object.defineProperty(z,"responseHeaders",{value:W,enumerable:!0})}let H=e($,"responseBody");if(typeof H==="string")Object.defineProperty(z,"responseBody",{value:KH(H,Z),enumerable:!0});let Y=e($,"request_id"),Q=e(B,"x-request-id"),V=typeof Y==="string"?Y:typeof Q==="string"?Q:typeof H==="string"?jH(iZ(H,Z)):void 0;if(typeof V==="string")Object.defineProperty(z,"request_id",{value:o$(V,Z),enumerable:!0});for(let W of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let U=Symbol.for(W);if(e($,U)===!0)Object.defineProperty(z,U,{value:!0})}return z}function NH($,Z){if(!$.includes("error")&&(!$.includes("\\u00")||!HH.test($)&&!YH.test($)))return $;let X;try{X=JSON.parse($)}catch{return $}if(X?.type==="error"||X?.error||X?.response?.error)return R7($,Z);return $}var MH=D$(Response.prototype,"status"),FH=D$(Response.prototype,"statusText"),_H=D$(Response.prototype,"headers"),LH=D$(Response.prototype,"body"),OH=Response.prototype.text,A7=Headers.prototype.entries;async function E7($,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,M)=>D.slice(0,D.length-M.length)+NH(M,Z))};if(!A3($))throw Error("Invalid provider response");let J=MH.call($),z=_H.call($),G=LH.call($),B=new Headers;for(let[j,N]of A7.call(z))B.append(j,N);let H={status:J,statusText:_1(FH.call($),Z),headers:B};if(J<200||J>299){for(let[N,D]of A7.call(z)){if(_1(N,Z?.toLowerCase())!==N){H.headers.delete(N);continue}try{H.headers.set(N,_1(D,Z))}catch{H.headers.delete(N)}}H.headers.delete("content-length");let j=await OH.call($);return new Response(iZ(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}),V=new TextEncoder,W="",U=!0;return new Response(new ReadableStream({async pull(j){try{for(;;){let N=await Y.read();W+=Q.decode(N.value,{stream:!N.done});let D=!1;for(;;){let M=/\r?\n\r?\n/.exec(W);if(!M)break;let O=M.index+M[0].length;j.enqueue(V.encode(K(W.slice(0,O)))),W=W.slice(O),D=!0}if(N.done){if(W)j.enqueue(V.encode(K(W)));j.close();return}if(D)return}}catch(N){j.error(L1(N,Z))}},async cancel(j){try{await Y.cancel(j)}catch(N){throw L1(N,Z)}finally{Y.releaseLock()}}}),H)}catch(J){throw L1(J,Z)}}var I7={name:"@cortexkit/pi-openai-auth",version:"1.4.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.23.0","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.12.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 S3=new Map;function b7($){return S3.get($)?.accountId}function x7($){return S3.delete($)}function k7($){return N7(S3,$,(Z,X)=>S3.set(Z,X))}import{join as d7}from"node:path";import{createHash as bH}from"node:crypto";import{constants as h7}from"node:fs";import{lstat as u7,mkdir as v7,open as l7,unlink as xH}from"node:fs/promises";import{dirname as q$,resolve as m7}from"node:path";import{setTimeout as kH}from"node:timers/promises";import{rmdirSync as CH,statSync as y7,utimesSync as TH}from"node:fs";import{mkdir as AH,rmdir as SH,stat as nZ,utimes as RH}from"node:fs/promises";var EH=30000,R3=1e4,IH=3000,rZ,t$=new Map;process.once("exit",()=>{for(let[$,Z]of t$)try{if(Z.renewedAt+R3<Date.now())continue;let X=y7($);if(oZ(X,Z)&&X.mtime.getTime()===Z.mtime)CH($)}catch{}});function oZ($,Z){return $.dev===Z.dev&&$.ino===Z.ino}function e$($){return typeof $==="object"&&$!==null&&"code"in $?$.code:void 0}function f7(){return Object.assign(Error("Pi auth lock held"),{code:"ELOCKED"})}async function tZ($){try{await SH($)}catch(Z){if(e$(Z)!=="ENOENT")throw Z}}async function eZ($,Z){try{await AH($)}catch(X){if(e$(X)!=="EEXIST")throw X;if(Z<=0)throw f7();let J;try{J=(await nZ($)).mtime.getTime()}catch(z){if(e$(z)==="ENOENT")return eZ($,0);throw z}if(!(J<Date.now()-Z))throw f7();return await tZ($),eZ($,0)}try{if(!rZ){let z=new Date(Math.ceil(Date.now()/1000)*1000+5);await RH($,z,z)}let X=await nZ($),J=X.mtime.getTime();return rZ??=J%1000===0?"s":"ms",{dev:X.dev,ino:X.ino,mtime:J}}catch(X){throw await tZ($).catch(()=>{}),X}}async function g7($,Z,X){let J=`${$}.lock`,z=await eZ(J,EH),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 V(){if(!H&&B+R3<Date.now())Q()}function W(j=IH){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 W(1000)}async function K(){if(V(),H)return;let j;try{j=y7(J)}catch(D){U(D);return}if(V(),H)return;if(!oZ(j,z)||j.mtime.getTime()!==G){Q();return}let N=new Date(rZ==="s"?Math.ceil(Date.now()/1000)*1000:Date.now());try{TH(J,N,N)}catch(D){U(D);return}if(V(),H)return;G=N.getTime(),B=Date.now(),t$.set(J,{...z,mtime:G,renewedAt:B}),W()}return X?.(async()=>{if(Y)clearTimeout(Y);await K()}),W(),{assertFresh:V,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 nZ(J)}catch(D){if(e$(D)!=="ENOENT")throw D;Q();return}if(j()||!oZ(N,z)||G!==N.mtime.getTime()){Q();return}await tZ(J)}}}class n extends Error{code;constructor($){super(`Pi slot: ${$}`);this.code=$,this.name="PiSlotError"}}function fH($){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 V=$[Z];if(V==='"'){z();continue}if(V==="{"||V==="[")Y++;if(V==="}"||V==="]"){if(Y===0)break;Y--}if(V===","&&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 Z6($){if(Array.isArray($))return`[${$.map(Z6).join(",")}]`;if(Z2($))return`{${Object.keys($).sort().map((Z)=>`${JSON.stringify(Z)}:${Z6($[Z])}`).join(",")}}`;return JSON.stringify($)}function y0($){return bH("sha256").update(Z6($)).digest("hex")}function $2($){return Z2($)?$.code:void 0}async function w7($,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 n(Z?"invalid-stash":"invalid-auth");return G}catch(z){if($2(z)==="ENOENT")return;throw z}let J;try{J=await l7($,h7.O_RDONLY|h7.O_NOFOLLOW);let z=await J.stat();if(!z.isFile()||Z&&(z.mode&511)!==384)throw new n("unsafe-path");await X?.($);let G=await u7($);if(!G.isFile()||G.dev!==z.dev||G.ino!==z.ino)throw new n("unsafe-path");let B=await J.readFile(),H=B.toString("utf8");if(!B.equals(Buffer.from(H)))throw new n(Z?"invalid-stash":"invalid-auth");return H}catch(z){if($2(z)==="ENOENT"&&!J)return;if($2(z)==="ELOOP"||$2(z)==="ENOENT")throw new n("unsafe-path");throw z}finally{await J?.close()}}function yH($,Z){try{let X=JSON.parse($);if(!Z2(X))throw Error();let J=fH($),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 n("invalid-auth")}}function gH($){let Z=$.property?.value;return Z?$.text.slice(Z.offset,Z.offset+Z.length):null}function p7($,Z,X){let{text:J,root:z,property:G}=$,B=z.children??[];if(G){let Q=G.value;if(!Q)throw new n("invalid-auth");if(X!==null)return J.slice(0,Q.offset)+X+J.slice(Q.offset+Q.length);let V=B.indexOf(G),W=B[V-1],U=B[V+1],K=W?W.offset+W.length:G.offset,j=!W&&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 hH($){if(I)return;let Z=await l7($,"r");try{await Z.sync()}finally{await Z.close()}}async function $6($,Z,X,J){await L0($,null,{serialize:()=>Z,durable:!0,durability:I?"file-only-on-windows":void 0,beforeRename:async()=>{await J?.($),X()}})}function X6($){return vH($)}function vH($,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 n("invalid-options");let B=m7($.authPath),H=m7($.stashPath);if(B===H||H===`${B}.lock`)throw new n("invalid-options");let Y=y0(B),Q=y0(z),V={type:"api_key",key:z},W=(D)=>y0(D)===y0(V);async function U(){let D=await w7(H,!0,X?.afterReadCheck);if(D===void 0)return;try{let M=JSON.parse(D);if(M.version!==1||M.provider!==J||M.authIdentity!==Y||M.placeholderIdentity!==Q||M.entry!==null&&!Z2(M.entry)||M.sha256!==y0(M.entry)||(M.entry===null?M.entryJson!==null:typeof M.entryJson!=="string"||y0(JSON.parse(M.entryJson))!==M.sha256))throw Error();return M}catch{throw new n("invalid-stash")}}async function K(D){let M,O,R=!1,F=()=>{if(O?.(),R)throw new n("lock-compromised")};try{if(I)await q0(q$(B));else await v7(q$(B),{recursive:!0,mode:448});let q=Date.now()+G,_=0;while(!M)try{let A=await g7(B,()=>{R=!0},X?.onRenew);M=A.release,O=A.assertFresh}catch(A){if($2(A)!=="ELOCKED")throw A;let b=q-Date.now();if(b<=0)throw new n("lock-timeout");await kH(Math.min(Math.round(Math.min(10*2**_++,1000)*(1+Math.random())),b))}F();let S=await D(F);return F(),S}catch(q){if(q instanceof n||q instanceof a)throw q;throw new n("io")}finally{await M?.().catch(()=>{}),F()}}async function j(){let D=yH(await w7(B,!1,X?.afterReadCheck)??"{}",J),M=await U();return{auth:D,stash:M}}async function N(D){D(),await xH(H),await hH(q$(H)),Z?.("stash-deleted")}return{inspect:()=>K(async()=>{let{auth:D,stash:M}=await j();return{slot:W(D.entry)?"placeholder":D.entry===null?"empty":!M||y0(D.entry)===M.sha256?"original":"foreign",stash:M?"valid":"missing"}}),enterVault:()=>K(async(D)=>{let{auth:M,stash:O}=await j();if(W(M.entry)){if(!O)throw new n("missing-stash");return}if(O&&y0(M.entry)!==O.sha256)throw new n("conflict");if(!O){if(I)await q0(q$(H));else{await v7(q$(H),{recursive:!0,mode:448});let F=await u7(q$(H));if(!F.isDirectory()||(F.mode&511)!==448)throw new n("unsafe-path")}let R={version:1,provider:J,authIdentity:Y,placeholderIdentity:Q,entry:M.entry,entryJson:gH(M),sha256:y0(M.entry)};await $6(H,JSON.stringify(R),D,X?.beforeRename),Z?.("stash-written")}await $6(B,p7(M,J,JSON.stringify(V)),D,X?.beforeRename),Z?.("auth-written")}),exitVault:()=>K(async(D)=>{let{auth:M,stash:O}=await j();if(!O){if(W(M.entry))throw new n("missing-stash");return"nothing-to-do"}if(W(M.entry))await $6(B,p7(M,J,O.entryJson),D,X?.beforeRename),Z?.("auth-written");else if(y0(M.entry)!==O.sha256)return"conflict";return await N(D),"restored"})}}import{getAgentDir as mH}from"@earendil-works/pi-coding-agent";var X2="openai-auth-vault-mode-not-a-credential",c7="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.",s7="A Pi login was added while connected to the vault. Both that login and the stashed original are kept; neither was overwritten.";function a7($){return X6({authPath:d7(mH(),"auth.json"),provider:"openai-codex",stashPath:d7(M3($),"pi-openai-codex-login.json"),placeholderKey:X2})}function wH($){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=u1(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 pH($,Z={}){let X=Z.beginAccountLogin??U9,J=Z.packageVersion??I7.version,z=dZ({vault:$.vault,changed:Z.afterApply,...Z.vaultWait?{wait:Z.vaultWait}:{}}),G=cZ({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 H0("quota-check-failed",H.map((Y)=>`${Y.account}: ${Y.error??"quota check failed"}`).join(`
|
|
114
|
+
`))},extras:[wH(()=>$.mainQuota()),lZ({getPin:async(B)=>b7(B),clearPin:async(B)=>x7(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 V;try{V=await $.disconnectVault?.()}catch{let W=!1;try{await Z.afterApply?.()}catch{W=!0}let U=await $.readAuthority();throw new H0("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.",...W?["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.`,...V==="conflict"?[s7]:[]].join(`
|
|
116
|
+
`)}},Q=H.actions??[];return{...H,actions:[...Q.map((V)=>V.id==="disconnect"&&$.disconnectVault?{...V,run:Y.run}:V),...$.vaultMode()&&$.disconnectVault&&!Q.some((V)=>V.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 uH($,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 R4(pH(X,Z),$.ui,{sessionId:$.sessionManager.getSessionId()})}function i7($,Z={}){$.registerCommand(F1,{description:"OpenAI accounts: add and manage accounts, quota, routing and limits",handler:(X,J)=>uH(J,Z)})}import{connect as lH}from"node:net";import{connect as dH}from"node:tls";var cH="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",n7=["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 J6{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+cH));this.expectedAccept=Buffer.from(new Uint8Array(Y)).toString("base64");let Q={};for(let[U,K]of Object.entries(Z))Q[U.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${J}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${H}`];for(let U of n7)if(Q[U]!==void 0)V.push(`${sH(U)}: ${Q[U]}`);for(let[U,K]of Object.entries(Z))if(!n7.includes(U.toLowerCase())&&U.toLowerCase()!=="content-length")V.push(`${U}: ${K}`);let W=`${V.join(`\r
|
|
117
117
|
`)}\r
|
|
118
118
|
\r
|
|
119
|
-
`;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let
|
|
119
|
+
`;try{this.log("connect_start",{host:J,port:z,tls:X.protocol==="https:"});let U=()=>{this.socket?.write(W)},K=X.protocol==="https:"?dH({host:J,port:z,servername:J},U):lH({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=aH(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,Q=X&127,B=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],B=4}else if(Q===127){if($.length<10)return;Q=0;for(let Y=0;Y<8;Y++)Q=Q*256+$[2+Y];B=10}if(G)B+=4;if($.length<B+Q)return;let H=$.slice(B,B+Q);this.rxBuffer=$.slice(B+Q),this.handleFrame(J,z,H)}}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=jB(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 B=7;B>=0;B--)z.push(X/2**(8*B)&255)}let G=new Uint8Array(X);for(let B=0;B<X;B++)G[B]=Z[B]^J[B%4];let Q=new Uint8Array(z.length+4+X);Q.set(z,0),Q.set(J,z.length),Q.set(G,z.length+4);try{this.socket?.write(Q)}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 VB($){return $}function UB($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function jB($){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 CB}from"node:fs";var KB=15000;function n$($){if(!$)return;let Z=t1($);return Z?e1(Z):void 0}class c4{deps;now;token;identity;quota;snapshot;firstPolledFor;inflight;lastPull;constructor($){this.deps=$,this.now=$.now??Date.now}observeToken($){if(!$)return;let Z=n$($);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 $=Q$(this.quota);if(!$&&!this.snapshot)return;return{...this.snapshot?.resetCreditsAvailable!==void 0?{resetCreditsAvailable:this.snapshot.resetCreditsAvailable}:{},...this.snapshot?.spendControl?{spendControl:this.snapshot.spendControl}:{},...$}}requestReading($=!1){let Z=this.now();if(!$&&this.lastPull!==void 0&&Z-this.lastPull<(this.deps.pullRetryMs??KB))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=S0($,this.now(),X);if(J)this.merge(J);return!0}owns($){if(!this.token)return!1;let Z=n$($);return Z&&this.identity?Z===this.identity:$===this.token}merge($){try{let Z=E0(this.quota,$);if(B0(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 DB}from"node:os";import{join as A5}from"node:path";function qB(){return process.env.PI_AGENT_DIR?.trim()||A5(DB(),".pi","agent")}function S5(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||A5(qB(),v2)}function NB($=S5()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||CZ($)}function R5($=S5()){return{configPath:$,statePath:NB($)}}function s4($){return $!==void 0&&($.vault===!0||!!$.token)}function E5($,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(k0(G.credential))return!1;if(G.id===R0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return Q3(Q$(G.quota),Z,X)})}function N3($,Z){let X=$.now(),J=P7(Z,$.storage,X);return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...B0(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function I5($){let Z=$.accounts(),X=S7(N3($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await FB($,Z,$.sessionId);if(J)return J}return MB($,Z)}async function MB($,Z){let X=A7($.mode),J=E7({...N3($,Z),placement:X,mainId:$.mainId});if(J.kind==="block")return $.log?.debug("pool admission blocked the request",{reason:J.block.reason}),{kind:"blocked",block:J.block};if(J.lastPath)$.log?.debug("pool admission: every account is exhausted; probing anyway",{order:J.order});let z=new Map(Z.map((Y)=>[Y.id,Y])),G=J7($.storage),Q=[],B=new Set,H;for(;;){let Y=E3(J.order.filter((j)=>!B.has(j)),Q,G);if(Y===void 0)break;let W=z.get(Y);if(!s4(W)){B.add(Y);continue}let V=await $.send(W);if(!V){B.add(Y);continue}H={attempt:V,accountId:W.id},Q.push({id:W.id,...V.status!==void 0?{status:V.status}:{}})}if(H)return{kind:"sent",...H};return{kind:"blocked",block:{reason:"no-credential"}}}async function FB($,Z,X){let J=$.requestBytes,z=new Map(Z.map((D)=>[D.id,D])),G=N3($,Z),Q=C4(G),B={requestBytes:J,reservePercent:(D)=>V1($.storage,D===R0?void 0:D),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},H=(D,M,P)=>(E,F)=>{let q=new Set(E);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:D.rows.map((L)=>L.id).filter((L)=>!M.excluded.has(L)),excludeAccountIds:E,quotaCheckedAtByAccount:Object.fromEntries(D.rows.map((L)=>[L.id,M.projections.get(L.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(P.map((L)=>[L.id,L.identity])),select:(L)=>b7(D,B,q,L),persist:F})},Y=H(G,Q,Z),W=Y([],!0);if(!W)return;let V=W.accountId,j=(D)=>{let M=Y([V],!0);if(!M)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:V,toAccountId:M.accountId,reason:D}),V=M.accountId,!0},K=x7(G,B,V);if(K.kind==="none")return;if(K.kind==="move"){if(!j(K.reason)&&K.reason==="killswitch")return}else if(K.kind==="detour"){let D=Y([V],!1);if(!D)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:V,servedAccountId:D.accountId}),V=D.accountId}let U=z.get(V);if(!s4(U))return;let N=await $.send(U);if(!N)return;if(N.status===401||N.status===403||N.status===429){let D=$.accounts();G=N3($,D),Q=C4(G),Y=H(G,Q,D);let M=k7(G,Q,V,N.status);if(M.action==="migrate"){let P=V;if(j(M.reason)&&V!==P){let E=D.find((q)=>q.id===V),F=s4(E)?await $.send(E):void 0;if(E&&F)N=F,U=E;else V=P}}}return{kind:"sent",attempt:N,accountId:U.id}}var LB=500,_B=15000;function M3($,Z,X){return new Promise((J,z)=>{let G=setTimeout(()=>J(X()),Z);G.unref?.(),$.then((Q)=>{clearTimeout(G),J(Q)},(Q)=>{clearTimeout(G),z(Q)})})}var OB={info(){},warn(){}};class i4{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??OB}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 M3(this.startRead($),this.deps.readBudgetMs??LB,()=>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}|${k4($.configPath)}|${k4($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=VZ({provider:"openai",configPath:$.configPath,statePath:$.statePath,quota:P3,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,Q=z.lastRefreshedAt??0;if(G>=Q)this.rotated.delete(X.id);else J={...J,credential:z}}return o7(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??_B))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){r7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:f4(X.quota,Z),needsFirstReading:!1}))}recordSnapshot($,Z,X,J){if(!this.snapshot.active||this.disposed||this.setAside())return;let z=this.snapshot.rows.find((j)=>j.id===$);if(z?.type!=="oauth")return;let G=n$(X);if(!(G&&z.identity?G===z.identity:k1(z)?.access===X))return;let B=S0(Z,this.now(),J);if(!B)return;if(this.applyObservation(z,B),z.credentialEpoch===void 0)return;let H={credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}},Y=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 Y.recordQuota(z.id,H,B)}).catch((j)=>{this.log.warn("pool quota not recorded",{rowId:z.id,error:j instanceof Error?j.message:String(j)})});this.writes.set(z.id,V),V.finally(()=>{if(this.writes.get(z.id)===V)this.writes.delete(z.id)})}rowForToken($){let Z=n$($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:k1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=j4(Z),z=[];for(let G of $){if(!G.candidate)continue;let Q=k1(G);if(!Q)continue;let B=(Q.expires??0)-X;if(!(!Q.access||!Q.expires||B<=J)||this.refreshBackedOff(G,X))continue;z.push(this.refresh(G.id))}return Promise.all(z).then(()=>{})}refreshBackedOff($,Z=this.now()){let X=k1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===r1(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=k1($);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?k1(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($,t7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return e7($,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 PB=_4,TB=500,AB=64;function SB(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function r$($,Z){return{type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:SB(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function RB($){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 ${T7} 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 EB($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class a4{main;pool;vault;deps;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??R5;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new c4({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 J$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:R0}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new i4({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 s9({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=E$({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 J$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new N4({host:"pi",stateDir:H3(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??C5(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=CB($.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=V4($).then((J)=>{return this.storageCache={key:Z,storage:J},J},()=>this.storageCache?.storage??null);this.storageRead={key:Z,promise:X}}return M3(this.storageRead.promise,this.deps.readBudgetMs??TB,()=>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 B=this.main.quotaMap();Z.push({id:R0,token:X,...J?{identity:J}:{},...B?{quota:B}:{}})}let G=this.pool.peek(),Q=this.now();if(G.active)for(let B of E5(G.rows,$,Q,J,z))Z.push({id:B.id,token:this.pool.usableToken(B,Q),...B.identity?{identity:B.identity}:{},...B.quota!==void 0?{quota:B.quota}:{}})}poolRowById($){return this.pool.peek().rows.find((Z)=>Z.id===$)}requestPull($){if($===R0)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>AB){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=H9(J),G=Y9(J),Q=this.vaultTokens.get(Z);if(Q?.id===$)this.vault.recordSnapshot($,z,G,Q.receipt);else if($===R0)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=EB($);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,W9(J))}stream($,Z,X){let J=this.deps.createStream(),z=this.deps.installWebSocket?.()??(()=>{});return(async()=>{try{if(await this.readAuthority()!=="local"&&X?.apiKey!==a$){J.push(r$($,_5));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(r$($,G.refusal?D7(G.refusal,this.vault.name):RB(G.block)));return}if(G.head)J.push(G.head);if(G.rest)for(;;){let Q=await G.rest.next();if(Q.done)break;J.push(Q.value)}}catch(G){J.push(r$($,D1(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 M3(this.vault.awaitRequestRoster().then(()=>!0),Y3,()=>!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",Q=!1,B=0,Y=await(()=>I5({accounts:()=>{let W=this.accounts(J);return B=W.length,W},storage:J,mode:G,mainId:z?V3(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??PB,send:(W)=>W.vault?this.vaultAttempt($,Z,X,W.id).then((V)=>{if(!V)Q=!0;return V}):W.token?this.attempt($,Z,X,W.id,W.token):Promise.resolve(void 0),placePin:Y5}))();if(Y.kind==="blocked"){if(z&&(B===0||Q))return{...Y,refusal:Q?"vault-refused":q7(this.vault)};if(z&&Y.block.reason==="no-credential")return{...Y,refusal:"vault-empty"};return Y}return{kind:"sent",...Y.attempt}}async attempt($,Z,X,J,z){let G,Q;try{let W=X?.fetch??globalThis.fetch;Q=this.deps.streamSimple($,Z,{...X,apiKey:z,fetch:Object.assign(async(V,j)=>{try{return await G5(await W(V,j),z,"event-stream")}catch(K){throw D1(K,z)}},W),onResponse:async(V,j)=>{G=V.status,this.recordHeaders(J,z,V.headers),await X?.onResponse?.(V,j)}})}catch(W){return{head:r$($,D1(W,z).message),rest:void 0}}let B=async function*(){try{for await(let W of Q){if(W.type==="error")W.error.errorMessage=K1(W.error.errorMessage??"",z);yield W}}catch(W){yield r$($,D1(W,z).message)}}(),H=await B.next(),Y=H.done?void 0:H.value;return{...G!==void 0?{status:G}:{},head:Y,rest:H.done||Y?.type==="error"?void 0:B}}async vaultAttempt($,Z,X,J){let z;return await this.vault.send(J,async(Q,B)=>{return this.rememberVaultToken(Q,{id:J,receipt:{credentialId:B.credentialId,accountIdentitySource:B.accountIdentitySource,...B.accountIdentity!==void 0?{accountIdentity:B.accountIdentity}:{},...B.expectedAccountIdentity!==void 0?{expectedAccountIdentity:B.expectedAccountIdentity}:{}}}),z=await this.attempt($,Z,X,J,Q),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:R0,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 t$="https://chatgpt.com/backend-api",x5;class r4 extends d4{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=x5;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var o$=0,n4;function xB(){let $=globalThis;if(o$===0)n4=$.WebSocket,$.WebSocket=r4;return o$++,()=>{if(o$=Math.max(0,o$-1),o$===0){if($.WebSocket===r4)$.WebSocket=n4;n4=void 0}}}var kB=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:t$,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:t$,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:t$,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:t$,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}],fB=5000;function b5($,Z){$.registerProvider("openai-codex",{baseUrl:t$,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:a$}:{},models:kB,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function yB(){return new a4({streamSimple:($,Z,X)=>bB($,Z,X),createStream:IB,installWebSocket:xB})}async function gB($){let Z=yB();x5=(Q,B)=>Z.observeWebSocketMessage(Q,B);let X,J,z=(Q=!0)=>Z.syncVaultSlot(X?async()=>{b5($,Z),await X?.()}:void 0,Q),G=()=>{z(!1).catch(()=>{J?.("Pi could not load the vault login slot. Reopen the session or disconnect in /openai.","error")})};if(P5($,{pool:Z.commandSupport(),afterApply:z,onContext:(Q)=>{X=()=>Q.modelRegistry.refresh(),J=(B,H)=>Q.ui.notify(B,H)}}),await z().catch(()=>{}),b5($,Z),setInterval(G,fB).unref?.(),typeof $.on==="function")$.on("session_start",async(Q,B)=>{X=()=>B.modelRegistry.refresh(),J=(H,Y)=>B.ui.notify(H,Y),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 B.modelRegistry.getApiKeyForProvider("openai-codex"))}catch{}})}export{b5 as registerPiProvider,xB as installRawCodexWebSocket,gB as default,yB 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=iH(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 sH($){return $}function aH($,Z){let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function iH($){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 zY}from"node:fs";var nH=15000;function J2($){if(!$)return;let Z=z$($);return Z?G$(Z):void 0}class z6{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 $=j$(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??nH))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=S0($,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=v0(this.quota,$);if($0(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 rH}from"node:os";import{join as r7}from"node:path";function oH(){return process.env.PI_AGENT_DIR?.trim()||r7(rH(),".pi","agent")}function o7(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||r7(oH(),s2)}function tH($=o7()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||f4($)}function t7($=o7()){return{configPath:$,statePath:tH($)}}function G6($){return $!==void 0&&($.vault===!0||!!$.token)}function e7($,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(f0(G.credential))return!1;if(G.id===E0)return!1;if(J&&G.identity===J)return!1;if(G.identity!==void 0&&z.has(G.identity))return!1;return D3(j$(G.quota),Z,X)})}function E3($,Z){let X=$.now(),J=a5(Z,$.storage,X);return{rows:Z.map((G)=>({id:G.id,kind:G.kind??"oauth",...$0(G.quota)?{quota:G.quota}:{}})),now:X,rateLimitMarks:new Map,refreshBackoff:$.refreshBackoff(Z),killswitch:J,requestPull:$.requestPull}}async function $X($){let Z=$.accounts(),X=r5(E3($,Z),$.firstReadingWaitMs);if(X)await X,Z=$.accounts();if($.mode==="sticky-balanced"&&$.sessionId){let J=await $Y($,Z,$.sessionId);if(J)return J}return eH($,Z)}async function eH($,Z){let X=n5($.mode),J=E3($,Z),z=t5({...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((V)=>[V.id,V])),B=A5($.storage),H=[],Y=new Set,Q;for(;;){let V=p3(z.order.filter((K)=>!Y.has(K)),H,B);if(V===void 0)break;let W=G.get(V);if(!G6(W)){Y.add(V);continue}let U=await $.send(W);if(!U){Y.add(V);continue}Q={attempt:U,accountId:W.id},H.push({id:W.id,...U.status!==void 0?{status:U.status}:{}})}if(Q)return ZX($,J,Q.accountId),{kind:"sent",...Q};return{kind:"blocked",block:{reason:"no-credential"}}}async function $Y($,Z,X){let J=$.requestBytes,z=new Map(Z.map((D)=>[D.id,D])),G=E3($,Z),B=yZ(G),H={requestBytes:J,reservePercent:(D)=>N1($.storage,D===E0?void 0:D),resetCredits:()=>{return},onEmptyWeightedSet:()=>{$.log?.debug("sticky routing: no fresh weighted candidates; using configured order")}},Y=(D,M,O)=>(R,F)=>{let q=new Set(R);return $.placePin({sessionId:X,requestBytes:J,validPinnedAccountIds:D.rows.map((_)=>_.id).filter((_)=>!M.excluded.has(_)),excludeAccountIds:R,quotaCheckedAtByAccount:Object.fromEntries(D.rows.map((_)=>[_.id,M.projections.get(_.id)?.checkedAt])),wireAccountIdByAccount:Object.fromEntries(O.map((_)=>[_.id,_.identity])),select:(_)=>$7(D,H,q,_),persist:F})},Q=Y(G,B,Z),V=Q([],!0);if(!V)return;let W=V.accountId,U=(D)=>{let M=Q([W],!0);if(!M)return!1;return $.log?.debug("sticky routing: migrated session pin",{fromAccountId:W,toAccountId:M.accountId,reason:D}),W=M.accountId,!0},K=Z7(G,H,W);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([W],!1);if(!D)return;$.log?.debug("sticky routing: pinned account awaits a quota reading",{pinnedAccountId:W,servedAccountId:D.accountId}),W=D.accountId}let j=z.get(W);if(!G6(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=yZ(G),Q=Y(G,B,D);let M=X7(G,B,W,N.status);if(M.action==="migrate"){let O=W;if(U(M.reason)&&W!==O){let R=D.find((q)=>q.id===W),F=G6(R)?await $.send(R):void 0;if(R&&F)N=F,j=R;else W=O}}}return ZX($,G,j.id),{kind:"sent",attempt:N,accountId:j.id}}function ZX($,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 ZY=500,XY=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 JY={info(){},warn(){}};class B6{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??JY}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??ZY,()=>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}|${sZ($.configPath)}|${sZ($.statePath)}`}storeFor($){if(this.store?.configPath===$.configPath)return this.store.store;let Z=O4({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 L7(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??XY))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){_7(this.pending,$,Z),this.replaceRow($.id,(X)=>({...X,quota:aZ(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:v1(z)?.access===X))return;let H=S0(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()),W=(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,W),W.finally(()=>{if(this.writes.get(z.id)===W)this.writes.delete(z.id)})}rowForToken($){let Z=J2($);return this.snapshot.rows.find((X)=>Z&&X.identity?X.identity===Z:v1(X)?.access===$)}refreshDueTokens($,Z){if(this.setAside())return Promise.resolve();let X=this.now(),J=AZ(Z),z=[];for(let G of $){if(!G.candidate)continue;let B=v1(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=v1($);if(!X)return!1;let J=this.backoff.get($.id);return Boolean(J&&J.tokenHash===X$(X.refresh)&&J.nextRetryAt>Z)}usableToken($,Z=this.now()){if(this.setAside())return;let X=v1($);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?v1(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($,O7(Z,X,this.now(),this.backoff.get($)))}refreshBackoffFor($){return P7($,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 GY=kZ,BY=500,HY=d("routing"),YY=64;function QY(){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:QY(),stopReason:"error",errorMessage:Z,timestamp:Date.now()}}}function WY($){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 ${i5} 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 VY($){for(let[Z,X]of Object.entries($)){if(Z.toLowerCase()!=="authorization")continue;return/^Bearer\s+(.+)$/i.exec(X.trim())?.[1]}return}class H6{main;pool;vault;deps;creditsServing=new fZ;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??t7;let Z=()=>$.fetchImpl??globalThis.fetch;this.main=new z6({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 Q$({accessToken:X,fetchImpl:Z(),now:this.now,...J?{accountId:J}:{},accountKey:E0}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.pool=new B6({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 D5({refreshToken:X.refresh,fetchImpl:Z(),now:this.now}),z=h$({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 Q$({accessToken:J.access,fetchImpl:Z(),now:this.now,...X.identity?{accountId:X.identity}:{},accountKey:X.id}),G=S0(z,this.now(),!0);if(!G)throw Error("the quota poll returned no reading");return{snapshot:z,observation:G}}}),this.vault=$.vault??new EZ({host:"pi",stateDir:M3(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??a7(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=zY($.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=CZ($).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??BY,()=>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:E0,token:X,...J?{identity:J}:{},...H?{quota:H}:{}})}let G=this.pool.peek(),B=this.now();if(G.active)for(let H of e7(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($===E0)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>YY){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=L9(J),G=O9(J),B=this.vaultTokens.get(Z);if(B?.id===$)this.vault.recordSnapshot($,z,G,B.receipt);else if($===E0)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=VY($);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,P9(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($,c7));return}let G=await this.route($,Z,X);if(G.kind==="blocked"){J.push(z2($,G.refusal?v5(G.refusal,this.vault.name):WY(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($,L1(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),F3,()=>!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(()=>$X({accounts:()=>{let V=this.accounts(J);return H=V.length,V},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:(V)=>this.pool.refreshBackoffFor(V.map((W)=>this.poolRowById(W.id)).filter((W)=>W!==void 0)),requestPull:(V)=>this.requestPull(V),firstReadingWaitMs:this.deps.firstReadingWaitMs??GY,send:(V)=>V.vault?this.vaultAttempt($,Z,X,V.id).then((W)=>{if(!W)B=!0;return W}):V.token?this.attempt($,Z,X,V.id,V.token):Promise.resolve(void 0),placePin:k7,creditsServing:this.creditsServing,log:{debug:()=>{},info:(V,W)=>HY.info(V,W)}}))();if(Q.kind==="blocked"){if(z&&(H===0||B))return{...Q,refusal:B?"vault-refused":m5(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 V=X?.fetch??globalThis.fetch;B=this.deps.streamSimple($,Z,{...X,apiKey:z,fetch:Object.assign(async(W,U)=>{try{return await E7(await V(W,U),z,"event-stream")}catch(K){throw L1(K,z)}},V),onResponse:async(W,U)=>{G=W.status,this.recordHeaders(J,z,W.headers),await X?.onResponse?.(W,U)}})}catch(V){return{head:z2($,L1(V,z).message),rest:void 0}}let H=async function*(){try{for await(let V of B){if(V.type==="error")V.error.errorMessage=_1(V.error.errorMessage??"",z);yield V}}catch(V){yield z2($,L1(V,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:E0,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",JX;class Q6 extends J6{constructor($,Z){let X=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),X);let J=JX;if(J)this.addEventListener("message",(z)=>{let G=z?.data;if(typeof G==="string")J(X,G)})}}var G2=0,Y6;function KY(){let $=globalThis;if(G2===0)Y6=$.WebSocket,$.WebSocket=Q6;return G2++,()=>{if(G2=Math.max(0,G2-1),G2===0){if($.WebSocket===Q6)$.WebSocket=Y6;Y6=void 0}}}var DY=[{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}],qY=5000;function XX($,Z){$.registerProvider("openai-codex",{baseUrl:B2,api:"openai-codex-responses",name:"OpenAI Codex (CortexKit)",...Z.vaultMode()?{apiKey:X2}:{},models:DY,streamSimple:(X,J,z)=>Z.stream(X,J,z)})}function NY(){return new H6({streamSimple:($,Z,X)=>jY($,Z,X),createStream:UY,installWebSocket:KY})}async function MY($){let Z=NY();JX=(B,H)=>Z.observeWebSocketMessage(B,H);let X,J,z=(B=!0)=>Z.syncVaultSlot(X?async()=>{XX($,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(i7($,{pool:Z.commandSupport(),afterApply:z,onContext:(B)=>{X=()=>B.modelRegistry.refresh(),J=(H,Y)=>B.ui.notify(H,Y)}}),await z().catch(()=>{}),XX($,Z),setInterval(G,qY).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{XX as registerPiProvider,KY as installRawCodexWebSocket,MY as default,NY as createPiOpenAIRuntime};
|