@cortexkit/opencode-openai-auth 1.20.0 → 1.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +7 -7
- package/dist/{index-xbh03w1v.js → index-09rjj0qc.js} +2 -2
- package/dist/{index-0jknjejt.js → index-3yf405db.js} +2 -2
- package/dist/{index-3898z307.js → index-62e0dx41.js} +2 -2
- package/dist/{index-62xhtkv8.js → index-h7veb7th.js} +1 -1
- package/dist/{index-asjkhkty.js → index-hybc4q33.js} +2 -2
- package/dist/{index-663p60em.js → index-j5fk9tyk.js} +1 -1
- package/dist/index-mfvnmkrh.js +64 -0
- package/dist/{index-74mg470w.js → index-q3j22pg7.js} +2 -2
- package/dist/{index-z1hz7e5y.js → index-qfer1qeq.js} +1 -1
- package/dist/{index-pdsqgqng.js → index-rrmycmen.js} +1 -1
- package/dist/{index-d5er9yht.js → index-tv6zrkss.js} +2 -2
- package/dist/{index-wy84wezx.js → index-vyc1q51y.js} +2 -2
- package/dist/{index-7tkppvqd.js → index-x9h58tf9.js} +2 -2
- package/dist/{index-r6k6hh93.js → index-y9k6nshb.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/{token-y3kre94n.js → token-t7hstws6.js} +1 -1
- package/dist/token-util-33bcnrmj.js +1 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +1 -1
- package/dist/index-2dxas810.js +0 -64
- package/dist/token-util-kwahm03g.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ad as t0,Bd as o7,Bf as D7,Cd as q1,Cf as P7,Dd as z5,Ef as g8,Fd as d6,Ff as f8,Gd as I0,Hd as nZ,Hf as k6,Id as b0,If as A7,Kd as G5,Ke as b4,Kf as iZ,Ld as Q5,Md as B5,Ne as L4,Od as i7,Oe as q7,Pd as r7,Pe as b8,Qd as r1,Rd as v0,Sd as v3,Sf as E7,Td as h3,Ud as p3,Vd as c5,Wd as s5,Yd as c6,Zd as A9,_d as w2,af as b$,be as a5,cf as k8,de as n5,df as n6,ee as i5,fe as x6,ff as x8,ge as r5,gf as I4,ie as o5,if as E4,je as t5,jf as p0,ke as y6,le as u7,lf as j1,me as e5,ne as $Z,of as y8,pe as t7,pf as V7,qe as g4,re as e7,se as F7,te as K7,uf as A4,xe as g6,ye as f6,zf as N7}from"./index-3898z307.js";import{$f as m1,Yf as Q3,Zf as P0,_f as B3,ag as l0,cg as W3,dg as Y3}from"./index-7tkppvqd.js";import{rg as Q8}from"./index-wy84wezx.js";import{sg as r8}from"./index-74mg470w.js";import{Bg as N$,Cg as f4,Dg as D$,Eg as x0,zg as g7}from"./index-pdsqgqng.js";import{Hg as n3,Mg as t}from"./index-xbh03w1v.js";import{Ng as Z6,Pg as u1,Ug as G3}from"./index-asjkhkty.js";class b 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 Z4 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 O2="identity-contradicted: ",R1="duplicate-identity";function n0($,Z,J){let X=$.rosterRow(Z);if(!X)return;X.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:J})}function J4($,Z){let J=$.rosterRow(Z);if(!J)return;J.enabled=!0;let X=$.entry(Z);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,$.setEntry(Z,z)}}function S2($,Z){let J=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),X=[];for(let z of J.slice(1))n0($,z.id,"duplicate-identity"),X.push(z.id);return X}function z2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,S2($,J)}import{AsyncLocalStorage as l$}from"node:async_hooks";var n4=new l$,d$=new l$;function a($){if(n4.getStore()!==void 0)throw new Z4($)}function c$(){if(n4.getStore()?.storeLocksReleased===!1||d$.getStore())throw new Z4("updateLimitsNamespace")}function G0($){return d$.run(!0,$)}function Q0($,Z,J=!1){return n4.run({operation:$,storeLocksReleased:J&&n4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function s$($,Z,J,X,z){if(!Z)return;try{await Q0($,()=>Z(J,X),!0)}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:J,error:G instanceof Error?G.message:String(G)})}}import{setTimeout as V3}from"node:timers/promises";function G2($,Z,J){if(J!==void 0)throw new b({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 X4}from"node:crypto";var v="commonAuthPool",i0=1,N0="rows",i4="retiredEpochs",z4=1,I1=300000,g=v;function RJ($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(S(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function Q2($){return X4("sha256").update(RJ($)).digest("hex")}function a$($){if(!S($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function IJ($){if(!S($)||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 r="commonAuthProviderState";function S($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var bJ=new Set(["__proto__","constructor","prototype"]);function A2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(bJ.has($))return"id is a reserved object key";return}function b1($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function n$($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function D0($){return X4("sha256").update(n$($)).digest("hex")}function E0($){return X4("sha256").update(`credential-stamp\x00${n$($)}`).digest("hex")}function f0($){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 X4("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function k1($,Z,J,X={}){return{credentialEpoch:Z,digest:E0($),dispatch:f0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function E2($,Z){let J=$?.credentialBound?G0(()=>$.credentialBound?.(Z)):Z;return X4("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function G4($,Z,J,X){if(!Z||J===void 0)return;if(!S($)||!Object.hasOwn($,r))return;let z=e($[g]);if(!z||z.providerState===void 0||z.digest!==E0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function s($){return Number.isSafeInteger($)&&$>=1}function e($){if(!S($))return;let Z=$.credentialEpoch;if(!s(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 J="staged"in $?IJ($.staged):void 0;if("staged"in $&&!J)return;let X={...J?{staged:J}:{},...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(!S(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!b1(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...X,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 kJ($,Z,J){if($.identity!==J)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 xJ($,Z,J,X){if(!$)return"none";if(!S(X)||!Object.hasOwn(X,g))return"missing";let z=e(X[g]);if(!z)return"malformed";if(z.digest!==E0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!kJ(z.binding,$,J))return"mismatched";if(z.dispatch!==f0($))return"mismatched";return"bound"}function x1($){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(!S(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(!(v in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let J=Z[v];if(!S(J))return{status:"error",reason:`${v} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${v}.schemaVersion is invalid`};if(X>i0)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${i0}`};if(N0 in J&&!S(J[N0]))return{status:"error",reason:`${v}.${N0} is not an object`};return{status:"ready",exists:!0,config:Z}}function i$($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!S($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!S($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function R2($){return Array.isArray($.accounts)?$.accounts:[]}function r$($){let Z=$[v];if(!S(Z))return{};let J=Z[N0];return S(J)?J:{}}function yJ($){return S($.accounts)?$.accounts:{}}function gJ($){if(!S($))return"not an object";let Z=A2($.id);if(Z)return Z;if($.type==="api")return b1($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function fJ($,Z){if(!S($))return;let J=$.credentialEpoch;if(!s(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?G0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!G0(()=>Z.validate(X)))return;if("staged"in $&&!a$($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function vJ($,Z){if(!S(Z))return;if($.type==="api"){let X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let J=Z.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function r4($,Z){return R2($).find((J)=>S(J)&&J.id===Z)}function o$($){if(!S($[v]))$[v]={};return $[v]}function y1($){let Z=o$($);if(!S(Z[N0]))Z[N0]={};return Z[N0]}function R0($,Z){let J=r$($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return S(X)?X:void 0}function o4($,Z,J){Object.defineProperty(y1($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function t$($,Z){let J=$[v];if(!S(J))return;let X=J[i4];if(!S(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return s(z)?z:void 0}function e$($,Z){let J=R0($,Z)?.credentialEpoch;return s(J)?J:void 0}function t4($,Z){return Math.max(t$($,Z)??0,e$($,Z)??0)+1}function $3($,Z){let J=[...Z];if(J.length===0)return;let X=o$($),z=S(X[i4])?X[i4]:{},G={},Q=(W,B)=>Object.defineProperty(G,W,{value:B,enumerable:!0,writable:!0,configurable:!0});for(let[W,B]of Object.entries(z))if(s(B))Q(W,B);for(let W of J)Q(W,Math.max(t$($,W)??0,e$($,W)??1));X[i4]=G}function r0($,Z,J,X){let z=r$($),G=yJ(Z),Q=new Set,W=[];for(let B of R2($)){let Y=gJ(B),H=S(B)&&typeof B.id==="string"?B.id:void 0,V=H===void 0?void 0:z[H],U=S(V)&&Object.hasOwn(V,"staged"),j=U?a$(V.staged):void 0;if(Y||!S(B)||H===void 0||Q.has(H)){if(H!==void 0&&!Q.has(H))Q.add(H);if(H!==void 0)W.push({id:H,type:S(B)&&B.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...j?{staged:j}:{}});continue}Q.add(H);let q=B.type==="api"?"api":"oauth",F=Object.hasOwn(z,H),K=F?fJ(z[H],J):void 0,N=vJ(B,G[H]),D=B.enabled!==!1,T=K?K.credentialEpoch:F?void 0:1,M=typeof B.accountId==="string"&&B.accountId?B.accountId:void 0,P={id:H,type:q,enabled:D,needsFirstReading:K?K.needsFirstReading:q==="oauth",hasEntry:F,candidate:!1,...typeof B.label==="string"?{label:B.label}:{},...typeof B.addedAt==="number"?{addedAt:B.addedAt}:{},...M!==void 0?{identity:M}:{},...N?{credential:N,fingerprint:D0(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...j?{staged:j}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...hJ(G[H],N,T,M,X),stamp:xJ(N,T,M,G[H])};if(F&&!K)P.invalid="entry";else P.candidate=D&&N!==void 0&&!U;W.push(P)}return W}function hJ($,Z,J,X,z){if(!S($)||!Object.hasOwn($,r))return{};let G=G4($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[r];if(!z||!G0(()=>z.validate(Q)))return{providerStateDropped:"invalid"};if(E2(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function h($){return $.identity??$.id}function Q4($,Z){if($===void 0||$>Z+I1)return Z;return Math.max(Z,$+1)}function g1($,Z){return Q4($,Z)>Z+I1}function I2($){let{id:Z,credential:J,identity:X,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:J.type,addedAt:G,...X!==void 0?{accountId:X}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}}}function Z3($,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 J3($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function X3($,Z={}){if(!S($))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)&&!b1($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var e4="transition",z3="transitionMark";function mJ($){if(!S($))return;let Z=$[e4];if(!S(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 B4($,Z,J){if(J.enabled)J4($,Z);else n0($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[z3]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)S2($,z.identity)}function wJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function uJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function pJ($,Z,J,X={}){let z=S(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of r0($,Z,J)){if(Q.invalid||Q.staged||!Q.credential)continue;let W=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!S(W))continue;let B=e(W[g]);if(!B?.binding)continue;if(B.digest!==E0(Q.credential))continue;let Y=Q.credentialEpoch??1;if(B.credentialEpoch>Y){if(!uJ(B))continue;if(X.requireCredentialStamps){if(B.dispatch===void 0)continue;if(B.dispatch!==f0(wJ(Q.credential,B.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...B,binding:B.binding}})}else if(B.credentialEpoch===Y&&B.dispatch!==void 0&&B.dispatch===f0(Q.credential)&&B.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:B.binding.identity});else if(B.credentialEpoch===Y&&B.binding.identity===Q.identity){if(X.requireCredentialStamps&&B.dispatch!==f0(Q.credential))continue;let H=mJ(W[g]);if(H&&R0($,Q.id)?.[z3]!==H.mark)G.set(Q.id,{kind:"transition",transition:H})}}return G}function f1($,Z,J,X){let G={...$.entry(Z)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(O2))delete G.disabledReason;$.setEntry(Z,G);let Q=$.rosterRow(Z);if(!Q)return;if(X.identity!==void 0)Q.accountId=X.identity;else delete Q.accountId;if(X.baseURL!==void 0)Q.baseURL=X.baseURL;if(X.authHeader!==void 0)Q.authHeader=X.authHeader}function v1($,Z,J,X={}){let z=pJ($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>r0(G,Z,J),rosterRow:(W)=>r4(G,W),entry:(W)=>R0(G,W),setEntry:(W,B)=>o4(G,W,B)};for(let[W,B]of z)if(B.kind==="replace")f1(Q,W,B.stamp.credentialEpoch,B.stamp.binding);for(let[W,B]of z)if(B.kind==="identity")z2(Q,W,B.identity);else if(B.kind==="transition")B4(Q,W,B.transition);else if(B.stamp.binding.identity!==void 0)S2(Q,B.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function h1($,Z,J,X={}){let{config:z,torn:G}=v1($,Z,J,X),Q=r0(z,Z,J,X.providerState);for(let W of Q){if(G.includes(W.id))W.torn=!0,W.candidate=!1;if(X.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return Q}var lJ=[5,10,20,40,80,160,320,400];async function $6($){for(let Z=0;;Z++)try{return await G3($,Z6)}catch(J){if(J.code==="ENOENT")return;let X=lJ[Z];if(X===void 0||!u1(J))throw J;await V3(X)}}function w1($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function H3($){return x1(w1(await $6($)))}async function n($){for(let Z=0;Z<3;Z++){let J,X,z;try{J=await $6($.configPath),X=await $6($.statePath),z=await $6($.configPath)}catch(W){if(u1(W))break;throw W}if(J!==z){if(Z<2)await V3(2+Math.floor(Math.random()*4));continue}let G=x1(w1(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=i$(w1(X));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:h1(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 Z0($,Z,J,X="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:$.reason});return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,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 U3{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,J,X,z){this.ctx=$,this.snapshot=Z,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return h1(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 J=this.entry($);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let Z=this.stateAccount($)?.[g];return S(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){G2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),r4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(S(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return y1(this.config)}entry($){return this.entries(),R0(this.config,$)}setEntry($,Z){o4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=v1(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=S(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return S(J)?J:void 0}dropStateAccount($){if(S(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!S(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(),J=new Set;for(let B of Z)if(S(B)&&typeof B.id==="string")J.add(B.id);let X=new Set;for(let B of R2(this.snapshot.config))if(S(B)&&typeof B.id==="string"&&!J.has(B.id))X.add(B.id);for(let B of Object.keys(this.entries()))if(!J.has(B))X.add(B);$3(this.config,X);let z=this.entries(),G={};for(let[B,Y]of Object.entries(z))if(J.has(B))Object.defineProperty(G,B,{value:Y,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[v],W={...this.config,version:z4,accounts:Z,[v]:{...Q,schemaVersion:i0,[N0]:G}};await this.write(this.ctx.configPath,W,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let B of X)this.ctx.removedIds.add(B);this.config=W}),this.config=W}async commitState($,Z={}){let J={...this.state,version:z4,accounts:S(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,Z.durable??!1),this.state=J,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await m1(this.ctx.statePath)}catch($){throw new b({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 m1(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await B3($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${J}-write`,this.info),await this.locks.assertAll()}},()=>{if(X)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${J}-write`,this.info)}}async function q3($,Z){let J=new v0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let W of $.storeLocks)await J.acquire(W);let z=await n($);if(z.status==="error")throw Z0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[W,B]of Object.entries(z.config))if(!Z.includes(W))G[W]=B;G.version=z4,G[v]={schemaVersion:i0,[N0]:{}};let Q={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",Q),await J.assertAll()}}),X.writes++,await $.onStep?.("after-config-write",Q),"initialized"}catch(z){throw o0(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function w($,Z,J,X,z,G={}){let Q=Z.held.length;try{for(let Y of $.storeLocks)await Z.acquire(Y);let W=await n($);if(W.status!=="ready")throw Z0(W,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let B=new U3($,W,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))B.assertNotStaged(X.rowId);if(G.completeTorn??!0)await B.completeTorn();return await z(B)}finally{await Z.releaseTo(Q)}}function o0($,Z,J,X){let z=Z==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if(Z==="publishRoster"&&X.publicationDecided)return new b({operation:Z,...J!==void 0?{rowId:J}:{},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 Q3)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof b){if($.phase===z&&$.rowId===J&&$.operation===Z&&$.committed===G)return $;return new b({operation:Z,...J!==void 0?{rowId:J}:{},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,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof Y3)return new b({...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 W3)return new b({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new b({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function l($,Z,J,X,z){let G=new v0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(W){let B=o0(W,Z,J,Q);if(B.kind!=="after-persist-hook")await s$(Z,X,J,B,$.logger);throw B}finally{await G.releaseAll()}}function J0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(h(Z))}`,path:$.ctx.statePath}}async function M0($,Z,J){let X=await n($.ctx);if(X.status!=="ready")throw Z0(X,Z,J);let z=X.rows.find((Y)=>Y.id===J),G=R0(X.config,J),Q=X.state.accounts,W=S(Q)&&Object.hasOwn(Q,J)?Q[J]:void 0,B=S(W)?W[g]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))G2(Z,J,G.staged);if(!z&&S(B)&&Object.hasOwn(B,"staged"))G2(Z,J,B.staged);if(!z)throw B0(Z,J);return{result:X,row:z}}function B0($,Z){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function o($,Z){if(Z.unbound)throw O($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function O($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function p1($,Z){if(!s(Z?.credentialEpoch))throw O("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function W4($,Z,J){if(!J)throw B0("pull",$);if(J.invalid)throw O("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw O("pull",$,"no-credential",`row ${$} holds no credential`);if(o("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==Z.credentialEpoch||J.identity!==Z.identity)throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function Y4($,Z,J,X){let z=G0(()=>$.codec.merge(J,X));if(!G0(()=>$.codec.validate(z)))throw O("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function J6($,Z,J,X){let{ctx:z}=$,G=new v0(z.lockDefaults,z.lockEnv),Q={writes:0};try{p1(Z,J),await w(z,G,Q,{operation:"pull",rowId:Z},async(W)=>{W.assertNotStaged(Z);let B=W.row(Z);W4(Z,J,B);let Y=W.entry(Z);if(!Y)throw B0("pull",Z);let H=Y4(z,Z,Y.quota,X);W.setEntry(Z,{...Y,quota:H,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw o0(W,"pull",Z,Q)}finally{await G.releaseAll()}}async function j3($,Z,J={}){c$();let{ctx:X}=$;await l(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let V of X.storeLocks)await z.acquire(V);let Q=await n(X);if(Q.status!=="ready")throw Z0(Q,"updateLimitsNamespace",void 0);let W=Q.rows.map(({id:V,credentialEpoch:U,identity:j})=>({id:V,credentialEpoch:U,identity:j})),B=await Q0("updateLimitsNamespace",()=>Z(structuredClone(Q.config.commonAuthLimits),W)),Y={...Q.config,commonAuthLimits:B},H={operation:"updateLimitsNamespace",rowId:void 0};try{await P0(X.configPath,Y,{beforeRename:async()=>{await X.onStep?.("before-config-write",H),await z.assertAll(),J.beforePublish?.()}})}catch(V){if(V&&typeof V==="object"&&"published"in V&&V.published===!0)J.onPublished?.();throw V}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",H)})}function h0($,Z,J,X,z="the provider state"){if(!$)throw O(Z,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(X);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw O(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!G0(()=>$.validate(G)))throw O(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function V4($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:h0($,Z,J,G0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function F3($,Z,J,X,z){let G=$?.onReplace,Q=G?G0(()=>G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:J,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...X!==void 0?{identity:X}:{},...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:h0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function K3($,Z,J,X,z){if(Z.kind==="set")return E2($,Z.value);if(Z.kind==="clear")return;return G4(J,X?.credential,z,X?.identity)}async function N3($,Z,J,X,z={}){a("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return l(G,Q,Z,z.onFailure,async(W,B)=>{let Y=G.providerState;if(!Y)throw O(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw O(Q,Z,"invalid-input","a mutator is required");let H=S(J)?J.credentialEpoch:void 0;if(!s(H))throw O(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await M0($,Q,Z);await W.acquire(J0($,V));for(let U of z.extraLocks??[])await W.acquire(U);return w(G,W,B,{operation:Q,rowId:Z},async(U)=>{let j=U.row(Z);if(!j)throw B0(Q,Z);if(h(j)!==h(V))throw O(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(j.invalid)throw O(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!j.credential)throw O(Q,Z,"no-credential",`row ${Z} holds no credential`);if(o(Q,j),(j.credentialEpoch??1)!==H||j.identity!==J.identity)throw O(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let F=await l1(U,Y,Q,j,X);if(F.kind!=="changed")return{id:Z,outcome:"unchanged",...F.kind==="unchanged"&&F.value!==void 0?{providerState:F.value}:{}};return U.setStateAccount(Z,F.account),await U.commitState(),F.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:F.value}})})}var D3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function l1($,Z,J,X,z,G=!1){let{id:Q,credential:W}=X;if(!W)throw O(J,Q,"no-credential",`row ${Q} holds no credential`);let B=X.credentialEpoch??1,Y=$.stateAccount(Q),H=Y?.[g],V=e(H);if(!S(H)||!V?.binding||V.digest!==E0(W)||V.credentialEpoch!==B||V.binding.identity!==X.identity)throw O(J,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let U=X.providerState===void 0?void 0:structuredClone(X.providerState),j=await Q0(J,()=>z(U,X));if(G&&j===D3)return{kind:"declined"};let q=j===void 0?void 0:h0(Z,J,Q,j,"the provider state the mutator returned"),F=Y!==void 0&&Object.hasOwn(Y,r);if(q===void 0?!F:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(q))return{kind:"unchanged",...q!==void 0?{value:q}:{}};let K={...Y};if(q===void 0){delete K[r];let N={...H};delete N.providerState,K[g]=N}else{K[r]=q;let N=E2(Z,q);if(V.providerState!==N)K[g]={...H,providerState:N}}return{kind:"changed",...q!==void 0?{value:q}:{},account:K}}import{randomUUID as P3}from"node:crypto";async function Q6($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:Q,type:W,label:B,enabled:Y,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}=G;return{id:Q,type:W,label:B,enabled:Y,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}}),z=await Q0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw O($.info.operation,Z,"row-protected",z)}var dJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function cJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function sJ($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!S(X)){if(J.baseURL===void 0)throw O($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:cJ(X),Q=J.baseURL?.trim()??G.baseURL,W=J.authHeader??G.authHeader;if(Q!==G.baseURL||W!==G.authHeader)throw O($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:Q,authHeader:W}}function M3($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),Q=X??(G?G.identity:S(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function X6($,Z,J,X,z={}){let G=sJ(Z,J,X),Q=Z.stateAccount(J),W=z.providerState??{kind:"keep"},B=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,Y=typeof B==="number"?B:1,H=K3($.ctx.providerState,W,Q,Q&&Object.hasOwn(Q,r)?Z.row(J):void 0,Y),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??Q4(V,$.ctx.now()):void 0,j={...Q??{}};for(let K of dJ)delete j[K];if(z.clearErrors)delete j.lastRefreshError,delete j.lastQuotaRefreshError,delete j.quota;if(W.kind==="clear")delete j[r];else if(W.kind==="set")j[r]=W.value;let q=J3(G,U),F={...j,...Z3(G,U),[g]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[e4]:z.transition}:{},...k1(q,Y,z.binding??M3(Z,J,q,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:q,account:F}}async function z6($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function B6($,Z,J,X,z={}){return z6(Z,J,X6($,Z,J,X,z))}async function aJ($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=G4(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[g]:k1(Z.credential,Z.credentialEpoch??1,M3($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function c1($,Z,J){let X=$==="add"?A2(Z):void 0;if(X)throw O($,Z,"invalid-input",X);let z=X3(J,{baseURLOptional:$==="rotate"});if(z)throw O($,Z,"invalid-input",z)}function W6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw O($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function k2($,Z,J){if(J!==void 0&&!s(S(J)?J.credentialEpoch:void 0))throw O($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function Y6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw O($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function G6($,Z){return O($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function H4($,Z){return O($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function nJ($,Z,J,X){let{id:z,credential:G,identity:Q}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!b2(Z.state,z))return;let W=()=>{throw O("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},B=Z.stateAccount(z),Y=e(B?.[g]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return W();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return W();let H=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[V]=r0({accounts:[I2({id:z,credential:H,identity:Y.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:t4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return W();if(Q!==void 0&&Q!==V.identity)return W();if(E0(G)!==Y.digest)return W();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return W();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return W()}else if(f0(G)!==Y.dispatch)return W();if(Y.providerState!==void 0&&V.providerState===void 0)return W();if(X!==void 0&&E2($.ctx.providerState,X)!==Y.providerState)return W();return V}function iJ($,Z,J,X){let{id:z,credential:G,identity:Q,label:W}=J,B=Z.rosterRow(z),Y=()=>{throw O("add",z,B?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=Z.stateAccount(z),V=e(H?.[g]),U=V?.staged;if(!V?.binding||!U||V.replace||V.dispatch===void 0)return Y();if(B&&(B.type!==G.type||B.label!==W||B.accountId!==Q))return Y();if(U.reservation!==J.stage?.reservation||U.label!==W||U.disabledReason!==J.disabled?.reason||V.binding.identity!==Q)return Y();let j=X===void 0?void 0:Q2(X),q=H?.[r],F=q===void 0?void 0:Q2(q);if(U.providerState!==j||U.providerState!==F)return Y();if(E0(G)!==V.digest||f0(G)!==V.dispatch)return Y();let K=B?Z.config:{accounts:[{...I2({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},N=r0(K,Z.state,$.ctx.codec,$.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==U.label||N.identity!==V.binding.identity||N.disabledReason!==U.disabledReason||N.staged?.reservation!==U.reservation)return Y();if(B)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(t4(Z.config,z)!==V.credentialEpoch)return Y();return Z.roster().push({...I2({id:z,credential:G,identity:Q,label:W,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function C3($,Z,J={}){a("add");let{ctx:X}=$,{id:z,credential:G,identity:Q,label:W}=Z,B=Z.stage!==void 0||Z.disabled!==void 0,Y=await l(X,"add",z,J.onFailure,async(H,V)=>{c1("add",z,G);let U=J.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw O("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(U)||Z.stage!==void 0&&(W!==void 0&&typeof W!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!S(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!S(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||U==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw O("add",z,"invalid-input","staging requires a reservation and a disabled reason");let j=Z.providerState===void 0?void 0:h0(X.providerState,"add",z,Z.providerState);if(await H.acquire(J0($,{id:z,identity:Q})),G.type==="oauth")await H.acquire(J.providerLock??$.providerLock);for(let q of J.extraLocks??[])await H.acquire(q);return w(X,H,V,{operation:"add",rowId:z},async(q)=>{await Q6(q,z,J.protect);let F=S(q.state.accounts)?q.state.accounts:{},K=Object.entries(F).find(([I,f])=>{if(I===z||q.rosterRow(I)||!S(f))return!1;let c=f[g];if(!S(c)||!Object.hasOwn(c,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw O("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw O("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&U!=="rotate"&&(q.rosterRow(z)||b2(q.state,z)))return iJ($,q,Z,j);if(U==="rotate"){q.assertNotStaged(z);let I=q.rows().find((f)=>f.fingerprint===D0(G));if(I)q.assertNotStaged(I.id)}if(U==="refuse"){let I=q.rows().find((a0)=>a0.fingerprint===D0(G)||a0.id===z&&a0.credential),f=S(q.state.accounts)?q.state.accounts:{},c=Object.entries(f).find(([,a0])=>{if(!S(a0))return!1;if(G.type==="oauth")return a0.refresh===G.refresh;return typeof a0.apiKey==="string"&&a0.apiKey.trim()===G.apiKey.trim()})?.[0],p$=I?.id??c??z;if(I||c!==void 0||b2(q.state,z))throw O("add",p$,"credential-exists",`row ${p$} already holds this secret or id`)}if(U==="stage-duplicate"&&(q.rosterRow(z)||b2(q.state,z)))throw O("add",z,"id-exists",`row ${z} already exists`);let N=nJ($,q,Z,j),D=q.rows(),T=D0(G),M=U==="rotate"&&!N&&D.find((I)=>I.invalid===void 0&&I.fingerprint===T);if(M){if(q.assertNotStaged(M.id),o("add",M),Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw G6("add",M.id);let I=X6($,q,M.id,G,{...j!==void 0?{providerState:V4(X.providerState,"add",M.id,M.providerState,j)}:{}});await q.completeTorn(),q.assertNotStaged(M.id);let f=await z6(q,M.id,I);return{id:M.id,outcome:"rotated",credential:f,credentialEpoch:M.credentialEpoch??1}}let P=D.find((I)=>I.id===z);if(P){if(P.invalid)throw O("add",z,"invalid-row",`row ${z} is invalid`);if(P.credential)throw O("add",z,"id-exists",`row ${z} already holds a credential`);if(o("add",P),P.type!==G.type)throw O("add",z,"type-mismatch",`row ${z} is a ${P.type} row`);if(Q!==void 0&&P.identity!==void 0&&Q!==P.identity)throw G6("add",z);if(!P.hasEntry)q.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=X6($,q,z,G,{clearErrors:!0,...j!==void 0?{providerState:{kind:"set",value:j}}:{}});await q.completeTorn();let f=await z6(q,z,I);if(!P.hasEntry)await q.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:P.credentialEpoch??1}}let _=t4(q.config,z);if(!s(_))throw O("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=N?.identity??Q;q.roster().push(I2({id:z,credential:G,...C!==void 0?{identity:C}:{},...W!==void 0?{label:W}:{},addedAt:X.now()})),q.setEntry(z,{credentialEpoch:_,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let L="added";if(Z.disabled)n0(q,z,Z.disabled.reason),L="added-disabled";if(!Z.disabled&&C!==void 0&&G.type==="oauth"){if(D.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))n0(q,z,R1),L="added-disabled"}if(N?.credential)return await q.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??_};q.dropStateAccount(z);let A=X6($,q,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...W!==void 0?{label:W}:{},...j!==void 0?{providerState:Q2(j)}:{}}}:{},...j!==void 0?{providerState:{kind:"set",value:j}}:{}});if(U==="rotate")await q.completeTorn();let x=await z6(q,z,A);return await q.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:_}},{completeTorn:!1})});if(!B&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))$.firePull(Y.id,"add");return Y}async function T3($,Z,J,X={},z={}){a("replace");let{ctx:G}=$,Q=await l(G,"replace",Z,z.onFailure,async(W,B)=>{c1("replace",Z,J),k2("replace",Z,z.attribution);let Y=X.providerState===void 0?void 0:h0(G.providerState,"replace",Z,X.providerState),{row:H}=await M0($,"replace",Z);if(await W.acquire(J0($,H)),J.type==="oauth")await W.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await W.acquire(V);return w(G,W,B,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)Y6("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let U=W6("replace",Z,V.row(Z),J);if(h(U)!==h(H))throw H4("replace",Z);let j=V.entry(Z)?.credentialEpoch,q=(typeof j==="number"?j:1)+1;if(!s(q))throw O("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let F=F3(G.providerState,U,q,X.identity,Y),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(f1(V,Z,q,K),X.identity!==void 0)S2(V,X.identity);let N=await B6($,V,Z,J,{clearErrors:!0,binding:K,providerState:F});return await V.commitConfig(),{id:Z,credential:N,credentialEpoch:q}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return Q}async function L3($,Z,J,X={},z={}){a("rotate");let{ctx:G}=$;return l(G,"rotate",Z,z.onFailure,async(Q,W)=>{c1("rotate",Z,J),k2("rotate",Z,z.attribution);let B=X.providerState===void 0?void 0:h0(G.providerState,"rotate",Z,X.providerState),{row:Y}=await M0($,"rotate",Z);if(await Q.acquire(J0($,Y)),X.identity!==void 0&&J.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await Q.acquire(H);return w(G,Q,W,{operation:"rotate",rowId:Z},async(H)=>{if(z.attribution!==void 0)Y6("rotate",Z,H.row(Z),z.attribution),await H.completeTorn();let V=W6("rotate",Z,H.row(Z),J);if(h(V)!==h(Y))throw H4("rotate",Z);if(o("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw G6("rotate",Z);let U=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,j=await B6($,H,Z,J,{identity:U,...B!==void 0?{providerState:V4(G.providerState,"rotate",Z,V.providerState,B)}:{}}),q=!1;if(!V.hasEntry)H.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),q=!0;if(X.identity!==void 0&&V.identity!==X.identity)z2(H,Z,X.identity),q=!0;if(q)await H.commitConfig();return{id:Z,credential:j}},{completeTorn:z.attribution===void 0})})}async function _3($,Z,J,X,z){a(Z);let{ctx:G}=$,Q=G.providerState,W=z.attribution,B=z.providerState;return l(G,Z,J,z.onFailure,async(Y,H)=>{if(k2(Z,J,W),B!==void 0){if(typeof B!=="function")throw O(Z,J,"invalid-input","the provider-state mutator must be a function");if(W===void 0)throw O(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw O(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await M0($,Z,J);await Y.acquire(J0($,V));for(let U of z.extraLocks??[])await Y.acquire(U);return w(G,Y,H,{operation:Z,rowId:J},async(U)=>{await Q6(U,J,z.protect),U.assertNotStaged(J);let j=U.row(J),q=X.enabled?W6("enable",J,j):j;if(!q||!U.rosterRow(J))throw B0(Z,J);if(h(q)!==h(V))throw H4(Z,J);if(W!==void 0)Y6(Z,J,q,W);if(X.enabled&&q.disabledReason?.startsWith(O2))throw O("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let F=!X.enabled||!q.enabled||q.disabledReason!==void 0;if(X.enabled&&F&&q.type==="oauth"){let M=q.identity===void 0?void 0:U.rows().find((P)=>P.id!==J&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===q.identity);if(M)throw O("enable",J,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${J}`)}if(B===void 0||Q===void 0){if(await U.completeTorn(),!F)return{id:J};if(X.enabled)J4(U,J);else n0(U,J,X.reason);return await U.commitConfig(),{id:J}}if(!q.credential)throw O(Z,J,"no-credential",`row ${J} holds no credential`);o(Z,q);let K=await l1(U,Q,Z,q,B,!0);if(K.kind==="declined")return{id:J,declined:!0};await U.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(F){if(X.enabled)J4(U,J);else n0(U,J,X.reason);await U.commitConfig()}return N}if(!F)return U.setStateAccount(J,K.account),await U.commitState(),N;let D=X.enabled?{mark:P3(),enabled:!0}:{mark:P3(),enabled:!1,reason:X.reason},T=K.account[g];return U.setStateAccount(J,{...K.account,[g]:{...T,[e4]:D}}),await U.commitState(),B4(U,J,D),await U.commitConfig(),N},{completeTorn:!1})})}function O3($,Z,J,X={}){return _3($,"disable",Z,{enabled:!1,reason:J},X)}function S3($,Z,J={}){return _3($,"enable",Z,{enabled:!0},J)}async function A3($,Z,J={}){a("remove");let{ctx:X}=$;return l(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw O("remove",Z,"invalid-input","id must be non-empty");let Q=J.attribution;if(k2("remove",Z,Q),J.staged!==void 0&&(!S(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw O("remove",Z,"invalid-input","a staged removal needs a reservation");let W=await n(X);if(W.status!=="ready")throw Z0(W,"remove",Z);let B=W.rows.find((H)=>H.id===Z);if(!B&&!b2(W.state,Z))throw B0("remove",Z);let Y=h(B??{id:Z});await z.acquire(J0($,B??{id:Z}));for(let H of J.extraLocks??[])await z.acquire(H);return w(X,z,G,{operation:"remove",rowId:Z},async(H)=>{let V=H.reservation(Z);if(V!==void 0){if(!S(V)||!J.staged||V.reservation!==J.staged.reservation)throw O("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw O("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=H.row(Z),j=b2(H.state,Z);if(!U&&!j)throw B0("remove",Z);if(h(U??{id:Z})!==Y)throw H4("remove",Z);if(Q!==void 0)if(U)V6(Z,U,Q);else rJ($,H,Z,Q);let q=J.protect;if(q){let F={row:U,config:H.snapshot.config,state:H.snapshot.state},K=await Q0("remove",()=>q(Z,F));if(K!==void 0)throw O("remove",Z,"row-protected",K)}if(U){if(Q===void 0)await H.completeTorn();H.dropRosterRows(Z),await H.commitConfig()}if(j)H.dropStateAccount(Z),await H.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function V6($,Z,J,X="remove"){if(Y6(X,$,Z,J),Z.torn)throw O(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw O(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function rJ($,Z,J,X){let z=()=>O("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(J),Q=e(G?.[g]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let W;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();W={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")W={type:"oauth",refresh:G.refresh};else throw z();let[B]=r0({accounts:[I2({id:J,credential:W,identity:Q.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!B?.credential||B.invalid||B.stamp!=="bound")throw z();if(Q.credentialEpoch!==X.credentialEpoch||Q.binding.identity!==X.identity)throw O("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function b2($,Z){let J=$.accounts;return S(J)&&Object.hasOwn(J,Z)}function d1($){return S($)&&typeof $.id==="string"?$.id:void 0}function oJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let Q=d1(G);if(Q!==void 0)J.add(Q)}let X=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(X.has(G))return`id ${G} appears more than once`;if(!J.has(G))return`id ${G} is not in the roster`;X.add(G)}let z=[...J].filter((G)=>!X.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function tJ($,Z){let J=new Map;for(let G of $){let Q=d1(G);if(Q===void 0)continue;let W=J.get(Q);if(W)W.push(G);else J.set(Q,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>d1(G)===void 0?G:X[z++])}async function E3($,Z,J={}){a("reorder");let{ctx:X}=$,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let W of J.extraLocks??[])await G.acquire(W);return w(X,G,Q,{operation:"reorder",rowId:void 0},async(W)=>{let B=W.roster(),Y=oJ(B,Z);if(Y)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let H=[...Z],V=tJ(B,H);if(V.every((U,j)=>U===B[j]))return{ids:H,outcome:"unchanged"};return W.config.accounts=V,await W.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function R3($,Z,J,X,z={}){return a("recordIdentity"),l($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw O("recordIdentity",Z,"invalid-input","identity must be non-empty");let W=S(X)?X.credentialEpoch:void 0;if(!s(W))throw O("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:B}=await M0($,"recordIdentity",Z);await G.acquire(J0($,B)),await G.acquire(z.providerLock??$.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return w($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(Y)=>{let H=W6("recordIdentity",Z,Y.row(Z));if(h(H)!==h(B))throw H4("recordIdentity",Z);if(o("recordIdentity",H),(H.credentialEpoch??1)!==W)throw O("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw G6("recordIdentity",Z);if(H.identity===void 0)await aJ(Y,H,J);let V=z2(Y,Z,J);return await Y.commitConfig(),{id:Z,disabled:V}})})}function b3($){let Z=$[v];return S(Z)&&S(Z.publications)?Z.publications:{}}function k3($,Z){let J=b3($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!S(X)||X.operationId!==Z||typeof X.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(X.planDigest)||!["committed","cleaned"].includes(String(X.phase))||!Array.isArray(X.removed)||!Array.isArray(X.finalized)||X.removed.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch))||X.finalized.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw O("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function x3($,Z){let J=await n($.ctx);if(J.status!=="ready")throw Z0(J,"publishRoster",Z);return k3(J.config,Z)}function eJ($,Z){let J=()=>{throw O("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))J();let X=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!S(z)||typeof z.id!=="string"||A2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),k2("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();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"))J();if(Z.order.some((z)=>typeof z!=="string"||A2(z))||new Set(Z.order).size!==Z.order.length)J()}function y3($,Z){$.entries();let J=$.config[v],X={...b3($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function $X($,Z,J){let X=new Set;for(let Q of R2($.config)){if(!S(Q)||typeof Q.id!=="string")continue;if(X.has(Q.id))throw O("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(Q.id)}let z=new Set(Z.remove.map((Q)=>Q.id)),G=J.filter((Q)=>Q.invalid!=="roster"&&!z.has(Q.id));if(G.length!==Z.order.length||Z.order.some((Q)=>!G.some((W)=>W.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw O("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function I3($,Z){await $.assertAll();for(let X of Z.removed)if(e($.stateAccount(X.id)?.[g])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=e(z?.[g]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let Q={...z[g]};delete Q.staged,$.setStateAccount(X.id,{...z,[g]:Q})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return y3($,J),await $.commitConfig({durable:!0}),J}async function g3($,Z,J={}){return a("publishRoster"),l($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw O("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=Q2(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((W)=>S(W)&&typeof W.id==="string");for(let W=0;;W++){let B=await n($.ctx);if(B.status!=="ready")throw Z0(B,"publishRoster",Z.operationId);let Y=new Map(Q.map(({id:V})=>[V,h(B.rows.find((U)=>U.id===V)??{id:V})]));for(let V of[...new Set(Y.values())].sort())await X.acquire(J0($,{id:V}));await X.acquire(J.providerLock??$.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await w($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let U=V.rows();if(Q.some(({id:P})=>h(U.find((_)=>_.id===P)??{id:P})!==Y.get(P)))return;let j=k3(V.config,Z.operationId);if(j){if(j.planDigest!==G)throw O("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(j.phase==="cleaned")return{outcome:"already-cleaned",receipt:j};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await I3(V,j)}}eJ($,Z);let q=$X(V,Z,U),F=[];for(let P of Z.remove){V.assertNotStaged(P.id);let _=U.find((C)=>C.id===P.id);if(!_)throw O("publishRoster",P.id,"attribution","the removed row no longer exists");if(V6(P.id,_,P.attribution,"publishRoster"),!_.credential||P.fingerprint!==void 0&&D0(_.credential)!==P.fingerprint)throw O("publishRoster",P.id,"attribution","the removed secret no longer matches");F.push(_)}let K=[];for(let P of Z.finalize){let _=U.find((f)=>f.id===P.id),C=e(V.stateAccount(P.id)?.[g]);if(!_||_.staged?.reservation!==P.reservation||C?.staged?.reservation!==P.reservation||_.enabled)throw O("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(P.id),A=V.rosterRow(P.id),x=L?.[r],I=x===void 0?void 0:Q2(x);if(!C?.staged||C.staged.label!==A?.label||C.staged.disabledReason!==_.disabledReason||C.staged.providerState!==I)throw O("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");V6(P.id,_,P.attribution,"publishRoster"),K.push(_)}let N=q.find((P)=>P.torn);if(N)throw O("publishRoster",Z.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let D=new Set;for(let P of q){if(!(Z.finalize.find((C)=>C.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(D.has(P.identity))throw O("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");D.add(P.identity)}for(let P of q)if(P.identity!==void 0&&P.fingerprint!==void 0&&q.some((_)=>_.id!==P.id&&_.identity!==void 0&&_.identity!==P.identity&&_.fingerprint===P.fingerprint))throw O("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of K)if(P.identity!==void 0&&F.some((_)=>_.identity!==void 0&&_.identity!==P.identity&&_.fingerprint===P.fingerprint))throw O("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await Q6(V,Z.operationId,J.protect);let T={operationId:Z.operationId,planDigest:G,phase:"committed",removed:F.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:Z.finalize.map((P,_)=>({id:P.id,credentialEpoch:K[_]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of Z.remove)V.dropRosterRows(P.id);for(let P of Z.finalize){let _=V.rosterRow(P.id);_.enabled=P.enabled;let C={...V.entry(P.id)};if(delete C.staged,P.enabled)delete C.disabledReason;else C.disabledReason=P.disabledReason;V.setEntry(P.id,C)}let M=V.roster().filter((P)=>!S(P)||typeof P.id!=="string"||U.find((_)=>_.id===P.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((P)=>V.rosterRow(P)),...M],y3(V,T),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await I3(V,T)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),W>=1)throw O("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class s1{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,J,X,z){this.rt=$,this.hook=Z,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let J=this.run($,Z);this.inflight.add(J),J.finally(()=>this.inflight.delete(J))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let J=this.rt(),{ctx:X}=J,z=new v0(X.lockDefaults,X.lockEnv),G={writes:0};try{let Q=await w(X,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let H=Y.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)o("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.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(),!Q){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let W;try{W=await this.hook?.(Q)}catch(Y){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await(J.publishQuota??((Y,H,V)=>J6(J,Y,H,V)))($,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},W)}catch(Q){this.firedAtLoad.delete($);let W=o0(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,W)}catch(B){this.logger?.warn("pull failure hook threw",{rowId:$,error:B instanceof Error?B.message:String(B)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:W.kind})}finally{await z.releaseAll()}}}var f3=100,H6=128;class a1{rt;timeoutMs;clock;pending=new Map;warned=new Set;wake=new Set;logger;timer;committedAt;running;closing;closed=!1;stopped=!1;failures=0;constructor($,Z=1000,J=h3){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??t("store")}async record($,Z,J){try{this.assertOpen($),p1($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await M0(this.rt,"pull",$);W4($,X.attribution,z),Y4(this.rt.ctx,$,this.overlayRow({...z,quota:R0(G.config,$)?.quota}).quota,X.observation),await this.room($),this.assertOpen($);let Q=this.pending.get($)??[];if(Q.push(X),this.pending.set($,Q),Q.length>=H6)this.flushNow();else this.schedule(f3)}catch(X){throw o0(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<H6)return;let{ctx:Z}=this.rt,J=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued($)>=H6){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw O("pull",$,"lock-contention",`pool quota queue for ${$} is full (${H6} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let Q=()=>{clearTimeout(W),this.wake.delete(Q),G()},W=setTimeout(Q,z);this.wake.add(Q)})}}assertOpen($){if(this.closed)throw O("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{W4($.id,J.attribution,$),Z={...Z,quota:Y4(this.rt.ctx,$.id,Z.quota,J.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;let Z=this.closed?0:(this.committedAt??-1/0)+v3-this.clock.now();if(this.timer=this.clock.schedule(Math.max($,Z),()=>{return this.timer=void 0,this.flush()}),!this.closed)this.timer.unref?.()}cancelTimer(){this.timer?.cancel(),this.timer=void 0}flushNow(){if(this.running)return;this.cancelTimer(),this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return this.running??Promise.resolve();let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new v0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await w(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let Q of $){let{id:W,attribution:B,observation:Y}=Q,H=JSON.stringify([W,B.credentialEpoch,B.identity]);try{z.assertNotStaged(W),W4(W,B,z.row(W))}catch(j){if(!(j instanceof b))throw j;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:W,kind:j.kind});continue}let V=z.entry(W);if(!V)continue;let U;try{U=Y4(Z,W,V.quota,Y)}catch(j){let q=`codec:${H}`;if(!this.warned.has(q))this.warned.add(q),this.warn("pool quota publication dropped; the quota codec refused it",{id:W,error:j instanceof Error?j.message:String(j)});continue}z.setEntry(W,{...V,quota:U,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set($);for(let[z,G]of this.pending){let Q=G.filter((W)=>!X.has(W));if(Q.length)this.pending.set(z,Q);else this.pending.delete(z)}this.failures=0}catch(X){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{await J.releaseAll(),this.running=void 0;for(let z of this.wake)z();let X=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):f3;this.schedule(X)}})(),this.running}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){this.cancelTimer();let $,Z,J=new Promise((X)=>{Z=()=>{if(!this.pending.size)X()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([J,new Promise((X)=>{$=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),this.cancelTimer(),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((X,z)=>X+z.length,0)});this.pending.clear();for(let X of this.wake)X()}}}import{randomUUID as ZX}from"node:crypto";function n1($,Z){if(G2("refresh",$,Z?.staged),!Z)throw O("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw O("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw O("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw O("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function m3($){return O("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function w3($,Z,J,X={}){a("refresh");let{ctx:z}=$;return l(z,"refresh",Z,X.onFailure,async(G,Q)=>{let{row:W}=await M0($,"refresh",Z);n1(Z,W);let B=await X.refuse?.(W);if(B!==void 0)return{status:"refused",rowId:Z,reason:B};let Y=h(W),H;for(let q=0;;q++){await G.acquire(J0($,{id:Z,identity:Y===Z?void 0:Y})),await G.acquire(X.providerLock??$.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await w(z,G,{writes:0},{operation:"refresh",rowId:Z},async(N)=>{let D=n1(Z,N.row(Z));if(o("refresh",D),!D.hasEntry)N.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=n1(Z,N.row(Z));if(h(D)!==Y)return{keyNow:h(D)};let T=await X.refuse?.(D);if(T!==void 0)return{refused:T};return{row:D,credential:D.credential,credentialEpoch:D.credentialEpoch,identity:D.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),q>=1)throw O("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Y=K.keyNow;continue}H=K;break}if(g1(H.credential.lastRefreshedAt,z.now()))throw m3(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:q})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw O("refresh",Z,"provider","the provider returned no refresh token",!0);let U=V.providerState===void 0?void 0:h0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),j=await w(z,G,Q,{operation:"refresh",rowId:Z},async(q)=>{let F=q.row(Z),K=q.entry(Z);if(!F||F.invalid||!K||K.credentialEpoch!==H.credentialEpoch||F.identity!==H.identity)throw new b({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`});o("refresh",F);let N=await X.refuse?.(F);if(N!==void 0)return{refused:N};let D=z.now(),T=F.credential?.type==="oauth"?F.credential.lastRefreshedAt:void 0;if(g1(T,D))throw m3(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},P=F.identity!==void 0&&V.identity!==void 0&&F.identity!==V.identity?{expectedIdentity:F.identity,returnedIdentity:V.identity}:void 0,_=P?{mark:ZX(),enabled:!1,reason:`${O2}${JSON.stringify(P)}`}:void 0,C=F.identity===void 0&&V.identity?V.identity:void 0,L=await B6($,q,Z,M,{stamp:Q4(T,D),transition:_,identity:C,...U!==void 0?{providerState:V4(z.providerState,"refresh",Z,F.providerState,U)}:{}});if(_!==void 0)B4(q,Z,_),await q.commitConfig();let A=F.identity;if(C!==void 0)z2(q,Z,C),A=C,await q.commitConfig();return{stored:L,identity:A,contradiction:P,refused:void 0}});if(j.refused!==void 0)return{status:"refused",rowId:Z,reason:j.refused};if(j.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...j.contradiction,credential:j.stored};if(X.onPersisted)try{let q=X.onPersisted;await Q0("refresh",()=>q(Z,j.stored),!0)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:j.stored,message:"the after-persist hook threw; the rotation stays committed",cause:q})}return{status:"rotated",rowId:Z,credential:j.stored,...j.identity!==void 0?{identity:j.identity}:{}}})}import{isDeepStrictEqual as u3}from"node:util";var j6=Object.freeze(["version","accounts",v]);function U6($){let Z={};for(let[J,X]of Object.entries($))if(!j6.includes(J))q6(Z,J,X);return Z}function q6($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function JX($,Z){let J={};for(let[X,z]of Object.entries($))if(j6.includes(X)||X==="commonAuthLimits")q6(J,X,z);else if(Object.hasOwn(Z,X))q6(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))q6(J,X,z);return J}function i1($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var XX=new p3;function l3($){return d3($.ctx.configPath)}async function d3($){let Z=async([X=$]=[])=>{let z=await H3(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:U6(z.config)}},J=Z6?await Z():await XX.read([$],Z);return structuredClone(J)}async function c3($,Z,J={}){a("updateSettings");let{ctx:X}=$,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of J.extraLocks??[])await G.acquire(B);let W=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let B=await n(X);if(B.status!=="ready")throw Z0(B,"updateSettings",void 0);let Y=U6(B.config),H=structuredClone(Y),V=await Q0("updateSettings",()=>Z(H)),U=V===void 0?H:V;if(!S(U))throw i1("the settings mutator must produce an object");let j=j6.filter((K)=>Object.hasOwn(U,K));if(j.length>0)throw i1(`settings cannot set the pool-owned key(s) ${j.join(", ")}`);if(Object.hasOwn(U,"commonAuthLimits")&&(!Object.hasOwn(Y,"commonAuthLimits")||!u3(U.commonAuthLimits,Y.commonAuthLimits)))throw i1("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let q=JX(B.config,U);if(u3(U6(q),Y))return{settings:Y,outcome:"unchanged"};let F={operation:"updateSettings",rowId:void 0};return await P0(X.configPath,q,{beforeRename:async()=>{await X.onStep?.("before-config-write",F),await G.assertAll()}}),Q.writes++,await X.onStep?.("after-config-write",F),{settings:U6(q),outcome:"updated"}}finally{await G.releaseTo(W)}})}var s3=new Map;function zX($){let Z=s3.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},s3.set($,Z);return Z}function a3($){if($.status==="ready")return{status:"ready",schemaVersion:i0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function U4($){let Z=zX($.configPath),J={...r1,...$.lockOptions},X={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:J,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 s1(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Y,H)=>z.fire(Y,H)},Q=$.coalesceQuota?new a1(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,W=(Y,H,V)=>Q?Q.record(Y,H,V):J6(G,Y,H,V);G.publishQuota=W;let B=(Y)=>{if(Y.status==="ready"&&Q)return{...Y,rows:Q.overlay(Y.rows)};return Y};return{async load(){let Y=B(await n(X));if(Y.status==="ready"){for(let H of Y.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return a3(Y)},async read(){return a3(B(await n(X)))},async initialize(Y={}){return{status:await q3(X,Y.dropKeys??[])}},add:(Y,H)=>C3(G,Y,H),publishRoster:(Y,H)=>g3(G,Y,H),publication:(Y)=>x3(G,Y),replace:(Y,H,V,U)=>T3(G,Y,H,V,U),rotate:(Y,H,V,U)=>L3(G,Y,H,V,U),updateProviderState:(Y,H,V,U)=>N3(G,Y,H,V,U),disable:(Y,H,V)=>O3(G,Y,H,V),enable:(Y,H)=>S3(G,Y,H),remove:(Y,H)=>A3(G,Y,H),reorder:(Y,H)=>E3(G,Y,H),readSettings:()=>l3(G),updateSettings:(Y,H)=>c3(G,Y,H),updateLimitsNamespace:(Y,H)=>j3(G,Y,H),recordIdentity:(Y,H,V,U)=>R3(G,Y,H,V,U),refresh:(Y,H,V)=>w3(G,Y,H,V),recordQuota:W,close:()=>Q?.close()??Promise.resolve(),dispose:()=>Q?.close()??Promise.resolve(),requestReading:(Y)=>z.fire(Y,"admission"),pullsSettled:()=>z.settled()}}var GX=[/\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 e1($={}){let{redactStrings:Z}=n3({...$,extraValuePatterns:[...GX,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class u extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var i3=/^[a-z][a-z0-9-]{0,63}$/,o1={code:"action-failed",text:"That action failed."},QX=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 q4($){if($ instanceof u)return{code:i3.test($.code)?$.code:o1.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:QX.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return o1}var r3="This cannot be undone. Continue?",BX=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function WX($){let Z=$.toLowerCase().replace(/[-_]/g,"");return BX.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function YX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function t1($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>t1(z,`${Z}[${G}]`,J));if(!YX($))return $;let X={};for(let[z,G]of Object.entries($)){if(WX(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:t1(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function o3($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=t1($,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:X.redacted});return z}function VX($){return{value:String($.value),label:String($.label)}}function HX($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(VX),...$.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 $9($){if($.irreversible===!0)return{message:$.confirm||r3,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function t3($){let Z=$9($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(HX),...Z?{confirm:Z}:{}}}function UX($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function qX($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:UX($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(t3)}}function jX($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(qX),actions:(Z.actions??[]).map(t3),...Z.facts!==void 0?{facts:Z.facts}:{}}}function e3($,Z,J){return{command:$,title:Z,sections:J.map(jX)}}function $5($,Z,J,X){return o3({command:$,menu:e3($,Z,J)},$,X)}function Z5($,Z,J,X,z){return o3({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:i3.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:e3($,Z,J)},$,z)}var W5="disabled from the command menu";function FX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C0($){return FX($)?{...$}:{}}function KX($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((J)=>{if(Z.has(J.id))return!1;return Z.add(J.id),!0})}function NX($,Z){return $.label??Z??$.id}function F6($,Z){return t0($.quota)?b0($.quota,Z):void 0}function Y5($,Z){return`${$} ${Z}${$===1?"":"s"}`}var x2="Actions";function DX($){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 J5($,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 X5($){return q4($).text}function J9($){if($.settings)return $.settings;let{store:Z,extraLocks:J}=$,X=J?{extraLocks:J}:{};return{async read(){let z=await Z.readSettings();return z.status==="error"?{}:z.settings},async update(z){await Z.updateSettings(z,X)}}}async function PX($){let{store:Z}=$,J=await Z.read(),X=await J9($).read(),z=await $.routing?.vaultOrder?.();return{load:J,rows:KX(J),settings:X,...z?{vault:z}:{}}}function K6($,Z){let J=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...J!==void 0?{identity:J}:{}},name:NX($,J)}}function MX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((V)=>V.id),Q=DX(Z.load),W=Z.rows.filter((V)=>V.enabled).length,B=Z.rows.map((V,U)=>{let{account:j,name:q}=K6(V,$),F=[V.type==="api"?"API key":"OAuth",...j.identity!==void 0?[j.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,W5,z),`Disabled ${q}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${q}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((D,T)=>({value:String(T+1),label:String(T+1)})),value:String(U+1)}],run:async({values:D})=>{let T=Number(D.position),M=G.filter((_)=>_!==V.id);return M.splice(T-1,0,V.id),(await J.reorder(M,z)).outcome==="unchanged"?`${q} is already at position ${T}.`:`Moved ${q} to position ${T}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${q}? Its stored credential is deleted.`,run:async()=>{return await J.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${q}.`}}),{id:V.id,label:q,detail:F,group:"Accounts",status:K,account:j,actions:N}}),Y=$.accounts?.login,H=[];if(Y&&!Q)H.push({id:"add",label:Y.label??"Add account",group:x2,knobs:Y.knobs??[],run:async({values:V,invocation:U})=>{let j=await Y.run(V,U);if(j.status==="cancelled")return{ok:!1,text:j.message??"Login cancelled."};if(j.status==="ready"){let q=await J.add(j.account,z);return J5(j.account.label??q.id,q)}return j.completion.then(async(q)=>{if(!q){U.notify("Login cancelled.","warning");return}let F=await J.add(q,z);U.notify(J5(q.label??F.id,F))},(q)=>{U.notify(`Adding the account failed: ${X5(q)}`,"error")}).catch((q)=>{U.notify(`Adding the account failed: ${X5(q)}`,"error")}),j.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${Y5(Z.rows.length,"account")}, ${W} enabled`],items:Q?[]:B,actions:H}}}function CX($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if($.quota?.check)await $.quota.check(H,V);else{for(let U of H)$.store.requestReading(U);await $.store.pullsSettled()}},Q=Z.rows.filter((H)=>H.candidate),W=Q.map((H)=>{let{account:V,name:U}=K6(H,$),j=F6(H,J);return{id:H.id,label:U,group:z,status:I0(j,{now:X,form:"compact"}),detail:I0(j,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:q})=>{return await G([H.id],q),`Checked quota for ${U}.`}}]}}),B=Z.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=K6(H,$),U=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",j=I0(F6(H,J),{now:X,form:"compact"});return`${V} (${U}): ${j}`}),Y=[];if(Q.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:x2,run:async({invocation:H})=>{let V=Q.map((U)=>U.id);return await G(V,H),`Checked quota for ${Y5(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:B,items:W,actions:Y}}}async function TX($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function Z9($){return new u("vault-invalid-order",$)}function LX($){let Z=$.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>Z.filter((z)=>z.id===X||z.label===X);return{ids:Z.map((X)=>X.id),nameOf:(X)=>Z.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let z=Z.find((G)=>G.id===X);return z&&!/[,\n]/.test(z.label)&&J(z.label).length===1?z.label:X},resolve:(X)=>{let z=[];for(let G of X){let Q=J(G);if(Q.length===0)throw Z9(`"${G}" is not a vault account.`);if(Q.length>1)throw Z9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let W=Q[0].id;if(z.includes(W))throw Z9(`"${G}" names an account already in the order.`);z.push(W)}return z}}}function _X($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=J9($),Q=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],W=C0(Z.settings.routing).mode,B=typeof W==="string"&&Q.some((N)=>N.value===W)?W:"ordered",Y=Q5(B),H=Z.vault?LX(Z.vault):void 0,V=H?H.ids:Z.rows.map((N)=>N.id),U=(N)=>H?H.nameOf(N):N,j=B5(V,Y.placement,$.routing?.formerMainId??G5),F=[`Mode: ${Q.find((N)=>N.value===B)?.label??B}`];if(V.length>0)F.push(`${H?"Vault account order":"Roster order"}: ${V.map(U).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==V.join())F.push(`Tried in order: ${j.map(U).join(", ")}`);let K=[{id:"mode",label:"Change mode",group:x2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:B}],run:async({values:N})=>{let D=String(N.mode);return await G.update((T)=>{T.routing={...C0(T.routing),mode:D};return}),`Routing mode set to ${Q.find((T)=>T.value===D)?.label??D}.`}}];if(V.length>1)K.push({id:"order",label:"Set order",group:x2,knobs:[{kind:"text",id:"order",label:H?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:H?V.map(H.entryOf).join(", "):V.join(", "),required:!0}],run:async({values:N})=>{let T=String(N.order).split(H?/[,\n]+/:/[\s,]+/).map((P)=>P.trim()).filter((P)=>P.length>0),M=Z.vault&&H?await TX(Z.vault,H.resolve(T)):await J.reorder(T,z);return M.outcome==="unchanged"?"The order is unchanged.":`Order set to ${M.ids.map(U).join(", ")}.`}});if($.routing?.sameAccountWait){let D=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],T=C0(Z.settings.routing).maxSameAccountWait,M=String(T===0||T==="max"?T:15),P=(_)=>D.find((C)=>C.value===_)?.label??_;F.push(`Longest wait on the same account: ${P(M)}`),K.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:x2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:D,value:M}],run:async({values:_})=>{let C=String(_.maxSameAccountWait),L=C==="max"?"max":Number(C);return await G.update((A)=>{A.routing={...C0(A.routing),maxSameAccountWait:L};return}),`Longest wait on the same account set to ${P(C)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:F,actions:K}}}function OX($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of F6(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function SX($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of F6(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,z5(G));return(z)=>X.get(z)??z}function AX($,Z){let J=J9($),X=C0(Z.settings.killswitch),z=X.enabled===!0,G=C0(X.accounts),Q=OX($,Z),W=SX($,Z),B=z?"on":"off",Y=Z.rows.map((H)=>{let{account:V,name:U}=K6(H,$),j=C0(G[H.id]),q=Q.filter((F)=>typeof j[F]==="number");return{id:H.id,label:U,group:`Floors · killswitch ${B}`,status:q.length===0?"no floors":q.map((F)=>`${W(F)} ≥${j[F]}%`).join(" · "),account:V,actions:[{id:"floors",label:"Set floors",knobs:Q.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${W(F)}`,min:0,max:100,...typeof j[F]==="number"?{value:j[F]}:{}})),run:async({values:F})=>{return await J.update((K)=>{let N=C0(K.killswitch),D=C0(N.accounts),T=C0(D[H.id]);for(let M of Q){let P=F[M];if(typeof P==="number")T[M]=P;else if(P===null)delete T[M]}if(Object.keys(T).length>0)D[H.id]=T;else delete D[H.id];if(Object.keys(D).length>0)N.accounts=D;else delete N.accounts;K.killswitch=N;return}),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${B}`],items:Y,actions:[{id:"killswitch",label:z?"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:x2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:H})=>{let V=H.enabled===!0;return await J.update((U)=>{U.killswitch={...C0(U.killswitch),enabled:V};return}),`Killswitch ${V?"on":"off"}.`}}]}}}async function V5($){let Z=await PX($);return[MX($,Z),CX($,Z),_X($,Z),AX($,Z)]}var EX=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),X9=["accounts","quota","routing","limits"];function H5($,Z){let{sessionId:J}=$,X=$.notify.bind($);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X(Z(String(z))):X(Z(String(z)),G)})}function RX($,Z){switch($.kind){case"choice":{let J=Z??$.value;if(typeof J==="string"&&$.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let J=Z??$.value;return typeof J==="boolean"?{value:J}:{problem:`${$.label} must be on or off.`}}case"number":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&X<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&X>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:X}}case"text":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${$.label} must be text.`}}}}function IX($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=RX(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function bX($,Z){let J=$.find((z)=>z.id===Z.sectionId);if(!J)return;return(Z.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function B2($){let Z=$.logger??t("commands"),J=e1($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},W=X9.filter((U)=>!Q[U]);for(let U of X9)if(Q[U]&&$[U]!==void 0)throw Error(`the ${U} section is replaced; its built-in options cannot also be given`);let B=$.store;if(W.length>0&&!B)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let Y=new Set;for(let U of G){if(EX.has(U.id)||Y.has(U.id))throw Error(`extra section id ${U.id} is taken`);Y.add(U.id)}async function H(U,j,q,F){try{return{id:U,slot:j,title:q.title,content:await q.build(F)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:U,error:J(K instanceof Error?K.message:String(K))}),{id:U,slot:j,title:q.title,content:{lines:["This section could not be loaded."]}}}}async function V(U){let j=B&&W.length>0?await V5({store:B,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.settings?{settings:$.settings}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],q=[];for(let F of X9){let K=Q[F];if(K)q.push(await H(F,F,K,U));else{let N=j.find((D)=>D.slot===F);if(N)q.push(N)}}if($.cache)q.push(await H("cache","cache",$.cache,U));if($.diagnostics)q.push(await H("diagnostics","diagnostics",$.diagnostics,U));for(let F of G)q.push(await H(F.id,"extra",F,U));return q}return{command:$.command,async open(U){let j=H5(U,J);return $5($.command,$.title,await V(j),X)},async apply(U,j){let q=H5(j,J),F=async(M)=>Z5($.command,$.title,await V(q),M,X),K=U.command===$.command?bX(await V(q),U):void 0;if(!K)return F({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=$9(K);if(N&&U.confirmed!==!0)return F({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=IX(K.knobs??[],U.values);if("problem"in D)return F({ok:!1,code:"invalid-input",text:D.problem});let T;try{let M=await K.run({values:D.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:q});T=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let P=q4(M);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:P.code,error:J(M instanceof Error?M.message:String(M))}),T={ok:!1,...P}}return F(T)}}}function kX($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function xX($){if($===null||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.command!=="string"||typeof Z.sectionId!=="string"||typeof Z.actionId!=="string")return;if(Z.itemId!==void 0&&typeof Z.itemId!=="string")return;if(Z.sessionId!==void 0&&typeof Z.sessionId!=="string")return;if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return;let J={};if(Z.values!==void 0){if(Z.values===null||typeof Z.values!=="object"||Array.isArray(Z.values))return;for(let[X,z]of Object.entries(Z.values)){if(!kX(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:Z.command,sectionId:Z.sectionId,actionId:Z.actionId,...typeof Z.itemId==="string"?{itemId:Z.itemId}:{},...Z.values!==void 0?{values:J}:{},...Z.confirmed===!0?{confirmed:!0}:{},...typeof Z.sessionId==="string"?{sessionId:Z.sessionId}:{}}}function R($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function U5($,Z){if($.kind!==Z.kind)return!1;if($.kind==="model")return Z.kind==="model"&&$.model===Z.model;if($.kind==="family")return Z.kind==="family"&&$.family===Z.family;return!0}function yX($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function N6($,Z,J){return $.excludedForRequest.some((X)=>R(X.account,Z)&&U5(X.scope,J))}function y2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>R(X.account,Z.account)&&U5(X.scope,Z.scope))?$.tried:[...$.tried,{account:{...Z.account},scope:{...Z.scope}}];return{...$,tried:J,saw429:$.saw429||Z.status===429,...Z.kind==="payment-balance"?{sawPaymentBalance:!0}:{},lastStatus:Z.status}}case"retain":{if(Z.cause==="credential-recovery"||$.retainedAttempts.includes(Z.attemptId))return $;let J=$.retains.find((X)=>R(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!R(X.account,Z.account)),{account:{...Z.account},count:(J?.count??0)+1,startedAt:J?.startedAt??Z.clockNow,lastRetainedAt:Z.clockNow}]}}case"exclude":if($.excludedAttempts.includes(Z.attemptId))return $;return{...$,excludedAttempts:[...$.excludedAttempts,Z.attemptId],excludedForRequest:N6($,Z.account,Z.scope)?$.excludedForRequest:[...$.excludedForRequest,{account:{...Z.account},scope:{...Z.scope}}]};case"switch":return $.switchedAttempts.includes(Z.attemptId)?$:{...$,switchedAttempts:[...$.switchedAttempts,Z.attemptId],switches:$.switches+1};case"blocked":return $.blockedSince===void 0?{...$,blockedSince:Z.clockNow}:$;case"selected":{let{blockedSince:J,...X}=$;return X}}}var z9=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function W2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function D6(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!R(Z.accountKey,Z.currentAccountKey)||!Number.isFinite(Z.lastAcceptedAt))return!1;let J=$.get(Z.sessionId);if(J&&J.lastAcceptedAt>Z.lastAcceptedAt)return!1;let X=typeof Z.ttlMs==="number"?[Z.ttlMs]:Z.ttlMs,z=X?.length?Math.max(...X.map(W2)):W2(void 0);if($.set(Z.sessionId,Object.freeze({accountKey:Object.freeze({...Z.accountKey}),lastAcceptedAt:Z.lastAcceptedAt,ttlMs:z})),$.size>256){let G,Q=Number.POSITIVE_INFINITY;for(let[W,B]of $)if(B.lastAcceptedAt<Q)G=W,Q=B.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function P6($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var j4=3621000;function m0($){return $===0||$===15||$==="max"?$:15}function F4($){let Z=m0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!R(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=W2(J.ttlMs),z=J.lastAcceptedAt+X;if(X===0||!Number.isFinite(z))return;return{cacheExpiresAt:z,maxWaitMs:Z==="max"?Number.POSITIVE_INFINITY:900000}}import{createHash as gX}from"node:crypto";function G9($,Z){let J=gX("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}function M6($,Z){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let J;for(let X of $.candidates){if(!R(X.account,X.readingAccount)||X.identity!==void 0&&X.readingIdentity!==void 0&&X.identity!==X.readingIdentity)continue;let z=X.windows.filter((B)=>B.blockedBy&&P6(B.scope,$.effectiveModel,$.familyOf));if(!z.length)continue;let G=z.map((B)=>{let Y=B.reset,H=Y?.observedAt??Y?.checkedAt;return Y&&H!==void 0&&Number.isFinite(H)&&Z-H<=$.maxAgeMs&&Number.isFinite(Y.at)&&Y.at>Z?Y.at:void 0});if(G.some((B)=>B===void 0))continue;let Q=Math.max(...G);if(J&&J.resetAt<=Q)continue;let W=z.some((B)=>B.blockedBy!=="exhausted"&&B.reset?.at===Q);J={account:X.account,resetAt:Q,checkpoint:{accountKey:{...X.account},decidedAt:Z,blockers:W?[]:z.flatMap((B)=>B.blockedBy==="exhausted"&&B.reset?[{window:B.window,resetAt:B.reset.at}]:[])}}}return J}function q5($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function j5($,Z){return q5($,Z)&&m0($.scan?.maxSameAccountWait)===0}function F5($,Z,J,X){if(!q5(X,Z))return;let z=X.scan,G=m0(z?.maxSameAccountWait),Q=z&&M6(z,$.now),W=Q?Q.resetAt-$.now:300000,B=z?.activity,Y=z?.accountKey??$.attempted,H=B&&Y&&R(B.accountKey,Y)?W2(B.ttlMs)||300000:300000,V=Math.min(W,G==="max"?H:900000),U=G===0||$.host==="pi"&&$.wake?.kind==="terminal",j=U?Q?W:void 0:V,q=Z.refusals.quota[$.host],F={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":U?"json-412":q.family,messageKey:X.messageKey??q.messageKey,retryable:$.host!=="pi"&&!U,hostRetry:$.host==="pi"||U?"veto":"leave",history:J,...j===void 0?{}:{retryAfterMs:j},...Q?{resetAt:Q.resetAt}:{}};if(!Q||U||$.host==="opencode1")return F;let K={delayMs:V,retryAfterMs:V,resetAt:Q.resetAt,target:$.now+V,checkpoint:Q.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...K,action:"wait-then-reselect"};if($.hostPhase!=="retry")return F;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||V>j4)return F;return{...K,action:"hold",account:Q.account}}function Q9($,Z,J){return{accountKey:{...$},decidedAt:Z,blockers:J.filter((X)=>X.confirmed&&Number.isFinite(X.resetAt)).map((X)=>({window:X.window,resetAt:X.resetAt}))}}function K5($,Z,J,X){let{checkpoint:z,target:G}=$;if(!R(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let Q=(W)=>{let B=W.resetAt;return W.confirmed&&B!==void 0&&Number.isFinite(B)&&B<=G&&z.blockers.some((Y)=>Y.window===W.window&&Number.isFinite(Y.resetAt)&&B<=Y.resetAt)};return J.filter((W)=>Q(W)&&J.filter((B)=>B.confirmed&&B.window===W.window).every(Q)).map((W)=>W.window)}function C6($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function g2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function k0($,Z,J,X,z){let G=z&&F5($,Z,J,z);if(G)return G;let Q=Z.refusals[X][$.host];return{action:"refuse",reason:X,family:z?.family??Q.family,messageKey:z?.messageKey??Q.messageKey,retryable:z?.retryable??Q.retryable,hostRetry:z?.hostRetry??Q.hostRetry,history:J,...z?.retryAfterMs===void 0?{}:{retryAfterMs:z.retryAfterMs},...z?.resetAt===void 0?{}:{resetAt:z.resetAt}}}function fX($,Z,J,X,z){let G=$.hold;if(Z.shortLimit.holdBound==="disabled"||$.host==="opencode2"&&($.hostPhase!=="retry"||$.remainingRetries===void 0||!($.remainingRetries>=1))||!X?.admitted||!G||G.maxWaitMs<=0||Number.isNaN(G.maxWaitMs)||!Number.isFinite(G.cacheExpiresAt)||G.maxDelayMs!==void 0&&(!Number.isFinite(G.maxDelayMs)||G.maxDelayMs<0)||!z.length||z.some((Y)=>!C6(Y.resetAt,$.now)))return;let Q=Math.max(...z.map((Y)=>Y.resetAt)),W=Z.shortLimit.jitter==="session-sha256"?G9($.sessionId,Q-$.now):Q-$.now,B=$.now+W;if(!Number.isFinite(B)||B>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&W>j4||G.maxDelayMs!==void 0&&W>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:W,retryAfterMs:W,target:B,checkpoint:Q9(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":g2($,Z),history:J}}function vX($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=y2(J,{type:"blocked",clockNow:$.clockNow});let Q=X.map((j)=>{let q=j.blockers.filter((F)=>!(F.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(q.some((F)=>!C6(F.until,$.now)))return;return q.length?{candidate:j,time:Math.max(...q.map((F)=>F.until))}:void 0}).filter((j)=>j!==void 0).reduce((j,q)=>!j||q.time<j.time?q:j,void 0),W=Q?Q.time-$.now:X.some((j)=>j.blockers.some((q)=>q.kind!=="soft"))?z.hardFallbackMs:void 0,B=$.poolWaitBudgetMs??z.budgetMs,Y=$.clockNow-(J.blockedSince??$.clockNow);if(B>0&&(Y>=B||W!==void 0&&W>B))return k0($,Z,J,"quota",$.terminal);let H=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(H<=0)return k0($,Z,J,"incomplete");if(W===void 0)return k0($,Z,J,"quota",$.terminal);let V=Math.min(W,H,B>0?B-Y:Number.POSITIVE_INFINITY),U=Q?.candidate??X[0];if(!U)return;return{action:"wait-then-reselect",delayMs:V,target:$.now+V,checkpoint:Q9(U.account,$.now,U.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:g2($,Z),history:J}}function B9($,Z){let J=$.history,X=(C,L=$.phase==="pre-send"?!0:$.failureRetryable??!0,A="leave")=>({action:"pass",reason:C,retryable:L,hostRetry:A,history:J});if($.phase==="after-limit"&&$.host==="opencode2"&&(!$.delivery.owned||!$.delivery.attributable))return X("not-owned");let z=$.status??$.signal?.status;if($.phase==="after-limit"&&$.attempted)J=y2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&R($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((C)=>C.admitted),Q=G.filter((C)=>!N6(J,C.account,$.requestScope)),W=Q.find((C)=>$.attempted&&R(C.account,$.attempted)),B=$.signalApplicable!==!1&&$.signal&&$.attempted&&R($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&B?.kind==="model-unavailable"&&W)return{action:"exclude-for-request",account:W.account,scope:$.requestScope,effects:z9,reason:"model-unavailable",retryable:!0,hostRetry:g2($,Z),history:J};if(G.length&&!Q.length)return k0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||j5($.terminal,Z))?k0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let C=$.wake,L=Q.find((c)=>R(c.account,C.checkpoint.accountKey)),A=L?.confirmedBlockers??(L&&B&&R(B.account,L.account)?B.windows:[]),x=L?K5(C,L.account,A,$.now):[],I=$.hold,f=C.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&C.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&C.target-C.checkpoint.decidedAt<=I.maxWaitMs;if(L&&Number.isFinite(C.target)&&C.target>=C.checkpoint.decidedAt&&$.now>=C.target&&f&&L.blockers.every((c)=>c.until!==void 0&&Number.isFinite(c.until)&&c.until<=$.now)&&(L.ready||A.some((c)=>c.confirmed))&&A.filter((c)=>c.confirmed).every((c)=>x.includes(c.window)))return{action:"retain",account:L.account,liftedWindows:x,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:y2(J,{type:"selected"})}}if($.credentialRecovery&&W)return{action:"retain",account:W.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:g2($,Z),history:J};let Y=Z.unconfirmedRetainLimit,H=$.unconfirmedRetainCount,V=z===429&&Y!==void 0&&H!==void 0,U=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(B?.kind==="payment-cap"||z===402&&B?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!B&&!V&&!$.terminal&&(U.attributedLimitOnly||z===void 0||!U.statuses.includes(z)))return X("unhandled-failure");let j=Q.find((C)=>$.selection&&R(C.account,$.selection.account)&&C.placementEligible),q=j&&(j.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&Q.length===1&&j.blockers.length>0&&j.blockers.every((C)=>C.kind==="soft")),F=q&&(!$.attempted||!R(j.account,$.attempted))?j:void 0,K=(C,L="ready-alternative")=>({action:"reroute",account:C.account,pin:$.selection?.pin??"preserve",reason:L,retryable:!0,hostRetry:g2($,Z),history:y2(J,{type:"selected"})}),N=$.phase==="pre-send"?W??Q.find((C)=>$.selection&&R(C.account,$.selection.account)):W,D=(N?.confirmedBlockers??($.phase==="after-limit"?B?.windows:void 0)??[]).filter((C)=>C.confirmed);if(D.length){if(Z.shortLimit.preference==="ready-alternative-first"&&F)return K(F);let C=fX($,Z,J,N,D);if(C)return C}let T=Z.unknown[$.host],M=$.phase==="after-limit"&&!D.length&&(z===429||B?.kind==="rate-limit"||B?.kind==="quota-exhausted"||B?.kind==="capacity"),P=V&&H>=Y;if(M&&W&&(T.affinity==="always"||$.affinity==="sticky")){if(V&&P){if(F)return K(F,"unconfirmed-retry-limit")}else if(V||T.action==="retain"){let C=[...$.retryHintsMs??[],B?.retryAfterMs].filter((L)=>L!==void 0&&Number.isFinite(L)&&(V||L>=0));return{action:"retain",account:W.account,reason:"unconfirmed-limit",...V?{retryMs:Math.min(60000,...C.map((L)=>Math.max(0,L))),incrementUnconfirmedRetain:!0}:T.hint==="minimum"?{retryMs:Math.min(T.defaultMs,...C)}:{},retryable:!0,hostRetry:g2($,Z),history:J}}else if(T.action==="pass")return X("unconfirmed-limit")}if(F)return K(F);if($.phase==="pre-send"&&q)return K(j);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&j&&Q.every((C)=>!C.ready)&&Q.every((C)=>C.blockers.length>0&&C.blockers.every((L)=>L.kind==="hard")))return K(j);let _=vX($,Z,J,Q);if(_)return _;if($.phase==="pre-send"&&!Q.length)return k0($,Z,J,$.terminal?.reason??"auth",$.terminal);if($.host==="opencode2"&&$.hostPhase==="retry"&&!$.terminal){if(Z.markedPool.retryExhaustion==="host-delay")return X("host-delay");if(Z.markedPool.retryExhaustion==="same-host-delay"&&W)return{action:"retain",account:W.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let C=$.phase==="pre-send"&&Q.length>0&&Q.every((x)=>!x.ready),L=Q.filter((x)=>x.placementEligible),A=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&L.length>0&&L.every((x)=>!x.ready&&x.blockers.length>0&&x.blockers.every((I)=>I.cause==="payment-balance"&&C6(I.until,$.now)));if(A||C||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let x=(A?L:Q).flatMap((I)=>I.blockers.map((f)=>f.until)).filter((I)=>C6(I,$.now));return k0($,Z,J,"quota",{source:"pool",reason:"quota",...A?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:x.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...x)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return k0($,Z,J,$.terminal.reason,$.terminal);if(B?.kind==="auth"||B?.kind==="account-access")return k0($,Z,J,"auth");if(B||z===429||Q.some((C)=>C.blockers.length))return k0($,Z,J,"quota");return X("no-override")}function f2($){if(!Number.isFinite($))return"unknown";let Z=Math.ceil(Math.max(0,$)/1000);if(Z<60)return`${Z}s`;let J=Math.ceil(Z/60),X=Math.floor(J/1440);if(X>=100)return"over 99 days";let z=Math.floor(J/60)%24,G=J%60;if(X>0)return`${X}d ${z}h ${G}m`;if(z>0)return`${z}h ${G}m`;return`${G}m`}var v2=({resetAt:$,now:Z})=>f2($-Z);var Y9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class N4 extends Error{[Y9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class D4 extends Error{[Y9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function V9($){let Z=$&&typeof $==="object"&&Reflect.get($,Y9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function w0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var Y2=($)=>Number.isSafeInteger($)&&$>=0,W9=($)=>typeof $==="number"&&Number.isFinite($),N5=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",K4=($,Z)=>Array.isArray($)&&$.every(Z);function P5($,Z){return w0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function D5($,Z){if(!w0($)||!w0($.scope))return!1;let J=$.scope;return P5($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function hX($,Z){return $.namespace===Z&&typeof $.generation==="string"&&Y2($.revision)&&Y2($.lowWatermark)&&K4($.marks,(J)=>w0(J)&&D5(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&K4(J.entries,(X)=>w0(X)&&N5(X.cause)&&W9(X.until)&&W9(X.evidenceAt)&&Y2(X.baseRevision)&&Y2(X.committedRevision)))&&K4($.tombstones,(J)=>w0(J)&&D5(J.key,Z)&&Y2(J.revision)&&N5(J.cause))&&K4($.operationIds,(J)=>w0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&Y2(J.revision))&&K4($.access,(J)=>w0(J)&&P5(J.account,Z)&&W9(J.eligibilityStateUpdatedAt)&&Y2(J.committedRevision))}class P4{namespace;logger;replaced=!1;terminal;constructor($,Z){this.namespace=$,this.logger=Z}assertWritable(){if(this.terminal)throw this.terminal}decode($){if(this.assertWritable(),$===void 0)return{};let Z;if(!w0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new D4,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!hX($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new N4,this.terminal;return{replacement:Z}}didCommit($){if(!$||this.replaced)return!1;this.replaced=!0;try{this.logger?.warn(`limits envelope replaced: ${$}`)}catch{}return!0}}var mX=[/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],wX=new RegExp(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"].join("|"),"i");function h2($){let Z=$.toLowerCase();return Z.includes("too_many_requests")||Z.includes("exhausted")||Z.includes("unavailable")||mX.some((J)=>J.test($))||wX.test($)}class T6 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function H9($){let Z=new Map(Object.entries($.refusals??{})),J=new Map(Object.entries($.retryable??{}));for(let[X,z]of Z)for(let G of[void 0,"45s","2m","1h 30m","99d 23h 59m","over 99 days"])for(let Q of[[],["this account"]]){let W=Object.freeze({labels:Object.freeze(Q),reset:G}),B;try{B=z(W)}catch{throw new T6(X)}if(typeof B!=="string"||h2(B))throw new T6(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var uX=/[^\s@]+@[^\s@]+\.[^\s@]+/;function U9($){return uX.test($)}function q9($){return U9($)||h2($)?"this account":$}class j9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function L6($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-F9(Z);return J>=0?Math.ceil(J/1000):void 0}function F9($){return Number.isFinite($)&&$>=0?$:0}function C5($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function pX($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function T5($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${f2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${pX(Z)}`}function L5($,Z,J){let X=C5($),z=X===void 0?void 0:v2({resetAt:X,now:Z}),G=L6($.retryAfterMs,$.noticeDelayMs);return T5($.family,z,G,J)}function lX($,Z){let J=$.now+F9($.noticeDelayMs??0),X=()=>L5($,J,Z);try{let z=C5($),G=z===void 0?void 0:($.messages?.formatReset??v2)({resetAt:z,now:J}),Q=L6($.retryAfterMs,$.noticeDelayMs),W=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(q9):[]),reset:G,retryIn:!Z&&Q!==void 0?f2(Q*1000):void 0}),B=$.messages?.render($.messageKey,W,Z);return typeof B==="string"?B:T5($.family,G,Q,Z)}catch{return X()}}function M5($,Z){switch($){case"openai-429":return JSON.stringify({error:{message:Z,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}});case"claude-429":return JSON.stringify({type:"error",error:{type:"rate_limit_error",message:Z}});case"json-412":return JSON.stringify({error:{code:412,status:"FAILED_PRECONDITION",message:Z}});case"claustrum-429":return JSON.stringify({error:"claustrum-auth: accounts-rate-limited"});case"claustrum-402":return JSON.stringify({error:"claustrum-auth: insufficient balance"});default:return Z}}function K9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=M5($.family,lX($,Z));if(Z&&(h2(X)||U9(X))){let Q=$.now+F9($.noticeDelayMs??0);X=M5($.family,L5($,Q,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new j9(X)};if($.family==="pi-final")return{...J,kind:"text",body:X};let z=new Headers($.family==="json-412"?$.extraHeaders:void 0);z.set("content-type","application/json"),z.delete("retry-after");let G=L6($.retryAfterMs,$.noticeDelayMs);if(G!==void 0)z.set("retry-after",String(G));return{...J,kind:"http",status:$.family==="json-412"?412:$.family==="claustrum-402"?402:429,headers:z,body:X}}function u0($,Z){return R($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function N9($,Z){if(!u0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function D9($,Z,J){if(!u0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var P9=Object.freeze({kind:"failure-ladder",mergeLaw:"max-until",hintFloorMs:2000,quotaSteps:Object.freeze([60000,300000,1800000,7200000]),byKind:Object.freeze({"rate-limit":30000}),byReason:Object.freeze({"server-error":20000,unknown:60000}),capacity:Object.freeze({baseMs:45000,spreadMs:15000}),defaultMs:60000});function _6($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((Q,W)=>{if(!Q)return W;if($==="latest-evidence"&&W.evidenceAt!==Q.evidenceAt)return W.evidenceAt>Q.evidenceAt?W:Q;return W.committedRevision>Q.committedRevision?W:Q},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,Q)=>J<G.until&&!z.some((W,B)=>B!==Q&&W.until>=G.until&&W.baseRevision>=G.baseRevision&&(W.until>G.until||W.baseRevision>G.baseRevision||W.committedRevision>G.committedRevision||W.committedRevision===G.committedRevision&&B<Q))).sort((G,Q)=>G.committedRevision-Q.committedRevision)}function M4($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var O5=1024;function M9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function O6($,Z){return M9($.cause)===void 0||$.cause===Z}function S5($){return JSON.stringify([p($.key),M9($.cause)])}function T0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function cX($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p($){let Z=$.scope;return JSON.stringify([cX($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function _5($){return JSON.stringify([$.producerId,$.operationId])}function V2($,Z){let J=new Map;for(let B of $.tombstones){let Y=p(B.key),H=J.get(Y);if(H)H.push(B);else J.set(Y,[B])}let X=$.marks.flatMap((B)=>{let Y=J.get(p(B.key)),H=_6(B.mergeLaw,Y?B.entries.filter((V)=>!Y.some((U)=>O6(U,V.cause)&&V.baseRevision<U.revision)):B.entries,Z);return H.length?[{...B,entries:H}]:[]}),z=$.lowWatermark,G=(B)=>{let Y=[...B].sort((V,U)=>V.revision-U.revision),H=Math.max(0,Y.length-O5);for(let V of Y.slice(0,H))z=Math.max(z,V.revision+1);return Y.slice(H)},Q=G($.tombstones),W=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:Q,operationIds:W,lowWatermark:z}}function H2($,Z,J){let X=V2($,J.now),z=[];for(let G of Z){let Q=(K)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:K})};if(G.binding.account.namespace!==X.namespace){Q("wrong-namespace");continue}if(G.baseRevision<X.lowWatermark){Q("below-watermark");continue}if(G.baseRevision>X.revision){Q("future-revision");continue}let W=J.bindings.find((K)=>R(K.account,G.binding.account));if(!W){Q("unknown-account");continue}let B=D9(G.binding,W,J.authorizeEpoch);if(B){Q(B);continue}let Y=X.operationIds.find((K)=>_5(K)===_5(G));if(Y){z.push({...Y,status:"duplicate"});continue}let H=W.account,V=X.revision+1,U=[...X.marks],j=[...X.tombstones],q=[...X.access];if(G.type==="mark"){let K={account:H,scope:G.scope,window:G.window},N=p(K),D=U.find((M)=>p(M.key)===N);if(j.some((M)=>G.baseRevision<M.revision&&O6(M,G.cause)&&p(M.key)===N)){Q("cleared");continue}if(D&&D.mergeLaw!==G.mergeLaw){Q("merge-law-conflict");continue}let T=_6(G.mergeLaw,[...D?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:V,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(U=U.filter((M)=>p(M.key)!==N),T.length)U.push({key:K,mergeLaw:G.mergeLaw,entries:T})}else if(G.type==="clear"){let K=M9(G.cause),N=G.keys.map((M)=>({...M,account:H})).filter((M)=>G.cause===void 0||!U.some((P)=>p(P.key)===p(M)&&P.entries.some((_)=>_.cause!==G.cause))),D=new Set(N.map(p)),T=G.evidenceAt;if(T!==void 0&&U.some((M)=>D.has(p(M.key))&&M.entries.some((P)=>P.evidenceAt>T))){Q("newer-evidence");continue}U=U.filter((M)=>!D.has(p(M.key))),j=j.filter((M)=>!D.has(p(M.key))||K!==void 0&&M.cause!==K);for(let M of new Map(N.map((P)=>[p(P),P])).values())j.push({key:M,revision:V,...K===void 0?{}:{cause:K}})}else{let K={account:H,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:V},N=q.find((D)=>R(D.account,H));q=q.filter((D)=>!R(D.account,H)),q.push(N?M4(N,K):K)}let F={producerId:G.producerId,operationId:G.operationId,revision:V};X=V2({...X,revision:V,marks:U,tombstones:j,access:q,operationIds:[...X.operationIds,F]},J.now),z.push({...F,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as sX}from"node:fs";import{basename as A5,dirname as E5,join as aX,resolve as nX}from"node:path";function C4($){let Z=nX($),J=[A5(Z)],X=E5(Z);for(;;)try{return aX(sX.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let Q=E5(X);if(Q===X)return Z;J.push(A5(X)),X=Q}}class L0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as tX}from"node:crypto";import{isDeepStrictEqual as I5}from"node:util";import{AsyncResource as iX}from"node:async_hooks";import{randomUUID as R5}from"node:crypto";import{isDeepStrictEqual as rX}from"node:util";var oX=new iX("common-auth-limits-recovery");class T4{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=oX.runInAsyncScope(async()=>{await Promise.resolve();let Z=!1;try{await $(),Z=!0}catch(J){try{this.logger?.warn("limits envelope recovery failed; agreement remains degraded",{error:J instanceof Error?J.message:String(J)})}catch{}}finally{if(this.running=void 0,Z)for(let J of this.listeners)try{J()}catch{}}})}}class U2{seen;missingGeneration;incorporated;remember($,Z){if(this.seen&&this.seen.revision>$.revision)return;if(this.seen=structuredClone($),this.missingGeneration=void 0,Z)this.incorporated=structuredClone(Z)}retained($){let Z=rX($,this.incorporated)?void 0:$;return[this.seen,Z].filter((J)=>J!==void 0&&(J===this.seen||J.revision>0))}lost($,Z){return this.retained(Z).some((J)=>!$||J.generation!==$.generation||$.revision<J.revision||J.tombstones.some((X)=>X.revision>$.lowWatermark&&!$.tombstones.some((z)=>p(z.key)===p(X.key)&&O6(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=R5();let z=$??T0(J,this.missingGeneration??R5()),G=[...this.retained(Z),z],Q=new Map,W=new Map,B=new Map,Y=new Map,H=0;for(let U of G){H=Math.max(H,U.revision,U.lowWatermark);for(let j of U.marks){let q=p(j.key),F=Q.get(q);if(F&&F.mergeLaw!==j.mergeLaw)throw Error("limits-recovery-merge-law-conflict");Q.set(q,{...j,entries:[...F?.entries??[],...j.entries]});for(let K of j.entries)H=Math.max(H,K.baseRevision,K.committedRevision)}for(let j of U.tombstones){let q=S5(j),F=W.get(q);if(!F||F.revision<j.revision)W.set(q,j);H=Math.max(H,j.revision)}for(let j of U.operationIds){let q=JSON.stringify([j.producerId,j.operationId]),F=B.get(q);if(!F||F.revision<j.revision)B.set(q,j);H=Math.max(H,j.revision)}for(let j of U.access){let{namespace:q,accountId:F,incarnation:K}=j.account,N=JSON.stringify([q,F,K]),D=Y.get(N);Y.set(N,D?M4(D,j):j),H=Math.max(H,j.committedRevision)}}let V=H+1;if(!Number.isSafeInteger(V))throw Error("limits-revision-exhausted");return V2({...z,revision:V,lowWatermark:V,marks:[...Q.values()],tombstones:[...W.values()],operationIds:[...B.values()],access:[...Y.values()]},X)}}function b5($,Z){return Z.flatMap((J)=>J.credentialEpoch===void 0?[]:[{account:{namespace:$,accountId:J.id,incarnation:String(J.credentialEpoch)},credentialEpoch:String(J.credentialEpoch),...J.identity===void 0?{}:{identity:J.identity}}])}async function C9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new L0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=tX(),G=new U2,Q=new P4(J,$.logger),W=new T4($.logger),B=$.now??Date.now,Y=async()=>{let j=await Z.read();if(j.status!=="ready"){if(j.status==="error"&&j.kind==="snapshot-contended")throw Error(j.reason);throw new L0("pool-not-ready")}return b5(J,j.rows)},H=async()=>{let j=await Z.readSettings();if(j.status!=="ready")throw new L0("pool-not-ready");return Q.decode(j.settings.commonAuthLimits)},V=async(j)=>{Q.assertWritable();let q=await Y(),F=await H(),K;for(let N=0;N<3;N++){let D=await Y(),T=await H(),M=I5(q,D)&&I5(F,T);if(K={snapshot:F.snapshot??T0(J,z),bindings:q,authoritative:M},M){if(!F.replacement&&G.lost(F.snapshot,j))return W.schedule(()=>U.commit([],j)),{snapshot:G.recover(F.snapshot,j,J,B()),bindings:q,authoritative:!1,degradedAgreement:!0};if(F.snapshot)G.remember(F.snapshot);return K}q=D,F=T}return K},U={namespace:J,read:V,subscribe:W.subscribe,async commit(j,q){Q.assertWritable();let F,K,N=()=>{if(Q.didCommit(K)&&F)G=new U2,G.remember(F.snapshot,q)};try{await X((D,T)=>{let M=b5(J,T),P=Q.decode(D),_=P.snapshot;K=P.replacement;let C=!K&&G.lost(_,q),L=H2(C?G.recover(_,q,J,B()):_??T0(J,z),j,{now:B(),bindings:M,authorizeEpoch:(A,x)=>A.credentialEpoch===x.credentialEpoch});return F={...L,bindings:M,authoritative:!0,degradedAgreement:C},L.snapshot},{beforePublish:()=>Q.assertWritable(),onPublished:N})}catch(D){if(Q.assertWritable(),D instanceof b&&(D.kind==="pending-migration"||D.kind==="load-error"))throw new L0("pool-not-ready");throw D}if(!F)throw Error("Pool limits mutator was not called");return N(),G.remember(F.snapshot,q),F}};return await V(),U}function m2($){if($&&typeof $==="object"){for(let Z of Object.values($))m2(Z);Object.freeze($)}return $}function _0($){return{opencode1:$,opencode2:$,pi:$}}var q2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},k5={...q2,action:"retain",affinity:"sticky"},y5={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function A6($,Z){return{auth:_0(y5),quota:_0($),incomplete:_0(Z),"model-unavailable":_0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var S6={kind:"off"},g5={requestEscape:"off",retryExhaustion:"terminal"},f5={statuses:[],attributedLimitOnly:!0},x5={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},v5=m2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:_0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{...q2,action:"retain",hint:"minimum"},opencode2:q2,pi:{...q2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:_0(f5),markedPool:g5,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:A6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),h5=m2({evidence:"typed",markers:_0(P9),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"off",unknown:_0(q2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:{kind:"earliest",budgetMs:300000,requestDeadlineMs:600000,hardFallbackMs:60000,singleEligibleSoftExemption:!0},execution:"engine",requestExclusion:"on",advance:_0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:g5,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:A6(x5,{...x5,messageKey:"incomplete.timeout"})}),e0=m2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:S6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:k5,opencode2:q2,pi:k5},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:_0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:A6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),m5=m2({evidence:"hints-only",markers:{opencode1:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"},opencode2:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"marker"},pi:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"}},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(q2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:f5,pi:{statuses:[401,429],attributedLimitOnly:!1}},markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"host-delay"},terminalMetadata:"baseline",terminalPolicy:"status-history",terminalStatusHistory:{minRetryMs:1000,defaultRetryMs:60000,paymentBalance:{family:"claustrum-402",messageKey:"payment.insufficient-balance"}},refusals:A6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...y5,messageKey:"incomplete.no-account"})}),eX=m2({"confirmed-affinity":v5,"earliest-pool-engine":h5,"window-router":e0,"status-vault-order":m5});import{AsyncResource as $z}from"node:async_hooks";var R6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),Zz="@cortexkit/common-auth/limits-registry/schema-v",E6=1000,w5=5000,j2=new $z("common-auth-limits"),Jz={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function Xz(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(Zz)&&J!==R6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,R6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,R6,Z),Z}function F2($){return JSON.stringify([$.producerId,$.operationId])}class u5{adapter;clock;restrictive;listeners=new Set;owners=0;activity=D6();journal=new Map;failed=new Set;restrictions=new Map;snapshot;recoveryView;bindings=[];lastReloadAt=Number.NEGATIVE_INFINITY;lastActivity=Number.NEGATIVE_INFINITY;lastReadAttempt=Number.NEGATIVE_INFINITY;generation=0;degradedAgreement=!1;abandoned;lastFailure;dirty=!0;live=!1;publicationTimer;reloadTimer;unsubscribe;reading;writing;handoff=Promise.resolve();resolveAbandonment;abandonment=new Promise(($)=>{this.resolveAbandonment=$});constructor($){this.adapter=$.adapter,this.clock=$.clock??Jz,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=V9($);if(Z){this.abandoned=Z,this.lastFailure=$,this.live=!1,this.generation++,this.cancelTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.journal.clear(),this.failed.clear(),this.restrictions.clear(),this.recoveryView=void 0,this.resolveAbandonment();for(let J of this.listeners)try{J.onAbandon?.(Z)}catch{}return}this.degradedAgreement=!0,this.lastFailure=$}reconcile($){if(this.abandoned)return!1;if($.snapshot.schemaVersion!==1||$.snapshot.namespace!==this.adapter.namespace)throw Error("limits-schema-mismatch");if(!$.authoritative){if($.degradedAgreement&&this.snapshot&&$.snapshot.revision>this.snapshot.revision)this.recoveryView=$;return this.fail(Error("limits-unverifiable-snapshot")),!1}if(this.snapshot&&$.snapshot.generation===this.snapshot.generation&&$.snapshot.revision<this.snapshot.revision)return!1;this.snapshot=$.snapshot,this.recoveryView=void 0,this.bindings=$.bindings.map((Z)=>{let J=this.bindings.find((X)=>R(X.account,Z.account));return J?N9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((Q)=>R(Q.account,X.binding.account)),G=this.snapshot.access.find((Q)=>R(Q.account,X.binding.account));if(!z||!u0(z,X.binding)||X.type==="access"&&G&&G.committedRevision>J.revision&&G.eligibilityStateUpdatedAt>=X.eligibilityStateUpdatedAt)this.restrictions.delete(Z)}if($.degradedAgreement)this.fail(Error("limits-envelope-recovered"));return!$.degradedAgreement}touch(){this.lastActivity=this.clock.now(),this.armReload()}cancelTimers(){if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);if(this.reloadTimer!==void 0)this.clock.clearTimeout(this.reloadTimer);this.publicationTimer=this.reloadTimer=void 0}schedulePublish($){if(!this.live)return;if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);j2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,j2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=w5)return;j2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=w5)return;j2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+E6-this.clock.now()))})}async start($){if(this.abandoned)throw this.lastFailure;this.adapter=$,this.live=!0;let Z=++this.generation;if(await this.reload(),this.abandoned||!this.snapshot)throw this.lastFailure??Error("limits-hydration-failed");if(this.unsubscribe=$.subscribe?.(()=>{if(!this.live||this.generation!==Z)return;this.dirty=!0,j2.runInAsyncScope(()=>{this.reload()})}),this.journal.size)this.schedulePublish(0)}reload(){if(this.abandoned)return Promise.resolve();if(this.reading)return this.reading;let $=this.clock.now();return this.lastReadAttempt=$,this.reading=j2.runInAsyncScope(async()=>{try{if(this.dirty=!1,this.reconcile(await this.adapter.read(this.snapshot))){if(this.lastReloadAt=$,!this.journal.size&&!this.failed.size&&!this.restrictions.size)this.degradedAgreement=!1,this.lastFailure=void 0}}catch(Z){this.dirty=!0,this.fail(Z)}}).finally(()=>{this.reading=void 0,this.armReload()}),this.reading}provisional(){if(this.abandoned)return T0(this.adapter.namespace,this.snapshot?.generation??"");let $=this.recoveryView?.snapshot??this.snapshot,Z=[...this.journal.values()].map((X)=>X.command).filter((X)=>X.type==="mark"),J=H2(V2($,this.clock.now()),Z,{now:this.clock.now(),bindings:this.bindings,authorizeEpoch:(X,z)=>X.credentialEpoch===z.credentialEpoch}).snapshot;return{...this.snapshot,marks:J.marks,tombstones:$.tombstones,access:$.access}}enqueue($,Z){if(this.abandoned)return;if($.binding.account.namespace!==this.adapter.namespace)throw Error("wrong-namespace");let J=F2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>F2(z)===J))return;this.journal.set(J,{command:structuredClone($),event:Z}),this.touch();let X=[...this.journal.values()].some((z)=>z.command.type!=="mark");this.schedulePublish(X?0:E6)}flush(){if(this.abandoned)return this.writing??Promise.resolve();if(this.writing)return this.writing;if(!this.journal.size)return Promise.resolve();return this.writing=j2.runInAsyncScope(async()=>{let $=[...this.journal.values()];while($.length&&!this.abandoned){try{let X=await this.adapter.commit($.map((z)=>z.command),this.snapshot);if(this.abandoned)return;if(this.reconcile(X),!X.authoritative)throw Error("limits-unverifiable-commit");for(let z of $){let G=X.outcomes.find((Q)=>F2(Q)===F2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(V9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof L0&&X.code==="pool-not-ready")for(let z of $)this.settle(z,{...z.command,status:"rejected",reason:"pool-not-ready"});else{for(let z of $)if(this.journal.has(F2(z.command)))this.failed.add(F2(z.command));this.fail(X);break}}let Z=[...this.journal.values()],J=Z.findLastIndex((X)=>X.command.type!=="mark");$=Z.slice(0,J+1)}}).finally(()=>{if(this.writing=void 0,this.journal.size&&this.live)this.schedulePublish(E6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=F2(J);if(this.journal.delete(X),this.failed.delete(X),Z.status==="rejected"){if(this.fail(Error(Z.reason??"limits-command-rejected")),J.type==="access"&&this.restrictive(J.state)){if(this.restrictions.set(X,{command:J,revision:this.snapshot.revision}),Z.reason==="below-watermark"&&J.baseRevision<this.snapshot.lowWatermark&&($.recoveryRetries??0)<3)this.journal.set(X,{...$,recoveryRetries:($.recoveryRetries??0)+1,command:{...J,baseRevision:this.snapshot.revision}})}for(let z of this.listeners)try{z.onRejected?.(J,Z)}catch{}}else if(Z.revision!==void 0&&(J.type==="mark"||$.event==="success"))for(let z of this.listeners)try{z.onEvent?.({type:J.type==="mark"?"mark":"success",command:J,revision:Z.revision})}catch{}}async beforeDispatch($){if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};this.touch();let Z=()=>[...this.journal.values()].some((z)=>z.command.type!=="mark"&&R(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=E6)await Promise.race([this.reload(),this.abandonment]);if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};let J=(this.recoveryView?.bindings??this.bindings).find((z)=>R(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!u0(J,$)||[...this.restrictions.values()].some((z)=>R(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>R(z.account,$.account)&&this.restrictive(z.state))}}async stop(){this.live=!1,this.generation++,this.cancelTimers(),await this.flush(),await this.reading,this.unsubscribe?.(),this.unsubscribe=void 0,this.cancelTimers()}}async function T9($){let Z=Xz(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new u5($),Z.namespaces.set($.adapter.namespace,J);let X=J,z={onAbandon:$.onAbandon,onEvent:$.onEvent,onRejected:$.onRejected},G=X.owners++===0;if(X.listeners.add(z),G)X.handoff=X.handoff.catch(()=>{}).then(()=>X.start($.adapter));try{await X.handoff}catch(B){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),B}let Q=!1,W=()=>{if(Q)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return W(),X.provisional()},get lastReloadAt(){return X.lastReloadAt},get degradedAgreement(){return X.degradedAgreement},get lastFailure(){return X.lastFailure},get pendingCommands(){return X.journal.size},activity:X.activity,observe(B){return W(),{binding:structuredClone(B),baseRevision:X.snapshot.revision}},enqueue(B,Y){W(),X.enqueue(B,Y)},beforeDispatch(B){return W(),X.beforeDispatch(B)},flush(){return W(),X.flush()},reload(){return W(),X.reload()},dispose(){if(Q)return X.handoff;if(Q=!0,X.owners--,!X.owners)X.handoff=X.handoff.then(()=>X.stop()).finally(()=>X.listeners.delete(z));else X.listeners.delete(z);return X.handoff}}}function $2($){let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));if(typeof Z!=="function")return;let J=Z($);return typeof J==="object"&&J!==null?J:void 0}function L9($){try{let J=$2($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=F4($);if(!Z||!Number.isFinite($.now))return 0;return Math.floor(Math.max(0,Math.min(Z.maxWaitMs,Z.cacheExpiresAt-$.now))/1000)}function E($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as Qz}from"node:fs";import{rm as d5}from"node:fs/promises";import{dirname as Bz,join as ZZ}from"node:path";import{resolveClaustrumConnectionPath as Wz}from"@cortexkit/claustrum-client";function p5($,Z){if(!$)return;let J=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function _9($){if(!E($)||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 zz($){let Z=_9($.total),J=_9($.remaining);if(Z===void 0||J===void 0||Z<0||J<0)return;let X=Z-J,z=$.spendable===!1,G=Z>0?X/Z*100:z?100:0;return{limit:Z,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...E($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function Gz($,Z){if(!E($))return;let J=_9($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function O9($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function l5($,Z){let J=p5($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=p5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="individual_limit"):void 0,G=E(z)?zz(z):void 0,Q=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="credits"):void 0,W=Gz(Q,Z.fetchedAt),B=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...W&&{credits:W},...W&&E(Q)&&typeof Q.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function I6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var S9="ck auth reclassify --from-registry";function b6($,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 \`${I6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${S9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var W0=t("vault"),JZ="openai-auth";var Yz={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},XZ={opencode:"OpenCode",pi:"Pi"},Vz=[{selector:{category:"openai-native"},operation:"read"}];function E9($){return a5(JZ,$)}function Hz($){return`ChatGPT for ${XZ[$]}`}function v6($){return ZZ(Bz($),"openai-auth-vault")}function K2($,Z){return{...i5({stateDir:$,host:Z}),rosterPath:ZZ($,`${Z}-roster.json`)}}var zZ=2000,gq=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],Uz={"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 ${S9} 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 fq($,Z){if($!=="vault-no-grant")return Uz[$];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: ${I6(Z)}`}function vq($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let J=$.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function qz($){let Z=g6($);return Z?f6(Z):void 0}class jz{host;name;paths;#Z;#$;#B=new Map;#W=new Map;#q=new Map;#j;#J;#Y;#z;#F=!1;#K=!1;#V=Promise.withResolvers();#H="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=E9($.host),this.paths=K2($.stateDir,$.host),this.#$=new e5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:Yz,pluginId:JZ,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:qz,insula:{provider:"codex",normalize:l5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:(Z)=>this.#_(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...W0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")W0.warn(Z,J)}}})}#N(){return(this.#Z.connectionFile??Wz)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#Z.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>W0.debug("vault transport error",{errorClass:$})}}#C(){return(this.#Z.connectScoped?.()??$Z(this.#D())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){let X=this.#q.get($);if(X?.source===Z&&X.reason===J)return;this.#q.set($,{source:Z,reason:J}),W0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#T(){return this.#Z.connectEnrollment?.()??n5(this.#D())}#X($,Z){this.#J=x0(Z),W0.warn($,{host:this.host,error:this.#J,...Z instanceof s5&&Z.reason?{reason:Z.reason}:{}})}#Q(){if(w2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=Qz($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#Q(),Z=await r5(this.paths,this.name);if($===this.#Q()){if(Z!==this.#H)W0.info("vault authority",{host:this.host,authority:Z});return this.#H=Z,this.#U=$,Z}return"unreadable"}enrolled(){return w2()||this.#U!==this.#Q()||this.#H!=="local"}async#L(){if(this.#U!==this.#Q())await this.authority();return this.enrolled()}start(){if(this.#F||this.#K)return;this.#F=!0,this.#$.start()}#_($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#$.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(!["vault","host"].includes(await this.authority()))return;let $=this.#z;if($)await $.catch(()=>{return});if(this.snapshot()||!["vault","host"].includes(await this.authority()))return;await(this.#z??this.#P()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#J=void 0,Z}catch($){return this.#X("vault roster refresh failed",$),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}watchState(){return this.#$.watchState()}keptReceiptState(){return this.#$.keptReceiptState()}grantReach(){return this.#$.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.#$.routingRows().map((Z)=>{let J=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,J){let X=!1;try{return await this.#$.send($,(z)=>{return X=!0,Z(z.accessToken,z)},{site:J.site,...J.signal?{signal:J.signal}:{}})}catch(z){if(X)throw z;this.#X("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#$.authorize($,Z.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#$.reportFailure($,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot($,Z,J,X){let z=k6(Z,(this.#Z.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#$.recordQuota($,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}reportUsage($,Z,J){try{let X;if("headers"in Z){let z={};if(Z.headers.forEach((G,Q)=>{if(Q.startsWith("x-codex-"))z[Q]=G}),Object.keys(z).length===0)return;X={headers:z}}else X={frame:Z.frame};this.#$.reportUsage({routeId:$,credentialId:J.credentialId,reading:{provider:"codex",observedAtMs:(this.#Z.now??Date.now)(),...X,...J.accountIdentity?{account:J.accountIdentity}:{}}})}catch{}}pollQuota($,Z=!0){let J=this.#W.get($);if(J)return J;let X=this.#O($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#O($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await y6(this.paths.rosterPath))?.rows.find((W)=>W.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#M($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let W=k6(O9(z,this.routes().find((Y)=>Y.id===$)?.quota),z.primary.checkedAt,!0);if(!W)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,W))return this.#G($,"insula",null),{ok:!0};return this.#G($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#$.lookupInsulaQuotaForRoute($),Q=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G($,"insula",Q),{ok:!1,error:`insula ${Q}`}}return this.#M($,Z)}async#M($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let W=Z?void 0:await this.#$.cachedInsulaQuota(Q);if(W!==void 0){let Y=k6(O9(W,this.routes().find((H)=>H.id===$)?.quota),W.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#$.recordQuota($,Y,Q),new Response(null,{status:200})}let B=await L4({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:W0});return await this.recordSnapshot($,B,!0,Q),J=void 0,new Response(null,{status:200})}catch(W){J=x0(W);let B=W?.status;if(typeof B==="number")return new Response(null,{status:B});throw W}},{site:"quota"}).catch((G)=>{J=x0(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading($){let Z=this.#B.get($);if(Z)return Z;let J=this.pollQuota($,!1).catch((X)=>{W0.warn("vault quota poll failed",{routeId:$,error:x0(X)})}).finally(()=>{this.#B.delete($)});return this.#B.set($,J),J}async pollStale($){let Z=(this.#Z.now??Date.now)(),J=[];for(let X of this.routes()){let z=Fz(X.quota);if(z!==void 0&&Z-z<$)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder($){let Z=await this.authority();if(Z!=="vault"&&Z!=="host")throw Error("Vault order can only be changed in vault mode.");return this.#$.reorder($)}async decline($){await this.#$.decline($),W0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),W0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await x6(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof c5?X.kind:"unreadable-state"}}let J=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:J!==void 0,accounts:J?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){if(await this.authority()==="host")throw new u("vault-host",A9);let $=await this.#T().catch((Z)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${x0(Z)}. Is the vault running?`)});try{let Z=new o5({client:$,paths:this.paths,proposedName:this.name,displayName:Hz(this.host),requestedGrants:Vz,...this.#Z.now?{now:this.#Z.now}:{}}),J=await Z.status();if(J.state==="denied"||J.state==="blocked")await Z.resetTerminal();let X=await Z.reconcile();if(W0.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{$.close()}}waitForApproval($={}){return this.#Y??=(async()=>{let Z=$.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),J=$.pollIntervalMs??2000,X=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=X)return z;await Z(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){if(await this.authority()==="host")throw new u("vault-host",A9);await d5(this.paths.tokenPath,{force:!0}),await d5(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,W0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())t5({mode:"custody",auth:$,provider:"openai"})}close(){this.#K=!0,this.#V.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function Fz($){if(!$)return;let Z=b0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function h6($,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}`,...Z.requestedGrantsStatus==="sent"?[]:[`Then grant OpenAI access to the name you approved with --name (defaults to ${$}):`,` ${I6($)}`]]}function GZ($,Z,J){let X=`${XZ[$]} (${J.state==="approved"?J.approvedName??Z:Z})`;switch(J.state){case"approved":return`${X}: connected to the Claustrum vault.`;case"idle":return`${X}: not connected to the Claustrum vault.`;case"pending":return J.requestId?`${X}: waiting for approval of request ${J.requestId}.`:`${X}: enrollment request not taken yet${J.retryCode?` (${J.retryCode})`:""}.`;case"denied":return`${X}: the vault denied the enrollment request.`;case"blocked":return`${X}: enrollment stopped (${J.code}).`;case"unavailable":return`${X}: the vault is unavailable (${J.code}).`;case"busy":return`${X}: another process is enrolling right now.`}}function R9($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let J=Z.approvedName??$.name,X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${J}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${b6(J,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...h6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
1
|
+
import{$d as w2,Af as N7,Bd as t0,Cd as o7,Cf as D7,Dd as q1,Df as P7,Ed as z5,Ff as g8,Gd as d6,Gf as f8,Hd as I0,Id as nZ,If as k6,Jd as b0,Jf as A7,Ld as G5,Le as b4,Lf as iZ,Md as Q5,Nd as B5,Oe as L4,Pd as i7,Pe as q7,Qd as r7,Qe as b8,Rd as r1,Sd as v0,Td as v3,Tf as E7,Ud as h3,Vd as p3,Wd as c5,Xd as s5,Zd as c6,_d as A9,bf as b$,ce as a5,df as k8,ee as n5,ef as n6,fe as i5,ge as x6,gf as x8,he as r5,hf as I4,je as o5,jf as E4,ke as t5,kf as p0,le as y6,me as u7,mf as j1,ne as e5,oe as $Z,pf as y8,qe as t7,qf as V7,re as g4,se as e7,te as F7,ue as K7,vf as A4,ye as g6,ze as f6}from"./index-62e0dx41.js";import{$f as B3,Zf as Q3,_f as P0,ag as m1,bg as l0,dg as W3,eg as Y3}from"./index-x9h58tf9.js";import{sg as Q8}from"./index-vyc1q51y.js";import{tg as r8}from"./index-q3j22pg7.js";import{Ag as g7,Cg as N$,Dg as f4,Eg as D$,Fg as x0}from"./index-rrmycmen.js";import{Ig as n3,Ng as t}from"./index-09rjj0qc.js";import{Og as Z6,Qg as u1,Vg as G3}from"./index-hybc4q33.js";class b 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 Z4 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 O2="identity-contradicted: ",R1="duplicate-identity";function n0($,Z,J){let X=$.rosterRow(Z);if(!X)return;X.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:J})}function J4($,Z){let J=$.rosterRow(Z);if(!J)return;J.enabled=!0;let X=$.entry(Z);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,$.setEntry(Z,z)}}function S2($,Z){let J=$.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===Z),X=[];for(let z of J.slice(1))n0($,z.id,"duplicate-identity"),X.push(z.id);return X}function z2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,S2($,J)}import{AsyncLocalStorage as l$}from"node:async_hooks";var n4=new l$,d$=new l$;function a($){if(n4.getStore()!==void 0)throw new Z4($)}function c$(){if(n4.getStore()?.storeLocksReleased===!1||d$.getStore())throw new Z4("updateLimitsNamespace")}function G0($){return d$.run(!0,$)}function Q0($,Z,J=!1){return n4.run({operation:$,storeLocksReleased:J&&n4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function s$($,Z,J,X,z){if(!Z)return;try{await Q0($,()=>Z(J,X),!0)}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:$,rowId:J,error:G instanceof Error?G.message:String(G)})}}import{setTimeout as V3}from"node:timers/promises";function G2($,Z,J){if(J!==void 0)throw new b({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 X4}from"node:crypto";var v="commonAuthPool",i0=1,N0="rows",i4="retiredEpochs",z4=1,I1=300000,g=v;function RJ($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(S(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function Q2($){return X4("sha256").update(RJ($)).digest("hex")}function a$($){if(!S($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function IJ($){if(!S($)||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 r="commonAuthProviderState";function S($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var bJ=new Set(["__proto__","constructor","prototype"]);function A2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(bJ.has($))return"id is a reserved object key";return}function b1($){let Z=typeof $==="string"?$.trim():"";if(!Z)return!1;try{let J=new URL(Z);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function n$($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function D0($){return X4("sha256").update(n$($)).digest("hex")}function E0($){return X4("sha256").update(`credential-stamp\x00${n$($)}`).digest("hex")}function f0($){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 X4("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function k1($,Z,J,X={}){return{credentialEpoch:Z,digest:E0($),dispatch:f0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function E2($,Z){let J=$?.credentialBound?G0(()=>$.credentialBound?.(Z)):Z;return X4("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function G4($,Z,J,X){if(!Z||J===void 0)return;if(!S($)||!Object.hasOwn($,r))return;let z=e($[g]);if(!z||z.providerState===void 0||z.digest!==E0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function s($){return Number.isSafeInteger($)&&$>=1}function e($){if(!S($))return;let Z=$.credentialEpoch;if(!s(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 J="staged"in $?IJ($.staged):void 0;if("staged"in $&&!J)return;let X={...J?{staged:J}:{},...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(!S(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!b1(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:Z,digest:$.digest,...X,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 kJ($,Z,J){if($.identity!==J)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 xJ($,Z,J,X){if(!$)return"none";if(!S(X)||!Object.hasOwn(X,g))return"missing";let z=e(X[g]);if(!z)return"malformed";if(z.digest!==E0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!kJ(z.binding,$,J))return"mismatched";if(z.dispatch!==f0($))return"mismatched";return"bound"}function x1($){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(!S(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(!(v in Z))return Array.isArray(Z.accounts)?{status:"pending-migration",config:Z}:{status:"ready",exists:!0,config:Z};let J=Z[v];if(!S(J))return{status:"error",reason:`${v} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${v}.schemaVersion is invalid`};if(X>i0)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${i0}`};if(N0 in J&&!S(J[N0]))return{status:"error",reason:`${v}.${N0} is not an object`};return{status:"ready",exists:!0,config:Z}}function i$($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!S($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!S($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function R2($){return Array.isArray($.accounts)?$.accounts:[]}function r$($){let Z=$[v];if(!S(Z))return{};let J=Z[N0];return S(J)?J:{}}function yJ($){return S($.accounts)?$.accounts:{}}function gJ($){if(!S($))return"not an object";let Z=A2($.id);if(Z)return Z;if($.type==="api")return b1($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function fJ($,Z){if(!S($))return;let J=$.credentialEpoch;if(!s(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?G0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!G0(()=>Z.validate(X)))return;if("staged"in $&&!a$($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function vJ($,Z){if(!S(Z))return;if($.type==="api"){let X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if($.corrupt===!0)return;let J=Z.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof Z.access==="string"?{access:Z.access}:{},...typeof Z.expires==="number"?{expires:Z.expires}:{},...typeof Z.lastRefreshedAt==="number"?{lastRefreshedAt:Z.lastRefreshedAt}:{}}}function r4($,Z){return R2($).find((J)=>S(J)&&J.id===Z)}function o$($){if(!S($[v]))$[v]={};return $[v]}function y1($){let Z=o$($);if(!S(Z[N0]))Z[N0]={};return Z[N0]}function R0($,Z){let J=r$($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return S(X)?X:void 0}function o4($,Z,J){Object.defineProperty(y1($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function t$($,Z){let J=$[v];if(!S(J))return;let X=J[i4];if(!S(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return s(z)?z:void 0}function e$($,Z){let J=R0($,Z)?.credentialEpoch;return s(J)?J:void 0}function t4($,Z){return Math.max(t$($,Z)??0,e$($,Z)??0)+1}function $3($,Z){let J=[...Z];if(J.length===0)return;let X=o$($),z=S(X[i4])?X[i4]:{},G={},Q=(W,B)=>Object.defineProperty(G,W,{value:B,enumerable:!0,writable:!0,configurable:!0});for(let[W,B]of Object.entries(z))if(s(B))Q(W,B);for(let W of J)Q(W,Math.max(t$($,W)??0,e$($,W)??1));X[i4]=G}function r0($,Z,J,X){let z=r$($),G=yJ(Z),Q=new Set,W=[];for(let B of R2($)){let Y=gJ(B),H=S(B)&&typeof B.id==="string"?B.id:void 0,V=H===void 0?void 0:z[H],U=S(V)&&Object.hasOwn(V,"staged"),j=U?a$(V.staged):void 0;if(Y||!S(B)||H===void 0||Q.has(H)){if(H!==void 0&&!Q.has(H))Q.add(H);if(H!==void 0)W.push({id:H,type:S(B)&&B.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...j?{staged:j}:{}});continue}Q.add(H);let q=B.type==="api"?"api":"oauth",F=Object.hasOwn(z,H),K=F?fJ(z[H],J):void 0,N=vJ(B,G[H]),D=B.enabled!==!1,T=K?K.credentialEpoch:F?void 0:1,M=typeof B.accountId==="string"&&B.accountId?B.accountId:void 0,P={id:H,type:q,enabled:D,needsFirstReading:K?K.needsFirstReading:q==="oauth",hasEntry:F,candidate:!1,...typeof B.label==="string"?{label:B.label}:{},...typeof B.addedAt==="number"?{addedAt:B.addedAt}:{},...M!==void 0?{identity:M}:{},...N?{credential:N,fingerprint:D0(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...j?{staged:j}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...hJ(G[H],N,T,M,X),stamp:xJ(N,T,M,G[H])};if(F&&!K)P.invalid="entry";else P.candidate=D&&N!==void 0&&!U;W.push(P)}return W}function hJ($,Z,J,X,z){if(!S($)||!Object.hasOwn($,r))return{};let G=G4($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[r];if(!z||!G0(()=>z.validate(Q)))return{providerStateDropped:"invalid"};if(E2(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function h($){return $.identity??$.id}function Q4($,Z){if($===void 0||$>Z+I1)return Z;return Math.max(Z,$+1)}function g1($,Z){return Q4($,Z)>Z+I1}function I2($){let{id:Z,credential:J,identity:X,label:z,addedAt:G}=$;return{id:Z,...z!==void 0?{label:z}:{},type:J.type,addedAt:G,...X!==void 0?{accountId:X}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}}}function Z3($,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 J3($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function X3($,Z={}){if(!S($))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)&&!b1($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var e4="transition",z3="transitionMark";function mJ($){if(!S($))return;let Z=$[e4];if(!S(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 B4($,Z,J){if(J.enabled)J4($,Z);else n0($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[z3]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)S2($,z.identity)}function wJ($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function uJ($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function pJ($,Z,J,X={}){let z=S(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of r0($,Z,J)){if(Q.invalid||Q.staged||!Q.credential)continue;let W=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!S(W))continue;let B=e(W[g]);if(!B?.binding)continue;if(B.digest!==E0(Q.credential))continue;let Y=Q.credentialEpoch??1;if(B.credentialEpoch>Y){if(!uJ(B))continue;if(X.requireCredentialStamps){if(B.dispatch===void 0)continue;if(B.dispatch!==f0(wJ(Q.credential,B.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...B,binding:B.binding}})}else if(B.credentialEpoch===Y&&B.dispatch!==void 0&&B.dispatch===f0(Q.credential)&&B.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:B.binding.identity});else if(B.credentialEpoch===Y&&B.binding.identity===Q.identity){if(X.requireCredentialStamps&&B.dispatch!==f0(Q.credential))continue;let H=mJ(W[g]);if(H&&R0($,Q.id)?.[z3]!==H.mark)G.set(Q.id,{kind:"transition",transition:H})}}return G}function f1($,Z,J,X){let G={...$.entry(Z)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(O2))delete G.disabledReason;$.setEntry(Z,G);let Q=$.rosterRow(Z);if(!Q)return;if(X.identity!==void 0)Q.accountId=X.identity;else delete Q.accountId;if(X.baseURL!==void 0)Q.baseURL=X.baseURL;if(X.authHeader!==void 0)Q.authHeader=X.authHeader}function v1($,Z,J,X={}){let z=pJ($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>r0(G,Z,J),rosterRow:(W)=>r4(G,W),entry:(W)=>R0(G,W),setEntry:(W,B)=>o4(G,W,B)};for(let[W,B]of z)if(B.kind==="replace")f1(Q,W,B.stamp.credentialEpoch,B.stamp.binding);for(let[W,B]of z)if(B.kind==="identity")z2(Q,W,B.identity);else if(B.kind==="transition")B4(Q,W,B.transition);else if(B.stamp.binding.identity!==void 0)S2(Q,B.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function h1($,Z,J,X={}){let{config:z,torn:G}=v1($,Z,J,X),Q=r0(z,Z,J,X.providerState);for(let W of Q){if(G.includes(W.id))W.torn=!0,W.candidate=!1;if(X.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return Q}var lJ=[5,10,20,40,80,160,320,400];async function $6($){for(let Z=0;;Z++)try{return await G3($,Z6)}catch(J){if(J.code==="ENOENT")return;let X=lJ[Z];if(X===void 0||!u1(J))throw J;await V3(X)}}function w1($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function H3($){return x1(w1(await $6($)))}async function n($){for(let Z=0;Z<3;Z++){let J,X,z;try{J=await $6($.configPath),X=await $6($.statePath),z=await $6($.configPath)}catch(W){if(u1(W))break;throw W}if(J!==z){if(Z<2)await V3(2+Math.floor(Math.random()*4));continue}let G=x1(w1(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=i$(w1(X));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:h1(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 Z0($,Z,J,X="before-first-write"){if($.status==="error"&&$.kind==="snapshot-contended")return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:$.reason});return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:X,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 U3{ctx;snapshot;locks;progress;info;config;state;constructor($,Z,J,X,z){this.ctx=$,this.snapshot=Z,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone(Z.config),this.state=structuredClone(Z.state)}rows(){return h1(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 J=this.entry($);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let Z=this.stateAccount($)?.[g];return S(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){G2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),r4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(S(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return y1(this.config)}entry($){return this.entries(),R0(this.config,$)}setEntry($,Z){o4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=v1(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=S(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return S(J)?J:void 0}dropStateAccount($){if(S(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!S(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(),J=new Set;for(let B of Z)if(S(B)&&typeof B.id==="string")J.add(B.id);let X=new Set;for(let B of R2(this.snapshot.config))if(S(B)&&typeof B.id==="string"&&!J.has(B.id))X.add(B.id);for(let B of Object.keys(this.entries()))if(!J.has(B))X.add(B);$3(this.config,X);let z=this.entries(),G={};for(let[B,Y]of Object.entries(z))if(J.has(B))Object.defineProperty(G,B,{value:Y,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[v],W={...this.config,version:z4,accounts:Z,[v]:{...Q,schemaVersion:i0,[N0]:G}};await this.write(this.ctx.configPath,W,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let B of X)this.ctx.removedIds.add(B);this.config=W}),this.config=W}async commitState($,Z={}){let J={...this.state,version:z4,accounts:S(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,Z.durable??!1),this.state=J,$)this.progress.committed=$}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await m1(this.ctx.statePath)}catch($){throw new b({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 m1(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await B3($,Z,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${J}-write`,this.info),await this.locks.assertAll()}},()=>{if(X)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${J}-write`,this.info)}}async function q3($,Z){let J=new v0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let W of $.storeLocks)await J.acquire(W);let z=await n($);if(z.status==="error")throw Z0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[W,B]of Object.entries(z.config))if(!Z.includes(W))G[W]=B;G.version=z4,G[v]={schemaVersion:i0,[N0]:{}};let Q={operation:"initialize",rowId:void 0};return await P0($.configPath,G,{beforeRename:async()=>{await $.onStep?.("before-config-write",Q),await J.assertAll()}}),X.writes++,await $.onStep?.("after-config-write",Q),"initialized"}catch(z){throw o0(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function w($,Z,J,X,z,G={}){let Q=Z.held.length;try{for(let Y of $.storeLocks)await Z.acquire(Y);let W=await n($);if(W.status!=="ready")throw Z0(W,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let B=new U3($,W,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))B.assertNotStaged(X.rowId);if(G.completeTorn??!0)await B.completeTorn();return await z(B)}finally{await Z.releaseTo(Q)}}function o0($,Z,J,X){let z=Z==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if(Z==="publishRoster"&&X.publicationDecided)return new b({operation:Z,...J!==void 0?{rowId:J}:{},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 Q3)return new b({operation:Z,...J!==void 0?{rowId:J}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:$});if($ instanceof b){if($.phase===z&&$.rowId===J&&$.operation===Z&&$.committed===G)return $;return new b({operation:Z,...J!==void 0?{rowId:J}:{},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,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:$};if($ instanceof Y3)return new b({...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 W3)return new b({...Q,retryable:!0,kind:"lock-contention",message:$.message});return new b({...Q,retryable:!1,kind:"unexpected",message:$ instanceof Error?$.message:String($)})}async function l($,Z,J,X,z){let G=new v0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(W){let B=o0(W,Z,J,Q);if(B.kind!=="after-persist-hook")await s$(Z,X,J,B,$.logger);throw B}finally{await G.releaseAll()}}function J0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(h(Z))}`,path:$.ctx.statePath}}async function M0($,Z,J){let X=await n($.ctx);if(X.status!=="ready")throw Z0(X,Z,J);let z=X.rows.find((Y)=>Y.id===J),G=R0(X.config,J),Q=X.state.accounts,W=S(Q)&&Object.hasOwn(Q,J)?Q[J]:void 0,B=S(W)?W[g]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))G2(Z,J,G.staged);if(!z&&S(B)&&Object.hasOwn(B,"staged"))G2(Z,J,B.staged);if(!z)throw B0(Z,J);return{result:X,row:z}}function B0($,Z){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${Z} in the pool`})}function o($,Z){if(Z.unbound)throw O($,Z.id,"unbound-credential",`row ${Z.id}'s credential is not the one this store stamped for it (stamp ${Z.stamp}); replace it with fresh material`)}function O($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function p1($,Z){if(!s(Z?.credentialEpoch))throw O("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function W4($,Z,J){if(!J)throw B0("pull",$);if(J.invalid)throw O("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw O("pull",$,"no-credential",`row ${$} holds no credential`);if(o("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==Z.credentialEpoch||J.identity!==Z.identity)throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`})}function Y4($,Z,J,X){let z=G0(()=>$.codec.merge(J,X));if(!G0(()=>$.codec.validate(z)))throw O("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function J6($,Z,J,X){let{ctx:z}=$,G=new v0(z.lockDefaults,z.lockEnv),Q={writes:0};try{p1(Z,J),await w(z,G,Q,{operation:"pull",rowId:Z},async(W)=>{W.assertNotStaged(Z);let B=W.row(Z);W4(Z,J,B);let Y=W.entry(Z);if(!Y)throw B0("pull",Z);let H=Y4(z,Z,Y.quota,X);W.setEntry(Z,{...Y,quota:H,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw o0(W,"pull",Z,Q)}finally{await G.releaseAll()}}async function j3($,Z,J={}){c$();let{ctx:X}=$;await l(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let V of X.storeLocks)await z.acquire(V);let Q=await n(X);if(Q.status!=="ready")throw Z0(Q,"updateLimitsNamespace",void 0);let W=Q.rows.map(({id:V,credentialEpoch:U,identity:j})=>({id:V,credentialEpoch:U,identity:j})),B=await Q0("updateLimitsNamespace",()=>Z(structuredClone(Q.config.commonAuthLimits),W)),Y={...Q.config,commonAuthLimits:B},H={operation:"updateLimitsNamespace",rowId:void 0};try{await P0(X.configPath,Y,{beforeRename:async()=>{await X.onStep?.("before-config-write",H),await z.assertAll(),J.beforePublish?.()}})}catch(V){if(V&&typeof V==="object"&&"published"in V&&V.published===!0)J.onPublished?.();throw V}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",H)})}function h0($,Z,J,X,z="the provider state"){if(!$)throw O(Z,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(X);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw O(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!G0(()=>$.validate(G)))throw O(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function V4($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:h0($,Z,J,G0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function F3($,Z,J,X,z){let G=$?.onReplace,Q=G?G0(()=>G(Z.providerState===void 0?void 0:structuredClone(Z.providerState),{id:Z.id,credentialEpoch:J,...Z.identity!==void 0?{previousIdentity:Z.identity}:{},...X!==void 0?{identity:X}:{},...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:h0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function K3($,Z,J,X,z){if(Z.kind==="set")return E2($,Z.value);if(Z.kind==="clear")return;return G4(J,X?.credential,z,X?.identity)}async function N3($,Z,J,X,z={}){a("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return l(G,Q,Z,z.onFailure,async(W,B)=>{let Y=G.providerState;if(!Y)throw O(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw O(Q,Z,"invalid-input","a mutator is required");let H=S(J)?J.credentialEpoch:void 0;if(!s(H))throw O(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await M0($,Q,Z);await W.acquire(J0($,V));for(let U of z.extraLocks??[])await W.acquire(U);return w(G,W,B,{operation:Q,rowId:Z},async(U)=>{let j=U.row(Z);if(!j)throw B0(Q,Z);if(h(j)!==h(V))throw O(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(j.invalid)throw O(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!j.credential)throw O(Q,Z,"no-credential",`row ${Z} holds no credential`);if(o(Q,j),(j.credentialEpoch??1)!==H||j.identity!==J.identity)throw O(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let F=await l1(U,Y,Q,j,X);if(F.kind!=="changed")return{id:Z,outcome:"unchanged",...F.kind==="unchanged"&&F.value!==void 0?{providerState:F.value}:{}};return U.setStateAccount(Z,F.account),await U.commitState(),F.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:F.value}})})}var D3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function l1($,Z,J,X,z,G=!1){let{id:Q,credential:W}=X;if(!W)throw O(J,Q,"no-credential",`row ${Q} holds no credential`);let B=X.credentialEpoch??1,Y=$.stateAccount(Q),H=Y?.[g],V=e(H);if(!S(H)||!V?.binding||V.digest!==E0(W)||V.credentialEpoch!==B||V.binding.identity!==X.identity)throw O(J,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let U=X.providerState===void 0?void 0:structuredClone(X.providerState),j=await Q0(J,()=>z(U,X));if(G&&j===D3)return{kind:"declined"};let q=j===void 0?void 0:h0(Z,J,Q,j,"the provider state the mutator returned"),F=Y!==void 0&&Object.hasOwn(Y,r);if(q===void 0?!F:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(q))return{kind:"unchanged",...q!==void 0?{value:q}:{}};let K={...Y};if(q===void 0){delete K[r];let N={...H};delete N.providerState,K[g]=N}else{K[r]=q;let N=E2(Z,q);if(V.providerState!==N)K[g]={...H,providerState:N}}return{kind:"changed",...q!==void 0?{value:q}:{},account:K}}import{randomUUID as P3}from"node:crypto";async function Q6($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:Q,type:W,label:B,enabled:Y,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}=G;return{id:Q,type:W,label:B,enabled:Y,disabledReason:H,identity:V,credentialEpoch:U,stamp:j,staged:q,torn:F,invalid:K}}),z=await Q0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw O($.info.operation,Z,"row-protected",z)}var dJ=["access","refresh","expires","lastRefreshedAt","apiKey"];function cJ($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function sJ($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!S(X)){if(J.baseURL===void 0)throw O($.info.operation,Z,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=$.row(Z)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:cJ(X),Q=J.baseURL?.trim()??G.baseURL,W=J.authHeader??G.authHeader;if(Q!==G.baseURL||W!==G.authHeader)throw O($.info.operation,Z,"endpoint-mismatch",`row ${Z} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:Q,authHeader:W}}function M3($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),Q=X??(G?G.identity:S(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function X6($,Z,J,X,z={}){let G=sJ(Z,J,X),Q=Z.stateAccount(J),W=z.providerState??{kind:"keep"},B=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,Y=typeof B==="number"?B:1,H=K3($.ctx.providerState,W,Q,Q&&Object.hasOwn(Q,r)?Z.row(J):void 0,Y),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,U=G.type==="oauth"?z.stamp??Q4(V,$.ctx.now()):void 0,j={...Q??{}};for(let K of dJ)delete j[K];if(z.clearErrors)delete j.lastRefreshError,delete j.lastQuotaRefreshError,delete j.quota;if(W.kind==="clear")delete j[r];else if(W.kind==="set")j[r]=W.value;let q=J3(G,U),F={...j,...Z3(G,U),[g]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[e4]:z.transition}:{},...k1(q,Y,z.binding??M3(Z,J,q,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:q,account:F}}async function z6($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function B6($,Z,J,X,z={}){return z6(Z,J,X6($,Z,J,X,z))}async function aJ($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=G4(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[g]:k1(Z.credential,Z.credentialEpoch??1,M3($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function c1($,Z,J){let X=$==="add"?A2(Z):void 0;if(X)throw O($,Z,"invalid-input",X);let z=X3(J,{baseURLOptional:$==="rotate"});if(z)throw O($,Z,"invalid-input",z)}function W6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw O($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function k2($,Z,J){if(J!==void 0&&!s(S(J)?J.credentialEpoch:void 0))throw O($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function Y6($,Z,J,X){if(!J)throw B0($,Z);if(J.invalid)throw O($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw O($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function G6($,Z){return O($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function H4($,Z){return O($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function nJ($,Z,J,X){let{id:z,credential:G,identity:Q}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!b2(Z.state,z))return;let W=()=>{throw O("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},B=Z.stateAccount(z),Y=e(B?.[g]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return W();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return W();let H=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[V]=r0({accounts:[I2({id:z,credential:H,identity:Y.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:t4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return W();if(Q!==void 0&&Q!==V.identity)return W();if(E0(G)!==Y.digest)return W();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return W();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return W()}else if(f0(G)!==Y.dispatch)return W();if(Y.providerState!==void 0&&V.providerState===void 0)return W();if(X!==void 0&&E2($.ctx.providerState,X)!==Y.providerState)return W();return V}function iJ($,Z,J,X){let{id:z,credential:G,identity:Q,label:W}=J,B=Z.rosterRow(z),Y=()=>{throw O("add",z,B?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=Z.stateAccount(z),V=e(H?.[g]),U=V?.staged;if(!V?.binding||!U||V.replace||V.dispatch===void 0)return Y();if(B&&(B.type!==G.type||B.label!==W||B.accountId!==Q))return Y();if(U.reservation!==J.stage?.reservation||U.label!==W||U.disabledReason!==J.disabled?.reason||V.binding.identity!==Q)return Y();let j=X===void 0?void 0:Q2(X),q=H?.[r],F=q===void 0?void 0:Q2(q);if(U.providerState!==j||U.providerState!==F)return Y();if(E0(G)!==V.digest||f0(G)!==V.dispatch)return Y();let K=B?Z.config:{accounts:[{...I2({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:U.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:U.disabledReason,staged:{reservation:U.reservation}}}}},N=r0(K,Z.state,$.ctx.codec,$.ctx.providerState).find((D)=>D.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==U.label||N.identity!==V.binding.identity||N.disabledReason!==U.disabledReason||N.staged?.reservation!==U.reservation)return Y();if(B)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(t4(Z.config,z)!==V.credentialEpoch)return Y();return Z.roster().push({...I2({id:z,credential:G,identity:Q,label:W,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:U.disabledReason,staged:{reservation:U.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function C3($,Z,J={}){a("add");let{ctx:X}=$,{id:z,credential:G,identity:Q,label:W}=Z,B=Z.stage!==void 0||Z.disabled!==void 0,Y=await l(X,"add",z,J.onFailure,async(H,V)=>{c1("add",z,G);let U=J.onExisting??"rotate";if(Z.stage!==void 0&&U==="rotate")throw O("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(U)||Z.stage!==void 0&&(W!==void 0&&typeof W!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!S(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!S(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||U==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw O("add",z,"invalid-input","staging requires a reservation and a disabled reason");let j=Z.providerState===void 0?void 0:h0(X.providerState,"add",z,Z.providerState);if(await H.acquire(J0($,{id:z,identity:Q})),G.type==="oauth")await H.acquire(J.providerLock??$.providerLock);for(let q of J.extraLocks??[])await H.acquire(q);return w(X,H,V,{operation:"add",rowId:z},async(q)=>{await Q6(q,z,J.protect);let F=S(q.state.accounts)?q.state.accounts:{},K=Object.entries(F).find(([I,f])=>{if(I===z||q.rosterRow(I)||!S(f))return!1;let c=f[g];if(!S(c)||!Object.hasOwn(c,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(K)throw O("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw O("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&U!=="rotate"&&(q.rosterRow(z)||b2(q.state,z)))return iJ($,q,Z,j);if(U==="rotate"){q.assertNotStaged(z);let I=q.rows().find((f)=>f.fingerprint===D0(G));if(I)q.assertNotStaged(I.id)}if(U==="refuse"){let I=q.rows().find((a0)=>a0.fingerprint===D0(G)||a0.id===z&&a0.credential),f=S(q.state.accounts)?q.state.accounts:{},c=Object.entries(f).find(([,a0])=>{if(!S(a0))return!1;if(G.type==="oauth")return a0.refresh===G.refresh;return typeof a0.apiKey==="string"&&a0.apiKey.trim()===G.apiKey.trim()})?.[0],p$=I?.id??c??z;if(I||c!==void 0||b2(q.state,z))throw O("add",p$,"credential-exists",`row ${p$} already holds this secret or id`)}if(U==="stage-duplicate"&&(q.rosterRow(z)||b2(q.state,z)))throw O("add",z,"id-exists",`row ${z} already exists`);let N=nJ($,q,Z,j),D=q.rows(),T=D0(G),M=U==="rotate"&&!N&&D.find((I)=>I.invalid===void 0&&I.fingerprint===T);if(M){if(q.assertNotStaged(M.id),o("add",M),Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw G6("add",M.id);let I=X6($,q,M.id,G,{...j!==void 0?{providerState:V4(X.providerState,"add",M.id,M.providerState,j)}:{}});await q.completeTorn(),q.assertNotStaged(M.id);let f=await z6(q,M.id,I);return{id:M.id,outcome:"rotated",credential:f,credentialEpoch:M.credentialEpoch??1}}let P=D.find((I)=>I.id===z);if(P){if(P.invalid)throw O("add",z,"invalid-row",`row ${z} is invalid`);if(P.credential)throw O("add",z,"id-exists",`row ${z} already holds a credential`);if(o("add",P),P.type!==G.type)throw O("add",z,"type-mismatch",`row ${z} is a ${P.type} row`);if(Q!==void 0&&P.identity!==void 0&&Q!==P.identity)throw G6("add",z);if(!P.hasEntry)q.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=X6($,q,z,G,{clearErrors:!0,...j!==void 0?{providerState:{kind:"set",value:j}}:{}});await q.completeTorn();let f=await z6(q,z,I);if(!P.hasEntry)await q.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:P.credentialEpoch??1}}let _=t4(q.config,z);if(!s(_))throw O("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=N?.identity??Q;q.roster().push(I2({id:z,credential:G,...C!==void 0?{identity:C}:{},...W!==void 0?{label:W}:{},addedAt:X.now()})),q.setEntry(z,{credentialEpoch:_,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let L="added";if(Z.disabled)n0(q,z,Z.disabled.reason),L="added-disabled";if(!Z.disabled&&C!==void 0&&G.type==="oauth"){if(D.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))n0(q,z,R1),L="added-disabled"}if(N?.credential)return await q.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??_};q.dropStateAccount(z);let A=X6($,q,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...W!==void 0?{label:W}:{},...j!==void 0?{providerState:Q2(j)}:{}}}:{},...j!==void 0?{providerState:{kind:"set",value:j}}:{}});if(U==="rotate")await q.completeTorn();let x=await z6(q,z,A);return await q.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:_}},{completeTorn:!1})});if(!B&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))$.firePull(Y.id,"add");return Y}async function T3($,Z,J,X={},z={}){a("replace");let{ctx:G}=$,Q=await l(G,"replace",Z,z.onFailure,async(W,B)=>{c1("replace",Z,J),k2("replace",Z,z.attribution);let Y=X.providerState===void 0?void 0:h0(G.providerState,"replace",Z,X.providerState),{row:H}=await M0($,"replace",Z);if(await W.acquire(J0($,H)),J.type==="oauth")await W.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await W.acquire(V);return w(G,W,B,{operation:"replace",rowId:Z},async(V)=>{if(z.attribution!==void 0)Y6("replace",Z,V.row(Z),z.attribution),await V.completeTorn();let U=W6("replace",Z,V.row(Z),J);if(h(U)!==h(H))throw H4("replace",Z);let j=V.entry(Z)?.credentialEpoch,q=(typeof j==="number"?j:1)+1;if(!s(q))throw O("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let F=F3(G.providerState,U,q,X.identity,Y),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(f1(V,Z,q,K),X.identity!==void 0)S2(V,X.identity);let N=await B6($,V,Z,J,{clearErrors:!0,binding:K,providerState:F});return await V.commitConfig(),{id:Z,credential:N,credentialEpoch:q}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return Q}async function L3($,Z,J,X={},z={}){a("rotate");let{ctx:G}=$;return l(G,"rotate",Z,z.onFailure,async(Q,W)=>{c1("rotate",Z,J),k2("rotate",Z,z.attribution);let B=X.providerState===void 0?void 0:h0(G.providerState,"rotate",Z,X.providerState),{row:Y}=await M0($,"rotate",Z);if(await Q.acquire(J0($,Y)),X.identity!==void 0&&J.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let H of z.extraLocks??[])await Q.acquire(H);return w(G,Q,W,{operation:"rotate",rowId:Z},async(H)=>{if(z.attribution!==void 0)Y6("rotate",Z,H.row(Z),z.attribution),await H.completeTorn();let V=W6("rotate",Z,H.row(Z),J);if(h(V)!==h(Y))throw H4("rotate",Z);if(o("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw G6("rotate",Z);let U=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,j=await B6($,H,Z,J,{identity:U,...B!==void 0?{providerState:V4(G.providerState,"rotate",Z,V.providerState,B)}:{}}),q=!1;if(!V.hasEntry)H.setEntry(Z,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),q=!0;if(X.identity!==void 0&&V.identity!==X.identity)z2(H,Z,X.identity),q=!0;if(q)await H.commitConfig();return{id:Z,credential:j}},{completeTorn:z.attribution===void 0})})}async function _3($,Z,J,X,z){a(Z);let{ctx:G}=$,Q=G.providerState,W=z.attribution,B=z.providerState;return l(G,Z,J,z.onFailure,async(Y,H)=>{if(k2(Z,J,W),B!==void 0){if(typeof B!=="function")throw O(Z,J,"invalid-input","the provider-state mutator must be a function");if(W===void 0)throw O(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw O(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await M0($,Z,J);await Y.acquire(J0($,V));for(let U of z.extraLocks??[])await Y.acquire(U);return w(G,Y,H,{operation:Z,rowId:J},async(U)=>{await Q6(U,J,z.protect),U.assertNotStaged(J);let j=U.row(J),q=X.enabled?W6("enable",J,j):j;if(!q||!U.rosterRow(J))throw B0(Z,J);if(h(q)!==h(V))throw H4(Z,J);if(W!==void 0)Y6(Z,J,q,W);if(X.enabled&&q.disabledReason?.startsWith(O2))throw O("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let F=!X.enabled||!q.enabled||q.disabledReason!==void 0;if(X.enabled&&F&&q.type==="oauth"){let M=q.identity===void 0?void 0:U.rows().find((P)=>P.id!==J&&P.invalid===void 0&&P.type==="oauth"&&P.enabled&&P.identity===q.identity);if(M)throw O("enable",J,"duplicate-identity",`row ${M.id} is enabled with the same identity as row ${J}`)}if(B===void 0||Q===void 0){if(await U.completeTorn(),!F)return{id:J};if(X.enabled)J4(U,J);else n0(U,J,X.reason);return await U.commitConfig(),{id:J}}if(!q.credential)throw O(Z,J,"no-credential",`row ${J} holds no credential`);o(Z,q);let K=await l1(U,Q,Z,q,B,!0);if(K.kind==="declined")return{id:J,declined:!0};await U.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(F){if(X.enabled)J4(U,J);else n0(U,J,X.reason);await U.commitConfig()}return N}if(!F)return U.setStateAccount(J,K.account),await U.commitState(),N;let D=X.enabled?{mark:P3(),enabled:!0}:{mark:P3(),enabled:!1,reason:X.reason},T=K.account[g];return U.setStateAccount(J,{...K.account,[g]:{...T,[e4]:D}}),await U.commitState(),B4(U,J,D),await U.commitConfig(),N},{completeTorn:!1})})}function O3($,Z,J,X={}){return _3($,"disable",Z,{enabled:!1,reason:J},X)}function S3($,Z,J={}){return _3($,"enable",Z,{enabled:!0},J)}async function A3($,Z,J={}){a("remove");let{ctx:X}=$;return l(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw O("remove",Z,"invalid-input","id must be non-empty");let Q=J.attribution;if(k2("remove",Z,Q),J.staged!==void 0&&(!S(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw O("remove",Z,"invalid-input","a staged removal needs a reservation");let W=await n(X);if(W.status!=="ready")throw Z0(W,"remove",Z);let B=W.rows.find((H)=>H.id===Z);if(!B&&!b2(W.state,Z))throw B0("remove",Z);let Y=h(B??{id:Z});await z.acquire(J0($,B??{id:Z}));for(let H of J.extraLocks??[])await z.acquire(H);return w(X,z,G,{operation:"remove",rowId:Z},async(H)=>{let V=H.reservation(Z);if(V!==void 0){if(!S(V)||!J.staged||V.reservation!==J.staged.reservation)throw O("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw O("remove",Z,"attribution",`row ${Z} is no longer reserved`);let U=H.row(Z),j=b2(H.state,Z);if(!U&&!j)throw B0("remove",Z);if(h(U??{id:Z})!==Y)throw H4("remove",Z);if(Q!==void 0)if(U)V6(Z,U,Q);else rJ($,H,Z,Q);let q=J.protect;if(q){let F={row:U,config:H.snapshot.config,state:H.snapshot.state},K=await Q0("remove",()=>q(Z,F));if(K!==void 0)throw O("remove",Z,"row-protected",K)}if(U){if(Q===void 0)await H.completeTorn();H.dropRosterRows(Z),await H.commitConfig()}if(j)H.dropStateAccount(Z),await H.commitState();return{id:Z,outcome:U?"removed":"completed"}},{completeTorn:!1})})}function V6($,Z,J,X="remove"){if(Y6(X,$,Z,J),Z.torn)throw O(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw O(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function rJ($,Z,J,X){let z=()=>O("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=Z.stateAccount(J),Q=e(G?.[g]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let W;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();W={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")W={type:"oauth",refresh:G.refresh};else throw z();let[B]=r0({accounts:[I2({id:J,credential:W,identity:Q.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!B?.credential||B.invalid||B.stamp!=="bound")throw z();if(Q.credentialEpoch!==X.credentialEpoch||Q.binding.identity!==X.identity)throw O("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function b2($,Z){let J=$.accounts;return S(J)&&Object.hasOwn(J,Z)}function d1($){return S($)&&typeof $.id==="string"?$.id:void 0}function oJ($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let Q=d1(G);if(Q!==void 0)J.add(Q)}let X=new Set;for(let G of Z){if(typeof G!=="string")return"ids must be an array of roster ids";if(X.has(G))return`id ${G} appears more than once`;if(!J.has(G))return`id ${G} is not in the roster`;X.add(G)}let z=[...J].filter((G)=>!X.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function tJ($,Z){let J=new Map;for(let G of $){let Q=d1(G);if(Q===void 0)continue;let W=J.get(Q);if(W)W.push(G);else J.set(Q,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>d1(G)===void 0?G:X[z++])}async function E3($,Z,J={}){a("reorder");let{ctx:X}=$,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let W of J.extraLocks??[])await G.acquire(W);return w(X,G,Q,{operation:"reorder",rowId:void 0},async(W)=>{let B=W.roster(),Y=oJ(B,Z);if(Y)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let H=[...Z],V=tJ(B,H);if(V.every((U,j)=>U===B[j]))return{ids:H,outcome:"unchanged"};return W.config.accounts=V,await W.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function R3($,Z,J,X,z={}){return a("recordIdentity"),l($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw O("recordIdentity",Z,"invalid-input","identity must be non-empty");let W=S(X)?X.credentialEpoch:void 0;if(!s(W))throw O("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:B}=await M0($,"recordIdentity",Z);await G.acquire(J0($,B)),await G.acquire(z.providerLock??$.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return w($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(Y)=>{let H=W6("recordIdentity",Z,Y.row(Z));if(h(H)!==h(B))throw H4("recordIdentity",Z);if(o("recordIdentity",H),(H.credentialEpoch??1)!==W)throw O("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw G6("recordIdentity",Z);if(H.identity===void 0)await aJ(Y,H,J);let V=z2(Y,Z,J);return await Y.commitConfig(),{id:Z,disabled:V}})})}function b3($){let Z=$[v];return S(Z)&&S(Z.publications)?Z.publications:{}}function k3($,Z){let J=b3($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!S(X)||X.operationId!==Z||typeof X.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(X.planDigest)||!["committed","cleaned"].includes(String(X.phase))||!Array.isArray(X.removed)||!Array.isArray(X.finalized)||X.removed.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch))||X.finalized.some((z)=>!S(z)||typeof z.id!=="string"||!s(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw O("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function x3($,Z){let J=await n($.ctx);if(J.status!=="ready")throw Z0(J,"publishRoster",Z);return k3(J.config,Z)}function eJ($,Z){let J=()=>{throw O("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId||!Array.isArray(Z.remove)||!Array.isArray(Z.finalize)||!Array.isArray(Z.order))J();let X=new Set;for(let z of[...Z.remove,...Z.finalize]){if(!S(z)||typeof z.id!=="string"||A2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),k2("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of Z.remove)if($.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();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"))J();if(Z.order.some((z)=>typeof z!=="string"||A2(z))||new Set(Z.order).size!==Z.order.length)J()}function y3($,Z){$.entries();let J=$.config[v],X={...b3($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function $X($,Z,J){let X=new Set;for(let Q of R2($.config)){if(!S(Q)||typeof Q.id!=="string")continue;if(X.has(Q.id))throw O("publishRoster",Z.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(Q.id)}let z=new Set(Z.remove.map((Q)=>Q.id)),G=J.filter((Q)=>Q.invalid!=="roster"&&!z.has(Q.id));if(G.length!==Z.order.length||Z.order.some((Q)=>!G.some((W)=>W.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw O("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function I3($,Z){await $.assertAll();for(let X of Z.removed)if(e($.stateAccount(X.id)?.[g])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=e(z?.[g]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let Q={...z[g]};delete Q.staged,$.setStateAccount(X.id,{...z,[g]:Q})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return y3($,J),await $.commitConfig({durable:!0}),J}async function g3($,Z,J={}){return a("publishRoster"),l($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!S(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw O("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=Q2(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((W)=>S(W)&&typeof W.id==="string");for(let W=0;;W++){let B=await n($.ctx);if(B.status!=="ready")throw Z0(B,"publishRoster",Z.operationId);let Y=new Map(Q.map(({id:V})=>[V,h(B.rows.find((U)=>U.id===V)??{id:V})]));for(let V of[...new Set(Y.values())].sort())await X.acquire(J0($,{id:V}));await X.acquire(J.providerLock??$.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await w($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(V)=>{let U=V.rows();if(Q.some(({id:P})=>h(U.find((_)=>_.id===P)??{id:P})!==Y.get(P)))return;let j=k3(V.config,Z.operationId);if(j){if(j.planDigest!==G)throw O("publishRoster",Z.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(j.phase==="cleaned")return{outcome:"already-cleaned",receipt:j};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await I3(V,j)}}eJ($,Z);let q=$X(V,Z,U),F=[];for(let P of Z.remove){V.assertNotStaged(P.id);let _=U.find((C)=>C.id===P.id);if(!_)throw O("publishRoster",P.id,"attribution","the removed row no longer exists");if(V6(P.id,_,P.attribution,"publishRoster"),!_.credential||P.fingerprint!==void 0&&D0(_.credential)!==P.fingerprint)throw O("publishRoster",P.id,"attribution","the removed secret no longer matches");F.push(_)}let K=[];for(let P of Z.finalize){let _=U.find((f)=>f.id===P.id),C=e(V.stateAccount(P.id)?.[g]);if(!_||_.staged?.reservation!==P.reservation||C?.staged?.reservation!==P.reservation||_.enabled)throw O("publishRoster",P.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(P.id),A=V.rosterRow(P.id),x=L?.[r],I=x===void 0?void 0:Q2(x);if(!C?.staged||C.staged.label!==A?.label||C.staged.disabledReason!==_.disabledReason||C.staged.providerState!==I)throw O("publishRoster",P.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");V6(P.id,_,P.attribution,"publishRoster"),K.push(_)}let N=q.find((P)=>P.torn);if(N)throw O("publishRoster",Z.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let D=new Set;for(let P of q){if(!(Z.finalize.find((C)=>C.id===P.id)?.enabled??P.enabled)||P.type!=="oauth"||P.identity===void 0)continue;if(D.has(P.identity))throw O("publishRoster",P.id,"invalid-input","the final enabled roster repeats a known identity");D.add(P.identity)}for(let P of q)if(P.identity!==void 0&&P.fingerprint!==void 0&&q.some((_)=>_.id!==P.id&&_.identity!==void 0&&_.identity!==P.identity&&_.fingerprint===P.fingerprint))throw O("publishRoster",P.id,"attribution","the resulting pool gives the same secret different known identities");for(let P of K)if(P.identity!==void 0&&F.some((_)=>_.identity!==void 0&&_.identity!==P.identity&&_.fingerprint===P.fingerprint))throw O("publishRoster",P.id,"attribution","the staged secret belonged to a different known identity");await Q6(V,Z.operationId,J.protect);let T={operationId:Z.operationId,planDigest:G,phase:"committed",removed:F.map((P)=>({id:P.id,credentialEpoch:P.credentialEpoch??1})),finalized:Z.finalize.map((P,_)=>({id:P.id,credentialEpoch:K[_]?.credentialEpoch??1,reservation:P.reservation,enabled:P.enabled}))};for(let P of Z.remove)V.dropRosterRows(P.id);for(let P of Z.finalize){let _=V.rosterRow(P.id);_.enabled=P.enabled;let C={...V.entry(P.id)};if(delete C.staged,P.enabled)delete C.disabledReason;else C.disabledReason=P.disabledReason;V.setEntry(P.id,C)}let M=V.roster().filter((P)=>!S(P)||typeof P.id!=="string"||U.find((_)=>_.id===P.id)?.invalid==="roster");return V.config.accounts=[...Z.order.map((P)=>V.rosterRow(P)),...M],y3(V,T),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await I3(V,T)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),W>=1)throw O("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class s1{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor($,Z,J,X,z){this.rt=$,this.hook=Z,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire($,Z){if(!this.hook)return;if(Z==="load"){if(this.firedAtLoad.has($))return;this.firedAtLoad.add($)}let J=this.run($,Z);this.inflight.add(J),J.finally(()=>this.inflight.delete(J))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run($,Z){let J=this.rt(),{ctx:X}=J,z=new v0(X.lockDefaults,X.lockEnv),G={writes:0};try{let Q=await w(X,z,G,{operation:"pull",rowId:$},async(Y)=>{if(Y.reservation($)!==void 0)return;await Y.completeTorn();let H=Y.row($);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)o("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.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(),!Q){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let W;try{W=await this.hook?.(Q)}catch(Y){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Y})}await(J.publishQuota??((Y,H,V)=>J6(J,Y,H,V)))($,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},W)}catch(Q){this.firedAtLoad.delete($);let W=o0(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,W)}catch(B){this.logger?.warn("pull failure hook threw",{rowId:$,error:B instanceof Error?B.message:String(B)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:W.kind})}finally{await z.releaseAll()}}}var f3=100,H6=128;class a1{rt;timeoutMs;clock;pending=new Map;warned=new Set;wake=new Set;logger;timer;committedAt;running;closing;closed=!1;stopped=!1;failures=0;constructor($,Z=1000,J=h3){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??t("store")}async record($,Z,J){try{this.assertOpen($),p1($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await M0(this.rt,"pull",$);W4($,X.attribution,z),Y4(this.rt.ctx,$,this.overlayRow({...z,quota:R0(G.config,$)?.quota}).quota,X.observation),await this.room($),this.assertOpen($);let Q=this.pending.get($)??[];if(Q.push(X),this.pending.set($,Q),Q.length>=H6)this.flushNow();else this.schedule(f3)}catch(X){throw o0(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<H6)return;let{ctx:Z}=this.rt,J=Math.max(0,...Z.storeLocks.map((z)=>z.timeoutMs??Z.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued($)>=H6){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw O("pull",$,"lock-contention",`pool quota queue for ${$} is full (${H6} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let Q=()=>{clearTimeout(W),this.wake.delete(Q),G()},W=setTimeout(Q,z);this.wake.add(Q)})}}assertOpen($){if(this.closed)throw O("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{W4($.id,J.attribution,$),Z={...Z,quota:Y4(this.rt.ctx,$.id,Z.quota,J.observation),needsFirstReading:!1}}catch{}return Z}overlay($){return $.map((Z)=>this.overlayRow(Z))}schedule($){if(this.running||this.timer||!this.pending.size||this.stopped)return;let Z=this.closed?0:(this.committedAt??-1/0)+v3-this.clock.now();if(this.timer=this.clock.schedule(Math.max($,Z),()=>{return this.timer=void 0,this.flush()}),!this.closed)this.timer.unref?.()}cancelTimer(){this.timer?.cancel(),this.timer=void 0}flushNow(){if(this.running)return;this.cancelTimer(),this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return this.running??Promise.resolve();let $=[...this.pending.values()].flat(),Z={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new v0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await w(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let Q of $){let{id:W,attribution:B,observation:Y}=Q,H=JSON.stringify([W,B.credentialEpoch,B.identity]);try{z.assertNotStaged(W),W4(W,B,z.row(W))}catch(j){if(!(j instanceof b))throw j;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:W,kind:j.kind});continue}let V=z.entry(W);if(!V)continue;let U;try{U=Y4(Z,W,V.quota,Y)}catch(j){let q=`codec:${H}`;if(!this.warned.has(q))this.warned.add(q),this.warn("pool quota publication dropped; the quota codec refused it",{id:W,error:j instanceof Error?j.message:String(j)});continue}z.setEntry(W,{...V,quota:U,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set($);for(let[z,G]of this.pending){let Q=G.filter((W)=>!X.has(W));if(Q.length)this.pending.set(z,Q);else this.pending.delete(z)}this.failures=0}catch(X){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:X instanceof Error?X.message:String(X)})}finally{await J.releaseAll(),this.running=void 0;for(let z of this.wake)z();let X=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):f3;this.schedule(X)}})(),this.running}warn($,Z){try{this.logger.warn($,Z)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){this.cancelTimer();let $,Z,J=new Promise((X)=>{Z=()=>{if(!this.pending.size)X()},this.wake.add(Z),Z()});try{this.flush(),await Promise.race([J,new Promise((X)=>{$=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout($),this.cancelTimer(),this.wake.delete(Z),this.pending.size)this.warn("pool quota drain timed out; pending readings left",{accounts:this.pending.size,readings:[...this.pending.values()].reduce((X,z)=>X+z.length,0)});this.pending.clear();for(let X of this.wake)X()}}}import{randomUUID as ZX}from"node:crypto";function n1($,Z){if(G2("refresh",$,Z?.staged),!Z)throw O("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw O("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw O("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw O("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function m3($){return O("refresh",$,"refresh-stamp-ahead",`row ${$}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function w3($,Z,J,X={}){a("refresh");let{ctx:z}=$;return l(z,"refresh",Z,X.onFailure,async(G,Q)=>{let{row:W}=await M0($,"refresh",Z);n1(Z,W);let B=await X.refuse?.(W);if(B!==void 0)return{status:"refused",rowId:Z,reason:B};let Y=h(W),H;for(let q=0;;q++){await G.acquire(J0($,{id:Z,identity:Y===Z?void 0:Y})),await G.acquire(X.providerLock??$.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await w(z,G,{writes:0},{operation:"refresh",rowId:Z},async(N)=>{let D=n1(Z,N.row(Z));if(o("refresh",D),!D.hasEntry)N.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),D=n1(Z,N.row(Z));if(h(D)!==Y)return{keyNow:h(D)};let T=await X.refuse?.(D);if(T!==void 0)return{refused:T};return{row:D,credential:D.credential,credentialEpoch:D.credentialEpoch,identity:D.identity}});if("refused"in K)return{status:"refused",rowId:Z,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),q>=1)throw O("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);Y=K.keyNow;continue}H=K;break}if(g1(H.credential.lastRefreshedAt,z.now()))throw m3(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:q})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw O("refresh",Z,"provider","the provider returned no refresh token",!0);let U=V.providerState===void 0?void 0:h0(z.providerState,"refresh",Z,V.providerState,"the provider state the provider returned"),j=await w(z,G,Q,{operation:"refresh",rowId:Z},async(q)=>{let F=q.row(Z),K=q.entry(Z);if(!F||F.invalid||!K||K.credentialEpoch!==H.credentialEpoch||F.identity!==H.identity)throw new b({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`});o("refresh",F);let N=await X.refuse?.(F);if(N!==void 0)return{refused:N};let D=z.now(),T=F.credential?.type==="oauth"?F.credential.lastRefreshedAt:void 0;if(g1(T,D))throw m3(Z);let M={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},P=F.identity!==void 0&&V.identity!==void 0&&F.identity!==V.identity?{expectedIdentity:F.identity,returnedIdentity:V.identity}:void 0,_=P?{mark:ZX(),enabled:!1,reason:`${O2}${JSON.stringify(P)}`}:void 0,C=F.identity===void 0&&V.identity?V.identity:void 0,L=await B6($,q,Z,M,{stamp:Q4(T,D),transition:_,identity:C,...U!==void 0?{providerState:V4(z.providerState,"refresh",Z,F.providerState,U)}:{}});if(_!==void 0)B4(q,Z,_),await q.commitConfig();let A=F.identity;if(C!==void 0)z2(q,Z,C),A=C,await q.commitConfig();return{stored:L,identity:A,contradiction:P,refused:void 0}});if(j.refused!==void 0)return{status:"refused",rowId:Z,reason:j.refused};if(j.contradiction!==void 0)return{status:"identity-contradicted",rowId:Z,...j.contradiction,credential:j.stored};if(X.onPersisted)try{let q=X.onPersisted;await Q0("refresh",()=>q(Z,j.stored),!0)}catch(q){throw new b({operation:"refresh",rowId:Z,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:j.stored,message:"the after-persist hook threw; the rotation stays committed",cause:q})}return{status:"rotated",rowId:Z,credential:j.stored,...j.identity!==void 0?{identity:j.identity}:{}}})}import{isDeepStrictEqual as u3}from"node:util";var j6=Object.freeze(["version","accounts",v]);function U6($){let Z={};for(let[J,X]of Object.entries($))if(!j6.includes(J))q6(Z,J,X);return Z}function q6($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function JX($,Z){let J={};for(let[X,z]of Object.entries($))if(j6.includes(X)||X==="commonAuthLimits")q6(J,X,z);else if(Object.hasOwn(Z,X))q6(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))q6(J,X,z);return J}function i1($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var XX=new p3;function l3($){return d3($.ctx.configPath)}async function d3($){let Z=async([X=$]=[])=>{let z=await H3(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:U6(z.config)}},J=Z6?await Z():await XX.read([$],Z);return structuredClone(J)}async function c3($,Z,J={}){a("updateSettings");let{ctx:X}=$,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of J.extraLocks??[])await G.acquire(B);let W=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let B=await n(X);if(B.status!=="ready")throw Z0(B,"updateSettings",void 0);let Y=U6(B.config),H=structuredClone(Y),V=await Q0("updateSettings",()=>Z(H)),U=V===void 0?H:V;if(!S(U))throw i1("the settings mutator must produce an object");let j=j6.filter((K)=>Object.hasOwn(U,K));if(j.length>0)throw i1(`settings cannot set the pool-owned key(s) ${j.join(", ")}`);if(Object.hasOwn(U,"commonAuthLimits")&&(!Object.hasOwn(Y,"commonAuthLimits")||!u3(U.commonAuthLimits,Y.commonAuthLimits)))throw i1("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let q=JX(B.config,U);if(u3(U6(q),Y))return{settings:Y,outcome:"unchanged"};let F={operation:"updateSettings",rowId:void 0};return await P0(X.configPath,q,{beforeRename:async()=>{await X.onStep?.("before-config-write",F),await G.assertAll()}}),Q.writes++,await X.onStep?.("after-config-write",F),{settings:U6(q),outcome:"updated"}}finally{await G.releaseTo(W)}})}var s3=new Map;function zX($){let Z=s3.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},s3.set($,Z);return Z}function a3($){if($.status==="ready")return{status:"ready",schemaVersion:i0,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function U4($){let Z=zX($.configPath),J={...r1,...$.lockOptions},X={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:J,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 s1(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(Y,H)=>z.fire(Y,H)},Q=$.coalesceQuota?new a1(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,W=(Y,H,V)=>Q?Q.record(Y,H,V):J6(G,Y,H,V);G.publishQuota=W;let B=(Y)=>{if(Y.status==="ready"&&Q)return{...Y,rows:Q.overlay(Y.rows)};return Y};return{async load(){let Y=B(await n(X));if(Y.status==="ready"){for(let H of Y.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return a3(Y)},async read(){return a3(B(await n(X)))},async initialize(Y={}){return{status:await q3(X,Y.dropKeys??[])}},add:(Y,H)=>C3(G,Y,H),publishRoster:(Y,H)=>g3(G,Y,H),publication:(Y)=>x3(G,Y),replace:(Y,H,V,U)=>T3(G,Y,H,V,U),rotate:(Y,H,V,U)=>L3(G,Y,H,V,U),updateProviderState:(Y,H,V,U)=>N3(G,Y,H,V,U),disable:(Y,H,V)=>O3(G,Y,H,V),enable:(Y,H)=>S3(G,Y,H),remove:(Y,H)=>A3(G,Y,H),reorder:(Y,H)=>E3(G,Y,H),readSettings:()=>l3(G),updateSettings:(Y,H)=>c3(G,Y,H),updateLimitsNamespace:(Y,H)=>j3(G,Y,H),recordIdentity:(Y,H,V,U)=>R3(G,Y,H,V,U),refresh:(Y,H,V)=>w3(G,Y,H,V),recordQuota:W,close:()=>Q?.close()??Promise.resolve(),dispose:()=>Q?.close()??Promise.resolve(),requestReading:(Y)=>z.fire(Y,"admission"),pullsSettled:()=>z.settled()}}var GX=[/\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 e1($={}){let{redactStrings:Z}=n3({...$,extraValuePatterns:[...GX,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class u extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var i3=/^[a-z][a-z0-9-]{0,63}$/,o1={code:"action-failed",text:"That action failed."},QX=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 q4($){if($ instanceof u)return{code:i3.test($.code)?$.code:o1.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:QX.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return o1}var r3="This cannot be undone. Continue?",BX=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function WX($){let Z=$.toLowerCase().replace(/[-_]/g,"");return BX.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function YX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function t1($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>t1(z,`${Z}[${G}]`,J));if(!YX($))return $;let X={};for(let[z,G]of Object.entries($)){if(WX(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:t1(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function o3($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=t1($,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:Z,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:Z,fields:X.redacted});return z}function VX($){return{value:String($.value),label:String($.label)}}function HX($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(VX),...$.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 $9($){if($.irreversible===!0)return{message:$.confirm||r3,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function t3($){let Z=$9($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(HX),...Z?{confirm:Z}:{}}}function UX($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function qX($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:UX($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(t3)}}function jX($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(qX),actions:(Z.actions??[]).map(t3),...Z.facts!==void 0?{facts:Z.facts}:{}}}function e3($,Z,J){return{command:$,title:Z,sections:J.map(jX)}}function $5($,Z,J,X){return o3({command:$,menu:e3($,Z,J)},$,X)}function Z5($,Z,J,X,z){return o3({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:i3.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:e3($,Z,J)},$,z)}var W5="disabled from the command menu";function FX($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function C0($){return FX($)?{...$}:{}}function KX($){if($.status!=="ready")return[];let Z=new Set;return $.rows.filter((J)=>{if(Z.has(J.id))return!1;return Z.add(J.id),!0})}function NX($,Z){return $.label??Z??$.id}function F6($,Z){return t0($.quota)?b0($.quota,Z):void 0}function Y5($,Z){return`${$} ${Z}${$===1?"":"s"}`}var x2="Actions";function DX($){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 J5($,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 X5($){return q4($).text}function J9($){if($.settings)return $.settings;let{store:Z,extraLocks:J}=$,X=J?{extraLocks:J}:{};return{async read(){let z=await Z.readSettings();return z.status==="error"?{}:z.settings},async update(z){await Z.updateSettings(z,X)}}}async function PX($){let{store:Z}=$,J=await Z.read(),X=await J9($).read(),z=await $.routing?.vaultOrder?.();return{load:J,rows:KX(J),settings:X,...z?{vault:z}:{}}}function K6($,Z){let J=Z.accounts?.describeIdentity?Z.accounts.describeIdentity($):$.identity;return{account:{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...J!==void 0?{identity:J}:{}},name:NX($,J)}}function MX($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((V)=>V.id),Q=DX(Z.load),W=Z.rows.filter((V)=>V.enabled).length,B=Z.rows.map((V,U)=>{let{account:j,name:q}=K6(V,$),F=[V.type==="api"?"API key":"OAuth",...j.identity!==void 0?[j.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,W5,z),`Disabled ${q}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${q}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((D,T)=>({value:String(T+1),label:String(T+1)})),value:String(U+1)}],run:async({values:D})=>{let T=Number(D.position),M=G.filter((_)=>_!==V.id);return M.splice(T-1,0,V.id),(await J.reorder(M,z)).outcome==="unchanged"?`${q} is already at position ${T}.`:`Moved ${q} to position ${T}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${q}? Its stored credential is deleted.`,run:async()=>{return await J.remove(V.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${q}.`}}),{id:V.id,label:q,detail:F,group:"Accounts",status:K,account:j,actions:N}}),Y=$.accounts?.login,H=[];if(Y&&!Q)H.push({id:"add",label:Y.label??"Add account",group:x2,knobs:Y.knobs??[],run:async({values:V,invocation:U})=>{let j=await Y.run(V,U);if(j.status==="cancelled")return{ok:!1,text:j.message??"Login cancelled."};if(j.status==="ready"){let q=await J.add(j.account,z);return J5(j.account.label??q.id,q)}return j.completion.then(async(q)=>{if(!q){U.notify("Login cancelled.","warning");return}let F=await J.add(q,z);U.notify(J5(q.label??F.id,F))},(q)=>{U.notify(`Adding the account failed: ${X5(q)}`,"error")}).catch((q)=>{U.notify(`Adding the account failed: ${X5(q)}`,"error")}),j.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${Y5(Z.rows.length,"account")}, ${W} enabled`],items:Q?[]:B,actions:H}}}function CX($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if($.quota?.check)await $.quota.check(H,V);else{for(let U of H)$.store.requestReading(U);await $.store.pullsSettled()}},Q=Z.rows.filter((H)=>H.candidate),W=Q.map((H)=>{let{account:V,name:U}=K6(H,$),j=F6(H,J);return{id:H.id,label:U,group:z,status:I0(j,{now:X,form:"compact"}),detail:I0(j,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:q})=>{return await G([H.id],q),`Checked quota for ${U}.`}}]}}),B=Z.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=K6(H,$),U=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",j=I0(F6(H,J),{now:X,form:"compact"});return`${V} (${U}): ${j}`}),Y=[];if(Q.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:x2,run:async({invocation:H})=>{let V=Q.map((U)=>U.id);return await G(V,H),`Checked quota for ${Y5(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:B,items:W,actions:Y}}}async function TX($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function Z9($){return new u("vault-invalid-order",$)}function LX($){let Z=$.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>Z.filter((z)=>z.id===X||z.label===X);return{ids:Z.map((X)=>X.id),nameOf:(X)=>Z.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let z=Z.find((G)=>G.id===X);return z&&!/[,\n]/.test(z.label)&&J(z.label).length===1?z.label:X},resolve:(X)=>{let z=[];for(let G of X){let Q=J(G);if(Q.length===0)throw Z9(`"${G}" is not a vault account.`);if(Q.length>1)throw Z9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let W=Q[0].id;if(z.includes(W))throw Z9(`"${G}" names an account already in the order.`);z.push(W)}return z}}}function _X($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=J9($),Q=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],W=C0(Z.settings.routing).mode,B=typeof W==="string"&&Q.some((N)=>N.value===W)?W:"ordered",Y=Q5(B),H=Z.vault?LX(Z.vault):void 0,V=H?H.ids:Z.rows.map((N)=>N.id),U=(N)=>H?H.nameOf(N):N,j=B5(V,Y.placement,$.routing?.formerMainId??G5),F=[`Mode: ${Q.find((N)=>N.value===B)?.label??B}`];if(V.length>0)F.push(`${H?"Vault account order":"Roster order"}: ${V.map(U).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==V.join())F.push(`Tried in order: ${j.map(U).join(", ")}`);let K=[{id:"mode",label:"Change mode",group:x2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:B}],run:async({values:N})=>{let D=String(N.mode);return await G.update((T)=>{T.routing={...C0(T.routing),mode:D};return}),`Routing mode set to ${Q.find((T)=>T.value===D)?.label??D}.`}}];if(V.length>1)K.push({id:"order",label:"Set order",group:x2,knobs:[{kind:"text",id:"order",label:H?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:H?V.map(H.entryOf).join(", "):V.join(", "),required:!0}],run:async({values:N})=>{let T=String(N.order).split(H?/[,\n]+/:/[\s,]+/).map((P)=>P.trim()).filter((P)=>P.length>0),M=Z.vault&&H?await TX(Z.vault,H.resolve(T)):await J.reorder(T,z);return M.outcome==="unchanged"?"The order is unchanged.":`Order set to ${M.ids.map(U).join(", ")}.`}});if($.routing?.sameAccountWait){let D=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],T=C0(Z.settings.routing).maxSameAccountWait,M=String(T===0||T==="max"?T:15),P=(_)=>D.find((C)=>C.value===_)?.label??_;F.push(`Longest wait on the same account: ${P(M)}`),K.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:x2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:D,value:M}],run:async({values:_})=>{let C=String(_.maxSameAccountWait),L=C==="max"?"max":Number(C);return await G.update((A)=>{A.routing={...C0(A.routing),maxSameAccountWait:L};return}),`Longest wait on the same account set to ${P(C)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:F,actions:K}}}function OX($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of F6(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function SX($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of F6(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,z5(G));return(z)=>X.get(z)??z}function AX($,Z){let J=J9($),X=C0(Z.settings.killswitch),z=X.enabled===!0,G=C0(X.accounts),Q=OX($,Z),W=SX($,Z),B=z?"on":"off",Y=Z.rows.map((H)=>{let{account:V,name:U}=K6(H,$),j=C0(G[H.id]),q=Q.filter((F)=>typeof j[F]==="number");return{id:H.id,label:U,group:`Floors · killswitch ${B}`,status:q.length===0?"no floors":q.map((F)=>`${W(F)} ≥${j[F]}%`).join(" · "),account:V,actions:[{id:"floors",label:"Set floors",knobs:Q.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${W(F)}`,min:0,max:100,...typeof j[F]==="number"?{value:j[F]}:{}})),run:async({values:F})=>{return await J.update((K)=>{let N=C0(K.killswitch),D=C0(N.accounts),T=C0(D[H.id]);for(let M of Q){let P=F[M];if(typeof P==="number")T[M]=P;else if(P===null)delete T[M]}if(Object.keys(T).length>0)D[H.id]=T;else delete D[H.id];if(Object.keys(D).length>0)N.accounts=D;else delete N.accounts;K.killswitch=N;return}),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${B}`],items:Y,actions:[{id:"killswitch",label:z?"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:x2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:H})=>{let V=H.enabled===!0;return await J.update((U)=>{U.killswitch={...C0(U.killswitch),enabled:V};return}),`Killswitch ${V?"on":"off"}.`}}]}}}async function V5($){let Z=await PX($);return[MX($,Z),CX($,Z),_X($,Z),AX($,Z)]}var EX=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),X9=["accounts","quota","routing","limits"];function H5($,Z){let{sessionId:J}=$,X=$.notify.bind($);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X(Z(String(z))):X(Z(String(z)),G)})}function RX($,Z){switch($.kind){case"choice":{let J=Z??$.value;if(typeof J==="string"&&$.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${$.label}.`}}case"toggle":{let J=Z??$.value;return typeof J==="boolean"?{value:J}:{problem:`${$.label} must be on or off.`}}case"number":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${$.label} needs a number.`};if($.min!==void 0&&X<$.min)return{problem:`${$.label} must be at least ${$.min}.`};if($.max!==void 0&&X>$.max)return{problem:`${$.label} must be at most ${$.max}.`};return{value:X}}case"text":{let J=Z===void 0?$.value??null:Z;if(J===null||J==="")return $.required?{problem:`${$.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${$.label} must be text.`}}}}function IX($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=RX(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function bX($,Z){let J=$.find((z)=>z.id===Z.sectionId);if(!J)return;return(Z.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===Z.itemId)?.actions)?.find((z)=>z.id===Z.actionId)}function B2($){let Z=$.logger??t("commands"),J=e1($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},W=X9.filter((U)=>!Q[U]);for(let U of X9)if(Q[U]&&$[U]!==void 0)throw Error(`the ${U} section is replaced; its built-in options cannot also be given`);let B=$.store;if(W.length>0&&!B)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let Y=new Set;for(let U of G){if(EX.has(U.id)||Y.has(U.id))throw Error(`extra section id ${U.id} is taken`);Y.add(U.id)}async function H(U,j,q,F){try{return{id:U,slot:j,title:q.title,content:await q.build(F)}}catch(K){return Z.warn("command menu section failed to build",{command:$.command,section:U,error:J(K instanceof Error?K.message:String(K))}),{id:U,slot:j,title:q.title,content:{lines:["This section could not be loaded."]}}}}async function V(U){let j=B&&W.length>0?await V5({store:B,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.settings?{settings:$.settings}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],q=[];for(let F of X9){let K=Q[F];if(K)q.push(await H(F,F,K,U));else{let N=j.find((D)=>D.slot===F);if(N)q.push(N)}}if($.cache)q.push(await H("cache","cache",$.cache,U));if($.diagnostics)q.push(await H("diagnostics","diagnostics",$.diagnostics,U));for(let F of G)q.push(await H(F.id,"extra",F,U));return q}return{command:$.command,async open(U){let j=H5(U,J);return $5($.command,$.title,await V(j),X)},async apply(U,j){let q=H5(j,J),F=async(M)=>Z5($.command,$.title,await V(q),M,X),K=U.command===$.command?bX(await V(q),U):void 0;if(!K)return F({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=$9(K);if(N&&U.confirmed!==!0)return F({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let D=IX(K.knobs??[],U.values);if("problem"in D)return F({ok:!1,code:"invalid-input",text:D.problem});let T;try{let M=await K.run({values:D.values,...U.itemId!==void 0?{itemId:U.itemId}:{},invocation:q});T=typeof M==="string"?{ok:!0,text:M}:{ok:M.ok,text:M.text,...M.ok?{}:{code:M.code??"refused"}}}catch(M){let P=q4(M);Z.warn("command menu action failed",{command:$.command,section:U.sectionId,action:U.actionId,code:P.code,error:J(M instanceof Error?M.message:String(M))}),T={ok:!1,...P}}return F(T)}}}function kX($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function xX($){if($===null||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.command!=="string"||typeof Z.sectionId!=="string"||typeof Z.actionId!=="string")return;if(Z.itemId!==void 0&&typeof Z.itemId!=="string")return;if(Z.sessionId!==void 0&&typeof Z.sessionId!=="string")return;if(Z.confirmed!==void 0&&typeof Z.confirmed!=="boolean")return;let J={};if(Z.values!==void 0){if(Z.values===null||typeof Z.values!=="object"||Array.isArray(Z.values))return;for(let[X,z]of Object.entries(Z.values)){if(!kX(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:Z.command,sectionId:Z.sectionId,actionId:Z.actionId,...typeof Z.itemId==="string"?{itemId:Z.itemId}:{},...Z.values!==void 0?{values:J}:{},...Z.confirmed===!0?{confirmed:!0}:{},...typeof Z.sessionId==="string"?{sessionId:Z.sessionId}:{}}}function R($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function U5($,Z){if($.kind!==Z.kind)return!1;if($.kind==="model")return Z.kind==="model"&&$.model===Z.model;if($.kind==="family")return Z.kind==="family"&&$.family===Z.family;return!0}function yX($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function N6($,Z,J){return $.excludedForRequest.some((X)=>R(X.account,Z)&&U5(X.scope,J))}function y2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>R(X.account,Z.account)&&U5(X.scope,Z.scope))?$.tried:[...$.tried,{account:{...Z.account},scope:{...Z.scope}}];return{...$,tried:J,saw429:$.saw429||Z.status===429,...Z.kind==="payment-balance"?{sawPaymentBalance:!0}:{},lastStatus:Z.status}}case"retain":{if(Z.cause==="credential-recovery"||$.retainedAttempts.includes(Z.attemptId))return $;let J=$.retains.find((X)=>R(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!R(X.account,Z.account)),{account:{...Z.account},count:(J?.count??0)+1,startedAt:J?.startedAt??Z.clockNow,lastRetainedAt:Z.clockNow}]}}case"exclude":if($.excludedAttempts.includes(Z.attemptId))return $;return{...$,excludedAttempts:[...$.excludedAttempts,Z.attemptId],excludedForRequest:N6($,Z.account,Z.scope)?$.excludedForRequest:[...$.excludedForRequest,{account:{...Z.account},scope:{...Z.scope}}]};case"switch":return $.switchedAttempts.includes(Z.attemptId)?$:{...$,switchedAttempts:[...$.switchedAttempts,Z.attemptId],switches:$.switches+1};case"blocked":return $.blockedSince===void 0?{...$,blockedSince:Z.clockNow}:$;case"selected":{let{blockedSince:J,...X}=$;return X}}}var z9=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function W2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function D6(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!R(Z.accountKey,Z.currentAccountKey)||!Number.isFinite(Z.lastAcceptedAt))return!1;let J=$.get(Z.sessionId);if(J&&J.lastAcceptedAt>Z.lastAcceptedAt)return!1;let X=typeof Z.ttlMs==="number"?[Z.ttlMs]:Z.ttlMs,z=X?.length?Math.max(...X.map(W2)):W2(void 0);if($.set(Z.sessionId,Object.freeze({accountKey:Object.freeze({...Z.accountKey}),lastAcceptedAt:Z.lastAcceptedAt,ttlMs:z})),$.size>256){let G,Q=Number.POSITIVE_INFINITY;for(let[W,B]of $)if(B.lastAcceptedAt<Q)G=W,Q=B.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function P6($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var j4=3621000;function m0($){return $===0||$===15||$==="max"?$:15}function F4($){let Z=m0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!R(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=W2(J.ttlMs),z=J.lastAcceptedAt+X;if(X===0||!Number.isFinite(z))return;return{cacheExpiresAt:z,maxWaitMs:Z==="max"?Number.POSITIVE_INFINITY:900000}}import{createHash as gX}from"node:crypto";function G9($,Z){let J=gX("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}function M6($,Z){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let J;for(let X of $.candidates){if(!R(X.account,X.readingAccount)||X.identity!==void 0&&X.readingIdentity!==void 0&&X.identity!==X.readingIdentity)continue;let z=X.windows.filter((B)=>B.blockedBy&&P6(B.scope,$.effectiveModel,$.familyOf));if(!z.length)continue;let G=z.map((B)=>{let Y=B.reset,H=Y?.observedAt??Y?.checkedAt;return Y&&H!==void 0&&Number.isFinite(H)&&Z-H<=$.maxAgeMs&&Number.isFinite(Y.at)&&Y.at>Z?Y.at:void 0});if(G.some((B)=>B===void 0))continue;let Q=Math.max(...G);if(J&&J.resetAt<=Q)continue;let W=z.some((B)=>B.blockedBy!=="exhausted"&&B.reset?.at===Q);J={account:X.account,resetAt:Q,checkpoint:{accountKey:{...X.account},decidedAt:Z,blockers:W?[]:z.flatMap((B)=>B.blockedBy==="exhausted"&&B.reset?[{window:B.window,resetAt:B.reset.at}]:[])}}}return J}function q5($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function j5($,Z){return q5($,Z)&&m0($.scan?.maxSameAccountWait)===0}function F5($,Z,J,X){if(!q5(X,Z))return;let z=X.scan,G=m0(z?.maxSameAccountWait),Q=z&&M6(z,$.now),W=Q?Q.resetAt-$.now:300000,B=z?.activity,Y=z?.accountKey??$.attempted,H=B&&Y&&R(B.accountKey,Y)?W2(B.ttlMs)||300000:300000,V=Math.min(W,G==="max"?H:900000),U=G===0||$.host==="pi"&&$.wake?.kind==="terminal",j=U?Q?W:void 0:V,q=Z.refusals.quota[$.host],F={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":U?"json-412":q.family,messageKey:X.messageKey??q.messageKey,retryable:$.host!=="pi"&&!U,hostRetry:$.host==="pi"||U?"veto":"leave",history:J,...j===void 0?{}:{retryAfterMs:j},...Q?{resetAt:Q.resetAt}:{}};if(!Q||U||$.host==="opencode1")return F;let K={delayMs:V,retryAfterMs:V,resetAt:Q.resetAt,target:$.now+V,checkpoint:Q.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...K,action:"wait-then-reselect"};if($.hostPhase!=="retry")return F;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||V>j4)return F;return{...K,action:"hold",account:Q.account}}function Q9($,Z,J){return{accountKey:{...$},decidedAt:Z,blockers:J.filter((X)=>X.confirmed&&Number.isFinite(X.resetAt)).map((X)=>({window:X.window,resetAt:X.resetAt}))}}function K5($,Z,J,X){let{checkpoint:z,target:G}=$;if(!R(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let Q=(W)=>{let B=W.resetAt;return W.confirmed&&B!==void 0&&Number.isFinite(B)&&B<=G&&z.blockers.some((Y)=>Y.window===W.window&&Number.isFinite(Y.resetAt)&&B<=Y.resetAt)};return J.filter((W)=>Q(W)&&J.filter((B)=>B.confirmed&&B.window===W.window).every(Q)).map((W)=>W.window)}function C6($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function g2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function k0($,Z,J,X,z){let G=z&&F5($,Z,J,z);if(G)return G;let Q=Z.refusals[X][$.host];return{action:"refuse",reason:X,family:z?.family??Q.family,messageKey:z?.messageKey??Q.messageKey,retryable:z?.retryable??Q.retryable,hostRetry:z?.hostRetry??Q.hostRetry,history:J,...z?.retryAfterMs===void 0?{}:{retryAfterMs:z.retryAfterMs},...z?.resetAt===void 0?{}:{resetAt:z.resetAt}}}function fX($,Z,J,X,z){let G=$.hold;if(Z.shortLimit.holdBound==="disabled"||$.host==="opencode2"&&($.hostPhase!=="retry"||$.remainingRetries===void 0||!($.remainingRetries>=1))||!X?.admitted||!G||G.maxWaitMs<=0||Number.isNaN(G.maxWaitMs)||!Number.isFinite(G.cacheExpiresAt)||G.maxDelayMs!==void 0&&(!Number.isFinite(G.maxDelayMs)||G.maxDelayMs<0)||!z.length||z.some((Y)=>!C6(Y.resetAt,$.now)))return;let Q=Math.max(...z.map((Y)=>Y.resetAt)),W=Z.shortLimit.jitter==="session-sha256"?G9($.sessionId,Q-$.now):Q-$.now,B=$.now+W;if(!Number.isFinite(B)||B>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&W>j4||G.maxDelayMs!==void 0&&W>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:W,retryAfterMs:W,target:B,checkpoint:Q9(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":g2($,Z),history:J}}function vX($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=y2(J,{type:"blocked",clockNow:$.clockNow});let Q=X.map((j)=>{let q=j.blockers.filter((F)=>!(F.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(q.some((F)=>!C6(F.until,$.now)))return;return q.length?{candidate:j,time:Math.max(...q.map((F)=>F.until))}:void 0}).filter((j)=>j!==void 0).reduce((j,q)=>!j||q.time<j.time?q:j,void 0),W=Q?Q.time-$.now:X.some((j)=>j.blockers.some((q)=>q.kind!=="soft"))?z.hardFallbackMs:void 0,B=$.poolWaitBudgetMs??z.budgetMs,Y=$.clockNow-(J.blockedSince??$.clockNow);if(B>0&&(Y>=B||W!==void 0&&W>B))return k0($,Z,J,"quota",$.terminal);let H=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(H<=0)return k0($,Z,J,"incomplete");if(W===void 0)return k0($,Z,J,"quota",$.terminal);let V=Math.min(W,H,B>0?B-Y:Number.POSITIVE_INFINITY),U=Q?.candidate??X[0];if(!U)return;return{action:"wait-then-reselect",delayMs:V,target:$.now+V,checkpoint:Q9(U.account,$.now,U.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:g2($,Z),history:J}}function B9($,Z){let J=$.history,X=(C,L=$.phase==="pre-send"?!0:$.failureRetryable??!0,A="leave")=>({action:"pass",reason:C,retryable:L,hostRetry:A,history:J});if($.phase==="after-limit"&&$.host==="opencode2"&&(!$.delivery.owned||!$.delivery.attributable))return X("not-owned");let z=$.status??$.signal?.status;if($.phase==="after-limit"&&$.attempted)J=y2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&R($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((C)=>C.admitted),Q=G.filter((C)=>!N6(J,C.account,$.requestScope)),W=Q.find((C)=>$.attempted&&R(C.account,$.attempted)),B=$.signalApplicable!==!1&&$.signal&&$.attempted&&R($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&B?.kind==="model-unavailable"&&W)return{action:"exclude-for-request",account:W.account,scope:$.requestScope,effects:z9,reason:"model-unavailable",retryable:!0,hostRetry:g2($,Z),history:J};if(G.length&&!Q.length)return k0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||j5($.terminal,Z))?k0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let C=$.wake,L=Q.find((c)=>R(c.account,C.checkpoint.accountKey)),A=L?.confirmedBlockers??(L&&B&&R(B.account,L.account)?B.windows:[]),x=L?K5(C,L.account,A,$.now):[],I=$.hold,f=C.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&C.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&C.target-C.checkpoint.decidedAt<=I.maxWaitMs;if(L&&Number.isFinite(C.target)&&C.target>=C.checkpoint.decidedAt&&$.now>=C.target&&f&&L.blockers.every((c)=>c.until!==void 0&&Number.isFinite(c.until)&&c.until<=$.now)&&(L.ready||A.some((c)=>c.confirmed))&&A.filter((c)=>c.confirmed).every((c)=>x.includes(c.window)))return{action:"retain",account:L.account,liftedWindows:x,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:y2(J,{type:"selected"})}}if($.credentialRecovery&&W)return{action:"retain",account:W.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:g2($,Z),history:J};let Y=Z.unconfirmedRetainLimit,H=$.unconfirmedRetainCount,V=z===429&&Y!==void 0&&H!==void 0,U=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(B?.kind==="payment-cap"||z===402&&B?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!B&&!V&&!$.terminal&&(U.attributedLimitOnly||z===void 0||!U.statuses.includes(z)))return X("unhandled-failure");let j=Q.find((C)=>$.selection&&R(C.account,$.selection.account)&&C.placementEligible),q=j&&(j.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&Q.length===1&&j.blockers.length>0&&j.blockers.every((C)=>C.kind==="soft")),F=q&&(!$.attempted||!R(j.account,$.attempted))?j:void 0,K=(C,L="ready-alternative")=>({action:"reroute",account:C.account,pin:$.selection?.pin??"preserve",reason:L,retryable:!0,hostRetry:g2($,Z),history:y2(J,{type:"selected"})}),N=$.phase==="pre-send"?W??Q.find((C)=>$.selection&&R(C.account,$.selection.account)):W,D=(N?.confirmedBlockers??($.phase==="after-limit"?B?.windows:void 0)??[]).filter((C)=>C.confirmed);if(D.length){if(Z.shortLimit.preference==="ready-alternative-first"&&F)return K(F);let C=fX($,Z,J,N,D);if(C)return C}let T=Z.unknown[$.host],M=$.phase==="after-limit"&&!D.length&&(z===429||B?.kind==="rate-limit"||B?.kind==="quota-exhausted"||B?.kind==="capacity"),P=V&&H>=Y;if(M&&W&&(T.affinity==="always"||$.affinity==="sticky")){if(V&&P){if(F)return K(F,"unconfirmed-retry-limit")}else if(V||T.action==="retain"){let C=[...$.retryHintsMs??[],B?.retryAfterMs].filter((L)=>L!==void 0&&Number.isFinite(L)&&(V||L>=0));return{action:"retain",account:W.account,reason:"unconfirmed-limit",...V?{retryMs:Math.min(60000,...C.map((L)=>Math.max(0,L))),incrementUnconfirmedRetain:!0}:T.hint==="minimum"?{retryMs:Math.min(T.defaultMs,...C)}:{},retryable:!0,hostRetry:g2($,Z),history:J}}else if(T.action==="pass")return X("unconfirmed-limit")}if(F)return K(F);if($.phase==="pre-send"&&q)return K(j);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&j&&Q.every((C)=>!C.ready)&&Q.every((C)=>C.blockers.length>0&&C.blockers.every((L)=>L.kind==="hard")))return K(j);let _=vX($,Z,J,Q);if(_)return _;if($.phase==="pre-send"&&!Q.length)return k0($,Z,J,$.terminal?.reason??"auth",$.terminal);if($.host==="opencode2"&&$.hostPhase==="retry"&&!$.terminal){if(Z.markedPool.retryExhaustion==="host-delay")return X("host-delay");if(Z.markedPool.retryExhaustion==="same-host-delay"&&W)return{action:"retain",account:W.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let C=$.phase==="pre-send"&&Q.length>0&&Q.every((x)=>!x.ready),L=Q.filter((x)=>x.placementEligible),A=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&L.length>0&&L.every((x)=>!x.ready&&x.blockers.length>0&&x.blockers.every((I)=>I.cause==="payment-balance"&&C6(I.until,$.now)));if(A||C||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let x=(A?L:Q).flatMap((I)=>I.blockers.map((f)=>f.until)).filter((I)=>C6(I,$.now));return k0($,Z,J,"quota",{source:"pool",reason:"quota",...A?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:x.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...x)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return k0($,Z,J,$.terminal.reason,$.terminal);if(B?.kind==="auth"||B?.kind==="account-access")return k0($,Z,J,"auth");if(B||z===429||Q.some((C)=>C.blockers.length))return k0($,Z,J,"quota");return X("no-override")}function f2($){if(!Number.isFinite($))return"unknown";let Z=Math.ceil(Math.max(0,$)/1000);if(Z<60)return`${Z}s`;let J=Math.ceil(Z/60),X=Math.floor(J/1440);if(X>=100)return"over 99 days";let z=Math.floor(J/60)%24,G=J%60;if(X>0)return`${X}d ${z}h ${G}m`;if(z>0)return`${z}h ${G}m`;return`${G}m`}var v2=({resetAt:$,now:Z})=>f2($-Z);var Y9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class N4 extends Error{[Y9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class D4 extends Error{[Y9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function V9($){let Z=$&&typeof $==="object"&&Reflect.get($,Y9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function w0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var Y2=($)=>Number.isSafeInteger($)&&$>=0,W9=($)=>typeof $==="number"&&Number.isFinite($),N5=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",K4=($,Z)=>Array.isArray($)&&$.every(Z);function P5($,Z){return w0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function D5($,Z){if(!w0($)||!w0($.scope))return!1;let J=$.scope;return P5($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function hX($,Z){return $.namespace===Z&&typeof $.generation==="string"&&Y2($.revision)&&Y2($.lowWatermark)&&K4($.marks,(J)=>w0(J)&&D5(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&K4(J.entries,(X)=>w0(X)&&N5(X.cause)&&W9(X.until)&&W9(X.evidenceAt)&&Y2(X.baseRevision)&&Y2(X.committedRevision)))&&K4($.tombstones,(J)=>w0(J)&&D5(J.key,Z)&&Y2(J.revision)&&N5(J.cause))&&K4($.operationIds,(J)=>w0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&Y2(J.revision))&&K4($.access,(J)=>w0(J)&&P5(J.account,Z)&&W9(J.eligibilityStateUpdatedAt)&&Y2(J.committedRevision))}class P4{namespace;logger;replaced=!1;terminal;constructor($,Z){this.namespace=$,this.logger=Z}assertWritable(){if(this.terminal)throw this.terminal}decode($){if(this.assertWritable(),$===void 0)return{};let Z;if(!w0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new D4,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!hX($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new N4,this.terminal;return{replacement:Z}}didCommit($){if(!$||this.replaced)return!1;this.replaced=!0;try{this.logger?.warn(`limits envelope replaced: ${$}`)}catch{}return!0}}var mX=[/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],wX=new RegExp(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])","service.?(?:is.?)?(?:temporarily.?)?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","unable to forward upstream","upstream.?request.?failed","upstream_stream_read_error","stream was interrupted","http/?2 stream failed","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","request to \\S+ failed, reason:","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","stream disconnected before completion","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"].join("|"),"i");function h2($){let Z=$.toLowerCase();return Z.includes("too_many_requests")||Z.includes("exhausted")||Z.includes("unavailable")||mX.some((J)=>J.test($))||wX.test($)}class T6 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function H9($){let Z=new Map(Object.entries($.refusals??{})),J=new Map(Object.entries($.retryable??{}));for(let[X,z]of Z)for(let G of[void 0,"45s","2m","1h 30m","99d 23h 59m","over 99 days"])for(let Q of[[],["this account"]]){let W=Object.freeze({labels:Object.freeze(Q),reset:G}),B;try{B=z(W)}catch{throw new T6(X)}if(typeof B!=="string"||h2(B))throw new T6(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var uX=/[^\s@]+@[^\s@]+\.[^\s@]+/;function U9($){return uX.test($)}function q9($){return U9($)||h2($)?"this account":$}class j9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function L6($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-F9(Z);return J>=0?Math.ceil(J/1000):void 0}function F9($){return Number.isFinite($)&&$>=0?$:0}function C5($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function pX($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function T5($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${f2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${pX(Z)}`}function L5($,Z,J){let X=C5($),z=X===void 0?void 0:v2({resetAt:X,now:Z}),G=L6($.retryAfterMs,$.noticeDelayMs);return T5($.family,z,G,J)}function lX($,Z){let J=$.now+F9($.noticeDelayMs??0),X=()=>L5($,J,Z);try{let z=C5($),G=z===void 0?void 0:($.messages?.formatReset??v2)({resetAt:z,now:J}),Q=L6($.retryAfterMs,$.noticeDelayMs),W=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(q9):[]),reset:G,retryIn:!Z&&Q!==void 0?f2(Q*1000):void 0}),B=$.messages?.render($.messageKey,W,Z);return typeof B==="string"?B:T5($.family,G,Q,Z)}catch{return X()}}function M5($,Z){switch($){case"openai-429":return JSON.stringify({error:{message:Z,type:"rate_limit_exceeded",code:"rate_limit_exceeded"}});case"claude-429":return JSON.stringify({type:"error",error:{type:"rate_limit_error",message:Z}});case"json-412":return JSON.stringify({error:{code:412,status:"FAILED_PRECONDITION",message:Z}});case"claustrum-429":return JSON.stringify({error:"claustrum-auth: accounts-rate-limited"});case"claustrum-402":return JSON.stringify({error:"claustrum-auth: insufficient balance"});default:return Z}}function K9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=M5($.family,lX($,Z));if(Z&&(h2(X)||U9(X))){let Q=$.now+F9($.noticeDelayMs??0);X=M5($.family,L5($,Q,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new j9(X)};if($.family==="pi-final")return{...J,kind:"text",body:X};let z=new Headers($.family==="json-412"?$.extraHeaders:void 0);z.set("content-type","application/json"),z.delete("retry-after");let G=L6($.retryAfterMs,$.noticeDelayMs);if(G!==void 0)z.set("retry-after",String(G));return{...J,kind:"http",status:$.family==="json-412"?412:$.family==="claustrum-402"?402:429,headers:z,body:X}}function u0($,Z){return R($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function N9($,Z){if(!u0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function D9($,Z,J){if(!u0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var P9=Object.freeze({kind:"failure-ladder",mergeLaw:"max-until",hintFloorMs:2000,quotaSteps:Object.freeze([60000,300000,1800000,7200000]),byKind:Object.freeze({"rate-limit":30000}),byReason:Object.freeze({"server-error":20000,unknown:60000}),capacity:Object.freeze({baseMs:45000,spreadMs:15000}),defaultMs:60000});function _6($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((Q,W)=>{if(!Q)return W;if($==="latest-evidence"&&W.evidenceAt!==Q.evidenceAt)return W.evidenceAt>Q.evidenceAt?W:Q;return W.committedRevision>Q.committedRevision?W:Q},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,Q)=>J<G.until&&!z.some((W,B)=>B!==Q&&W.until>=G.until&&W.baseRevision>=G.baseRevision&&(W.until>G.until||W.baseRevision>G.baseRevision||W.committedRevision>G.committedRevision||W.committedRevision===G.committedRevision&&B<Q))).sort((G,Q)=>G.committedRevision-Q.committedRevision)}function M4($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var O5=1024;function M9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function O6($,Z){return M9($.cause)===void 0||$.cause===Z}function S5($){return JSON.stringify([p($.key),M9($.cause)])}function T0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function cX($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function p($){let Z=$.scope;return JSON.stringify([cX($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function _5($){return JSON.stringify([$.producerId,$.operationId])}function V2($,Z){let J=new Map;for(let B of $.tombstones){let Y=p(B.key),H=J.get(Y);if(H)H.push(B);else J.set(Y,[B])}let X=$.marks.flatMap((B)=>{let Y=J.get(p(B.key)),H=_6(B.mergeLaw,Y?B.entries.filter((V)=>!Y.some((U)=>O6(U,V.cause)&&V.baseRevision<U.revision)):B.entries,Z);return H.length?[{...B,entries:H}]:[]}),z=$.lowWatermark,G=(B)=>{let Y=[...B].sort((V,U)=>V.revision-U.revision),H=Math.max(0,Y.length-O5);for(let V of Y.slice(0,H))z=Math.max(z,V.revision+1);return Y.slice(H)},Q=G($.tombstones),W=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:Q,operationIds:W,lowWatermark:z}}function H2($,Z,J){let X=V2($,J.now),z=[];for(let G of Z){let Q=(K)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:K})};if(G.binding.account.namespace!==X.namespace){Q("wrong-namespace");continue}if(G.baseRevision<X.lowWatermark){Q("below-watermark");continue}if(G.baseRevision>X.revision){Q("future-revision");continue}let W=J.bindings.find((K)=>R(K.account,G.binding.account));if(!W){Q("unknown-account");continue}let B=D9(G.binding,W,J.authorizeEpoch);if(B){Q(B);continue}let Y=X.operationIds.find((K)=>_5(K)===_5(G));if(Y){z.push({...Y,status:"duplicate"});continue}let H=W.account,V=X.revision+1,U=[...X.marks],j=[...X.tombstones],q=[...X.access];if(G.type==="mark"){let K={account:H,scope:G.scope,window:G.window},N=p(K),D=U.find((M)=>p(M.key)===N);if(j.some((M)=>G.baseRevision<M.revision&&O6(M,G.cause)&&p(M.key)===N)){Q("cleared");continue}if(D&&D.mergeLaw!==G.mergeLaw){Q("merge-law-conflict");continue}let T=_6(G.mergeLaw,[...D?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:V,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(U=U.filter((M)=>p(M.key)!==N),T.length)U.push({key:K,mergeLaw:G.mergeLaw,entries:T})}else if(G.type==="clear"){let K=M9(G.cause),N=G.keys.map((M)=>({...M,account:H})).filter((M)=>G.cause===void 0||!U.some((P)=>p(P.key)===p(M)&&P.entries.some((_)=>_.cause!==G.cause))),D=new Set(N.map(p)),T=G.evidenceAt;if(T!==void 0&&U.some((M)=>D.has(p(M.key))&&M.entries.some((P)=>P.evidenceAt>T))){Q("newer-evidence");continue}U=U.filter((M)=>!D.has(p(M.key))),j=j.filter((M)=>!D.has(p(M.key))||K!==void 0&&M.cause!==K);for(let M of new Map(N.map((P)=>[p(P),P])).values())j.push({key:M,revision:V,...K===void 0?{}:{cause:K}})}else{let K={account:H,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:V},N=q.find((D)=>R(D.account,H));q=q.filter((D)=>!R(D.account,H)),q.push(N?M4(N,K):K)}let F={producerId:G.producerId,operationId:G.operationId,revision:V};X=V2({...X,revision:V,marks:U,tombstones:j,access:q,operationIds:[...X.operationIds,F]},J.now),z.push({...F,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as sX}from"node:fs";import{basename as A5,dirname as E5,join as aX,resolve as nX}from"node:path";function C4($){let Z=nX($),J=[A5(Z)],X=E5(Z);for(;;)try{return aX(sX.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let Q=E5(X);if(Q===X)return Z;J.push(A5(X)),X=Q}}class L0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as tX}from"node:crypto";import{isDeepStrictEqual as I5}from"node:util";import{AsyncResource as iX}from"node:async_hooks";import{randomUUID as R5}from"node:crypto";import{isDeepStrictEqual as rX}from"node:util";var oX=new iX("common-auth-limits-recovery");class T4{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=oX.runInAsyncScope(async()=>{await Promise.resolve();let Z=!1;try{await $(),Z=!0}catch(J){try{this.logger?.warn("limits envelope recovery failed; agreement remains degraded",{error:J instanceof Error?J.message:String(J)})}catch{}}finally{if(this.running=void 0,Z)for(let J of this.listeners)try{J()}catch{}}})}}class U2{seen;missingGeneration;incorporated;remember($,Z){if(this.seen&&this.seen.revision>$.revision)return;if(this.seen=structuredClone($),this.missingGeneration=void 0,Z)this.incorporated=structuredClone(Z)}retained($){let Z=rX($,this.incorporated)?void 0:$;return[this.seen,Z].filter((J)=>J!==void 0&&(J===this.seen||J.revision>0))}lost($,Z){return this.retained(Z).some((J)=>!$||J.generation!==$.generation||$.revision<J.revision||J.tombstones.some((X)=>X.revision>$.lowWatermark&&!$.tombstones.some((z)=>p(z.key)===p(X.key)&&O6(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=R5();let z=$??T0(J,this.missingGeneration??R5()),G=[...this.retained(Z),z],Q=new Map,W=new Map,B=new Map,Y=new Map,H=0;for(let U of G){H=Math.max(H,U.revision,U.lowWatermark);for(let j of U.marks){let q=p(j.key),F=Q.get(q);if(F&&F.mergeLaw!==j.mergeLaw)throw Error("limits-recovery-merge-law-conflict");Q.set(q,{...j,entries:[...F?.entries??[],...j.entries]});for(let K of j.entries)H=Math.max(H,K.baseRevision,K.committedRevision)}for(let j of U.tombstones){let q=S5(j),F=W.get(q);if(!F||F.revision<j.revision)W.set(q,j);H=Math.max(H,j.revision)}for(let j of U.operationIds){let q=JSON.stringify([j.producerId,j.operationId]),F=B.get(q);if(!F||F.revision<j.revision)B.set(q,j);H=Math.max(H,j.revision)}for(let j of U.access){let{namespace:q,accountId:F,incarnation:K}=j.account,N=JSON.stringify([q,F,K]),D=Y.get(N);Y.set(N,D?M4(D,j):j),H=Math.max(H,j.committedRevision)}}let V=H+1;if(!Number.isSafeInteger(V))throw Error("limits-revision-exhausted");return V2({...z,revision:V,lowWatermark:V,marks:[...Q.values()],tombstones:[...W.values()],operationIds:[...B.values()],access:[...Y.values()]},X)}}function b5($,Z){return Z.flatMap((J)=>J.credentialEpoch===void 0?[]:[{account:{namespace:$,accountId:J.id,incarnation:String(J.credentialEpoch)},credentialEpoch:String(J.credentialEpoch),...J.identity===void 0?{}:{identity:J.identity}}])}async function C9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new L0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=tX(),G=new U2,Q=new P4(J,$.logger),W=new T4($.logger),B=$.now??Date.now,Y=async()=>{let j=await Z.read();if(j.status!=="ready"){if(j.status==="error"&&j.kind==="snapshot-contended")throw Error(j.reason);throw new L0("pool-not-ready")}return b5(J,j.rows)},H=async()=>{let j=await Z.readSettings();if(j.status!=="ready")throw new L0("pool-not-ready");return Q.decode(j.settings.commonAuthLimits)},V=async(j)=>{Q.assertWritable();let q=await Y(),F=await H(),K;for(let N=0;N<3;N++){let D=await Y(),T=await H(),M=I5(q,D)&&I5(F,T);if(K={snapshot:F.snapshot??T0(J,z),bindings:q,authoritative:M},M){if(!F.replacement&&G.lost(F.snapshot,j))return W.schedule(()=>U.commit([],j)),{snapshot:G.recover(F.snapshot,j,J,B()),bindings:q,authoritative:!1,degradedAgreement:!0};if(F.snapshot)G.remember(F.snapshot);return K}q=D,F=T}return K},U={namespace:J,read:V,subscribe:W.subscribe,async commit(j,q){Q.assertWritable();let F,K,N=()=>{if(Q.didCommit(K)&&F)G=new U2,G.remember(F.snapshot,q)};try{await X((D,T)=>{let M=b5(J,T),P=Q.decode(D),_=P.snapshot;K=P.replacement;let C=!K&&G.lost(_,q),L=H2(C?G.recover(_,q,J,B()):_??T0(J,z),j,{now:B(),bindings:M,authorizeEpoch:(A,x)=>A.credentialEpoch===x.credentialEpoch});return F={...L,bindings:M,authoritative:!0,degradedAgreement:C},L.snapshot},{beforePublish:()=>Q.assertWritable(),onPublished:N})}catch(D){if(Q.assertWritable(),D instanceof b&&(D.kind==="pending-migration"||D.kind==="load-error"))throw new L0("pool-not-ready");throw D}if(!F)throw Error("Pool limits mutator was not called");return N(),G.remember(F.snapshot,q),F}};return await V(),U}function m2($){if($&&typeof $==="object"){for(let Z of Object.values($))m2(Z);Object.freeze($)}return $}function _0($){return{opencode1:$,opencode2:$,pi:$}}var q2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},k5={...q2,action:"retain",affinity:"sticky"},y5={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function A6($,Z){return{auth:_0(y5),quota:_0($),incomplete:_0(Z),"model-unavailable":_0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var S6={kind:"off"},g5={requestEscape:"off",retryExhaustion:"terminal"},f5={statuses:[],attributedLimitOnly:!0},x5={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},v5=m2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:_0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{...q2,action:"retain",hint:"minimum"},opencode2:q2,pi:{...q2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:_0(f5),markedPool:g5,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:A6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),h5=m2({evidence:"typed",markers:_0(P9),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"off",unknown:_0(q2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:{kind:"earliest",budgetMs:300000,requestDeadlineMs:600000,hardFallbackMs:60000,singleEligibleSoftExemption:!0},execution:"engine",requestExclusion:"on",advance:_0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:g5,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:A6(x5,{...x5,messageKey:"incomplete.timeout"})}),e0=m2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:S6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:k5,opencode2:q2,pi:k5},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:_0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:A6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),m5=m2({evidence:"hints-only",markers:{opencode1:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"},opencode2:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"marker"},pi:{kind:"hint",mergeLaw:"overwrite",defaultMs:60000,defaultMsByKind:{"payment-balance":300000},causes:["rate-limit","payment-balance"],ignoredKinds:["payment-cap"],minimumMs:0,zero:"accept",hintClock:"signal"}},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:_0(q2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:S6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:f5,pi:{statuses:[401,429],attributedLimitOnly:!1}},markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"host-delay"},terminalMetadata:"baseline",terminalPolicy:"status-history",terminalStatusHistory:{minRetryMs:1000,defaultRetryMs:60000,paymentBalance:{family:"claustrum-402",messageKey:"payment.insufficient-balance"}},refusals:A6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...y5,messageKey:"incomplete.no-account"})}),eX=m2({"confirmed-affinity":v5,"earliest-pool-engine":h5,"window-router":e0,"status-vault-order":m5});import{AsyncResource as $z}from"node:async_hooks";var R6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),Zz="@cortexkit/common-auth/limits-registry/schema-v",E6=1000,w5=5000,j2=new $z("common-auth-limits"),Jz={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function Xz(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(Zz)&&J!==R6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,R6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,R6,Z),Z}function F2($){return JSON.stringify([$.producerId,$.operationId])}class u5{adapter;clock;restrictive;listeners=new Set;owners=0;activity=D6();journal=new Map;failed=new Set;restrictions=new Map;snapshot;recoveryView;bindings=[];lastReloadAt=Number.NEGATIVE_INFINITY;lastActivity=Number.NEGATIVE_INFINITY;lastReadAttempt=Number.NEGATIVE_INFINITY;generation=0;degradedAgreement=!1;abandoned;lastFailure;dirty=!0;live=!1;publicationTimer;reloadTimer;unsubscribe;reading;writing;handoff=Promise.resolve();resolveAbandonment;abandonment=new Promise(($)=>{this.resolveAbandonment=$});constructor($){this.adapter=$.adapter,this.clock=$.clock??Jz,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=V9($);if(Z){this.abandoned=Z,this.lastFailure=$,this.live=!1,this.generation++,this.cancelTimers(),this.unsubscribe?.(),this.unsubscribe=void 0,this.journal.clear(),this.failed.clear(),this.restrictions.clear(),this.recoveryView=void 0,this.resolveAbandonment();for(let J of this.listeners)try{J.onAbandon?.(Z)}catch{}return}this.degradedAgreement=!0,this.lastFailure=$}reconcile($){if(this.abandoned)return!1;if($.snapshot.schemaVersion!==1||$.snapshot.namespace!==this.adapter.namespace)throw Error("limits-schema-mismatch");if(!$.authoritative){if($.degradedAgreement&&this.snapshot&&$.snapshot.revision>this.snapshot.revision)this.recoveryView=$;return this.fail(Error("limits-unverifiable-snapshot")),!1}if(this.snapshot&&$.snapshot.generation===this.snapshot.generation&&$.snapshot.revision<this.snapshot.revision)return!1;this.snapshot=$.snapshot,this.recoveryView=void 0,this.bindings=$.bindings.map((Z)=>{let J=this.bindings.find((X)=>R(X.account,Z.account));return J?N9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((Q)=>R(Q.account,X.binding.account)),G=this.snapshot.access.find((Q)=>R(Q.account,X.binding.account));if(!z||!u0(z,X.binding)||X.type==="access"&&G&&G.committedRevision>J.revision&&G.eligibilityStateUpdatedAt>=X.eligibilityStateUpdatedAt)this.restrictions.delete(Z)}if($.degradedAgreement)this.fail(Error("limits-envelope-recovered"));return!$.degradedAgreement}touch(){this.lastActivity=this.clock.now(),this.armReload()}cancelTimers(){if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);if(this.reloadTimer!==void 0)this.clock.clearTimeout(this.reloadTimer);this.publicationTimer=this.reloadTimer=void 0}schedulePublish($){if(!this.live)return;if(this.publicationTimer!==void 0)this.clock.clearTimeout(this.publicationTimer);j2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,j2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=w5)return;j2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=w5)return;j2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+E6-this.clock.now()))})}async start($){if(this.abandoned)throw this.lastFailure;this.adapter=$,this.live=!0;let Z=++this.generation;if(await this.reload(),this.abandoned||!this.snapshot)throw this.lastFailure??Error("limits-hydration-failed");if(this.unsubscribe=$.subscribe?.(()=>{if(!this.live||this.generation!==Z)return;this.dirty=!0,j2.runInAsyncScope(()=>{this.reload()})}),this.journal.size)this.schedulePublish(0)}reload(){if(this.abandoned)return Promise.resolve();if(this.reading)return this.reading;let $=this.clock.now();return this.lastReadAttempt=$,this.reading=j2.runInAsyncScope(async()=>{try{if(this.dirty=!1,this.reconcile(await this.adapter.read(this.snapshot))){if(this.lastReloadAt=$,!this.journal.size&&!this.failed.size&&!this.restrictions.size)this.degradedAgreement=!1,this.lastFailure=void 0}}catch(Z){this.dirty=!0,this.fail(Z)}}).finally(()=>{this.reading=void 0,this.armReload()}),this.reading}provisional(){if(this.abandoned)return T0(this.adapter.namespace,this.snapshot?.generation??"");let $=this.recoveryView?.snapshot??this.snapshot,Z=[...this.journal.values()].map((X)=>X.command).filter((X)=>X.type==="mark"),J=H2(V2($,this.clock.now()),Z,{now:this.clock.now(),bindings:this.bindings,authorizeEpoch:(X,z)=>X.credentialEpoch===z.credentialEpoch}).snapshot;return{...this.snapshot,marks:J.marks,tombstones:$.tombstones,access:$.access}}enqueue($,Z){if(this.abandoned)return;if($.binding.account.namespace!==this.adapter.namespace)throw Error("wrong-namespace");let J=F2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>F2(z)===J))return;this.journal.set(J,{command:structuredClone($),event:Z}),this.touch();let X=[...this.journal.values()].some((z)=>z.command.type!=="mark");this.schedulePublish(X?0:E6)}flush(){if(this.abandoned)return this.writing??Promise.resolve();if(this.writing)return this.writing;if(!this.journal.size)return Promise.resolve();return this.writing=j2.runInAsyncScope(async()=>{let $=[...this.journal.values()];while($.length&&!this.abandoned){try{let X=await this.adapter.commit($.map((z)=>z.command),this.snapshot);if(this.abandoned)return;if(this.reconcile(X),!X.authoritative)throw Error("limits-unverifiable-commit");for(let z of $){let G=X.outcomes.find((Q)=>F2(Q)===F2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(V9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof L0&&X.code==="pool-not-ready")for(let z of $)this.settle(z,{...z.command,status:"rejected",reason:"pool-not-ready"});else{for(let z of $)if(this.journal.has(F2(z.command)))this.failed.add(F2(z.command));this.fail(X);break}}let Z=[...this.journal.values()],J=Z.findLastIndex((X)=>X.command.type!=="mark");$=Z.slice(0,J+1)}}).finally(()=>{if(this.writing=void 0,this.journal.size&&this.live)this.schedulePublish(E6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=F2(J);if(this.journal.delete(X),this.failed.delete(X),Z.status==="rejected"){if(this.fail(Error(Z.reason??"limits-command-rejected")),J.type==="access"&&this.restrictive(J.state)){if(this.restrictions.set(X,{command:J,revision:this.snapshot.revision}),Z.reason==="below-watermark"&&J.baseRevision<this.snapshot.lowWatermark&&($.recoveryRetries??0)<3)this.journal.set(X,{...$,recoveryRetries:($.recoveryRetries??0)+1,command:{...J,baseRevision:this.snapshot.revision}})}for(let z of this.listeners)try{z.onRejected?.(J,Z)}catch{}}else if(Z.revision!==void 0&&(J.type==="mark"||$.event==="success"))for(let z of this.listeners)try{z.onEvent?.({type:J.type==="mark"?"mark":"success",command:J,revision:Z.revision})}catch{}}async beforeDispatch($){if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};this.touch();let Z=()=>[...this.journal.values()].some((z)=>z.command.type!=="mark"&&R(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=E6)await Promise.race([this.reload(),this.abandonment]);if(this.abandoned)return{snapshot:this.provisional(),blocked:!1};let J=(this.recoveryView?.bindings??this.bindings).find((z)=>R(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!u0(J,$)||[...this.restrictions.values()].some((z)=>R(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>R(z.account,$.account)&&this.restrictive(z.state))}}async stop(){this.live=!1,this.generation++,this.cancelTimers(),await this.flush(),await this.reading,this.unsubscribe?.(),this.unsubscribe=void 0,this.cancelTimers()}}async function T9($){let Z=Xz(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new u5($),Z.namespaces.set($.adapter.namespace,J);let X=J,z={onAbandon:$.onAbandon,onEvent:$.onEvent,onRejected:$.onRejected},G=X.owners++===0;if(X.listeners.add(z),G)X.handoff=X.handoff.catch(()=>{}).then(()=>X.start($.adapter));try{await X.handoff}catch(B){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),B}let Q=!1,W=()=>{if(Q)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return W(),X.provisional()},get lastReloadAt(){return X.lastReloadAt},get degradedAgreement(){return X.degradedAgreement},get lastFailure(){return X.lastFailure},get pendingCommands(){return X.journal.size},activity:X.activity,observe(B){return W(),{binding:structuredClone(B),baseRevision:X.snapshot.revision}},enqueue(B,Y){W(),X.enqueue(B,Y)},beforeDispatch(B){return W(),X.beforeDispatch(B)},flush(){return W(),X.flush()},reload(){return W(),X.reload()},dispose(){if(Q)return X.handoff;if(Q=!0,X.owners--,!X.owners)X.handoff=X.handoff.then(()=>X.stop()).finally(()=>X.listeners.delete(z));else X.listeners.delete(z);return X.handoff}}}function $2($){let Z=Reflect.get(globalThis,Symbol.for("cortexkit.routing"));if(typeof Z!=="function")return;let J=Z($);return typeof J==="object"&&J!==null?J:void 0}function L9($){try{let J=$2($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=F4($);if(!Z||!Number.isFinite($.now))return 0;return Math.floor(Math.max(0,Math.min(Z.maxWaitMs,Z.cacheExpiresAt-$.now))/1000)}function E($){return typeof $==="object"&&$!==null&&!Array.isArray($)}import{statSync as Qz}from"node:fs";import{rm as d5}from"node:fs/promises";import{dirname as Bz,join as ZZ}from"node:path";import{resolveClaustrumConnectionPath as Wz}from"@cortexkit/claustrum-client";function p5($,Z){if(!$)return;let J=$.rawUsedPercent??$.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:Z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...typeof $.windowMinutes==="number"&&Number.isFinite($.windowMinutes)&&$.windowMinutes>0&&{windowMinutes:$.windowMinutes}}}function _9($){if(!E($)||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 zz($){let Z=_9($.total),J=_9($.remaining);if(Z===void 0||J===void 0||Z<0||J<0)return;let X=Z-J,z=$.spendable===!1,G=Z>0?X/Z*100:z?100:0;return{limit:Z,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof $.resetsAt==="string"&&{resetsAt:$.resetsAt},...E($.total)&&typeof $.total.unit==="string"&&{unit:$.total.unit}}}function Gz($,Z){if(!E($))return;let J=_9($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function O9($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function l5($,Z){let J=p5($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=p5($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="individual_limit"):void 0,G=E(z)?zz(z):void 0,Q=Array.isArray($.spend)?$.spend.find((Y)=>E(Y)&&Y.id==="credits"):void 0,W=Gz(Q,Z.fetchedAt),B=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...W&&{credits:W},...W&&E(Q)&&typeof Q.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function I6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var S9="ck auth reclassify --from-registry";function b6($,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 \`${I6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${S9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var W0=t("vault"),JZ="openai-auth";var Yz={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},XZ={opencode:"OpenCode",pi:"Pi"},Vz=[{selector:{category:"openai-native"},operation:"read"}];function E9($){return a5(JZ,$)}function Hz($){return`ChatGPT for ${XZ[$]}`}function v6($){return ZZ(Bz($),"openai-auth-vault")}function K2($,Z){return{...i5({stateDir:$,host:Z}),rosterPath:ZZ($,`${Z}-roster.json`)}}var zZ=2000,gq=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],Uz={"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 ${S9} 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 fq($,Z){if($!=="vault-no-grant")return Uz[$];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: ${I6(Z)}`}function vq($){let Z=$.snapshot();if(Z===void 0)return"vault-unreachable";if(Z.rows.length===0){let J=$.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function qz($){let Z=g6($);return Z?f6(Z):void 0}class jz{host;name;paths;#Z;#$;#B=new Map;#W=new Map;#q=new Map;#j;#J;#Y;#z;#F=!1;#K=!1;#V=Promise.withResolvers();#H="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=E9($.host),this.paths=K2($.stateDir,$.host),this.#$=new e5({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:Yz,pluginId:JZ,connect:()=>this.#C(),isCustodyActive:()=>this.#L(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:qz,insula:{provider:"codex",normalize:l5},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:(Z)=>this.#_(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...W0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")W0.warn(Z,J)}}})}#N(){return(this.#Z.connectionFile??Wz)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#Z.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:($)=>W0.debug("vault transport error",{errorClass:$})}}#C(){return(this.#Z.connectScoped?.()??$Z(this.#D())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){let X=this.#q.get($);if(X?.source===Z&&X.reason===J)return;this.#q.set($,{source:Z,reason:J}),W0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#T(){return this.#Z.connectEnrollment?.()??n5(this.#D())}#X($,Z){this.#J=x0(Z),W0.warn($,{host:this.host,error:this.#J,...Z instanceof s5&&Z.reason?{reason:Z.reason}:{}})}#Q(){if(w2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=Qz($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#Q(),Z=await r5(this.paths,this.name);if($===this.#Q()){if(Z!==this.#H)W0.info("vault authority",{host:this.host,authority:Z});return this.#H=Z,this.#U=$,Z}return"unreadable"}enrolled(){return w2()||this.#U!==this.#Q()||this.#H!=="local"}async#L(){if(this.#U!==this.#Q())await this.authority();return this.enrolled()}start(){if(this.#F||this.#K)return;this.#F=!0,this.#$.start()}#_($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#P(){return this.#$.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(!["vault","host"].includes(await this.authority()))return;let $=this.#z;if($)await $.catch(()=>{return});if(this.snapshot()||!["vault","host"].includes(await this.authority()))return;await(this.#z??this.#P()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let $=this.#z;if($)await $.catch(()=>{return});let Z=await this.#P();return this.#J=void 0,Z}catch($){return this.#X("vault roster refresh failed",$),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}watchState(){return this.#$.watchState()}keptReceiptState(){return this.#$.keptReceiptState()}grantReach(){return this.#$.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.#$.routingRows().map((Z)=>{let J=$.get(Z.id)?.accountIdentity;return{id:Z.id,credentialId:$.get(Z.id)?.credentialId,kind:Z.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...Z.quota!==void 0?{quota:Z.quota}:{}}})}owns($){return(this.snapshot()?.rows??[]).some((Z)=>Z.routeId===$)}async send($,Z,J){let X=!1;try{return await this.#$.send($,(z)=>{return X=!0,Z(z.accessToken,z)},{site:J.site,...J.signal?{signal:J.signal}:{}})}catch(z){if(X)throw z;this.#X("vault refused to serve an account",z);return}}async authorize($,Z={}){try{return await this.#$.authorize($,Z.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure($,Z){if(Z!==401)return;try{await this.#$.reportFailure($,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot($,Z,J,X){let z=k6(Z,(this.#Z.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#$.recordQuota($,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}reportUsage($,Z,J){try{let X;if("headers"in Z){let z={};if(Z.headers.forEach((G,Q)=>{if(Q.startsWith("x-codex-"))z[Q]=G}),Object.keys(z).length===0)return;X={headers:z}}else X={frame:Z.frame};this.#$.reportUsage({routeId:$,credentialId:J.credentialId,reading:{provider:"codex",observedAtMs:(this.#Z.now??Date.now)(),...X,...J.accountIdentity?{account:J.accountIdentity}:{}}})}catch{}}pollQuota($,Z=!0){let J=this.#W.get($);if(J)return J;let X=this.#O($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#O($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await y6(this.paths.rosterPath))?.rows.find((W)=>W.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#M($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let W=k6(O9(z,this.routes().find((Y)=>Y.id===$)?.quota),z.primary.checkedAt,!0);if(!W)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,W))return this.#G($,"insula",null),{ok:!0};return this.#G($,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#$.lookupInsulaQuotaForRoute($),Q=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G($,"insula",Q),{ok:!1,error:`insula ${Q}`}}return this.#M($,Z)}async#M($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let W=Z?void 0:await this.#$.cachedInsulaQuota(Q);if(W!==void 0){let Y=k6(O9(W,this.routes().find((H)=>H.id===$)?.quota),W.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#$.recordQuota($,Y,Q),new Response(null,{status:200})}let B=await L4({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:W0});return await this.recordSnapshot($,B,!0,Q),J=void 0,new Response(null,{status:200})}catch(W){J=x0(W);let B=W?.status;if(typeof B==="number")return new Response(null,{status:B});throw W}},{site:"quota"}).catch((G)=>{J=x0(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading($){let Z=this.#B.get($);if(Z)return Z;let J=this.pollQuota($,!1).catch((X)=>{W0.warn("vault quota poll failed",{routeId:$,error:x0(X)})}).finally(()=>{this.#B.delete($)});return this.#B.set($,J),J}async pollStale($){let Z=(this.#Z.now??Date.now)(),J=[];for(let X of this.routes()){let z=Fz(X.quota);if(z!==void 0&&Z-z<$)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder($){let Z=await this.authority();if(Z!=="vault"&&Z!=="host")throw Error("Vault order can only be changed in vault mode.");return this.#$.reorder($)}async decline($){await this.#$.decline($),W0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),W0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await x6(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof c5?X.kind:"unreadable-state"}}let J=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:J!==void 0,accounts:J?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){if(await this.authority()==="host")throw new u("vault-host",A9);let $=await this.#T().catch((Z)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${x0(Z)}. Is the vault running?`)});try{let Z=new o5({client:$,paths:this.paths,proposedName:this.name,displayName:Hz(this.host),requestedGrants:Vz,...this.#Z.now?{now:this.#Z.now}:{}}),J=await Z.status();if(J.state==="denied"||J.state==="blocked")await Z.resetTerminal();let X=await Z.reconcile();if(W0.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{$.close()}}waitForApproval($={}){return this.#Y??=(async()=>{let Z=$.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),J=$.pollIntervalMs??2000,X=Date.now()+($.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if($.onPending?.(z),Date.now()>=X)return z;await Z(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){if(await this.authority()==="host")throw new u("vault-host",A9);await d5(this.paths.tokenPath,{force:!0}),await d5(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,W0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())t5({mode:"custody",auth:$,provider:"openai"})}close(){this.#K=!0,this.#V.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function Fz($){if(!$)return;let Z=b0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function h6($,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}`,...Z.requestedGrantsStatus==="sent"?[]:[`Then grant OpenAI access to the name you approved with --name (defaults to ${$}):`,` ${I6($)}`]]}function GZ($,Z,J){let X=`${XZ[$]} (${J.state==="approved"?J.approvedName??Z:Z})`;switch(J.state){case"approved":return`${X}: connected to the Claustrum vault.`;case"idle":return`${X}: not connected to the Claustrum vault.`;case"pending":return J.requestId?`${X}: waiting for approval of request ${J.requestId}.`:`${X}: enrollment request not taken yet${J.retryCode?` (${J.retryCode})`:""}.`;case"denied":return`${X}: the vault denied the enrollment request.`;case"blocked":return`${X}: enrollment stopped (${J.code}).`;case"unavailable":return`${X}: the vault is unavailable (${J.code}).`;case"busy":return`${X}: another process is enrolling right now.`}}function R9($,Z){if((Z.state==="blocked"||Z.state==="unavailable")&&Z.code==="unknown_method")return{ok:!1,text:'Enrollment stopped (unknown_method). This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), then run Connect again.'};switch(Z.state){case"approved":{let J=Z.approvedName??$.name,X=$.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${J}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${b6(J,$.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${Z.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...h6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
2
2
|
`)};default:return{ok:!1,text:`Enrollment is ${Z.state}.`}}}var I9="/backend-api/wham/rate-limit-reset-credits",Kz=`https://chatgpt.com${I9}`,HZ=`${I9}/consume`,Nz=`https://chatgpt.com${HZ}`,Dz=300000,Pz=60000,Mz=15000,Cz=60000;function u2($){return{configPath:$.configPath,statePath:$.statePath}}class Y0 extends Error{kind;cooldownUntil;constructor($,Z,J){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=J}}class N2 extends Error{kind;status;constructor($,Z,J){super(Z);this.name="ResetCreditError",this.kind=$,this.status=J}}function UZ($,Z,J){return{authorization:`Bearer ${$}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function w6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function qZ($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function u6($){if(!w6($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt)||$.chatgptAccountId!==void 0&&(typeof $.chatgptAccountId!=="string"||$.chatgptAccountId.length===0))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt,...typeof $.chatgptAccountId==="string"?{chatgptAccountId:$.chatgptAccountId}:{},...jZ($.rejectedStatus)?{rejectedStatus:$.rejectedStatus}:{},...typeof $.unknownAnswers==="number"&&Number.isSafeInteger($.unknownAnswers)&&$.unknownAnswers>0?{unknownAnswers:$.unknownAnswers}:{}}}function jZ($){return typeof $==="number"&&$>=400&&$<500&&$!==408&&$!==409&&$!==425&&$!==429}function m6($){return $.kind==="http_error"&&jZ($.status)}function FZ($,Z){return $.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z||$.rejectedStatus!==void 0}function Tz($,Z){if($.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z)throw new Y0("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function KZ($){return Boolean($&&Object.hasOwn($,"inFlight"))}function NZ($,Z){return Z-$.startedAt<Dz}function p2($,Z){if(!p0(Z))return;return $.reset?.[Z]}function DZ($){if(!$.reset)$.reset=Object.create(null);return $.reset}function PZ($,Z,J){if(!p0(Z))return;let X=DZ($),z=X[Z]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=z}function MZ($,Z){let J=qZ($),X=u6($?.inFlight);if(KZ($)&&!X)return{kind:"corrupt",beforeState:J};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:J,cooldownUntil:$.cooldownUntil};if(X&&NZ(X,Z))return{kind:"claim",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:J,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:J}}async function Lz($,Z){if(!p0(Z))return{kind:"fresh",beforeState:void 0};let J=await $.loadAccountsFn(u2($));return MZ(J?p2(J,Z):void 0,$.now())}async function _z($,Z){let J;if(await $.mutateAccountsFn((X)=>{let z=$.now(),G=p2(X,Z);if(J=MZ(G,z),J.kind==="corrupt")PZ(X,Z,z);return X},u2($)),!J)throw Error("corrupt reset state mutation did not run");return J}async function Oz($,Z,J,X){if(!p0(Z))return{kind:"fresh",beforeState:void 0};let z;if(await $.mutateAccountsFn((G)=>{let Q=$.now(),W=p2(G,Z),B=qZ(W),Y=u6(W?.inFlight);if(KZ(W)&&!Y)return PZ(G,Z,Q),z={kind:"corrupt",beforeState:B},G;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>Q)return z={kind:"cooldown",beforeState:B,cooldownUntil:W.cooldownUntil},G;if(Y&&NZ(Y,Q))return z={kind:"claim",beforeState:B,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;if(Y&&!FZ(Y,X))return z={kind:"expired_unreconciled",beforeState:B,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;let H=p6(J);if(!H)return z={kind:"fresh",beforeState:B},G;let V={redeemRequestId:$.randomUUID(),creditId:H.id,startedAt:Q,...X===void 0?{}:{chatgptAccountId:X}},U=DZ(G);return U[Z]={...W,inFlight:V},z={kind:"claim",beforeState:B,claim:{inFlight:V,selectedCredit:H}},G},u2($)),!z)throw Error("reset claim mutation did not run");return z}async function Sz($,Z,J,X,z){if(!p0(Z))return;if(!x9(X.kind))return Az($,Z,J,X,z);await $.mutateAccountsFn((G)=>{let Q=p2(G,Z),W=u6(Q?.inFlight);if(!Q||!W||W.redeemRequestId!==J.redeemRequestId||W.creditId!==J.creditId)return G;let B=$.now();if(delete Q.inFlight,Q.lastOutcome={code:X.kind,at:B},X.kind==="reset"||X.kind==="already_redeemed")Q.cooldownUntil=B+Cz;else delete Q.cooldownUntil;return G},u2($));return}function QZ($,Z){let J=u6($?.inFlight);return J&&J.redeemRequestId===Z.redeemRequestId&&J.creditId===Z.creditId?J:void 0}async function Az($,Z,J,X,z){let G=m6(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let B=await $.loadAccountsFn(u2($));return QZ(B?p2(B,Z):void 0,J)}let W;return await $.mutateAccountsFn((B)=>{W=void 0;let Y=p2(B,Z),H=QZ(Y,J);if(!Y||!H)return B;let V={...H};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(J.unknownAnswers??0))V.rejectedStatus=G;return Y.inFlight=V,W=V,B},u2($)),W}function _4($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function b9($,Z,J){if(!(Z||_4($.primary,J)||_4($.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function BZ($,Z){let J=$[Z];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function Ez($){if(!w6($))return;let Z=BZ($,"granted_at"),J=BZ($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||J===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:$.is_supported_by_plan}}async function k9($,Z,J){let X;try{X=await $(Kz,{method:"GET",headers:UZ(Z,I9,J),signal:AbortSignal.timeout(Mz)})}catch{throw new N2("http_error","reset credit list request failed")}if(!X.ok)throw new N2("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new N2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!w6(z))throw new N2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((Q)=>{let W=Ez(Q);return W===void 0?[]:[W]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function p6($){return[...$].filter(CZ).sort((Z,J)=>Date.parse(Z.expiresAt)-Date.parse(J.expiresAt))[0]}function CZ($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function TZ($){return $.filter(CZ).length}function x9($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function Rz($,Z,J,X,z){let G;try{G=await $(Nz,{method:"POST",headers:{...UZ(Z,HZ,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(Pz)})}catch(Y){return{kind:"ambiguous",raw:Y}}let Q;try{Q=await G.text()}catch(Y){return G.ok?{kind:"ambiguous",raw:Y}:{kind:"http_error",raw:Y,status:G.status}}let W=Q,B=!1;try{W=JSON.parse(Q),B=!0}catch{}if(!G.ok)return{kind:"http_error",raw:W,status:G.status};if(!B||!w6(W)||!x9(W.code))return{kind:"ambiguous",raw:W};return{kind:W.code,raw:W}}function WZ($){if($.kind==="cooldown")throw new Y0("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function YZ(){throw new Y0("expired_unreconciled","the previous reset attempt outcome is unknown")}function VZ($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function Iz($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";if(m6($))return"The server refused the request. A retry within five minutes reuses the same request and credit identifiers; after that, a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}function bz($,Z){if($)return"The server refused the request, but recording the refusal failed, so the saved redemption may still be treated as unknown and block a new attempt. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";if(Z)return"The server refused the request, but another send of the same request had an unknown outcome, so the saved redemption still blocks a new attempt until a retry settles it. A retry reuses the same request and credit identifiers; this does not prove the server did nothing.";return"The server refused the request, and another attempt has already settled or replaced the saved redemption. A new attempt is gated by the current saved state and fresh preconditions."}async function LZ($,Z){if(!p0(Z.accountKey))throw new Y0("invalid_account_key","the reset account key is reserved");let J=await $.resolveTarget(Z.accountKey);if(J.chatgptAccountId!==Z.expectedChatgptAccountId)throw new Y0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await Lz($,Z.accountKey);if(G.kind==="corrupt"){if(G=await _z($,Z.accountKey),G.kind==="corrupt")return VZ(J,G.beforeState)}if(G.kind==="cooldown")WZ(G);let Q;if(G.kind==="claim")Q=G.claim;else if(G.kind==="expired_unreconciled"&&(Z.retry||!FZ(G.claim.inFlight,X))){if(!Z.retry)YZ();Q=G.claim}else{if(Z.retry)throw new Y0("retry_without_inflight","there is no active reset credit redemption to retry");let[U,j]=await Promise.all([$.fetchUsage(J),k9($.fetchImpl,J.accessToken,z)]),q=b9(U,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!q.ok)throw new Y0("not_exhausted",q.reason);if(!p6(j.credits))throw new Y0("no_eligible_credit","no eligible reset credit was returned");let F=await Oz($,Z.accountKey,j.credits,X);if(F.kind==="corrupt")return VZ(J,F.beforeState);if(F.kind==="cooldown")WZ(F);if(F.kind==="expired_unreconciled")YZ();if(F.kind!=="claim")throw new Y0("no_eligible_credit","no eligible reset credit was available while claiming");Q=F.claim}Tz(Q.inFlight,X);let W=await Rz($.fetchImpl,J.accessToken,z,Q.inFlight.creditId,Q.inFlight.redeemRequestId),B,Y=!1;try{B=await Sz($,Z.accountKey,Q.inFlight,W,X)}catch{Y=!0}let H=Y&&x9(W.kind),V=m6(W)&&!Y&&B?.rejectedStatus!==void 0;return{target:J,selectedCredit:Q.selectedCredit,beforeState:G.beforeState,outcome:W,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":m6(W)&&!V?bz(Y,B):Iz(W),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function _Z($){let Z=[];for(let J of $)try{Z.push(...await J.run())}catch(X){Z.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:Z}}function OZ($,Z){let J=[$];if(Z.findings.length===0)return J.push("No problems found."),J;for(let X of Z.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function SZ($,Z){let J={applied:[],declined:[],failed:[]};for(let X of Z.findings){let z=X.repair;if(!z)continue;if(!await $.confirm(`Apply repair: ${z.label}?`)){J.declined.push(X);continue}try{await z.apply(),J.applied.push(X)}catch(G){J.failed.push({finding:X,error:G}),$.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function y9($){let Z=$.title??"Auth doctor";return{id:"doctor",label:$.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await _Z($.checks);for(let Q of OZ(Z,X))J.print(Q);let z=X.findings.filter((Q)=>Q.repair);if(z.length===0){if(X.findings.length>0)J.print("No repairs are available.");return}let G=await SZ(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as kz}from"node:child_process";import{win32 as xz}from"node:path";function EZ($,Z=process.platform,J=kz){try{if(Z==="win32"){let z=`Start-Process '${$.replaceAll("'","''")}'`,G=J(xz.resolve(process.env.SystemRoot??process.env.windir??"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe"),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(z,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return G.on("error",()=>{}),G.unref(),G.pid!==void 0}let X=J(Z==="darwin"?"open":"xdg-open",[$],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function AZ($,Z){if($.print(""),$.print("Open this URL in your browser and complete sign-in:"),$.print(""),$.print(Z.url),$.print(""),Z.instructions)$.print(Z.instructions),$.print("")}async function l6($,Z){let J=new AbortController,X=await $.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),AZ(Z,X);let z=!1;try{z=await($.openBrowser??EZ)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),Z.print("Could not open a browser. Switching to device authorization."),Z.print(""),X=await $.begin({headless:!0}),AZ(Z,X);return X.completion}var k={hide:"\x1B[?25l",show:"\x1B[?25h",up:($=1)=>`\x1B[${$}A`,clearLine:"\x1B[2K",clearScreen:"\x1B[2J",moveTo:($,Z)=>`\x1B[${$};${Z}H`,cyan:"\x1B[36m",green:"\x1B[32m",red:"\x1B[31m",dim:"\x1B[2m",reset:"\x1B[0m"};function g9($){let Z=$.toString(),J=[];for(let X=0;X<Z.length;){let z=Z[X];if(z==="\x1B"){let G=Z.slice(X,X+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let B={A:"up",B:"down",C:"right",D:"left"}[Q];if(B)J.push(B);X+=3}else if(X+1===Z.length){if(X===0)J.push("escape-start");X+=1}else if((Z[X+1]==="["||Z[X+1]==="O")&&X+2>=Z.length)break;else X+=1;continue}if(z==="\r"||z===`
|
|
3
3
|
`)J.push("enter");else if(z==="\x03")J.push("escape");else if(z&&z>=" ")J.push("char");X+=1}return J}var RZ=`${String.fromCharCode(27)}\\[[0-9;]*m`,yz=new RegExp(RZ,"g"),gz=new RegExp(`^${RZ}`);function IZ($){return $.replace(yz,"")}function D2($,Z){if(Z<=0)return"";if(IZ($).length<=Z)return $;let J=Z>=3?"...":".".repeat(Z),X=Math.max(0,Z-J.length),z="",G=0,Q=0;while(G<$.length&&Q<X){if($[G]==="\x1B"){let W=$.slice(G).match(gz);if(W){z+=W[0],G+=W[0].length;continue}}z+=$[G],G+=1,Q+=1}return z.includes("\x1B[")?`${z}${k.reset}${J}`:z+J}function f9(){return{input:process.stdin,output:process.stdout,signals:process}}function P2($){return $.input.isTTY===!0}function v9($,Z=""){$.output.write(`${Z}
|
|
4
4
|
`)}var fz=50;function vz($){if($==="red")return k.red;if($==="cyan")return k.cyan;return""}async function l2($,Z,J){if(!P2($))throw Error("Interactive select requires a TTY terminal");if(Z.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=$,Q=0,W=null,B=!1,Y=0,H=()=>{let V=z.columns??80,U=z.rows??24,j=Y;if(J.clearScreen)z.write(k.clearScreen+k.moveTo(1,1));else if(j>0)z.write(k.up(j));let q=0,F=(_)=>{z.write(`${k.clearLine}${_}
|
|
@@ -72,4 +72,4 @@ ${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}functio
|
|
|
72
72
|
`)}async function MW($){let Z;try{Z=await A0(m($,$4),"utf8")}catch(J){if(J.code==="ENOENT")return new Set;throw J}try{let J=JSON.parse(Z);if(Array.isArray(J?.files))return new Set(J.files.filter((X)=>typeof X==="string"))}catch{}return new Set}async function CW($,Z){await E1(m($,$4),`${JSON.stringify({version:1,files:Z},null,2)}
|
|
73
73
|
`)}async function TW($){await a4(m($,$4)).catch((Z)=>{if(Z.code!=="ENOENT")throw Z})}async function f$($,Z){await E1($,`${JSON.stringify(Z,null,2)}
|
|
74
74
|
`)}async function E1($,Z){await EJ(L1($)),await P0($,null,{serialize:()=>Z,durable:!0,durability:"file-only-on-windows"})}async function EJ($){if(process.platform==="win32")return;await lB($,{recursive:!0,mode:448}),await pB($,448)}async function T1($,Z,J){let X=performance.now();for(;;){let z=null;try{z=await l0({name:$,path:Z,ttlMs:FJ,renew:!0})}catch(G){if(G.code!=="ENOENT")throw G}if(z)return z;if(performance.now()-X>=J)throw new s4("lock-timeout",`${$} lock at ${Z}`);await new Promise((G)=>setTimeout(G,nB))}}async function K0($){try{return await jJ($),!0}catch(Z){let J=Z.code;if(J==="ENOENT"||J==="ENOTDIR")return!1;throw Z}}
|
|
75
|
-
export{U4 as
|
|
75
|
+
export{U4 as qa,u as ra,xX as sa,R as ta,yX as ua,D6 as va,m0 as wa,E as xa,JZ as ya,Vz as za,E9 as Aa,Hz as Ba,v6 as Ca,K2 as Da,gq as Ea,Uz as Fa,fq as Ga,vq as Ha,jz as Ia,h6 as Ja,GZ as Ka,R9 as La,y9 as Ma,f9 as Na,P2 as Oa,v9 as Pa,l2 as Qa,O4 as Ra,mz as Sa,lz as Ta,dz as Ua,H0 as Va,M2 as Wa,cz as Xa,R4 as Ya,nz as Za,sj as _a,aj as $a,nj as ab,ij as bb,rj as cb,oj as db,BK as eb,W7 as fb,BG as gb,$F as hb,ZF as ib,VG as jb,QF as kb,BF as lb,WF as mb,U7 as nb,UF as ob,$Q as pb,IK as qb,gK as rb,fK as sb,zQ as tb,vK as ub,hK as vb,mK as wb,wK as xb,dK as yb,cK as zb,sK as Ab,PF as Bb,qG as Cb,TF as Db,LF as Eb,wF as Fb,uF as Gb,d2 as Hb,pF as Ib,lF as Jb,_G as Kb,dF as Lb,cF as Mb,sF as Nb,OG as Ob,rF as Pb,oF as Qb,tF as Rb,SG as Sb,eF as Tb,c2 as Ub,X$ as Vb,mG as Wb,XK as Xb,VQ as Yb,RB as Zb,dD as _b,B8 as $b,nN as ac,iN as bc,mQ as cc,m4 as dc,uQ as ec,pQ as fc,ND as gc,DD as hc,cQ as ic,PD as jc,S0 as kc,MD as lc,CD as mc,TD as nc,U1 as oc,LD as pc,h4 as qc,M8 as rc,W1 as sc,_8 as tc,Y1 as uc,XD as vc,c8 as wc,KB as xc,DB as yc,PB as zc,bD as Ac,MB as Bc,kD as Cc,xD as Dc,eD as Ec,$P as Fc,FP as Gc,KP as Hc,NP as Ic};
|