@cortexkit/opencode-openai-auth 1.23.2 → 1.23.3
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 +2 -2
- package/dist/{index-by5wfvqm.js → index-9kges8jy.js} +1 -1
- package/dist/{index-t876xhkr.js → index-ekt6aq17.js} +1 -1
- package/dist/{index-v8w8j1wx.js → index-vf4nn20q.js} +1 -1
- package/dist/{index-v8wrmhyp.js → index-xkngfyvc.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/v2/server.js +3 -3
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ae as r8,Be as F6,Ce as X$,De as e2,Ge as aZ,Gf as _3,Ie as rZ,If as SX,Je as oZ,Jf as P6,Ke as m1,Le as tZ,Lf as AX,Mf as a1,Ne as eZ,Oe as $7,Of as s1,Pf as o0,Qe as Y6,Re as yJ,Rf as p6,Se as Z7,Te as J7,Uf as EX,Ve as nJ,Vf as EJ,We as Q4,Xe as sJ,Ye as H8,Ze as q8,_f as n1,bf as $1,cf as Z1,de as Y2,dg as U8,ee as dJ,fe as u6,fg as j8,ge as XZ,gg as F8,ie as j6,ig as RX,je as y0,jg as IX,ke as r7,le as h0,lf as ZJ,ne as zZ,ng as Q6,oe as GZ,of as r1,og as b8,pe as QZ,qg as o7,re as lJ,rf as u1,se as cJ,sf as kJ,te as S9,tf as _X,ue as d0,ve as g5,we as v5,xe as p5,ye as sZ,yg as f8,ze as iZ}from"./index-x00sxt2w.js";import{Dg as Q5,Eg as q0,Fg as Y5,Gg as F9,Hg as I0,Jg as B5,Kg as W5}from"./index-49ncs7dr.js";import{Yg as $X}from"./index-v8wrmhyp.js";import{Zg as lX}from"./index-drm4dk5y.js";import{eh as l8,ih as H3,jh as Y4,kh as q3,lh as v0}from"./index-wjp3q15r.js";import{oh as p4,th as d}from"./index-td4g5dc9.js";import{Ah as FJ,Bh as T1,Ch as NJ,Fh as DJ,uh as z0,vh as G4,wh as D9,zh as jJ}from"./index-4ktepxn1.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 D1 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 v2="identity-contradicted: ",G9="duplicate-identity";function X2($,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 P1($,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 w2($,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))X2($,z.id,"duplicate-identity"),X.push(z.id);return X}function N2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,w2($,J)}import{AsyncLocalStorage as c3}from"node:async_hooks";var L4=new c3,d3=new c3;function o($){if(L4.getStore()!==void 0)throw new D1($)}function n3(){if(L4.getStore()?.storeLocksReleased===!1||d3.getStore())throw new D1("updateLimitsNamespace")}function V0($){return d3.run(!0,$)}function H0($,Z,J=!1){return L4.run({operation:$,storeLocksReleased:J&&L4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function s3($,Z,J,X,z){if(!Z)return;try{await H0($,()=>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 V5}from"node:timers/promises";function D2($,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 K1}from"node:crypto";var v="commonAuthPool",z2=1,O0="rows",O4="retiredEpochs",C1=1,Q9=300000,h=v;function Sz($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(A(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function P2($){return K1("sha256").update(Sz($)).digest("hex")}function i3($){if(!A($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function Az($){if(!A($)||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 Z0="commonAuthProviderState";function A($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var Ez=new Set(["__proto__","constructor","prototype"]);function m2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(Ez.has($))return"id is a reserved object key";return}function Y9($){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 a3($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function T0($){return K1("sha256").update(a3($)).digest("hex")}function b0($){return K1("sha256").update(`credential-stamp\x00${a3($)}`).digest("hex")}function c0($){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 K1("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function B9($,Z,J,X={}){return{credentialEpoch:Z,digest:b0($),dispatch:c0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function u2($,Z){let J=$?.credentialBound?V0(()=>$.credentialBound?.(Z)):Z;return K1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function M1($,Z,J,X){if(!Z||J===void 0)return;if(!A($)||!Object.hasOwn($,Z0))return;let z=X0($[h]);if(!z||z.providerState===void 0||z.digest!==b0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function r($){return Number.isSafeInteger($)&&$>=1}function X0($){if(!A($))return;let Z=$.credentialEpoch;if(!r(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 $?Az($.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(!A(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!Y9(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 Rz($,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 Iz($,Z,J,X){if(!$)return"none";if(!A(X)||!Object.hasOwn(X,h))return"missing";let z=X0(X[h]);if(!z)return"malformed";if(z.digest!==b0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!Rz(z.binding,$,J))return"mismatched";if(z.dispatch!==c0($))return"mismatched";return"bound"}function W9($){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(!A(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(!A(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>z2)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${z2}`};if(O0 in J&&!A(J[O0]))return{status:"error",reason:`${v}.${O0} is not an object`};return{status:"ready",exists:!0,config:Z}}function r3($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!A($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!A($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function p2($){return Array.isArray($.accounts)?$.accounts:[]}function o3($){let Z=$[v];if(!A(Z))return{};let J=Z[O0];return A(J)?J:{}}function kz($){return A($.accounts)?$.accounts:{}}function xz($){if(!A($))return"not an object";let Z=m2($.id);if(Z)return Z;if($.type==="api")return Y9($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function bz($,Z){if(!A($))return;let J=$.credentialEpoch;if(!r(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?V0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!V0(()=>Z.validate(X)))return;if("staged"in $&&!i3($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function fz($,Z){if(!A(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 T4($,Z){return p2($).find((J)=>A(J)&&J.id===Z)}function t3($){if(!A($[v]))$[v]={};return $[v]}function V9($){let Z=t3($);if(!A(Z[O0]))Z[O0]={};return Z[O0]}function f0($,Z){let J=o3($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return A(X)?X:void 0}function _4($,Z,J){Object.defineProperty(V9($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function e3($,Z){let J=$[v];if(!A(J))return;let X=J[O4];if(!A(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return r(z)?z:void 0}function $5($,Z){let J=f0($,Z)?.credentialEpoch;return r(J)?J:void 0}function S4($,Z){return Math.max(e3($,Z)??0,$5($,Z)??0)+1}function Z5($,Z){let J=[...Z];if(J.length===0)return;let X=t3($),z=A(X[O4])?X[O4]:{},G={},Q=(B,Y)=>Object.defineProperty(G,B,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[B,Y]of Object.entries(z))if(r(Y))Q(B,Y);for(let B of J)Q(B,Math.max(e3($,B)??0,$5($,B)??1));X[O4]=G}function G2($,Z,J,X){let z=o3($),G=kz(Z),Q=new Set,B=[];for(let Y of p2($)){let W=xz(Y),V=A(Y)&&typeof Y.id==="string"?Y.id:void 0,H=V===void 0?void 0:z[V],q=A(H)&&Object.hasOwn(H,"staged"),j=q?i3(H.staged):void 0;if(W||!A(Y)||V===void 0||Q.has(V)){if(V!==void 0&&!Q.has(V))Q.add(V);if(V!==void 0)B.push({id:V,type:A(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...j?{staged:j}:{}});continue}Q.add(V);let U=Y.type==="api"?"api":"oauth",F=Object.hasOwn(z,V),N=F?bz(z[V],J):void 0,D=fz(Y,G[V]),P=Y.enabled!==!1,O=N?N.credentialEpoch:F?void 0:1,L=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,C={id:V,type:U,enabled:P,needsFirstReading:N?N.needsFirstReading:U==="oauth",hasEntry:F,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...L!==void 0?{identity:L}:{},...D?{credential:D,fingerprint:T0(D)}:{},...N?{credentialEpoch:N.credentialEpoch}:{},...j?{staged:j}:{},...N?.disabledReason!==void 0?{disabledReason:N.disabledReason}:{},...N&&"quota"in N?{quota:N.quota}:{},...yz(G[V],D,O,L,X),stamp:Iz(D,O,L,G[V])};if(F&&!N)C.invalid="entry";else C.candidate=P&&D!==void 0&&!q;B.push(C)}return B}function yz($,Z,J,X,z){if(!A($)||!Object.hasOwn($,Z0))return{};let G=M1($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[Z0];if(!z||!V0(()=>z.validate(Q)))return{providerStateDropped:"invalid"};if(u2(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function w($){return $.identity??$.id}function L1($,Z){if($===void 0||$>Z+Q9)return Z;return Math.max(Z,$+1)}function H9($,Z){return L1($,Z)>Z+Q9}function l2($){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 J5($,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 X5($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function z5($,Z={}){if(!A($))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)&&!Y9($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var A4="transition",G5="transitionMark";function hz($){if(!A($))return;let Z=$[A4];if(!A(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 O1($,Z,J){if(J.enabled)P1($,Z);else X2($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[G5]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)w2($,z.identity)}function gz($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function vz($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function wz($,Z,J,X={}){let z=A(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of G2($,Z,J)){if(Q.invalid||Q.staged||!Q.credential)continue;let B=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!A(B))continue;let Y=X0(B[h]);if(!Y?.binding)continue;if(Y.digest!==b0(Q.credential))continue;let W=Q.credentialEpoch??1;if(Y.credentialEpoch>W){if(!vz(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==c0(gz(Q.credential,Y.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===c0(Q.credential)&&Y.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===Q.identity){if(X.requireCredentialStamps&&Y.dispatch!==c0(Q.credential))continue;let V=hz(B[h]);if(V&&f0($,Q.id)?.[G5]!==V.mark)G.set(Q.id,{kind:"transition",transition:V})}}return G}function q9($,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(v2))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 U9($,Z,J,X={}){let z=wz($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>G2(G,Z,J),rosterRow:(B)=>T4(G,B),entry:(B)=>f0(G,B),setEntry:(B,Y)=>_4(G,B,Y)};for(let[B,Y]of z)if(Y.kind==="replace")q9(Q,B,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[B,Y]of z)if(Y.kind==="identity")N2(Q,B,Y.identity);else if(Y.kind==="transition")O1(Q,B,Y.transition);else if(Y.stamp.binding.identity!==void 0)w2(Q,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function j9($,Z,J,X={}){let{config:z,torn:G}=U9($,Z,J,X),Q=G2(z,Z,J,X.providerState);for(let B of Q){if(G.includes(B.id))B.torn=!0,B.candidate=!1;if(X.requireCredentialStamps&&B.stamp!=="bound")B.unbound=!0,B.candidate=!1}return Q}var mz=[5,10,20,40,80,160,320,400];async function E4($){for(let Z=0;;Z++)try{return await T1($,z0)}catch(J){if(J.code==="ENOENT")return;let X=mz[Z];if(X===void 0||!D9(J))throw J;await V5(X)}}function N9($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function H5($){return W9(N9(await E4($)))}async function t($){for(let Z=0;Z<3;Z++){let J,X,z;try{J=await E4($.configPath),X=await E4($.statePath),z=await E4($.configPath)}catch(B){if(D9(B))break;throw B}if(J!==z){if(Z<2)await V5(2+Math.floor(Math.random()*4));continue}let G=W9(N9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=r3(N9(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:j9(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 Y0($,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 q5{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 j9(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($)?.[h];return A(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){D2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),T4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(A(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return V9(this.config)}entry($){return this.entries(),f0(this.config,$)}setEntry($,Z){_4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=U9(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=A(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return A(J)?J:void 0}dropStateAccount($){if(A(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!A(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 Y of Z)if(A(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of p2(this.snapshot.config))if(A(Y)&&typeof Y.id==="string"&&!J.has(Y.id))X.add(Y.id);for(let Y of Object.keys(this.entries()))if(!J.has(Y))X.add(Y);Z5(this.config,X);let z=this.entries(),G={};for(let[Y,W]of Object.entries(z))if(J.has(Y))Object.defineProperty(G,Y,{value:W,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[v],B={...this.config,version:C1,accounts:Z,[v]:{...Q,schemaVersion:z2,[O0]:G}};await this.write(this.ctx.configPath,B,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=B}),this.config=B}async commitState($,Z={}){let J={...this.state,version:C1,accounts:A(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 F9(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 F9(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await Y5($,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 U5($,Z){let J=new d0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let B of $.storeLocks)await J.acquire(B);let z=await t($);if(z.status==="error")throw Y0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[B,Y]of Object.entries(z.config))if(!Z.includes(B))G[B]=Y;G.version=C1,G[v]={schemaVersion:z2,[O0]:{}};let Q={operation:"initialize",rowId:void 0};return await q0($.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 Q2(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function l($,Z,J,X,z,G={}){let Q=Z.held.length;try{for(let W of $.storeLocks)await Z.acquire(W);let B=await t($);if(B.status!=="ready")throw Y0(B,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new q5($,B,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Y.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await Z.releaseTo(Q)}}function Q2($,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 Q5)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 W5)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 B5)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 i($,Z,J,X,z){let G=new d0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(B){let Y=Q2(B,Z,J,Q);if(Y.kind!=="after-persist-hook")await s3(Z,X,J,Y,$.logger);throw Y}finally{await G.releaseAll()}}function B0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(w(Z))}`,path:$.ctx.statePath}}async function _0($,Z,J){let X=await t($.ctx);if(X.status!=="ready")throw Y0(X,Z,J);let z=X.rows.find((W)=>W.id===J),G=f0(X.config,J),Q=X.state.accounts,B=A(Q)&&Object.hasOwn(Q,J)?Q[J]:void 0,Y=A(B)?B[h]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))D2(Z,J,G.staged);if(!z&&A(Y)&&Object.hasOwn(Y,"staged"))D2(Z,J,Y.staged);if(!z)throw U0(Z,J);return{result:X,row:z}}function U0($,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 J0($,Z){if(Z.unbound)throw S($,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 S($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function P9($,Z){if(!r(Z?.credentialEpoch))throw S("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function _1($,Z,J){if(!J)throw U0("pull",$);if(J.invalid)throw S("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw S("pull",$,"no-credential",`row ${$} holds no credential`);if(J0("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 S1($,Z,J,X){let z=V0(()=>$.codec.merge(J,X));if(!V0(()=>$.codec.validate(z)))throw S("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function R4($,Z,J,X){let{ctx:z}=$,G=new d0(z.lockDefaults,z.lockEnv),Q={writes:0};try{P9(Z,J),await l(z,G,Q,{operation:"pull",rowId:Z},async(B)=>{B.assertNotStaged(Z);let Y=B.row(Z);_1(Z,J,Y);let W=B.entry(Z);if(!W)throw U0("pull",Z);let V=S1(z,Z,W.quota,X);B.setEntry(Z,{...W,quota:V,needsFirstReading:!1}),await B.commitConfig()},{completeTorn:!1})}catch(B){throw Q2(B,"pull",Z,Q)}finally{await G.releaseAll()}}async function j5($,Z,J={}){n3();let{ctx:X}=$;await i(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let H of X.storeLocks)await z.acquire(H);let Q=await t(X);if(Q.status!=="ready")throw Y0(Q,"updateLimitsNamespace",void 0);let B=Q.rows.map(({id:H,credentialEpoch:q,identity:j})=>({id:H,credentialEpoch:q,identity:j})),Y=await H0("updateLimitsNamespace",()=>Z(structuredClone(Q.config.commonAuthLimits),B)),W={...Q.config,commonAuthLimits:Y},V={operation:"updateLimitsNamespace",rowId:void 0};try{await q0(X.configPath,W,{beforeRename:async()=>{await X.onStep?.("before-config-write",V),await z.assertAll(),J.beforePublish?.()}})}catch(H){if(H&&typeof H==="object"&&"published"in H&&H.published===!0)J.onPublished?.();throw H}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",V)})}function n0($,Z,J,X,z="the provider state"){if(!$)throw S(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 S(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!V0(()=>$.validate(G)))throw S(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function A1($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:n0($,Z,J,V0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function F5($,Z,J,X,z){let G=$?.onReplace,Q=G?V0(()=>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:n0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function N5($,Z,J,X,z){if(Z.kind==="set")return u2($,Z.value);if(Z.kind==="clear")return;return M1(J,X?.credential,z,X?.identity)}async function D5($,Z,J,X,z={}){o("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return i(G,Q,Z,z.onFailure,async(B,Y)=>{let W=G.providerState;if(!W)throw S(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw S(Q,Z,"invalid-input","a mutator is required");let V=A(J)?J.credentialEpoch:void 0;if(!r(V))throw S(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:H}=await _0($,Q,Z);await B.acquire(B0($,H));for(let q of z.extraLocks??[])await B.acquire(q);return l(G,B,Y,{operation:Q,rowId:Z},async(q)=>{let j=q.row(Z);if(!j)throw U0(Q,Z);if(w(j)!==w(H))throw S(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(j.invalid)throw S(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!j.credential)throw S(Q,Z,"no-credential",`row ${Z} holds no credential`);if(J0(Q,j),(j.credentialEpoch??1)!==V||j.identity!==J.identity)throw S(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let F=await K9(q,W,Q,j,X);if(F.kind!=="changed")return{id:Z,outcome:"unchanged",...F.kind==="unchanged"&&F.value!==void 0?{providerState:F.value}:{}};return q.setStateAccount(Z,F.account),await q.commitState(),F.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:F.value}})})}var P5=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function K9($,Z,J,X,z,G=!1){let{id:Q,credential:B}=X;if(!B)throw S(J,Q,"no-credential",`row ${Q} holds no credential`);let Y=X.credentialEpoch??1,W=$.stateAccount(Q),V=W?.[h],H=X0(V);if(!A(V)||!H?.binding||H.digest!==b0(B)||H.credentialEpoch!==Y||H.binding.identity!==X.identity)throw S(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 q=X.providerState===void 0?void 0:structuredClone(X.providerState),j=await H0(J,()=>z(q,X));if(G&&j===P5)return{kind:"declined"};let U=j===void 0?void 0:n0(Z,J,Q,j,"the provider state the mutator returned"),F=W!==void 0&&Object.hasOwn(W,Z0);if(U===void 0?!F:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let N={...W};if(U===void 0){delete N[Z0];let D={...V};delete D.providerState,N[h]=D}else{N[Z0]=U;let D=u2(Z,U);if(H.providerState!==D)N[h]={...V,providerState:D}}return{kind:"changed",...U!==void 0?{value:U}:{},account:N}}import{randomUUID as K5}from"node:crypto";async function b4($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:Q,type:B,label:Y,enabled:W,disabledReason:V,identity:H,credentialEpoch:q,stamp:j,staged:U,torn:F,invalid:N}=G;return{id:Q,type:B,label:Y,enabled:W,disabledReason:V,identity:H,credentialEpoch:q,stamp:j,staged:U,torn:F,invalid:N}}),z=await H0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw S($.info.operation,Z,"row-protected",z)}var uz=["access","refresh","expires","lastRefreshedAt","apiKey"];function pz($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function lz($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!A(X)){if(J.baseURL===void 0)throw S($.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"}:pz(X),Q=J.baseURL?.trim()??G.baseURL,B=J.authHeader??G.authHeader;if(Q!==G.baseURL||B!==G.authHeader)throw S($.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:B}}function C5($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),Q=X??(G?G.identity:A(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 I4($,Z,J,X,z={}){let G=lz(Z,J,X),Q=Z.stateAccount(J),B=z.providerState??{kind:"keep"},Y=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,V=N5($.ctx.providerState,B,Q,Q&&Object.hasOwn(Q,Z0)?Z.row(J):void 0,W),H=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,q=G.type==="oauth"?z.stamp??L1(H,$.ctx.now()):void 0,j={...Q??{}};for(let N of uz)delete j[N];if(z.clearErrors)delete j.lastRefreshError,delete j.lastQuotaRefreshError,delete j.quota;if(B.kind==="clear")delete j[Z0];else if(B.kind==="set")j[Z0]=B.value;let U=X5(G,q),F={...j,...J5(G,q),[h]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[A4]:z.transition}:{},...B9(U,W,z.binding??C5(Z,J,U,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};return{stored:U,account:F}}async function k4($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function f4($,Z,J,X,z={}){return k4(Z,J,I4($,Z,J,X,z))}async function cz($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=M1(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[h]:B9(Z.credential,Z.credentialEpoch??1,C5($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function M9($,Z,J){let X=$==="add"?m2(Z):void 0;if(X)throw S($,Z,"invalid-input",X);let z=z5(J,{baseURLOptional:$==="rotate"});if(z)throw S($,Z,"invalid-input",z)}function y4($,Z,J,X){if(!J)throw U0($,Z);if(J.invalid)throw S($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw S($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function d2($,Z,J){if(J!==void 0&&!r(A(J)?J.credentialEpoch:void 0))throw S($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function h4($,Z,J,X,z){if(!J)throw U0($,Z);if(J.invalid)throw S($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity||z?.credential==="absent"&&J.credential!==void 0)throw S($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function x4($,Z){return S($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function E1($,Z){return S($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function dz($,Z,J,X){let{id:z,credential:G,identity:Q}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!c2(Z.state,z))return;let B=()=>{throw S("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(z),W=X0(Y?.[h]);if(!W?.binding||W.dispatch===void 0||W.replace)return B();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return B();let V=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[H]=G2({accounts:[l2({id:z,credential:V,identity:W.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:S4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!H?.credential||H.invalid||H.stamp!=="bound")return B();if(Q!==void 0&&Q!==H.identity)return B();if(b0(G)!==W.digest)return B();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return B();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return B()}else if(c0(G)!==W.dispatch)return B();if(W.providerState!==void 0&&H.providerState===void 0)return B();if(X!==void 0&&u2($.ctx.providerState,X)!==W.providerState)return B();return H}function nz($,Z,J,X){let{id:z,credential:G,identity:Q,label:B}=J,Y=Z.rosterRow(z),W=()=>{throw S("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),H=X0(V?.[h]),q=H?.staged;if(!H?.binding||!q||H.replace||H.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==B||Y.accountId!==Q))return W();if(q.reservation!==J.stage?.reservation||q.label!==B||q.disabledReason!==J.disabled?.reason||H.binding.identity!==Q)return W();let j=X===void 0?void 0:P2(X),U=V?.[Z0],F=U===void 0?void 0:P2(U);if(q.providerState!==j||q.providerState!==F)return W();if(b0(G)!==H.digest||c0(G)!==H.dispatch)return W();let N=Y?Z.config:{accounts:[{...l2({id:z,credential:G.type==="api"?{...G,baseURL:H.binding.baseURL??"",authHeader:H.binding.authHeader}:G,identity:H.binding.identity,label:q.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:H.credentialEpoch,disabledReason:q.disabledReason,staged:{reservation:q.reservation}}}}},D=G2(N,Z.state,$.ctx.codec,$.ctx.providerState).find((P)=>P.id===z);if(!D?.credential||D.invalid||D.stamp!=="bound"||D.type!==G.type||D.enabled||D.label!==q.label||D.identity!==H.binding.identity||D.disabledReason!==q.disabledReason||D.staged?.reservation!==q.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:D.credential,credentialEpoch:H.credentialEpoch};if(S4(Z.config,z)!==H.credentialEpoch)return W();return Z.roster().push({...l2({id:z,credential:G,identity:Q,label:B,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:H.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:q.disabledReason,staged:{reservation:q.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:D.credential,credentialEpoch:H.credentialEpoch}))}async function M5($,Z,J={}){o("add");let{ctx:X}=$,{id:z,credential:G,identity:Q,label:B}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,W=await i(X,"add",z,J.onFailure,async(V,H)=>{M9("add",z,G);let q=J.onExisting??"rotate";if(Z.stage!==void 0&&q==="rotate")throw S("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(q)||Z.stage!==void 0&&(B!==void 0&&typeof B!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!A(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!A(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||q==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw S("add",z,"invalid-input","staging requires a reservation and a disabled reason");let j=Z.providerState===void 0?void 0:n0(X.providerState,"add",z,Z.providerState);if(await V.acquire(B0($,{id:z,identity:Q})),G.type==="oauth")await V.acquire(J.providerLock??$.providerLock);for(let U of J.extraLocks??[])await V.acquire(U);return l(X,V,H,{operation:"add",rowId:z},async(U)=>{await b4(U,z,J.protect);let F=A(U.state.accounts)?U.state.accounts:{},N=Object.entries(F).find(([I,k])=>{if(I===z||U.rosterRow(I)||!A(k))return!1;let g=k[h];if(!A(g)||!Object.hasOwn(g,"staged"))return!1;return G.type==="oauth"?k.refresh===G.refresh:typeof k.apiKey==="string"&&k.apiKey.trim()===G.apiKey.trim()});if(N)throw S("add",N[0],"row-staged",`orphan ${N[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw S("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&q!=="rotate"&&(U.rosterRow(z)||c2(U.state,z)))return nz($,U,Z,j);if(q==="rotate"){U.assertNotStaged(z);let I=U.rows().find((k)=>k.fingerprint===T0(G));if(I)U.assertNotStaged(I.id)}if(q==="refuse"){let I=U.rows().find((p)=>p.fingerprint===T0(G)||p.id===z&&p.credential),k=A(U.state.accounts)?U.state.accounts:{},g=Object.entries(k).find(([,p])=>{if(!A(p))return!1;if(G.type==="oauth")return p.refresh===G.refresh;return typeof p.apiKey==="string"&&p.apiKey.trim()===G.apiKey.trim()})?.[0],c=I?.id??g??z;if(I||g!==void 0||c2(U.state,z))throw S("add",c,"credential-exists",`row ${c} already holds this secret or id`)}if(q==="stage-duplicate"&&(U.rosterRow(z)||c2(U.state,z)))throw S("add",z,"id-exists",`row ${z} already exists`);let D=dz($,U,Z,j),P=U.rows(),O=T0(G),L=q==="rotate"&&!D&&P.find((I)=>I.invalid===void 0&&I.fingerprint===O);if(L){if(U.assertNotStaged(L.id),J0("add",L),Q!==void 0&&L.identity!==void 0&&Q!==L.identity)throw x4("add",L.id);let I=I4($,U,L.id,G,{...j!==void 0?{providerState:A1(X.providerState,"add",L.id,L.providerState,j)}:{}});await U.completeTorn(),U.assertNotStaged(L.id);let k=await k4(U,L.id,I);return{id:L.id,outcome:"rotated",credential:k,credentialEpoch:L.credentialEpoch??1}}let C=P.find((I)=>I.id===z);if(C){if(C.invalid)throw S("add",z,"invalid-row",`row ${z} is invalid`);if(C.credential)throw S("add",z,"id-exists",`row ${z} already holds a credential`);if(J0("add",C),C.type!==G.type)throw S("add",z,"type-mismatch",`row ${z} is a ${C.type} row`);if(Q!==void 0&&C.identity!==void 0&&Q!==C.identity)throw x4("add",z);if(!C.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=I4($,U,z,G,{clearErrors:!0,...j!==void 0?{providerState:{kind:"set",value:j}}:{}});await U.completeTorn();let k=await k4(U,z,I);if(!C.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:k,credentialEpoch:C.credentialEpoch??1}}let T=S4(U.config,z);if(!r(T))throw S("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let K=D?.identity??Q;U.roster().push(l2({id:z,credential:G,...K!==void 0?{identity:K}:{},...B!==void 0?{label:B}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let M="added";if(Z.disabled)X2(U,z,Z.disabled.reason),M="added-disabled";if(!Z.disabled&&K!==void 0&&G.type==="oauth"){if(P.find((k)=>k.invalid===void 0&&k.type==="oauth"&&k.enabled&&k.identity===K))X2(U,z,G9),M="added-disabled"}if(D?.credential)return await U.commitConfig(),{id:z,outcome:M,credential:D.credential,credentialEpoch:D.credentialEpoch??T};U.dropStateAccount(z);let _=I4($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...B!==void 0?{label:B}:{},...j!==void 0?{providerState:P2(j)}:{}}}:{},...j!==void 0?{providerState:{kind:"set",value:j}}:{}});if(q==="rotate")await U.completeTorn();let R=await k4(U,z,_);return await U.commitConfig(),{id:z,outcome:M,credential:R,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))$.firePull(W.id,"add");return W}async function L5($,Z,J,X={},z={}){o("replace");let{ctx:G}=$,Q=await i(G,"replace",Z,z.onFailure,async(B,Y)=>{M9("replace",Z,J),d2("replace",Z,z.attribution);let W=z.attribution?.expect;if(W!==void 0&&(!A(W)||W.credential!=="absent"))throw S("replace",Z,"invalid-input","the attribution's credential expectation must be 'absent'");let V=X.providerState===void 0?void 0:n0(G.providerState,"replace",Z,X.providerState),{row:H}=await _0($,"replace",Z);if(await B.acquire(B0($,H)),J.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let q of z.extraLocks??[])await B.acquire(q);return l(G,B,Y,{operation:"replace",rowId:Z},async(q)=>{if(z.attribution!==void 0)h4("replace",Z,q.row(Z),z.attribution,W),await q.completeTorn();let j=y4("replace",Z,q.row(Z),J);if(w(j)!==w(H))throw E1("replace",Z);let U=q.entry(Z)?.credentialEpoch,F=(typeof U==="number"?U:1)+1;if(!r(F))throw S("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let N=F5(G.providerState,j,F,X.identity,V),D={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(q9(q,Z,F,D),X.identity!==void 0)w2(q,X.identity);let P=await f4($,q,Z,J,{clearErrors:!0,binding:D,providerState:N});return await q.commitConfig(),{id:Z,credential:P,credentialEpoch:F}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return Q}async function O5($,Z,J,X={},z={}){o("rotate");let{ctx:G}=$;return i(G,"rotate",Z,z.onFailure,async(Q,B)=>{M9("rotate",Z,J),d2("rotate",Z,z.attribution);let Y=X.providerState===void 0?void 0:n0(G.providerState,"rotate",Z,X.providerState),{row:W}=await _0($,"rotate",Z);if(await Q.acquire(B0($,W)),X.identity!==void 0&&J.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return l(G,Q,B,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)h4("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let H=y4("rotate",Z,V.row(Z),J);if(w(H)!==w(W))throw E1("rotate",Z);if(J0("rotate",H),X.identity!==void 0&&H.identity!==void 0&&X.identity!==H.identity)throw x4("rotate",Z);let q=X.identity!==void 0&&H.identity===void 0?X.identity:void 0,j=await f4($,V,Z,J,{identity:q,...Y!==void 0?{providerState:A1(G.providerState,"rotate",Z,H.providerState,Y)}:{}}),U=!1;if(!H.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:H.type==="oauth"}),U=!0;if(X.identity!==void 0&&H.identity!==X.identity)N2(V,Z,X.identity),U=!0;if(U)await V.commitConfig();return{id:Z,credential:j}},{completeTorn:z.attribution===void 0})})}async function T5($,Z,J,X,z){o(Z);let{ctx:G}=$,Q=G.providerState,B=z.attribution,Y=z.providerState;return i(G,Z,J,z.onFailure,async(W,V)=>{if(d2(Z,J,B),Y!==void 0){if(typeof Y!=="function")throw S(Z,J,"invalid-input","the provider-state mutator must be a function");if(B===void 0)throw S(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw S(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:H}=await _0($,Z,J);await W.acquire(B0($,H));for(let q of z.extraLocks??[])await W.acquire(q);return l(G,W,V,{operation:Z,rowId:J},async(q)=>{await b4(q,J,z.protect),q.assertNotStaged(J);let j=q.row(J),U=X.enabled?y4("enable",J,j):j;if(!U||!q.rosterRow(J))throw U0(Z,J);if(w(U)!==w(H))throw E1(Z,J);if(B!==void 0)h4(Z,J,U,B);if(X.enabled&&U.disabledReason?.startsWith(v2))throw S("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let F=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&F&&U.type==="oauth"){let L=U.identity===void 0?void 0:q.rows().find((C)=>C.id!==J&&C.invalid===void 0&&C.type==="oauth"&&C.enabled&&C.identity===U.identity);if(L)throw S("enable",J,"duplicate-identity",`row ${L.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||Q===void 0){if(await q.completeTorn(),!F)return{id:J};if(X.enabled)P1(q,J);else X2(q,J,X.reason);return await q.commitConfig(),{id:J}}if(!U.credential)throw S(Z,J,"no-credential",`row ${J} holds no credential`);J0(Z,U);let N=await K9(q,Q,Z,U,Y,!0);if(N.kind==="declined")return{id:J,declined:!0};await q.completeTorn();let D={id:J,providerStateOutcome:N.kind==="unchanged"?"unchanged":N.value===void 0?"cleared":"updated",...N.value!==void 0?{providerState:N.value}:{}};if(N.kind==="unchanged"){if(F){if(X.enabled)P1(q,J);else X2(q,J,X.reason);await q.commitConfig()}return D}if(!F)return q.setStateAccount(J,N.account),await q.commitState(),D;let P=X.enabled?{mark:K5(),enabled:!0}:{mark:K5(),enabled:!1,reason:X.reason},O=N.account[h];return q.setStateAccount(J,{...N.account,[h]:{...O,[A4]:P}}),await q.commitState(),O1(q,J,P),await q.commitConfig(),D},{completeTorn:!1})})}function _5($,Z,J,X={}){return T5($,"disable",Z,{enabled:!1,reason:J},X)}function S5($,Z,J={}){return T5($,"enable",Z,{enabled:!0},J)}async function A5($,Z,J={}){o("remove");let{ctx:X}=$;return i(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw S("remove",Z,"invalid-input","id must be non-empty");let Q=J.attribution;if(d2("remove",Z,Q),J.staged!==void 0&&(!A(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw S("remove",Z,"invalid-input","a staged removal needs a reservation");let B=await t(X);if(B.status!=="ready")throw Y0(B,"remove",Z);let Y=B.rows.find((V)=>V.id===Z);if(!Y&&!c2(B.state,Z))throw U0("remove",Z);let W=w(Y??{id:Z});await z.acquire(B0($,Y??{id:Z}));for(let V of J.extraLocks??[])await z.acquire(V);return l(X,z,G,{operation:"remove",rowId:Z},async(V)=>{let H=V.reservation(Z);if(H!==void 0){if(!A(H)||!J.staged||H.reservation!==J.staged.reservation)throw S("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw S("remove",Z,"attribution",`row ${Z} is no longer reserved`);let q=V.row(Z),j=c2(V.state,Z);if(!q&&!j)throw U0("remove",Z);if(w(q??{id:Z})!==W)throw E1("remove",Z);if(Q!==void 0)if(q)g4(Z,q,Q);else sz($,V,Z,Q);let U=J.protect;if(U){let F={row:q,config:V.snapshot.config,state:V.snapshot.state},N=await H0("remove",()=>U(Z,F));if(N!==void 0)throw S("remove",Z,"row-protected",N)}if(q){if(Q===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(j)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:q?"removed":"completed"}},{completeTorn:!1})})}function g4($,Z,J,X="remove"){if(h4(X,$,Z,J),Z.torn)throw S(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw S(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function sz($,Z,J,X){let z=()=>S("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=X0(G?.[h]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let B;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();B={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")B={type:"oauth",refresh:G.refresh};else throw z();let[Y]=G2({accounts:[l2({id:J,credential:B,identity:Q.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(Q.credentialEpoch!==X.credentialEpoch||Q.binding.identity!==X.identity)throw S("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function c2($,Z){let J=$.accounts;return A(J)&&Object.hasOwn(J,Z)}function C9($){return A($)&&typeof $.id==="string"?$.id:void 0}function iz($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let Q=C9(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 az($,Z){let J=new Map;for(let G of $){let Q=C9(G);if(Q===void 0)continue;let B=J.get(Q);if(B)B.push(G);else J.set(Q,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>C9(G)===void 0?G:X[z++])}async function E5($,Z,J={}){o("reorder");let{ctx:X}=$,z=J.onFailure;return i(X,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of J.extraLocks??[])await G.acquire(B);return l(X,G,Q,{operation:"reorder",rowId:void 0},async(B)=>{let Y=B.roster(),W=iz(Y,Z);if(W)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let V=[...Z],H=az(Y,V);if(H.every((q,j)=>q===Y[j]))return{ids:V,outcome:"unchanged"};return B.config.accounts=H,await B.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function R5($,Z,J,X,z={}){return o("recordIdentity"),i($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw S("recordIdentity",Z,"invalid-input","identity must be non-empty");let B=A(X)?X.credentialEpoch:void 0;if(!r(B))throw S("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await _0($,"recordIdentity",Z);await G.acquire(B0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return l($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(W)=>{let V=y4("recordIdentity",Z,W.row(Z));if(w(V)!==w(Y))throw E1("recordIdentity",Z);if(J0("recordIdentity",V),(V.credentialEpoch??1)!==B)throw S("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==J)throw x4("recordIdentity",Z);if(V.identity===void 0)await cz(W,V,J);let H=N2(W,Z,J);return await W.commitConfig(),{id:Z,disabled:H}})})}function k5($){let Z=$[v];return A(Z)&&A(Z.publications)?Z.publications:{}}function x5($,Z){let J=k5($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!A(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)=>!A(z)||typeof z.id!=="string"||!r(z.credentialEpoch))||X.finalized.some((z)=>!A(z)||typeof z.id!=="string"||!r(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw S("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function b5($,Z){let J=await t($.ctx);if(J.status!=="ready")throw Y0(J,"publishRoster",Z);return x5(J.config,Z)}function rz($,Z){let J=()=>{throw S("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!A(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(!A(z)||typeof z.id!=="string"||m2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),d2("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"||m2(z))||new Set(Z.order).size!==Z.order.length)J()}function f5($,Z){$.entries();let J=$.config[v],X={...k5($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function oz($,Z,J){let X=new Set;for(let Q of p2($.config)){if(!A(Q)||typeof Q.id!=="string")continue;if(X.has(Q.id))throw S("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((B)=>B.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw S("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function I5($,Z){await $.assertAll();for(let X of Z.removed)if(X0($.stateAccount(X.id)?.[h])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=X0(z?.[h]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let Q={...z[h]};delete Q.staged,$.setStateAccount(X.id,{...z,[h]:Q})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return f5($,J),await $.commitConfig({durable:!0}),J}async function y5($,Z,J={}){return o("publishRoster"),i($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!A(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw S("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=P2(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((B)=>A(B)&&typeof B.id==="string");for(let B=0;;B++){let Y=await t($.ctx);if(Y.status!=="ready")throw Y0(Y,"publishRoster",Z.operationId);let W=new Map(Q.map(({id:H})=>[H,w(Y.rows.find((q)=>q.id===H)??{id:H})]));for(let H of[...new Set(W.values())].sort())await X.acquire(B0($,{id:H}));await X.acquire(J.providerLock??$.providerLock);for(let H of J.extraLocks??[])await X.acquire(H);let V=await l($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(H)=>{let q=H.rows();if(Q.some(({id:C})=>w(q.find((T)=>T.id===C)??{id:C})!==W.get(C)))return;let j=x5(H.config,Z.operationId);if(j){if(j.planDigest!==G)throw S("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 H.markPublicationDecision(),await H.syncConfig(),{outcome:"cleaned",receipt:await I5(H,j)}}rz($,Z);let U=oz(H,Z,q),F=[];for(let C of Z.remove){H.assertNotStaged(C.id);let T=q.find((K)=>K.id===C.id);if(!T)throw S("publishRoster",C.id,"attribution","the removed row no longer exists");if(g4(C.id,T,C.attribution,"publishRoster"),!T.credential||C.fingerprint!==void 0&&T0(T.credential)!==C.fingerprint)throw S("publishRoster",C.id,"attribution","the removed secret no longer matches");F.push(T)}let N=[];for(let C of Z.finalize){let T=q.find((k)=>k.id===C.id),K=X0(H.stateAccount(C.id)?.[h]);if(!T||T.staged?.reservation!==C.reservation||K?.staged?.reservation!==C.reservation||T.enabled)throw S("publishRoster",C.id,"row-staged","the finalized row is not disabled under this reservation");let M=H.stateAccount(C.id),_=H.rosterRow(C.id),R=M?.[Z0],I=R===void 0?void 0:P2(R);if(!K?.staged||K.staged.label!==_?.label||K.staged.disabledReason!==T.disabledReason||K.staged.providerState!==I)throw S("publishRoster",C.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");g4(C.id,T,C.attribution,"publishRoster"),N.push(T)}let D=U.find((C)=>C.torn);if(D)throw S("publishRoster",Z.operationId,"attribution",`Row ${D.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let P=new Set;for(let C of U){if(!(Z.finalize.find((K)=>K.id===C.id)?.enabled??C.enabled)||C.type!=="oauth"||C.identity===void 0)continue;if(P.has(C.identity))throw S("publishRoster",C.id,"invalid-input","the final enabled roster repeats a known identity");P.add(C.identity)}for(let C of U)if(C.identity!==void 0&&C.fingerprint!==void 0&&U.some((T)=>T.id!==C.id&&T.identity!==void 0&&T.identity!==C.identity&&T.fingerprint===C.fingerprint))throw S("publishRoster",C.id,"attribution","the resulting pool gives the same secret different known identities");for(let C of N)if(C.identity!==void 0&&F.some((T)=>T.identity!==void 0&&T.identity!==C.identity&&T.fingerprint===C.fingerprint))throw S("publishRoster",C.id,"attribution","the staged secret belonged to a different known identity");await b4(H,Z.operationId,J.protect);let O={operationId:Z.operationId,planDigest:G,phase:"committed",removed:F.map((C)=>({id:C.id,credentialEpoch:C.credentialEpoch??1})),finalized:Z.finalize.map((C,T)=>({id:C.id,credentialEpoch:N[T]?.credentialEpoch??1,reservation:C.reservation,enabled:C.enabled}))};for(let C of Z.remove)H.dropRosterRows(C.id);for(let C of Z.finalize){let T=H.rosterRow(C.id);T.enabled=C.enabled;let K={...H.entry(C.id)};if(delete K.staged,C.enabled)delete K.disabledReason;else K.disabledReason=C.disabledReason;H.setEntry(C.id,K)}let L=H.roster().filter((C)=>!A(C)||typeof C.id!=="string"||q.find((T)=>T.id===C.id)?.invalid==="roster");return H.config.accounts=[...Z.order.map((C)=>H.rosterRow(C)),...L],f5(H,O),await H.syncState(),await H.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await I5(H,O)}},{completeTorn:!1});if(V)return V;if(await X.releaseAll(),B>=1)throw S("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class L9{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 d0(X.lockDefaults,X.lockEnv),G={writes:0};try{let Q=await l(X,z,G,{operation:"pull",rowId:$},async(W)=>{if(W.reservation($)!==void 0)return;await W.completeTorn();let V=W.row($);if(V?.unbound&&V.enabled&&V.type==="oauth"&&V.credential&&!V.invalid)J0("pull",V);if(!V?.candidate||V.type!=="oauth")return;if(!V.hasEntry)W.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let H=W.row($);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:$,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!Q){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let B;try{B=await this.hook?.(Q)}catch(W){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,V,H)=>R4(J,W,V,H)))($,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(Q){this.firedAtLoad.delete($);let B=Q2(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,B)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:B.kind})}finally{await z.releaseAll()}}}var h5=100,v4=128;class O9{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=v5){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??d("store")}async record($,Z,J){try{this.assertOpen($),P9($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await _0(this.rt,"pull",$);_1($,X.attribution,z),S1(this.rt.ctx,$,this.overlayRow({...z,quota:f0(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>=v4)this.flushNow();else this.schedule(h5)}catch(X){throw Q2(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<v4)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($)>=v4){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw S("pull",$,"lock-contention",`pool quota queue for ${$} is full (${v4} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let Q=()=>{clearTimeout(B),this.wake.delete(Q),G()},B=setTimeout(Q,z);this.wake.add(Q)})}}assertOpen($){if(this.closed)throw S("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{_1($.id,J.attribution,$),Z={...Z,quota:S1(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)+g5-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 d0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await l(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let Q of $){let{id:B,attribution:Y,observation:W}=Q,V=JSON.stringify([B,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(B),_1(B,Y,z.row(B))}catch(j){if(!(j instanceof b))throw j;if(!this.warned.has(V))this.warned.add(V),this.warn("pool quota publication dropped; account binding changed",{id:B,kind:j.kind});continue}let H=z.entry(B);if(!H)continue;let q;try{q=S1(Z,B,H.quota,W)}catch(j){let U=`codec:${V}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:B,error:j instanceof Error?j.message:String(j)});continue}z.setEntry(B,{...H,quota:q,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((B)=>!X.has(B));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()):h5;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 tz}from"node:crypto";function T9($,Z){if(D2("refresh",$,Z?.staged),!Z)throw S("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw S("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw S("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw S("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function w5($){return S("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 m5($,Z,J,X={}){o("refresh");let{ctx:z}=$;return i(z,"refresh",Z,X.onFailure,async(G,Q)=>{let{row:B}=await _0($,"refresh",Z);T9(Z,B);let Y=await X.refuse?.(B);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let W=w(B),V;for(let U=0;;U++){await G.acquire(B0($,{id:Z,identity:W===Z?void 0:W})),await G.acquire(X.providerLock??$.providerLock);for(let D of X.extraLocks??[])await G.acquire(D);let N=await l(z,G,{writes:0},{operation:"refresh",rowId:Z},async(D)=>{let P=T9(Z,D.row(Z));if(J0("refresh",P),!P.hasEntry)D.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await D.commitConfig(),P=T9(Z,D.row(Z));if(w(P)!==W)return{keyNow:w(P)};let O=await X.refuse?.(P);if(O!==void 0)return{refused:O};return{row:P,credential:P.credential,credentialEpoch:P.credentialEpoch,identity:P.identity}});if("refused"in N)return{status:"refused",rowId:Z,reason:N.refused};if("keyNow"in N){if(await G.releaseAll(),U>=1)throw S("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);W=N.keyNow;continue}V=N;break}if(H9(V.credential.lastRefreshedAt,z.now()))throw w5(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let H;try{H=await J(V.credential,V.row)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof H?.refresh!=="string"||!H.refresh.trim())throw S("refresh",Z,"provider","the provider returned no refresh token",!0);let q=H.providerState===void 0?void 0:n0(z.providerState,"refresh",Z,H.providerState,"the provider state the provider returned"),j=await l(z,G,Q,{operation:"refresh",rowId:Z},async(U)=>{let F=U.row(Z),N=U.entry(Z);if(!F||F.invalid||!N||N.credentialEpoch!==V.credentialEpoch||F.identity!==V.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`});J0("refresh",F);let D=await X.refuse?.(F);if(D!==void 0)return{refused:D};let P=z.now(),O=F.credential?.type==="oauth"?F.credential.lastRefreshedAt:void 0;if(H9(O,P))throw w5(Z);let L={type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires},C=F.identity!==void 0&&H.identity!==void 0&&F.identity!==H.identity?{expectedIdentity:F.identity,returnedIdentity:H.identity}:void 0,T=C?{mark:tz(),enabled:!1,reason:`${v2}${JSON.stringify(C)}`}:void 0,K=F.identity===void 0&&H.identity?H.identity:void 0,M=await f4($,U,Z,L,{stamp:L1(O,P),transition:T,identity:K,...q!==void 0?{providerState:A1(z.providerState,"refresh",Z,F.providerState,q)}:{}});if(T!==void 0)O1(U,Z,T),await U.commitConfig();let _=F.identity;if(K!==void 0)N2(U,Z,K),_=K,await U.commitConfig();return{stored:M,identity:_,contradiction:C,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 U=X.onPersisted;await H0("refresh",()=>U(Z,j.stored),!0)}catch(U){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:U})}return{status:"rotated",rowId:Z,credential:j.stored,...j.identity!==void 0?{identity:j.identity}:{}}})}import{isDeepStrictEqual as u5}from"node:util";var u4=Object.freeze(["version","accounts",v]);function w4($){let Z={};for(let[J,X]of Object.entries($))if(!u4.includes(J))m4(Z,J,X);return Z}function m4($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function ez($,Z){let J={};for(let[X,z]of Object.entries($))if(u4.includes(X)||X==="commonAuthLimits")m4(J,X,z);else if(Object.hasOwn(Z,X))m4(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))m4(J,X,z);return J}function _9($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var $G=new p5;function l5($){return c5($.ctx.configPath)}async function c5($){let Z=async([X=$]=[])=>{let z=await H5(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:w4(z.config)}},J=z0?await Z():await $G.read([$],Z);return structuredClone(J)}async function d5($,Z,J={}){o("updateSettings");let{ctx:X}=$,z=J.onFailure;return i(X,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let B=G.held.length;try{for(let N of X.storeLocks)await G.acquire(N);let Y=await t(X);if(Y.status!=="ready")throw Y0(Y,"updateSettings",void 0);let W=w4(Y.config),V=structuredClone(W),H=await H0("updateSettings",()=>Z(V)),q=H===void 0?V:H;if(!A(q))throw _9("the settings mutator must produce an object");let j=u4.filter((N)=>Object.hasOwn(q,N));if(j.length>0)throw _9(`settings cannot set the pool-owned key(s) ${j.join(", ")}`);if(Object.hasOwn(q,"commonAuthLimits")&&(!Object.hasOwn(W,"commonAuthLimits")||!u5(q.commonAuthLimits,W.commonAuthLimits)))throw _9("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let U=ez(Y.config,q);if(u5(w4(U),W))return{settings:W,outcome:"unchanged"};let F={operation:"updateSettings",rowId:void 0};return await q0(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",F),await G.assertAll()}}),Q.writes++,await X.onStep?.("after-config-write",F),{settings:w4(U),outcome:"updated"}}finally{await G.releaseTo(B)}})}var n5=new Map;function ZG($){let Z=n5.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},n5.set($,Z);return Z}function s5($){if($.status==="ready")return{status:"ready",schemaVersion:z2,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function R1($){let Z=ZG($.configPath),J={...S9,...$.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 L9(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(W,V)=>z.fire(W,V)},Q=$.coalesceQuota?new O9(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,B=(W,V,H)=>Q?Q.record(W,V,H):R4(G,W,V,H);G.publishQuota=B;let Y=(W)=>{if(W.status==="ready"&&Q)return{...W,rows:Q.overlay(W.rows)};return W};return{async load(){let W=Y(await t(X));if(W.status==="ready"){for(let V of W.rows)if((V.candidate||V.torn&&V.enabled)&&V.type==="oauth"&&V.needsFirstReading)z.fire(V.id,"load")}return s5(W)},async read(){return s5(Y(await t(X)))},async initialize(W={}){return{status:await U5(X,W.dropKeys??[])}},add:(W,V)=>M5(G,W,V),publishRoster:(W,V)=>y5(G,W,V),publication:(W)=>b5(G,W),replace:(W,V,H,q)=>L5(G,W,V,H,q),rotate:(W,V,H,q)=>O5(G,W,V,H,q),updateProviderState:(W,V,H,q)=>D5(G,W,V,H,q),disable:(W,V,H)=>_5(G,W,V,H),enable:(W,V)=>S5(G,W,V),remove:(W,V)=>A5(G,W,V),reorder:(W,V)=>E5(G,W,V),readSettings:()=>l5(G),updateSettings:(W,V)=>d5(G,W,V),updateLimitsNamespace:(W,V)=>j5(G,W,V),recordIdentity:(W,V,H,q)=>R5(G,W,V,H,q),refresh:(W,V,H)=>m5(G,W,V,H),recordQuota:B,close:()=>Q?.close()??Promise.resolve(),dispose:()=>Q?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var JG=[/\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 R9($={}){let{redactStrings:Z}=p4({...$,extraValuePatterns:[...JG,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class n extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var i5=/^[a-z][a-z0-9-]{0,63}$/,A9={code:"action-failed",text:"That action failed."},XG=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 I1($){if($ instanceof n)return{code:i5.test($.code)?$.code:A9.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:XG.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return A9}var a5="This cannot be undone. Continue?",zG=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function GG($){let Z=$.toLowerCase().replace(/[-_]/g,"");return zG.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function QG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function E9($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>E9(z,`${Z}[${G}]`,J));if(!QG($))return $;let X={};for(let[z,G]of Object.entries($)){if(GG(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:E9(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function r5($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=E9($,"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 YG($){return{value:String($.value),label:String($.label)}}function BG($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(YG),...$.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 I9($){if($.irreversible===!0)return{message:$.confirm||a5,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function o5($){let Z=I9($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(BG),...Z?{confirm:Z}:{}}}function WG($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function VG($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:WG($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(o5)}}function HG($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(VG),actions:(Z.actions??[]).map(o5),...Z.facts!==void 0?{facts:Z.facts}:{}}}function t5($,Z,J){return{command:$,title:Z,sections:J.map(HG)}}function e5($,Z,J,X){return r5({command:$,menu:t5($,Z,J)},$,X)}function $Z($,Z,J,X,z){return r5({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:i5.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:t5($,Z,J)},$,z)}var YZ="disabled from the command menu";function qG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function S0($){return qG($)?{...$}:{}}function UG($){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 jG($,Z){return $.label??Z??$.id}function l4($,Z){return Y2($.quota)?h0($.quota,Z):void 0}function BZ($,Z){return`${$} ${Z}${$===1?"":"s"}`}var n2="Actions";function FG($){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 ZZ($,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 JZ($){return I1($).text}function x9($){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 NG($){let{store:Z}=$,J=await Z.read(),X=await x9($).read(),z=await $.routing?.vaultOrder?.();return{load:J,rows:UG(J),settings:X,...z?{vault:z}:{}}}function c4($,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:jG($,J)}}function DG($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((H)=>H.id),Q=FG(Z.load),B=Z.rows.filter((H)=>H.enabled).length,Y=Z.rows.map((H,q)=>{let{account:j,name:U}=c4(H,$),F=[H.type==="api"?"API key":"OAuth",...j.identity!==void 0?[j.identity]:[],...!H.invalid&&!H.enabled&&H.disabledReason?[`disabled: ${H.disabledReason}`]:[]].join(" · "),N=H.invalid?"invalid":H.enabled?"enabled":"disabled",D=[];if(!H.invalid&&H.enabled)D.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(H.id,YZ,z),`Disabled ${U}.`}});if(!H.invalid&&!H.enabled)D.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(H.id,z),`Enabled ${U}.`}});if(G.length>1)D.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((P,O)=>({value:String(O+1),label:String(O+1)})),value:String(q+1)}],run:async({values:P})=>{let O=Number(P.position),L=G.filter((T)=>T!==H.id);return L.splice(O-1,0,H.id),(await J.reorder(L,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return D.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(H.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:H.id,label:U,detail:F,group:"Accounts",status:N,account:j,actions:D}}),W=$.accounts?.login,V=[];if(W&&!Q)V.push({id:"add",label:W.label??"Add account",group:n2,knobs:W.knobs??[],run:async({values:H,invocation:q})=>{let j=await W.run(H,q);if(j.status==="cancelled")return{ok:!1,text:j.message??"Login cancelled."};if(j.status==="ready"){let U=await J.add(j.account,z);return ZZ(j.account.label??U.id,U)}return j.completion.then(async(U)=>{if(!U){q.notify("Login cancelled.","warning");return}let F=await J.add(U,z);q.notify(ZZ(U.label??F.id,F))},(U)=>{q.notify(`Adding the account failed: ${JZ(U)}`,"error")}).catch((U)=>{q.notify(`Adding the account failed: ${JZ(U)}`,"error")}),j.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${BZ(Z.rows.length,"account")}, ${B} enabled`],items:Q?[]:Y,actions:V}}}function PG($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(V,H)=>{if($.quota?.check)await $.quota.check(V,H);else{for(let q of V)$.store.requestReading(q);await $.store.pullsSettled()}},Q=Z.rows.filter((V)=>V.candidate),B=Q.map((V)=>{let{account:H,name:q}=c4(V,$),j=l4(V,J);return{id:V.id,label:q,group:z,status:y0(j,{now:X,form:"compact"}),detail:y0(j,{now:X,form:"full"}),account:H,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([V.id],U),`Checked quota for ${q}.`}}]}}),Y=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:H}=c4(V,$),q=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",j=y0(l4(V,J),{now:X,form:"compact"});return`${H} (${q}): ${j}`}),W=[];if(Q.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:n2,run:async({invocation:V})=>{let H=Q.map((q)=>q.id);return await G(H,V),`Checked quota for ${BZ(H.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:B,actions:W}}}async function KG($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new n("vault-invalid-order",J.message,{cause:J});throw J}}function k9($){return new n("vault-invalid-order",$)}function CG($){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 k9(`"${G}" is not a vault account.`);if(Q.length>1)throw k9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let B=Q[0].id;if(z.includes(B))throw k9(`"${G}" names an account already in the order.`);z.push(B)}return z}}}function MG($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=x9($),Q=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=S0(Z.settings.routing).mode,Y=typeof B==="string"&&Q.some((D)=>D.value===B)?B:"ordered",W=GZ(Y),V=Z.vault?CG(Z.vault):void 0,H=V?V.ids:Z.rows.map((D)=>D.id),q=(D)=>V?V.nameOf(D):D,j=QZ(H,W.placement,$.routing?.formerMainId??zZ),F=[`Mode: ${Q.find((D)=>D.value===Y)?.label??Y}`];if(H.length>0)F.push(`${V?"Vault account order":"Roster order"}: ${H.map(q).join(", ")}`);if(W.mode==="ordered"&&j.join()!==H.join())F.push(`Tried in order: ${j.map(q).join(", ")}`);let N=[{id:"mode",label:"Change mode",group:n2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:Y}],run:async({values:D})=>{let P=String(D.mode);return await G.update((O)=>{O.routing={...S0(O.routing),mode:P};return}),`Routing mode set to ${Q.find((O)=>O.value===P)?.label??P}.`}}];if(H.length>1)N.push({id:"order",label:"Set order",group:n2,knobs:[{kind:"text",id:"order",label:V?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:V?H.map(V.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:D})=>{let O=String(D.order).split(V?/[,\n]+/:/[\s,]+/).map((C)=>C.trim()).filter((C)=>C.length>0),L=Z.vault&&V?await KG(Z.vault,V.resolve(O)):await J.reorder(O,z);return L.outcome==="unchanged"?"The order is unchanged.":`Order set to ${L.ids.map(q).join(", ")}.`}});if($.routing?.sameAccountWait){let P=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],O=S0(Z.settings.routing).maxSameAccountWait,L=String(O===0||O==="max"?O:15),C=(T)=>P.find((K)=>K.value===T)?.label??T;F.push(`Longest wait on the same account: ${C(L)}`),N.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:n2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:P,value:L}],run:async({values:T})=>{let K=String(T.maxSameAccountWait),M=K==="max"?"max":Number(K);return await G.update((_)=>{_.routing={...S0(_.routing),maxSameAccountWait:M};return}),`Longest wait on the same account set to ${C(K)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:F,actions:N}}}function LG($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of l4(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function OG($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of l4(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,XZ(G));return(z)=>X.get(z)??z}function TG($,Z){let J=x9($),X=S0(Z.settings.killswitch),z=X.enabled===!0,G=S0(X.accounts),Q=LG($,Z),B=OG($,Z),Y=z?"on":"off",W=Z.rows.map((V)=>{let{account:H,name:q}=c4(V,$),j=S0(G[V.id]),U=Q.filter((F)=>typeof j[F]==="number");return{id:V.id,label:q,group:`Floors · killswitch ${Y}`,status:U.length===0?"no floors":U.map((F)=>`${B(F)} ≥${j[F]}%`).join(" · "),account:H,actions:[{id:"floors",label:"Set floors",knobs:Q.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${B(F)}`,min:0,max:100,...typeof j[F]==="number"?{value:j[F]}:{}})),run:async({values:F})=>{return await J.update((N)=>{let D=S0(N.killswitch),P=S0(D.accounts),O=S0(P[V.id]);for(let L of Q){let C=F[L];if(typeof C==="number")O[L]=C;else if(C===null)delete O[L]}if(Object.keys(O).length>0)P[V.id]=O;else delete P[V.id];if(Object.keys(P).length>0)D.accounts=P;else delete D.accounts;N.killswitch=D;return}),`Floors updated for ${q}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${Y}`],items:W,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:n2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:V})=>{let H=V.enabled===!0;return await J.update((q)=>{q.killswitch={...S0(q.killswitch),enabled:H};return}),`Killswitch ${H?"on":"off"}.`}}]}}}async function WZ($){let Z=await NG($);return[DG($,Z),PG($,Z),MG($,Z),TG($,Z)]}var _G=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),b9=["accounts","quota","routing","limits"];function VZ($,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 SG($,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 AG($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=SG(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function EG($,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 K2($){let Z=$.logger??d("commands"),J=R9($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},B=b9.filter((q)=>!Q[q]);for(let q of b9)if(Q[q]&&$[q]!==void 0)throw Error(`the ${q} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(B.length>0&&!Y)throw Error(`a store is required for the built-in ${B.join(", ")} section${B.length>1?"s":""}`);let W=new Set;for(let q of G){if(_G.has(q.id)||W.has(q.id))throw Error(`extra section id ${q.id} is taken`);W.add(q.id)}async function V(q,j,U,F){try{return{id:q,slot:j,title:U.title,content:await U.build(F)}}catch(N){return Z.warn("command menu section failed to build",{command:$.command,section:q,error:J(N instanceof Error?N.message:String(N))}),{id:q,slot:j,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function H(q){let j=Y&&B.length>0?await WZ({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.settings?{settings:$.settings}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let F of b9){let N=Q[F];if(N)U.push(await V(F,F,N,q));else{let D=j.find((P)=>P.slot===F);if(D)U.push(D)}}if($.cache)U.push(await V("cache","cache",$.cache,q));if($.diagnostics)U.push(await V("diagnostics","diagnostics",$.diagnostics,q));for(let F of G)U.push(await V(F.id,"extra",F,q));return U}return{command:$.command,async open(q){let j=VZ(q,J);return e5($.command,$.title,await H(j),X)},async apply(q,j){let U=VZ(j,J),F=async(L)=>$Z($.command,$.title,await H(U),L,X),N=q.command===$.command?EG(await H(U),q):void 0;if(!N)return F({ok:!1,code:"unavailable",text:"That action is no longer available."});let D=I9(N);if(D&&q.confirmed!==!0)return F({ok:!1,code:"needs-confirmation",text:D.message,needsConfirmation:!0});let P=AG(N.knobs??[],q.values);if("problem"in P)return F({ok:!1,code:"invalid-input",text:P.problem});let O;try{let L=await N.run({values:P.values,...q.itemId!==void 0?{itemId:q.itemId}:{},invocation:U});O=typeof L==="string"?{ok:!0,text:L}:{ok:L.ok,text:L.text,...L.ok?{}:{code:L.code??"refused"}}}catch(L){let C=I1(L);Z.warn("command menu action failed",{command:$.command,section:q.sectionId,action:q.actionId,code:C.code,error:J(L instanceof Error?L.message:String(L))}),O={ok:!1,...C}}return F(O)}}}function RG($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function IG($){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(!RG(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 x($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function HZ($,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 kG($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function d4($,Z,J){return $.excludedForRequest.some((X)=>x(X.account,Z)&&HZ(X.scope,J))}function s2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>x(X.account,Z.account)&&HZ(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)=>x(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!x(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:d4($,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 f9=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function C2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function n4(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!x(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(C2)):C2(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[B,Y]of $)if(Y.lastAcceptedAt<Q)G=B,Q=Y.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function s4($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var k1=3621000;function s0($){return $===0||$===15||$==="max"?$:15}function x1($){let Z=s0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!x(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=C2(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 xG}from"node:crypto";function y9($,Z){let J=xG("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}var qZ=691200000;function i4($,Z){return UZ($,Z,!1)}function UZ($,Z,J){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let X;for(let z of $.candidates){if(!x(z.account,z.readingAccount)||z.identity!==void 0&&z.readingIdentity!==void 0&&z.identity!==z.readingIdentity){if(J)return;continue}let G=z.windows.filter((W)=>W.blockedBy&&s4(W.scope,$.effectiveModel,$.familyOf));if(!G.length){if(J)return;continue}let Q=G.map((W)=>{let V=W.reset,H=V?.observedAt??V?.checkedAt;return V&&H!==void 0&&Number.isFinite(H)&&Z-H<=$.maxAgeMs&&Number.isFinite(V.at)&&V.at>Z?V.at:void 0});if(Q.some((W)=>W===void 0)){if(J)return;continue}let B=Math.max(...Q);if(X&&X.resetAt<=B)continue;let Y=G.some((W)=>W.blockedBy!=="exhausted"&&W.reset?.at===B);X={account:z.account,resetAt:B,checkpoint:{accountKey:{...z.account},decidedAt:Z,blockers:Y?[]:G.flatMap((W)=>W.blockedBy==="exhausted"&&W.reset?[{window:W.window,resetAt:W.reset.at}]:[])}}}return X}function jZ($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function FZ($,Z){let J=$.scan,X=J?.waitForReset?.jitterMs;if($.reason!=="quota"||!J||X===void 0||!Number.isInteger(X)||X<0)return;let z=UZ(J,Z,!0);if(!z)return;return{kept:z,delayMs:Math.ceil((z.resetAt-Z)/1000)*1000+X}}function NZ($,Z,J){return jZ($,Z)&&s0($.scan?.maxSameAccountWait)===0&&!FZ($,J)}function DZ($,Z,J,X){let z=FZ(X,$.now);if(!z&&!jZ(X,Z))return;let G=X.scan,Q=s0(G?.maxSameAccountWait),B=z?.kept??(G&&i4(G,$.now)),Y=B?B.resetAt-$.now:300000,W=G?.activity,V=G?.accountKey??$.attempted,H=W&&V&&x(W.accountKey,V)?C2(W.ttlMs)||300000:300000,q=z?.delayMs??Math.min(Y,Q==="max"?H:900000),j=!z&&Q===0||$.host==="pi"&&$.wake?.kind==="terminal",U=j?B?Y:void 0:q,F=Z.refusals.quota[$.host],N={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":j?"json-412":F.family,messageKey:X.messageKey??F.messageKey,retryable:$.host!=="pi"&&!j,hostRetry:$.host==="pi"||j?"veto":"leave",history:J,...U===void 0?{}:{retryAfterMs:U},...B?{resetAt:B.resetAt}:{}};if(!B||j||$.host==="opencode1")return N;let D={delayMs:q,retryAfterMs:q,resetAt:B.resetAt,target:$.now+q,checkpoint:B.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...D,action:"wait-then-reselect"};if($.hostPhase!=="retry")return N;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||z&&Number.isNaN($.remainingRetries)||q>(z?qZ:k1))return N;return{...D,action:"hold",account:B.account}}function h9($,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 PZ($,Z,J,X){let{checkpoint:z,target:G}=$;if(!x(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let Q=(B)=>{let Y=B.resetAt;return B.confirmed&&Y!==void 0&&Number.isFinite(Y)&&Y<=G&&z.blockers.some((W)=>W.window===B.window&&Number.isFinite(W.resetAt)&&Y<=W.resetAt)};return J.filter((B)=>Q(B)&&J.filter((Y)=>Y.confirmed&&Y.window===B.window).every(Q)).map((B)=>B.window)}function a4($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function i2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function g0($,Z,J,X,z){let G=z&&DZ($,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 bG($,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((W)=>!a4(W.resetAt,$.now)))return;let Q=Math.max(...z.map((W)=>W.resetAt)),B=Z.shortLimit.jitter==="session-sha256"?y9($.sessionId,Q-$.now):Q-$.now,Y=$.now+B;if(!Number.isFinite(Y)||Y>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&B>k1||G.maxDelayMs!==void 0&&B>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:B,retryAfterMs:B,target:Y,checkpoint:h9(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":i2($,Z),history:J}}function fG($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=s2(J,{type:"blocked",clockNow:$.clockNow});let Q=X.map((j)=>{let U=j.blockers.filter((F)=>!(F.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(U.some((F)=>!a4(F.until,$.now)))return;return U.length?{candidate:j,time:Math.max(...U.map((F)=>F.until))}:void 0}).filter((j)=>j!==void 0).reduce((j,U)=>!j||U.time<j.time?U:j,void 0),B=Q?Q.time-$.now:X.some((j)=>j.blockers.some((U)=>U.kind!=="soft"))?z.hardFallbackMs:void 0,Y=$.poolWaitBudgetMs??z.budgetMs,W=$.clockNow-(J.blockedSince??$.clockNow);if(Y>0&&(W>=Y||B!==void 0&&B>Y))return g0($,Z,J,"quota",$.terminal);let V=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(V<=0)return g0($,Z,J,"incomplete");if(B===void 0)return g0($,Z,J,"quota",$.terminal);let H=Math.min(B,V,Y>0?Y-W:Number.POSITIVE_INFINITY),q=Q?.candidate??X[0];if(!q)return;return{action:"wait-then-reselect",delayMs:H,target:$.now+H,checkpoint:h9(q.account,$.now,q.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:i2($,Z),history:J}}function g9($,Z){let J=$.history,X=(K,M=$.phase==="pre-send"?!0:$.failureRetryable??!0,_="leave")=>({action:"pass",reason:K,retryable:M,hostRetry:_,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=s2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&x($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((K)=>K.admitted),Q=G.filter((K)=>!d4(J,K.account,$.requestScope)),B=Q.find((K)=>$.attempted&&x(K.account,$.attempted)),Y=$.signalApplicable!==!1&&$.signal&&$.attempted&&x($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&Y?.kind==="model-unavailable"&&B)return{action:"exclude-for-request",account:B.account,scope:$.requestScope,effects:f9,reason:"model-unavailable",retryable:!0,hostRetry:i2($,Z),history:J};if(G.length&&!Q.length)return g0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||NZ($.terminal,Z,$.now))?g0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let K=$.wake,M=Q.find((g)=>x(g.account,K.checkpoint.accountKey)),_=M?.confirmedBlockers??(M&&Y&&x(Y.account,M.account)?Y.windows:[]),R=M?PZ(K,M.account,_,$.now):[],I=$.hold,k=K.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&K.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&K.target-K.checkpoint.decidedAt<=I.maxWaitMs;if(M&&Number.isFinite(K.target)&&K.target>=K.checkpoint.decidedAt&&$.now>=K.target&&k&&M.blockers.every((g)=>g.until!==void 0&&Number.isFinite(g.until)&&g.until<=$.now)&&(M.ready||_.some((g)=>g.confirmed))&&_.filter((g)=>g.confirmed).every((g)=>R.includes(g.window)))return{action:"retain",account:M.account,liftedWindows:R,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:s2(J,{type:"selected"})}}if($.credentialRecovery&&B)return{action:"retain",account:B.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:i2($,Z),history:J};let W=Z.unconfirmedRetainLimit,V=$.unconfirmedRetainCount,H=z===429&&W!==void 0&&V!==void 0,q=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(Y?.kind==="payment-cap"||z===402&&Y?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!Y&&!H&&!$.terminal&&(q.attributedLimitOnly||z===void 0||!q.statuses.includes(z)))return X("unhandled-failure");let j=Q.find((K)=>$.selection&&x(K.account,$.selection.account)&&K.placementEligible),U=j&&(j.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&Q.length===1&&j.blockers.length>0&&j.blockers.every((K)=>K.kind==="soft")),F=U&&(!$.attempted||!x(j.account,$.attempted))?j:void 0,N=(K,M="ready-alternative")=>({action:"reroute",account:K.account,pin:$.selection?.pin??"preserve",reason:M,retryable:!0,hostRetry:i2($,Z),history:s2(J,{type:"selected"})}),D=$.phase==="pre-send"?B??Q.find((K)=>$.selection&&x(K.account,$.selection.account)):B,P=(D?.confirmedBlockers??($.phase==="after-limit"?Y?.windows:void 0)??[]).filter((K)=>K.confirmed);if(P.length){if(Z.shortLimit.preference==="ready-alternative-first"&&F)return N(F);let K=bG($,Z,J,D,P);if(K)return K}let O=Z.unknown[$.host],L=$.phase==="after-limit"&&!P.length&&(z===429||Y?.kind==="rate-limit"||Y?.kind==="quota-exhausted"||Y?.kind==="capacity"),C=H&&V>=W;if(L&&B&&(O.affinity==="always"||$.affinity==="sticky")){if(H&&C){if(F)return N(F,"unconfirmed-retry-limit")}else if(H||O.action==="retain"){let K=[...$.retryHintsMs??[],Y?.retryAfterMs].filter((M)=>M!==void 0&&Number.isFinite(M)&&(H||M>=0));return{action:"retain",account:B.account,reason:"unconfirmed-limit",...H?{retryMs:Math.min(60000,...K.map((M)=>Math.max(0,M))),incrementUnconfirmedRetain:!0}:O.hint==="minimum"?{retryMs:Math.min(O.defaultMs,...K)}:{},retryable:!0,hostRetry:i2($,Z),history:J}}else if(O.action==="pass")return X("unconfirmed-limit")}if(F)return N(F);if($.phase==="pre-send"&&U)return N(j);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&j&&Q.every((K)=>!K.ready)&&Q.every((K)=>K.blockers.length>0&&K.blockers.every((M)=>M.kind==="hard")))return N(j);let T=fG($,Z,J,Q);if(T)return T;if($.phase==="pre-send"&&!Q.length)return g0($,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"&&B)return{action:"retain",account:B.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let K=$.phase==="pre-send"&&Q.length>0&&Q.every((R)=>!R.ready),M=Q.filter((R)=>R.placementEligible),_=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&M.length>0&&M.every((R)=>!R.ready&&R.blockers.length>0&&R.blockers.every((I)=>I.cause==="payment-balance"&&a4(I.until,$.now)));if(_||K||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let R=(_?M:Q).flatMap((I)=>I.blockers.map((k)=>k.until)).filter((I)=>a4(I,$.now));return g0($,Z,J,"quota",{source:"pool",reason:"quota",..._?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:R.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...R)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return g0($,Z,J,$.terminal.reason,$.terminal);if(Y?.kind==="auth"||Y?.kind==="account-access")return g0($,Z,J,"auth");if(Y||z===429||Q.some((K)=>K.blockers.length))return g0($,Z,J,"quota");return X("no-override")}function a2($){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 r2=({resetAt:$,now:Z})=>a2($-Z);var w9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class f1 extends Error{[w9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class y1 extends Error{[w9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function m9($){let Z=$&&typeof $==="object"&&Reflect.get($,w9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function i0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var M2=($)=>Number.isSafeInteger($)&&$>=0,v9=($)=>typeof $==="number"&&Number.isFinite($),KZ=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",b1=($,Z)=>Array.isArray($)&&$.every(Z);function MZ($,Z){return i0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function CZ($,Z){if(!i0($)||!i0($.scope))return!1;let J=$.scope;return MZ($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function yG($,Z){return $.namespace===Z&&typeof $.generation==="string"&&M2($.revision)&&M2($.lowWatermark)&&b1($.marks,(J)=>i0(J)&&CZ(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&b1(J.entries,(X)=>i0(X)&&KZ(X.cause)&&v9(X.until)&&v9(X.evidenceAt)&&M2(X.baseRevision)&&M2(X.committedRevision)))&&b1($.tombstones,(J)=>i0(J)&&CZ(J.key,Z)&&M2(J.revision)&&KZ(J.cause))&&b1($.operationIds,(J)=>i0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&M2(J.revision))&&b1($.access,(J)=>i0(J)&&MZ(J.account,Z)&&v9(J.eligibilityStateUpdatedAt)&&M2(J.committedRevision))}class h1{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(!i0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new y1,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!yG($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new f1,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 hG=[/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],gG=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 o2($){let Z=$.toLowerCase();return Z.includes("too_many_requests")||Z.includes("exhausted")||Z.includes("unavailable")||hG.some((J)=>J.test($))||gG.test($)}class r4 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function u9($){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 B=Object.freeze({labels:Object.freeze(Q),reset:G}),Y;try{Y=z(B)}catch{throw new r4(X)}if(typeof Y!=="string"||o2(Y))throw new r4(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var vG=/[^\s@]+@[^\s@]+\.[^\s@]+/;function p9($){return vG.test($)}function l9($){return p9($)||o2($)?"this account":$}class c9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function o4($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-d9(Z);return J>=0?Math.ceil(J/1000):void 0}function d9($){return Number.isFinite($)&&$>=0?$:0}function OZ($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function wG($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function TZ($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${a2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${wG(Z)}`}function _Z($,Z,J){let X=OZ($),z=X===void 0?void 0:r2({resetAt:X,now:Z}),G=o4($.retryAfterMs,$.noticeDelayMs);return TZ($.family,z,G,J)}function mG($,Z){let J=$.now+d9($.noticeDelayMs??0),X=()=>_Z($,J,Z);try{let z=OZ($),G=z===void 0?void 0:($.messages?.formatReset??r2)({resetAt:z,now:J}),Q=o4($.retryAfterMs,$.noticeDelayMs),B=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(l9):[]),reset:G,retryIn:!Z&&Q!==void 0?a2(Q*1000):void 0}),Y=$.messages?.render($.messageKey,B,Z);return typeof Y==="string"?Y:TZ($.family,G,Q,Z)}catch{return X()}}function LZ($,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 n9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=LZ($.family,mG($,Z));if(Z&&(o2(X)||p9(X))){let Q=$.now+d9($.noticeDelayMs??0);X=LZ($.family,_Z($,Q,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new c9(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=o4($.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 a0($,Z){return x($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function s9($,Z){if(!a0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function i9($,Z,J){if(!a0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var a9=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 t4($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((Q,B)=>{if(!Q)return B;if($==="latest-evidence"&&B.evidenceAt!==Q.evidenceAt)return B.evidenceAt>Q.evidenceAt?B:Q;return B.committedRevision>Q.committedRevision?B:Q},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,Q)=>J<G.until&&!z.some((B,Y)=>Y!==Q&&B.until>=G.until&&B.baseRevision>=G.baseRevision&&(B.until>G.until||B.baseRevision>G.baseRevision||B.committedRevision>G.committedRevision||B.committedRevision===G.committedRevision&&Y<Q))).sort((G,Q)=>G.committedRevision-Q.committedRevision)}function g1($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var AZ=1024;function r9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function e4($,Z){return r9($.cause)===void 0||$.cause===Z}function EZ($){return JSON.stringify([s($.key),r9($.cause)])}function A0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function pG($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function s($){let Z=$.scope;return JSON.stringify([pG($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function SZ($){return JSON.stringify([$.producerId,$.operationId])}function L2($,Z){let J=new Map;for(let Y of $.tombstones){let W=s(Y.key),V=J.get(W);if(V)V.push(Y);else J.set(W,[Y])}let X=$.marks.flatMap((Y)=>{let W=J.get(s(Y.key)),V=t4(Y.mergeLaw,W?Y.entries.filter((H)=>!W.some((q)=>e4(q,H.cause)&&H.baseRevision<q.revision)):Y.entries,Z);return V.length?[{...Y,entries:V}]:[]}),z=$.lowWatermark,G=(Y)=>{let W=[...Y].sort((H,q)=>H.revision-q.revision),V=Math.max(0,W.length-AZ);for(let H of W.slice(0,V))z=Math.max(z,H.revision+1);return W.slice(V)},Q=G($.tombstones),B=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:Q,operationIds:B,lowWatermark:z}}function O2($,Z,J){let X=L2($,J.now),z=[];for(let G of Z){let Q=(N)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:N})};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 B=J.bindings.find((N)=>x(N.account,G.binding.account));if(!B){Q("unknown-account");continue}let Y=i9(G.binding,B,J.authorizeEpoch);if(Y){Q(Y);continue}let W=X.operationIds.find((N)=>SZ(N)===SZ(G));if(W){z.push({...W,status:"duplicate"});continue}let V=B.account,H=X.revision+1,q=[...X.marks],j=[...X.tombstones],U=[...X.access];if(G.type==="mark"){let N={account:V,scope:G.scope,window:G.window},D=s(N),P=q.find((L)=>s(L.key)===D);if(j.some((L)=>G.baseRevision<L.revision&&e4(L,G.cause)&&s(L.key)===D)){Q("cleared");continue}if(P&&P.mergeLaw!==G.mergeLaw){Q("merge-law-conflict");continue}let O=t4(G.mergeLaw,[...P?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:H,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(q=q.filter((L)=>s(L.key)!==D),O.length)q.push({key:N,mergeLaw:G.mergeLaw,entries:O})}else if(G.type==="clear"){let N=r9(G.cause),D=G.keys.map((L)=>({...L,account:V})).filter((L)=>G.cause===void 0||!q.some((C)=>s(C.key)===s(L)&&C.entries.some((T)=>T.cause!==G.cause))),P=new Set(D.map(s)),O=G.evidenceAt;if(O!==void 0&&q.some((L)=>P.has(s(L.key))&&L.entries.some((C)=>C.evidenceAt>O))){Q("newer-evidence");continue}q=q.filter((L)=>!P.has(s(L.key))),j=j.filter((L)=>!P.has(s(L.key))||N!==void 0&&L.cause!==N);for(let L of new Map(D.map((C)=>[s(C),C])).values())j.push({key:L,revision:H,...N===void 0?{}:{cause:N}})}else{let N={account:V,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:H},D=U.find((P)=>x(P.account,V));U=U.filter((P)=>!x(P.account,V)),U.push(D?g1(D,N):N)}let F={producerId:G.producerId,operationId:G.operationId,revision:H};X=L2({...X,revision:H,marks:q,tombstones:j,access:U,operationIds:[...X.operationIds,F]},J.now),z.push({...F,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as lG}from"node:fs";import{basename as RZ,dirname as IZ,join as cG,resolve as dG}from"node:path";function v1($){let Z=dG($),J=[RZ(Z)],X=IZ(Z);for(;;)try{return cG(lG.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let Q=IZ(X);if(Q===X)return Z;J.push(RZ(X)),X=Q}}class E0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as aG}from"node:crypto";import{isDeepStrictEqual as xZ}from"node:util";import{AsyncResource as nG}from"node:async_hooks";import{randomUUID as kZ}from"node:crypto";import{isDeepStrictEqual as sG}from"node:util";var iG=new nG("common-auth-limits-recovery");class w1{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=iG.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 T2{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=sG($,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)=>s(z.key)===s(X.key)&&e4(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=kZ();let z=$??A0(J,this.missingGeneration??kZ()),G=[...this.retained(Z),z],Q=new Map,B=new Map,Y=new Map,W=new Map,V=0;for(let q of G){V=Math.max(V,q.revision,q.lowWatermark);for(let j of q.marks){let U=s(j.key),F=Q.get(U);if(F&&F.mergeLaw!==j.mergeLaw)throw Error("limits-recovery-merge-law-conflict");Q.set(U,{...j,entries:[...F?.entries??[],...j.entries]});for(let N of j.entries)V=Math.max(V,N.baseRevision,N.committedRevision)}for(let j of q.tombstones){let U=EZ(j),F=B.get(U);if(!F||F.revision<j.revision)B.set(U,j);V=Math.max(V,j.revision)}for(let j of q.operationIds){let U=JSON.stringify([j.producerId,j.operationId]),F=Y.get(U);if(!F||F.revision<j.revision)Y.set(U,j);V=Math.max(V,j.revision)}for(let j of q.access){let{namespace:U,accountId:F,incarnation:N}=j.account,D=JSON.stringify([U,F,N]),P=W.get(D);W.set(D,P?g1(P,j):j),V=Math.max(V,j.committedRevision)}}let H=V+1;if(!Number.isSafeInteger(H))throw Error("limits-revision-exhausted");return L2({...z,revision:H,lowWatermark:H,marks:[...Q.values()],tombstones:[...B.values()],operationIds:[...Y.values()],access:[...W.values()]},X)}}function bZ($,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 o9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new E0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=aG(),G=new T2,Q=new h1(J,$.logger),B=new w1($.logger),Y=$.now??Date.now,W=async()=>{let j=await Z.read();if(j.status!=="ready"){if(j.status==="error"&&j.kind==="snapshot-contended")throw Error(j.reason);throw new E0("pool-not-ready")}return bZ(J,j.rows)},V=async()=>{let j=await Z.readSettings();if(j.status!=="ready")throw new E0("pool-not-ready");return Q.decode(j.settings.commonAuthLimits)},H=async(j)=>{Q.assertWritable();let U=await W(),F=await V(),N;for(let D=0;D<3;D++){let P=await W(),O=await V(),L=xZ(U,P)&&xZ(F,O);if(N={snapshot:F.snapshot??A0(J,z),bindings:U,authoritative:L},L){if(!F.replacement&&G.lost(F.snapshot,j))return B.schedule(()=>q.commit([],j)),{snapshot:G.recover(F.snapshot,j,J,Y()),bindings:U,authoritative:!1,degradedAgreement:!0};if(F.snapshot)G.remember(F.snapshot);return N}U=P,F=O}return N},q={namespace:J,read:H,subscribe:B.subscribe,async commit(j,U){Q.assertWritable();let F,N,D=()=>{if(Q.didCommit(N)&&F)G=new T2,G.remember(F.snapshot,U)};try{await X((P,O)=>{let L=bZ(J,O),C=Q.decode(P),T=C.snapshot;N=C.replacement;let K=!N&&G.lost(T,U),M=O2(K?G.recover(T,U,J,Y()):T??A0(J,z),j,{now:Y(),bindings:L,authorizeEpoch:(_,R)=>_.credentialEpoch===R.credentialEpoch});return F={...M,bindings:L,authoritative:!0,degradedAgreement:K},M.snapshot},{beforePublish:()=>Q.assertWritable(),onPublished:D})}catch(P){if(Q.assertWritable(),P instanceof b&&(P.kind==="pending-migration"||P.kind==="load-error"))throw new E0("pool-not-ready");throw P}if(!F)throw Error("Pool limits mutator was not called");return D(),G.remember(F.snapshot,U),F}};return await H(),q}function t2($){if($&&typeof $==="object"){for(let Z of Object.values($))t2(Z);Object.freeze($)}return $}function R0($){return{opencode1:$,opencode2:$,pi:$}}var _2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},fZ={..._2,action:"retain",affinity:"sticky"},hZ={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function Z6($,Z){return{auth:R0(hZ),quota:R0($),incomplete:R0(Z),"model-unavailable":R0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var $6={kind:"off"},gZ={requestEscape:"off",retryExhaustion:"terminal"},vZ={statuses:[],attributedLimitOnly:!0},yZ={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},wZ=t2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:R0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{..._2,action:"retain",hint:"minimum"},opencode2:_2,pi:{..._2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:R0(vZ),markedPool:gZ,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:Z6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),mZ=t2({evidence:"typed",markers:R0(a9),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"off",unknown:R0(_2),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:R0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:gZ,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:Z6(yZ,{...yZ,messageKey:"incomplete.timeout"})}),B2=t2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:$6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:fZ,opencode2:_2,pi:fZ},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:R0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:Z6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),uZ=t2({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:R0(_2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:vZ,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:Z6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...hZ,messageKey:"incomplete.no-account"})}),rG=t2({"confirmed-affinity":wZ,"earliest-pool-engine":mZ,"window-router":B2,"status-vault-order":uZ});import{AsyncResource as oG}from"node:async_hooks";var X6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),tG="@cortexkit/common-auth/limits-registry/schema-v",J6=1000,pZ=5000,S2=new oG("common-auth-limits"),eG={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function $Q(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(tG)&&J!==X6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,X6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,X6,Z),Z}function A2($){return JSON.stringify([$.producerId,$.operationId])}class lZ{adapter;clock;restrictive;listeners=new Set;owners=0;activity=n4();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??eG,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=m9($);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)=>x(X.account,Z.account));return J?s9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((Q)=>x(Q.account,X.binding.account)),G=this.snapshot.access.find((Q)=>x(Q.account,X.binding.account));if(!z||!a0(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);S2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,S2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=pZ)return;S2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=pZ)return;S2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+J6-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,S2.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=S2.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 A0(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=O2(L2($,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=A2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>A2(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:J6)}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=S2.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)=>A2(Q)===A2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(m9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof E0&&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(A2(z.command)))this.failed.add(A2(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(J6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=A2(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"&&x(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=J6)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)=>x(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!a0(J,$)||[...this.restrictions.values()].some((z)=>x(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>x(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=$Q(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new lZ($),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(Y){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),Y}let Q=!1,B=()=>{if(Q)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return B(),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(Y){return B(),{binding:structuredClone(Y),baseRevision:X.snapshot.revision}},enqueue(Y,W){B(),X.enqueue(Y,W)},beforeDispatch(Y){return B(),X.beforeDispatch(Y)},flush(){return B(),X.flush()},reload(){return B(),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 W2($){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 e9($){try{let J=W2($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=x1($);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 XQ}from"node:fs";import{rm as nZ}from"node:fs/promises";import{dirname as zQ,join as X7}from"node:path";import{resolveClaustrumConnectionPath as GQ}from"@cortexkit/claustrum-client";function cZ($,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 $$($){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 ZQ($){let Z=$$($.total),J=$$($.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 JQ($,Z){if(!E($))return;let J=$$($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function Z$($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function dZ($,Z){let J=cZ($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=cZ($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="individual_limit"):void 0,G=E(z)?ZQ(z):void 0,Q=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="credits"):void 0,B=JQ(Q,Z.fetchedAt),Y=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...B&&{credits:B},...B&&E(Q)&&typeof Q.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function z6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var J$="ck auth reclassify --from-registry";function G6($,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 \`${z6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${J$}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var j0=d("vault"),z7="openai-auth";var QQ={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},G7={opencode:"OpenCode",pi:"Pi"},YQ=[{selector:{category:"openai-native"},operation:"read"}];function z$($){return aZ(z7,$)}function BQ($){return`ChatGPT for ${G7[$]}`}function p1($){return X7(zQ($),"openai-auth-vault")}function r0($,Z){return{...oZ({stateDir:$,host:Z}),rosterPath:X7($,`${Z}-roster.json`)}}var Q7=2000,HD=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],WQ={"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 ${J$} 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 qD($,Z){if($!=="vault-no-grant")return WQ[$];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: ${z6(Z)}`}function UD($){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 VQ($){let Z=$1($);return Z?Z1(Z):void 0}class HQ{host;name;paths;#Z;#$;#B=new Map;#W=new Map;#Q=new Map;#j;#J;#V;#z;#F=!1;#N=!1;#H=Promise.withResolvers();#q="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=z$($.host),this.paths=r0($.stateDir,$.host),this.#$=new Z7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:QQ,pluginId:z7,connect:()=>this.#M(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:VQ,insula:{provider:"codex",normalize:dZ},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:(Z)=>{this.#J=void 0;let J=new Set(Z.rows.map((X)=>X.routeId));for(let X of this.#Q.keys())if(!J.has(X))this.#Q.delete(X)},onDiscovery:(Z)=>this.#T(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...j0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")j0.warn(Z,J)}}})}#D(){return(this.#Z.connectionFile??GQ)()}#P(){return{connectionFile:this.#D(),storagePath:this.paths.tokenPath,logger:($)=>j0.debug("vault transport error",{errorClass:$})}}#M(){return(this.#Z.connectScoped?.()??J7(this.#P())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){if(!this.owns($))return;let X=this.#Q.get($);if(X?.source===Z&&X.reason===J)return;this.#Q.set($,{source:Z,reason:J}),j0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#L(){return this.#Z.connectEnrollment?.()??rZ(this.#P())}#X($,Z){this.#J=v0(Z),j0.warn($,{host:this.host,error:this.#J,...Z instanceof iZ&&Z.reason?{reason:Z.reason}:{}})}#Y(){if(e2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=XQ($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#Y(),Z=await tZ(this.paths,this.name);if($===this.#Y()){if(Z!==this.#q)j0.info("vault authority",{host:this.host,authority:Z});return this.#q=Z,this.#U=$,Z}return"unreadable"}enrolled(){return e2()||this.#U!==this.#Y()||this.#q!=="local"}async#O(){if(this.#U!==this.#Y())await this.authority();return this.enrolled()}start(){if(this.#F||this.#N)return;this.#F=!0,this.#$.start()}#T($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#K(){return this.#$.refresh()}firstRoster(){return this.#H.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.#K()).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.#K();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=Q6(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.#_($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#_($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await Y6(this.paths.rosterPath))?.rows.find((B)=>B.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#C($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let B=Q6(Z$(z,this.routes().find((W)=>W.id===$)?.quota),z.primary.checkedAt,!0);if(!B)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,B))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.#C($,Z)}async#C($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let B=Z?void 0:await this.#$.cachedInsulaQuota(Q);if(B!==void 0){let W=Q6(Z$(B,this.routes().find((V)=>V.id===$)?.quota),B.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#$.recordQuota($,W,Q),new Response(null,{status:200})}let Y=await u1({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:j0});return await this.recordSnapshot($,Y,!0,Q),J=void 0,new Response(null,{status:200})}catch(B){J=v0(B);let Y=B?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw B}},{site:"quota"}).catch((G)=>{J=v0(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)=>{j0.warn("vault quota poll failed",{routeId:$,error:v0(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=qQ(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($),j0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),j0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await m1(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof sZ?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 n("vault-host",X$);let $=await this.#L().catch((Z)=>{throw new n("vault-unreachable",`Could not reach the Claustrum vault (${this.#D()}): ${v0(Z)}. Is the vault running?`)});try{let Z=new eZ({client:$,paths:this.paths,proposedName:this.name,displayName:BQ(this.host),requestedGrants:YQ,...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(j0.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.#V??=(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.#V=void 0}),this.#V}async disconnect(){if(await this.authority()==="host")throw new n("vault-host",X$);await nZ(this.paths.tokenPath,{force:!0}),await nZ(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,j0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())$7({mode:"custody",auth:$,provider:"openai"})}close(){this.#N=!0,this.#H.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function qQ($){if(!$)return;let Z=h0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function B6($,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 ${$}):`,` ${z6($)}`]]}function Y7($,Z,J){let X=`${G7[$]} (${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 G$($,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?`. ${G6(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:[...B6($.name,Z),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
1
|
+
import{Ae as r8,Be as F6,Ce as X$,De as e2,Ge as aZ,Gf as _3,Ie as rZ,If as SX,Je as oZ,Jf as P6,Ke as m1,Le as tZ,Lf as AX,Mf as a1,Ne as eZ,Oe as $7,Of as s1,Pf as o0,Qe as Y6,Re as yJ,Rf as p6,Se as Z7,Te as J7,Uf as EX,Ve as nJ,Vf as EJ,We as Q4,Xe as sJ,Ye as H8,Ze as q8,_f as n1,bf as $1,cf as Z1,de as Y2,dg as U8,ee as dJ,fe as u6,fg as j8,ge as XZ,gg as F8,ie as j6,ig as RX,je as y0,jg as IX,ke as r7,le as h0,lf as ZJ,ne as zZ,ng as Q6,oe as GZ,of as r1,og as b8,pe as QZ,qg as o7,re as lJ,rf as u1,se as cJ,sf as kJ,te as S9,tf as _X,ue as d0,ve as g5,we as v5,xe as p5,ye as sZ,yg as f8,ze as iZ}from"./index-x00sxt2w.js";import{Dg as Q5,Eg as q0,Fg as Y5,Gg as F9,Hg as I0,Jg as B5,Kg as W5}from"./index-49ncs7dr.js";import{Yg as $X}from"./index-xkngfyvc.js";import{Zg as lX}from"./index-drm4dk5y.js";import{eh as l8,ih as H3,jh as Y4,kh as q3,lh as v0}from"./index-wjp3q15r.js";import{oh as p4,th as d}from"./index-td4g5dc9.js";import{Ah as FJ,Bh as T1,Ch as NJ,Fh as DJ,uh as z0,vh as G4,wh as D9,zh as jJ}from"./index-4ktepxn1.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 D1 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 v2="identity-contradicted: ",G9="duplicate-identity";function X2($,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 P1($,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 w2($,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))X2($,z.id,"duplicate-identity"),X.push(z.id);return X}function N2($,Z,J){let X=$.rosterRow(Z);if(!X)return[];return X.accountId=J,w2($,J)}import{AsyncLocalStorage as c3}from"node:async_hooks";var L4=new c3,d3=new c3;function o($){if(L4.getStore()!==void 0)throw new D1($)}function n3(){if(L4.getStore()?.storeLocksReleased===!1||d3.getStore())throw new D1("updateLimitsNamespace")}function V0($){return d3.run(!0,$)}function H0($,Z,J=!1){return L4.run({operation:$,storeLocksReleased:J&&L4.getStore()?.storeLocksReleased!==!1},async()=>await Z())}async function s3($,Z,J,X,z){if(!Z)return;try{await H0($,()=>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 V5}from"node:timers/promises";function D2($,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 K1}from"node:crypto";var v="commonAuthPool",z2=1,O0="rows",O4="retiredEpochs",C1=1,Q9=300000,h=v;function Sz($){let Z=JSON.parse(JSON.stringify($)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(A(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J(Z)}function P2($){return K1("sha256").update(Sz($)).digest("hex")}function i3($){if(!A($)||Object.keys($).length!==1||typeof $.reservation!=="string"||!$.reservation)return;return{reservation:$.reservation}}function Az($){if(!A($)||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 Z0="commonAuthProviderState";function A($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var Ez=new Set(["__proto__","constructor","prototype"]);function m2($){if(typeof $!=="string"||$.length===0)return"id must be non-empty";if($.trim()!==$)return"id must not carry surrounding whitespace";if(Ez.has($))return"id is a reserved object key";return}function Y9($){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 a3($){return $.type==="oauth"?`oauth\x00${$.refresh}`:`api\x00${$.apiKey}`}function T0($){return K1("sha256").update(a3($)).digest("hex")}function b0($){return K1("sha256").update(`credential-stamp\x00${a3($)}`).digest("hex")}function c0($){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 K1("sha256").update(`credential-dispatch\x00${JSON.stringify(Z)}`).digest("hex")}function B9($,Z,J,X={}){return{credentialEpoch:Z,digest:b0($),dispatch:c0($),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function u2($,Z){let J=$?.credentialBound?V0(()=>$.credentialBound?.(Z)):Z;return K1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function M1($,Z,J,X){if(!Z||J===void 0)return;if(!A($)||!Object.hasOwn($,Z0))return;let z=X0($[h]);if(!z||z.providerState===void 0||z.digest!==b0(Z)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function r($){return Number.isSafeInteger($)&&$>=1}function X0($){if(!A($))return;let Z=$.credentialEpoch;if(!r(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 $?Az($.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(!A(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!Y9(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 Rz($,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 Iz($,Z,J,X){if(!$)return"none";if(!A(X)||!Object.hasOwn(X,h))return"missing";let z=X0(X[h]);if(!z)return"malformed";if(z.digest!==b0($))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==Z)return"mismatched";if(!z.binding||!Rz(z.binding,$,J))return"mismatched";if(z.dispatch!==c0($))return"mismatched";return"bound"}function W9($){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(!A(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(!A(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>z2)return{status:"error",reason:`${v}.schemaVersion ${X} is newer than ${z2}`};if(O0 in J&&!A(J[O0]))return{status:"error",reason:`${v}.${O0} is not an object`};return{status:"ready",exists:!0,config:Z}}function r3($){if(!$.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in $)return{status:"error",reason:"state file is not valid JSON"};if(!A($.value))return{status:"error",reason:"state root is not an object"};if("accounts"in $.value&&!A($.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:$.value}}function p2($){return Array.isArray($.accounts)?$.accounts:[]}function o3($){let Z=$[v];if(!A(Z))return{};let J=Z[O0];return A(J)?J:{}}function kz($){return A($.accounts)?$.accounts:{}}function xz($){if(!A($))return"not an object";let Z=m2($.id);if(Z)return Z;if($.type==="api")return Y9($.baseURL)?void 0:"invalid baseURL";if($.type==="oauth")return;return"unknown type"}function bz($,Z){if(!A($))return;let J=$.credentialEpoch;if(!r(J))return;if("needsFirstReading"in $&&typeof $.needsFirstReading!=="boolean")return;if("disabledReason"in $&&typeof $.disabledReason!=="string")return;let X="quota"in $&&Z.decode?V0(()=>Z.decode?.($.quota)):$.quota;if("quota"in $&&!V0(()=>Z.validate(X)))return;if("staged"in $&&!i3($.staged))return;return{credentialEpoch:J,needsFirstReading:$.needsFirstReading===!0,...typeof $.disabledReason==="string"?{disabledReason:$.disabledReason}:{},..."quota"in $?{quota:X}:{}}}function fz($,Z){if(!A(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 T4($,Z){return p2($).find((J)=>A(J)&&J.id===Z)}function t3($){if(!A($[v]))$[v]={};return $[v]}function V9($){let Z=t3($);if(!A(Z[O0]))Z[O0]={};return Z[O0]}function f0($,Z){let J=o3($),X=Object.hasOwn(J,Z)?J[Z]:void 0;return A(X)?X:void 0}function _4($,Z,J){Object.defineProperty(V9($),Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function e3($,Z){let J=$[v];if(!A(J))return;let X=J[O4];if(!A(X)||!Object.hasOwn(X,Z))return;let z=X[Z];return r(z)?z:void 0}function $5($,Z){let J=f0($,Z)?.credentialEpoch;return r(J)?J:void 0}function S4($,Z){return Math.max(e3($,Z)??0,$5($,Z)??0)+1}function Z5($,Z){let J=[...Z];if(J.length===0)return;let X=t3($),z=A(X[O4])?X[O4]:{},G={},Q=(B,Y)=>Object.defineProperty(G,B,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[B,Y]of Object.entries(z))if(r(Y))Q(B,Y);for(let B of J)Q(B,Math.max(e3($,B)??0,$5($,B)??1));X[O4]=G}function G2($,Z,J,X){let z=o3($),G=kz(Z),Q=new Set,B=[];for(let Y of p2($)){let W=xz(Y),V=A(Y)&&typeof Y.id==="string"?Y.id:void 0,H=V===void 0?void 0:z[V],q=A(H)&&Object.hasOwn(H,"staged"),j=q?i3(H.staged):void 0;if(W||!A(Y)||V===void 0||Q.has(V)){if(V!==void 0&&!Q.has(V))Q.add(V);if(V!==void 0)B.push({id:V,type:A(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,V),candidate:!1,invalid:"roster",stamp:"none",...j?{staged:j}:{}});continue}Q.add(V);let U=Y.type==="api"?"api":"oauth",F=Object.hasOwn(z,V),N=F?bz(z[V],J):void 0,D=fz(Y,G[V]),P=Y.enabled!==!1,O=N?N.credentialEpoch:F?void 0:1,L=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,C={id:V,type:U,enabled:P,needsFirstReading:N?N.needsFirstReading:U==="oauth",hasEntry:F,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},...L!==void 0?{identity:L}:{},...D?{credential:D,fingerprint:T0(D)}:{},...N?{credentialEpoch:N.credentialEpoch}:{},...j?{staged:j}:{},...N?.disabledReason!==void 0?{disabledReason:N.disabledReason}:{},...N&&"quota"in N?{quota:N.quota}:{},...yz(G[V],D,O,L,X),stamp:Iz(D,O,L,G[V])};if(F&&!N)C.invalid="entry";else C.candidate=P&&D!==void 0&&!q;B.push(C)}return B}function yz($,Z,J,X,z){if(!A($)||!Object.hasOwn($,Z0))return{};let G=M1($,Z,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=$[Z0];if(!z||!V0(()=>z.validate(Q)))return{providerStateDropped:"invalid"};if(u2(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function w($){return $.identity??$.id}function L1($,Z){if($===void 0||$>Z+Q9)return Z;return Math.max(Z,$+1)}function H9($,Z){return L1($,Z)>Z+Q9}function l2($){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 J5($,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 X5($,Z){if($.type==="api")return{...$,baseURL:$.baseURL.trim(),authHeader:$.authHeader??"authorization-bearer"};return{...$,...Z!==void 0?{lastRefreshedAt:Z}:{}}}function z5($,Z={}){if(!A($))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)&&!Y9($.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var A4="transition",G5="transitionMark";function hz($){if(!A($))return;let Z=$[A4];if(!A(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 O1($,Z,J){if(J.enabled)P1($,Z);else X2($,Z,J.reason??"");if(!$.rosterRow(Z))return;let X=$.entry(Z)??{credentialEpoch:1,needsFirstReading:!0};if($.setEntry(Z,{...X,[G5]:J.mark}),!J.enabled)return;let z=$.rows().find((G)=>G.id===Z);if(z?.type==="oauth"&&z.identity!==void 0)w2($,z.identity)}function gz($,Z){if($.type!=="api")return $;return{...$,...Z.baseURL!==void 0?{baseURL:Z.baseURL}:{},...Z.authHeader!==void 0?{authHeader:Z.authHeader}:{}}}function vz($){if(!$.binding)return!1;return $.replace===!0||$.dispatch===void 0}function wz($,Z,J,X={}){let z=A(Z.accounts)?Z.accounts:{},G=new Map;for(let Q of G2($,Z,J)){if(Q.invalid||Q.staged||!Q.credential)continue;let B=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!A(B))continue;let Y=X0(B[h]);if(!Y?.binding)continue;if(Y.digest!==b0(Q.credential))continue;let W=Q.credentialEpoch??1;if(Y.credentialEpoch>W){if(!vz(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==c0(gz(Q.credential,Y.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===c0(Q.credential)&&Y.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===Q.identity){if(X.requireCredentialStamps&&Y.dispatch!==c0(Q.credential))continue;let V=hz(B[h]);if(V&&f0($,Q.id)?.[G5]!==V.mark)G.set(Q.id,{kind:"transition",transition:V})}}return G}function q9($,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(v2))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 U9($,Z,J,X={}){let z=wz($,Z,J,X);if(z.size===0)return{config:$,torn:[]};let G=structuredClone($),Q={rows:()=>G2(G,Z,J),rosterRow:(B)=>T4(G,B),entry:(B)=>f0(G,B),setEntry:(B,Y)=>_4(G,B,Y)};for(let[B,Y]of z)if(Y.kind==="replace")q9(Q,B,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[B,Y]of z)if(Y.kind==="identity")N2(Q,B,Y.identity);else if(Y.kind==="transition")O1(Q,B,Y.transition);else if(Y.stamp.binding.identity!==void 0)w2(Q,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function j9($,Z,J,X={}){let{config:z,torn:G}=U9($,Z,J,X),Q=G2(z,Z,J,X.providerState);for(let B of Q){if(G.includes(B.id))B.torn=!0,B.candidate=!1;if(X.requireCredentialStamps&&B.stamp!=="bound")B.unbound=!0,B.candidate=!1}return Q}var mz=[5,10,20,40,80,160,320,400];async function E4($){for(let Z=0;;Z++)try{return await T1($,z0)}catch(J){if(J.code==="ENOENT")return;let X=mz[Z];if(X===void 0||!D9(J))throw J;await V5(X)}}function N9($){if($===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse($)}}catch(Z){return{exists:!0,parseError:Z}}}async function H5($){return W9(N9(await E4($)))}async function t($){for(let Z=0;Z<3;Z++){let J,X,z;try{J=await E4($.configPath),X=await E4($.statePath),z=await E4($.configPath)}catch(B){if(D9(B))break;throw B}if(J!==z){if(Z<2)await V5(2+Math.floor(Math.random()*4));continue}let G=W9(N9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=r3(N9(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:j9(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 Y0($,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 q5{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 j9(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($)?.[h];return A(Z)&&Object.hasOwn(Z,"staged")?Z.staged:void 0}assertNotStaged($){D2(this.info.operation,$,this.reservation($))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow($){return this.roster(),T4(this.config,$)}dropRosterRows($){let Z=this.roster(),J=Z.filter((X)=>!(A(X)&&X.id===$));return this.config.accounts=J,Z.length-J.length}entries(){return V9(this.config)}entry($){return this.entries(),f0(this.config,$)}setEntry($,Z){_4(this.config,$,Z)}async completeTorn(){let{config:$,torn:Z}=U9(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=A(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn(Z,$)?Z[$]:void 0;return A(J)?J:void 0}dropStateAccount($){if(A(this.state.accounts)&&Object.hasOwn(this.state.accounts,$))delete this.state.accounts[$]}setStateAccount($,Z){if(!A(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 Y of Z)if(A(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of p2(this.snapshot.config))if(A(Y)&&typeof Y.id==="string"&&!J.has(Y.id))X.add(Y.id);for(let Y of Object.keys(this.entries()))if(!J.has(Y))X.add(Y);Z5(this.config,X);let z=this.entries(),G={};for(let[Y,W]of Object.entries(z))if(J.has(Y))Object.defineProperty(G,Y,{value:W,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[v],B={...this.config,version:C1,accounts:Z,[v]:{...Q,schemaVersion:z2,[O0]:G}};await this.write(this.ctx.configPath,B,"config",$.counted??!0,$.durable??!1,()=>{if($.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=B}),this.config=B}async commitState($,Z={}){let J={...this.state,version:C1,accounts:A(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 F9(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 F9(this.ctx.configPath)}async write($,Z,J,X=!0,z=!1,G){await Y5($,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 U5($,Z){let J=new d0($.lockDefaults,$.lockEnv),X={writes:0};try{for(let B of $.storeLocks)await J.acquire(B);let z=await t($);if(z.status==="error")throw Y0(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[B,Y]of Object.entries(z.config))if(!Z.includes(B))G[B]=Y;G.version=C1,G[v]={schemaVersion:z2,[O0]:{}};let Q={operation:"initialize",rowId:void 0};return await q0($.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 Q2(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function l($,Z,J,X,z,G={}){let Q=Z.held.length;try{for(let W of $.storeLocks)await Z.acquire(W);let B=await t($);if(B.status!=="ready")throw Y0(B,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new q5($,B,Z,J,X);if(X.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(X.operation))Y.assertNotStaged(X.rowId);if(G.completeTorn??!0)await Y.completeTorn();return await z(Y)}finally{await Z.releaseTo(Q)}}function Q2($,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 Q5)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 W5)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 B5)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 i($,Z,J,X,z){let G=new d0($.lockDefaults,$.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(B){let Y=Q2(B,Z,J,Q);if(Y.kind!=="after-persist-hook")await s3(Z,X,J,Y,$.logger);throw Y}finally{await G.releaseAll()}}function B0($,Z){return{...$.rowLockOptions,name:`row-${encodeURIComponent(w(Z))}`,path:$.ctx.statePath}}async function _0($,Z,J){let X=await t($.ctx);if(X.status!=="ready")throw Y0(X,Z,J);let z=X.rows.find((W)=>W.id===J),G=f0(X.config,J),Q=X.state.accounts,B=A(Q)&&Object.hasOwn(Q,J)?Q[J]:void 0,Y=A(B)?B[h]:void 0;if(z&&!["enable","disable"].includes(Z)&&G&&Object.hasOwn(G,"staged"))D2(Z,J,G.staged);if(!z&&A(Y)&&Object.hasOwn(Y,"staged"))D2(Z,J,Y.staged);if(!z)throw U0(Z,J);return{result:X,row:z}}function U0($,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 J0($,Z){if(Z.unbound)throw S($,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 S($,Z,J,X,z=!1){return new b({operation:$,rowId:Z,phase:$==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function P9($,Z){if(!r(Z?.credentialEpoch))throw S("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function _1($,Z,J){if(!J)throw U0("pull",$);if(J.invalid)throw S("pull",$,"invalid-row",`row ${$} is invalid`);if(!J.credential)throw S("pull",$,"no-credential",`row ${$} holds no credential`);if(J0("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 S1($,Z,J,X){let z=V0(()=>$.codec.merge(J,X));if(!V0(()=>$.codec.validate(z)))throw S("pull",Z,"invalid-quota","the quota codec rejected the merged map");return z}async function R4($,Z,J,X){let{ctx:z}=$,G=new d0(z.lockDefaults,z.lockEnv),Q={writes:0};try{P9(Z,J),await l(z,G,Q,{operation:"pull",rowId:Z},async(B)=>{B.assertNotStaged(Z);let Y=B.row(Z);_1(Z,J,Y);let W=B.entry(Z);if(!W)throw U0("pull",Z);let V=S1(z,Z,W.quota,X);B.setEntry(Z,{...W,quota:V,needsFirstReading:!1}),await B.commitConfig()},{completeTorn:!1})}catch(B){throw Q2(B,"pull",Z,Q)}finally{await G.releaseAll()}}async function j5($,Z,J={}){n3();let{ctx:X}=$;await i(X,"updateLimitsNamespace",void 0,void 0,async(z,G)=>{for(let H of X.storeLocks)await z.acquire(H);let Q=await t(X);if(Q.status!=="ready")throw Y0(Q,"updateLimitsNamespace",void 0);let B=Q.rows.map(({id:H,credentialEpoch:q,identity:j})=>({id:H,credentialEpoch:q,identity:j})),Y=await H0("updateLimitsNamespace",()=>Z(structuredClone(Q.config.commonAuthLimits),B)),W={...Q.config,commonAuthLimits:Y},V={operation:"updateLimitsNamespace",rowId:void 0};try{await q0(X.configPath,W,{beforeRename:async()=>{await X.onStep?.("before-config-write",V),await z.assertAll(),J.beforePublish?.()}})}catch(H){if(H&&typeof H==="object"&&"published"in H&&H.published===!0)J.onPublished?.();throw H}G.writes++,J.onPublished?.(),await X.onStep?.("after-config-write",V)})}function n0($,Z,J,X,z="the provider state"){if(!$)throw S(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 S(Z,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!V0(()=>$.validate(G)))throw S(Z,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function A1($,Z,J,X,z){if(X===void 0||!$?.merge)return{kind:"set",value:z};return{kind:"set",value:n0($,Z,J,V0(()=>$.merge?.(structuredClone(X),structuredClone(z))),"the merged provider state")}}function F5($,Z,J,X,z){let G=$?.onReplace,Q=G?V0(()=>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:n0($,"replace",Z.id,Q,"the provider state onReplace returned")}}function N5($,Z,J,X,z){if(Z.kind==="set")return u2($,Z.value);if(Z.kind==="clear")return;return M1(J,X?.credential,z,X?.identity)}async function D5($,Z,J,X,z={}){o("updateProviderState");let{ctx:G}=$,Q="updateProviderState";return i(G,Q,Z,z.onFailure,async(B,Y)=>{let W=G.providerState;if(!W)throw S(Q,Z,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw S(Q,Z,"invalid-input","a mutator is required");let V=A(J)?J.credentialEpoch:void 0;if(!r(V))throw S(Q,Z,"invalid-input","the credential epoch the provider state was read at is required");let{row:H}=await _0($,Q,Z);await B.acquire(B0($,H));for(let q of z.extraLocks??[])await B.acquire(q);return l(G,B,Y,{operation:Q,rowId:Z},async(q)=>{let j=q.row(Z);if(!j)throw U0(Q,Z);if(w(j)!==w(H))throw S(Q,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0);if(j.invalid)throw S(Q,Z,"invalid-row",`row ${Z} failed validation`);if(!j.credential)throw S(Q,Z,"no-credential",`row ${Z} holds no credential`);if(J0(Q,j),(j.credentialEpoch??1)!==V||j.identity!==J.identity)throw S(Q,Z,"attribution",`the provider state for ${Z} was read for a credential or account the row no longer holds`,!0);let F=await K9(q,W,Q,j,X);if(F.kind!=="changed")return{id:Z,outcome:"unchanged",...F.kind==="unchanged"&&F.value!==void 0?{providerState:F.value}:{}};return q.setStateAccount(Z,F.account),await q.commitState(),F.value===void 0?{id:Z,outcome:"cleared"}:{id:Z,outcome:"updated",providerState:F.value}})})}var P5=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function K9($,Z,J,X,z,G=!1){let{id:Q,credential:B}=X;if(!B)throw S(J,Q,"no-credential",`row ${Q} holds no credential`);let Y=X.credentialEpoch??1,W=$.stateAccount(Q),V=W?.[h],H=X0(V);if(!A(V)||!H?.binding||H.digest!==b0(B)||H.credentialEpoch!==Y||H.binding.identity!==X.identity)throw S(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 q=X.providerState===void 0?void 0:structuredClone(X.providerState),j=await H0(J,()=>z(q,X));if(G&&j===P5)return{kind:"declined"};let U=j===void 0?void 0:n0(Z,J,Q,j,"the provider state the mutator returned"),F=W!==void 0&&Object.hasOwn(W,Z0);if(U===void 0?!F:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let N={...W};if(U===void 0){delete N[Z0];let D={...V};delete D.providerState,N[h]=D}else{N[Z0]=U;let D=u2(Z,U);if(H.providerState!==D)N[h]={...V,providerState:D}}return{kind:"changed",...U!==void 0?{value:U}:{},account:N}}import{randomUUID as K5}from"node:crypto";async function b4($,Z,J){if(!J)return;let X=$.rows().map((G)=>{let{id:Q,type:B,label:Y,enabled:W,disabledReason:V,identity:H,credentialEpoch:q,stamp:j,staged:U,torn:F,invalid:N}=G;return{id:Q,type:B,label:Y,enabled:W,disabledReason:V,identity:H,credentialEpoch:q,stamp:j,staged:U,torn:F,invalid:N}}),z=await H0($.info.operation,()=>J({id:Z,row:X.find((G)=>G.id===Z),rows:X,config:structuredClone($.snapshot.config)}));if(z!==void 0)throw S($.info.operation,Z,"row-protected",z)}var uz=["access","refresh","expires","lastRefreshedAt","apiKey"];function pz($){return{baseURL:String($.baseURL).trim(),authHeader:$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function lz($,Z,J){if(J.type!=="api")return J;let X=$.rosterRow(Z);if(!A(X)){if(J.baseURL===void 0)throw S($.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"}:pz(X),Q=J.baseURL?.trim()??G.baseURL,B=J.authHeader??G.authHeader;if(Q!==G.baseURL||B!==G.authHeader)throw S($.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:B}}function C5($,Z,J,X){let z=$.rosterRow(Z),G=$.row(Z),Q=X??(G?G.identity:A(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 I4($,Z,J,X,z={}){let G=lz(Z,J,X),Q=Z.stateAccount(J),B=z.providerState??{kind:"keep"},Y=Z.row(J)?.credentialEpoch??Z.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,V=N5($.ctx.providerState,B,Q,Q&&Object.hasOwn(Q,Z0)?Z.row(J):void 0,W),H=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,q=G.type==="oauth"?z.stamp??L1(H,$.ctx.now()):void 0,j={...Q??{}};for(let N of uz)delete j[N];if(z.clearErrors)delete j.lastRefreshError,delete j.lastQuotaRefreshError,delete j.quota;if(B.kind==="clear")delete j[Z0];else if(B.kind==="set")j[Z0]=B.value;let U=X5(G,q),F={...j,...J5(G,q),[h]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[A4]:z.transition}:{},...B9(U,W,z.binding??C5(Z,J,U,z.identity),{replace:z.binding!==void 0,...V!==void 0?{providerState:V}:{}})}};return{stored:U,account:F}}async function k4($,Z,J){return $.setStateAccount(Z,J.account),await $.commitState(J.stored),J.stored}async function f4($,Z,J,X,z={}){return k4(Z,J,I4($,Z,J,X,z))}async function cz($,Z,J){if(!Z.credential||Z.stamp!=="bound")return;let X=$.stateAccount(Z.id),z=M1(X,Z.credential,Z.credentialEpoch??1,Z.identity);$.setStateAccount(Z.id,{...X??{},[h]:B9(Z.credential,Z.credentialEpoch??1,C5($,Z.id,Z.credential,J),z!==void 0?{providerState:z}:{})}),await $.commitState()}function M9($,Z,J){let X=$==="add"?m2(Z):void 0;if(X)throw S($,Z,"invalid-input",X);let z=z5(J,{baseURLOptional:$==="rotate"});if(z)throw S($,Z,"invalid-input",z)}function y4($,Z,J,X){if(!J)throw U0($,Z);if(J.invalid)throw S($,Z,"invalid-row",`row ${Z} failed validation`);if(X&&X.type!==J.type)throw S($,Z,"type-mismatch",`row ${Z} holds a ${J.type} credential`);return J}function d2($,Z,J){if(J!==void 0&&!r(A(J)?J.credentialEpoch:void 0))throw S($,Z,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function h4($,Z,J,X,z){if(!J)throw U0($,Z);if(J.invalid)throw S($,Z,"invalid-row",`row ${Z} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity||z?.credential==="absent"&&J.credential!==void 0)throw S($,Z,"attribution",`the ${$} of ${Z} was issued for a credential or account the row no longer holds`,!0)}function x4($,Z){return S($,Z,"identity-mismatch",`row ${Z} is recorded for another account; a credential of a different account is a replacement`)}function E1($,Z){return S($,Z,"row-key-changed",`row ${Z}'s wire identity changed while its lock was being taken`,!0)}function dz($,Z,J,X){let{id:z,credential:G,identity:Q}=J;if(!$.ctx.requireCredentialStamps||Z.rosterRow(z)||!c2(Z.state,z))return;let B=()=>{throw S("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=Z.stateAccount(z),W=X0(Y?.[h]);if(!W?.binding||W.dispatch===void 0||W.replace)return B();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return B();let V=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[H]=G2({accounts:[l2({id:z,credential:V,identity:W.binding.identity,addedAt:0})],[v]:{rows:{[z]:{credentialEpoch:S4(Z.config,z)}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!H?.credential||H.invalid||H.stamp!=="bound")return B();if(Q!==void 0&&Q!==H.identity)return B();if(b0(G)!==W.digest)return B();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return B();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return B()}else if(c0(G)!==W.dispatch)return B();if(W.providerState!==void 0&&H.providerState===void 0)return B();if(X!==void 0&&u2($.ctx.providerState,X)!==W.providerState)return B();return H}function nz($,Z,J,X){let{id:z,credential:G,identity:Q,label:B}=J,Y=Z.rosterRow(z),W=()=>{throw S("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},V=Z.stateAccount(z),H=X0(V?.[h]),q=H?.staged;if(!H?.binding||!q||H.replace||H.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==B||Y.accountId!==Q))return W();if(q.reservation!==J.stage?.reservation||q.label!==B||q.disabledReason!==J.disabled?.reason||H.binding.identity!==Q)return W();let j=X===void 0?void 0:P2(X),U=V?.[Z0],F=U===void 0?void 0:P2(U);if(q.providerState!==j||q.providerState!==F)return W();if(b0(G)!==H.digest||c0(G)!==H.dispatch)return W();let N=Y?Z.config:{accounts:[{...l2({id:z,credential:G.type==="api"?{...G,baseURL:H.binding.baseURL??"",authHeader:H.binding.authHeader}:G,identity:H.binding.identity,label:q.label,addedAt:0}),enabled:!1}],[v]:{rows:{[z]:{credentialEpoch:H.credentialEpoch,disabledReason:q.disabledReason,staged:{reservation:q.reservation}}}}},D=G2(N,Z.state,$.ctx.codec,$.ctx.providerState).find((P)=>P.id===z);if(!D?.credential||D.invalid||D.stamp!=="bound"||D.type!==G.type||D.enabled||D.label!==q.label||D.identity!==H.binding.identity||D.disabledReason!==q.disabledReason||D.staged?.reservation!==q.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:D.credential,credentialEpoch:H.credentialEpoch};if(S4(Z.config,z)!==H.credentialEpoch)return W();return Z.roster().push({...l2({id:z,credential:G,identity:Q,label:B,addedAt:$.ctx.now()}),enabled:!1}),Z.setEntry(z,{credentialEpoch:H.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:q.disabledReason,staged:{reservation:q.reservation}}),Z.commitConfig().then(()=>({id:z,outcome:"completed",credential:D.credential,credentialEpoch:H.credentialEpoch}))}async function M5($,Z,J={}){o("add");let{ctx:X}=$,{id:z,credential:G,identity:Q,label:B}=Z,Y=Z.stage!==void 0||Z.disabled!==void 0,W=await i(X,"add",z,J.onFailure,async(V,H)=>{M9("add",z,G);let q=J.onExisting??"rotate";if(Z.stage!==void 0&&q==="rotate")throw S("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(q)||Z.stage!==void 0&&(B!==void 0&&typeof B!=="string"||Q!==void 0&&(typeof Q!=="string"||!Q))||Z.disabled!==void 0&&(!A(Z.disabled)||typeof Z.disabled.reason!=="string")||Z.stage!==void 0&&(!A(Z.stage)||typeof Z.stage.reservation!=="string"||!Z.stage.reservation||!Z.disabled)||q==="stage-duplicate"&&(!Z.disabled||!Z.stage))throw S("add",z,"invalid-input","staging requires a reservation and a disabled reason");let j=Z.providerState===void 0?void 0:n0(X.providerState,"add",z,Z.providerState);if(await V.acquire(B0($,{id:z,identity:Q})),G.type==="oauth")await V.acquire(J.providerLock??$.providerLock);for(let U of J.extraLocks??[])await V.acquire(U);return l(X,V,H,{operation:"add",rowId:z},async(U)=>{await b4(U,z,J.protect);let F=A(U.state.accounts)?U.state.accounts:{},N=Object.entries(F).find(([I,k])=>{if(I===z||U.rosterRow(I)||!A(k))return!1;let g=k[h];if(!A(g)||!Object.hasOwn(g,"staged"))return!1;return G.type==="oauth"?k.refresh===G.refresh:typeof k.apiKey==="string"&&k.apiKey.trim()===G.apiKey.trim()});if(N)throw S("add",N[0],"row-staged",`orphan ${N[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw S("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if(Z.stage&&q!=="rotate"&&(U.rosterRow(z)||c2(U.state,z)))return nz($,U,Z,j);if(q==="rotate"){U.assertNotStaged(z);let I=U.rows().find((k)=>k.fingerprint===T0(G));if(I)U.assertNotStaged(I.id)}if(q==="refuse"){let I=U.rows().find((p)=>p.fingerprint===T0(G)||p.id===z&&p.credential),k=A(U.state.accounts)?U.state.accounts:{},g=Object.entries(k).find(([,p])=>{if(!A(p))return!1;if(G.type==="oauth")return p.refresh===G.refresh;return typeof p.apiKey==="string"&&p.apiKey.trim()===G.apiKey.trim()})?.[0],c=I?.id??g??z;if(I||g!==void 0||c2(U.state,z))throw S("add",c,"credential-exists",`row ${c} already holds this secret or id`)}if(q==="stage-duplicate"&&(U.rosterRow(z)||c2(U.state,z)))throw S("add",z,"id-exists",`row ${z} already exists`);let D=dz($,U,Z,j),P=U.rows(),O=T0(G),L=q==="rotate"&&!D&&P.find((I)=>I.invalid===void 0&&I.fingerprint===O);if(L){if(U.assertNotStaged(L.id),J0("add",L),Q!==void 0&&L.identity!==void 0&&Q!==L.identity)throw x4("add",L.id);let I=I4($,U,L.id,G,{...j!==void 0?{providerState:A1(X.providerState,"add",L.id,L.providerState,j)}:{}});await U.completeTorn(),U.assertNotStaged(L.id);let k=await k4(U,L.id,I);return{id:L.id,outcome:"rotated",credential:k,credentialEpoch:L.credentialEpoch??1}}let C=P.find((I)=>I.id===z);if(C){if(C.invalid)throw S("add",z,"invalid-row",`row ${z} is invalid`);if(C.credential)throw S("add",z,"id-exists",`row ${z} already holds a credential`);if(J0("add",C),C.type!==G.type)throw S("add",z,"type-mismatch",`row ${z} is a ${C.type} row`);if(Q!==void 0&&C.identity!==void 0&&Q!==C.identity)throw x4("add",z);if(!C.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let I=I4($,U,z,G,{clearErrors:!0,...j!==void 0?{providerState:{kind:"set",value:j}}:{}});await U.completeTorn();let k=await k4(U,z,I);if(!C.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:k,credentialEpoch:C.credentialEpoch??1}}let T=S4(U.config,z);if(!r(T))throw S("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let K=D?.identity??Q;U.roster().push(l2({id:z,credential:G,...K!==void 0?{identity:K}:{},...B!==void 0?{label:B}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...Z.stage?{staged:{reservation:Z.stage.reservation}}:{}});let M="added";if(Z.disabled)X2(U,z,Z.disabled.reason),M="added-disabled";if(!Z.disabled&&K!==void 0&&G.type==="oauth"){if(P.find((k)=>k.invalid===void 0&&k.type==="oauth"&&k.enabled&&k.identity===K))X2(U,z,G9),M="added-disabled"}if(D?.credential)return await U.commitConfig(),{id:z,outcome:M,credential:D.credential,credentialEpoch:D.credentialEpoch??T};U.dropStateAccount(z);let _=I4($,U,z,G,{...Z.stage&&Z.disabled?{staged:{reservation:Z.stage.reservation,disabledReason:Z.disabled.reason,...B!==void 0?{label:B}:{},...j!==void 0?{providerState:P2(j)}:{}}}:{},...j!==void 0?{providerState:{kind:"set",value:j}}:{}});if(q==="rotate")await U.completeTorn();let R=await k4(U,z,_);return await U.commitConfig(),{id:z,outcome:M,credential:R,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))$.firePull(W.id,"add");return W}async function L5($,Z,J,X={},z={}){o("replace");let{ctx:G}=$,Q=await i(G,"replace",Z,z.onFailure,async(B,Y)=>{M9("replace",Z,J),d2("replace",Z,z.attribution);let W=z.attribution?.expect;if(W!==void 0&&(!A(W)||W.credential!=="absent"))throw S("replace",Z,"invalid-input","the attribution's credential expectation must be 'absent'");let V=X.providerState===void 0?void 0:n0(G.providerState,"replace",Z,X.providerState),{row:H}=await _0($,"replace",Z);if(await B.acquire(B0($,H)),J.type==="oauth")await B.acquire(z.providerLock??$.providerLock);for(let q of z.extraLocks??[])await B.acquire(q);return l(G,B,Y,{operation:"replace",rowId:Z},async(q)=>{if(z.attribution!==void 0)h4("replace",Z,q.row(Z),z.attribution,W),await q.completeTorn();let j=y4("replace",Z,q.row(Z),J);if(w(j)!==w(H))throw E1("replace",Z);let U=q.entry(Z)?.credentialEpoch,F=(typeof U==="number"?U:1)+1;if(!r(F))throw S("replace",Z,"invalid-row",`row ${Z}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let N=F5(G.providerState,j,F,X.identity,V),D={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(q9(q,Z,F,D),X.identity!==void 0)w2(q,X.identity);let P=await f4($,q,Z,J,{clearErrors:!0,binding:D,providerState:N});return await q.commitConfig(),{id:Z,credential:P,credentialEpoch:F}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")$.firePull(Z,"replace");return Q}async function O5($,Z,J,X={},z={}){o("rotate");let{ctx:G}=$;return i(G,"rotate",Z,z.onFailure,async(Q,B)=>{M9("rotate",Z,J),d2("rotate",Z,z.attribution);let Y=X.providerState===void 0?void 0:n0(G.providerState,"rotate",Z,X.providerState),{row:W}=await _0($,"rotate",Z);if(await Q.acquire(B0($,W)),X.identity!==void 0&&J.type==="oauth")await Q.acquire(z.providerLock??$.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return l(G,Q,B,{operation:"rotate",rowId:Z},async(V)=>{if(z.attribution!==void 0)h4("rotate",Z,V.row(Z),z.attribution),await V.completeTorn();let H=y4("rotate",Z,V.row(Z),J);if(w(H)!==w(W))throw E1("rotate",Z);if(J0("rotate",H),X.identity!==void 0&&H.identity!==void 0&&X.identity!==H.identity)throw x4("rotate",Z);let q=X.identity!==void 0&&H.identity===void 0?X.identity:void 0,j=await f4($,V,Z,J,{identity:q,...Y!==void 0?{providerState:A1(G.providerState,"rotate",Z,H.providerState,Y)}:{}}),U=!1;if(!H.hasEntry)V.setEntry(Z,{credentialEpoch:1,needsFirstReading:H.type==="oauth"}),U=!0;if(X.identity!==void 0&&H.identity!==X.identity)N2(V,Z,X.identity),U=!0;if(U)await V.commitConfig();return{id:Z,credential:j}},{completeTorn:z.attribution===void 0})})}async function T5($,Z,J,X,z){o(Z);let{ctx:G}=$,Q=G.providerState,B=z.attribution,Y=z.providerState;return i(G,Z,J,z.onFailure,async(W,V)=>{if(d2(Z,J,B),Y!==void 0){if(typeof Y!=="function")throw S(Z,J,"invalid-input","the provider-state mutator must be a function");if(B===void 0)throw S(Z,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!Q)throw S(Z,J,"invalid-input","the store was opened without a provider-state codec")}let{row:H}=await _0($,Z,J);await W.acquire(B0($,H));for(let q of z.extraLocks??[])await W.acquire(q);return l(G,W,V,{operation:Z,rowId:J},async(q)=>{await b4(q,J,z.protect),q.assertNotStaged(J);let j=q.row(J),U=X.enabled?y4("enable",J,j):j;if(!U||!q.rosterRow(J))throw U0(Z,J);if(w(U)!==w(H))throw E1(Z,J);if(B!==void 0)h4(Z,J,U,B);if(X.enabled&&U.disabledReason?.startsWith(v2))throw S("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let F=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&F&&U.type==="oauth"){let L=U.identity===void 0?void 0:q.rows().find((C)=>C.id!==J&&C.invalid===void 0&&C.type==="oauth"&&C.enabled&&C.identity===U.identity);if(L)throw S("enable",J,"duplicate-identity",`row ${L.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||Q===void 0){if(await q.completeTorn(),!F)return{id:J};if(X.enabled)P1(q,J);else X2(q,J,X.reason);return await q.commitConfig(),{id:J}}if(!U.credential)throw S(Z,J,"no-credential",`row ${J} holds no credential`);J0(Z,U);let N=await K9(q,Q,Z,U,Y,!0);if(N.kind==="declined")return{id:J,declined:!0};await q.completeTorn();let D={id:J,providerStateOutcome:N.kind==="unchanged"?"unchanged":N.value===void 0?"cleared":"updated",...N.value!==void 0?{providerState:N.value}:{}};if(N.kind==="unchanged"){if(F){if(X.enabled)P1(q,J);else X2(q,J,X.reason);await q.commitConfig()}return D}if(!F)return q.setStateAccount(J,N.account),await q.commitState(),D;let P=X.enabled?{mark:K5(),enabled:!0}:{mark:K5(),enabled:!1,reason:X.reason},O=N.account[h];return q.setStateAccount(J,{...N.account,[h]:{...O,[A4]:P}}),await q.commitState(),O1(q,J,P),await q.commitConfig(),D},{completeTorn:!1})})}function _5($,Z,J,X={}){return T5($,"disable",Z,{enabled:!1,reason:J},X)}function S5($,Z,J={}){return T5($,"enable",Z,{enabled:!0},J)}async function A5($,Z,J={}){o("remove");let{ctx:X}=$;return i(X,"remove",Z,J.onFailure,async(z,G)=>{if(typeof Z!=="string"||Z.length===0)throw S("remove",Z,"invalid-input","id must be non-empty");let Q=J.attribution;if(d2("remove",Z,Q),J.staged!==void 0&&(!A(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw S("remove",Z,"invalid-input","a staged removal needs a reservation");let B=await t(X);if(B.status!=="ready")throw Y0(B,"remove",Z);let Y=B.rows.find((V)=>V.id===Z);if(!Y&&!c2(B.state,Z))throw U0("remove",Z);let W=w(Y??{id:Z});await z.acquire(B0($,Y??{id:Z}));for(let V of J.extraLocks??[])await z.acquire(V);return l(X,z,G,{operation:"remove",rowId:Z},async(V)=>{let H=V.reservation(Z);if(H!==void 0){if(!A(H)||!J.staged||H.reservation!==J.staged.reservation)throw S("remove",Z,"row-staged",`row ${Z} is reserved for roster publication`)}else if(J.staged)throw S("remove",Z,"attribution",`row ${Z} is no longer reserved`);let q=V.row(Z),j=c2(V.state,Z);if(!q&&!j)throw U0("remove",Z);if(w(q??{id:Z})!==W)throw E1("remove",Z);if(Q!==void 0)if(q)g4(Z,q,Q);else sz($,V,Z,Q);let U=J.protect;if(U){let F={row:q,config:V.snapshot.config,state:V.snapshot.state},N=await H0("remove",()=>U(Z,F));if(N!==void 0)throw S("remove",Z,"row-protected",N)}if(q){if(Q===void 0)await V.completeTorn();V.dropRosterRows(Z),await V.commitConfig()}if(j)V.dropStateAccount(Z),await V.commitState();return{id:Z,outcome:q?"removed":"completed"}},{completeTorn:!1})})}function g4($,Z,J,X="remove"){if(h4(X,$,Z,J),Z.torn)throw S(X,$,"attribution",`row ${$} is between the writes of another operation; retry once it completes`,!0);if(Z.stamp!=="bound")throw S(X,$,"unbound-credential",`row ${$}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function sz($,Z,J,X){let z=()=>S("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=X0(G?.[h]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let B;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();B={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")B={type:"oauth",refresh:G.refresh};else throw z();let[Y]=G2({accounts:[l2({id:J,credential:B,identity:Q.binding.identity,addedAt:0})],[v]:{rows:{[J]:{credentialEpoch:Q.credentialEpoch}}}},Z.state,$.ctx.codec,$.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(Q.credentialEpoch!==X.credentialEpoch||Q.binding.identity!==X.identity)throw S("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function c2($,Z){let J=$.accounts;return A(J)&&Object.hasOwn(J,Z)}function C9($){return A($)&&typeof $.id==="string"?$.id:void 0}function iz($,Z){if(!Array.isArray(Z))return"ids must be an array of roster ids";let J=new Set;for(let G of $){let Q=C9(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 az($,Z){let J=new Map;for(let G of $){let Q=C9(G);if(Q===void 0)continue;let B=J.get(Q);if(B)B.push(G);else J.set(Q,[G])}let X=Z.flatMap((G)=>J.get(G)??[]),z=0;return $.map((G)=>C9(G)===void 0?G:X[z++])}async function E5($,Z,J={}){o("reorder");let{ctx:X}=$,z=J.onFailure;return i(X,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of J.extraLocks??[])await G.acquire(B);return l(X,G,Q,{operation:"reorder",rowId:void 0},async(B)=>{let Y=B.roster(),W=iz(Y,Z);if(W)throw new b({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let V=[...Z],H=az(Y,V);if(H.every((q,j)=>q===Y[j]))return{ids:V,outcome:"unchanged"};return B.config.accounts=H,await B.commitConfig(),{ids:V,outcome:"reordered"}},{completeTorn:!1})})}async function R5($,Z,J,X,z={}){return o("recordIdentity"),i($.ctx,"recordIdentity",Z,z.onFailure,async(G,Q)=>{if(typeof J!=="string"||J.length===0)throw S("recordIdentity",Z,"invalid-input","identity must be non-empty");let B=A(X)?X.credentialEpoch:void 0;if(!r(B))throw S("recordIdentity",Z,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await _0($,"recordIdentity",Z);await G.acquire(B0($,Y)),await G.acquire(z.providerLock??$.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return l($.ctx,G,Q,{operation:"recordIdentity",rowId:Z},async(W)=>{let V=y4("recordIdentity",Z,W.row(Z));if(w(V)!==w(Y))throw E1("recordIdentity",Z);if(J0("recordIdentity",V),(V.credentialEpoch??1)!==B)throw S("recordIdentity",Z,"attribution",`the identity for ${Z} was looked up for a credential the row no longer holds`,!0);if(V.identity!==void 0&&V.identity!==J)throw x4("recordIdentity",Z);if(V.identity===void 0)await cz(W,V,J);let H=N2(W,Z,J);return await W.commitConfig(),{id:Z,disabled:H}})})}function k5($){let Z=$[v];return A(Z)&&A(Z.publications)?Z.publications:{}}function x5($,Z){let J=k5($);if(!Object.hasOwn(J,Z))return;let X=J[Z];if(!A(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)=>!A(z)||typeof z.id!=="string"||!r(z.credentialEpoch))||X.finalized.some((z)=>!A(z)||typeof z.id!=="string"||!r(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw S("publishRoster",Z,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function b5($,Z){let J=await t($.ctx);if(J.status!=="ready")throw Y0(J,"publishRoster",Z);return x5(J.config,Z)}function rz($,Z){let J=()=>{throw S("publishRoster",Z?.operationId??"","invalid-input","the publication plan is invalid")};if(!A(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(!A(z)||typeof z.id!=="string"||m2(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),d2("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"||m2(z))||new Set(Z.order).size!==Z.order.length)J()}function f5($,Z){$.entries();let J=$.config[v],X={...k5($.config)};Object.defineProperty(X,Z.operationId,{value:Z,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function oz($,Z,J){let X=new Set;for(let Q of p2($.config)){if(!A(Q)||typeof Q.id!=="string")continue;if(X.has(Q.id))throw S("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((B)=>B.id===Q))||G.some((Q)=>!Z.order.includes(Q.id)))throw S("publishRoster",Z.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function I5($,Z){await $.assertAll();for(let X of Z.removed)if(X0($.stateAccount(X.id)?.[h])?.credentialEpoch===X.credentialEpoch&&!$.rosterRow(X.id))$.dropStateAccount(X.id);for(let X of Z.finalized){let z=$.stateAccount(X.id),G=X0(z?.[h]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let Q={...z[h]};delete Q.staged,$.setStateAccount(X.id,{...z,[h]:Q})}}await $.commitState(void 0,{durable:!0});let J={...Z,phase:"cleaned"};return f5($,J),await $.commitConfig({durable:!0}),J}async function y5($,Z,J={}){return o("publishRoster"),i($.ctx,"publishRoster",Z?.operationId??"",J.onFailure,async(X,z)=>{if(!A(Z)||typeof Z.operationId!=="string"||!Z.operationId)throw S("publishRoster",Z?.operationId??"","invalid-input","the publication needs an operation id");Z=structuredClone(Z);let G=P2(Z),Q=[...Array.isArray(Z.remove)?Z.remove:[],...Array.isArray(Z.finalize)?Z.finalize:[]].filter((B)=>A(B)&&typeof B.id==="string");for(let B=0;;B++){let Y=await t($.ctx);if(Y.status!=="ready")throw Y0(Y,"publishRoster",Z.operationId);let W=new Map(Q.map(({id:H})=>[H,w(Y.rows.find((q)=>q.id===H)??{id:H})]));for(let H of[...new Set(W.values())].sort())await X.acquire(B0($,{id:H}));await X.acquire(J.providerLock??$.providerLock);for(let H of J.extraLocks??[])await X.acquire(H);let V=await l($.ctx,X,z,{operation:"publishRoster",rowId:Z.operationId},async(H)=>{let q=H.rows();if(Q.some(({id:C})=>w(q.find((T)=>T.id===C)??{id:C})!==W.get(C)))return;let j=x5(H.config,Z.operationId);if(j){if(j.planDigest!==G)throw S("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 H.markPublicationDecision(),await H.syncConfig(),{outcome:"cleaned",receipt:await I5(H,j)}}rz($,Z);let U=oz(H,Z,q),F=[];for(let C of Z.remove){H.assertNotStaged(C.id);let T=q.find((K)=>K.id===C.id);if(!T)throw S("publishRoster",C.id,"attribution","the removed row no longer exists");if(g4(C.id,T,C.attribution,"publishRoster"),!T.credential||C.fingerprint!==void 0&&T0(T.credential)!==C.fingerprint)throw S("publishRoster",C.id,"attribution","the removed secret no longer matches");F.push(T)}let N=[];for(let C of Z.finalize){let T=q.find((k)=>k.id===C.id),K=X0(H.stateAccount(C.id)?.[h]);if(!T||T.staged?.reservation!==C.reservation||K?.staged?.reservation!==C.reservation||T.enabled)throw S("publishRoster",C.id,"row-staged","the finalized row is not disabled under this reservation");let M=H.stateAccount(C.id),_=H.rosterRow(C.id),R=M?.[Z0],I=R===void 0?void 0:P2(R);if(!K?.staged||K.staged.label!==_?.label||K.staged.disabledReason!==T.disabledReason||K.staged.providerState!==I)throw S("publishRoster",C.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");g4(C.id,T,C.attribution,"publishRoster"),N.push(T)}let D=U.find((C)=>C.torn);if(D)throw S("publishRoster",Z.operationId,"attribution",`Row ${D.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let P=new Set;for(let C of U){if(!(Z.finalize.find((K)=>K.id===C.id)?.enabled??C.enabled)||C.type!=="oauth"||C.identity===void 0)continue;if(P.has(C.identity))throw S("publishRoster",C.id,"invalid-input","the final enabled roster repeats a known identity");P.add(C.identity)}for(let C of U)if(C.identity!==void 0&&C.fingerprint!==void 0&&U.some((T)=>T.id!==C.id&&T.identity!==void 0&&T.identity!==C.identity&&T.fingerprint===C.fingerprint))throw S("publishRoster",C.id,"attribution","the resulting pool gives the same secret different known identities");for(let C of N)if(C.identity!==void 0&&F.some((T)=>T.identity!==void 0&&T.identity!==C.identity&&T.fingerprint===C.fingerprint))throw S("publishRoster",C.id,"attribution","the staged secret belonged to a different known identity");await b4(H,Z.operationId,J.protect);let O={operationId:Z.operationId,planDigest:G,phase:"committed",removed:F.map((C)=>({id:C.id,credentialEpoch:C.credentialEpoch??1})),finalized:Z.finalize.map((C,T)=>({id:C.id,credentialEpoch:N[T]?.credentialEpoch??1,reservation:C.reservation,enabled:C.enabled}))};for(let C of Z.remove)H.dropRosterRows(C.id);for(let C of Z.finalize){let T=H.rosterRow(C.id);T.enabled=C.enabled;let K={...H.entry(C.id)};if(delete K.staged,C.enabled)delete K.disabledReason;else K.disabledReason=C.disabledReason;H.setEntry(C.id,K)}let L=H.roster().filter((C)=>!A(C)||typeof C.id!=="string"||q.find((T)=>T.id===C.id)?.invalid==="roster");return H.config.accounts=[...Z.order.map((C)=>H.rosterRow(C)),...L],f5(H,O),await H.syncState(),await H.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await I5(H,O)}},{completeTorn:!1});if(V)return V;if(await X.releaseAll(),B>=1)throw S("publishRoster",Z.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class L9{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 d0(X.lockDefaults,X.lockEnv),G={writes:0};try{let Q=await l(X,z,G,{operation:"pull",rowId:$},async(W)=>{if(W.reservation($)!==void 0)return;await W.completeTorn();let V=W.row($);if(V?.unbound&&V.enabled&&V.type==="oauth"&&V.credential&&!V.invalid)J0("pull",V);if(!V?.candidate||V.type!=="oauth")return;if(!V.hasEntry)W.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let H=W.row($);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:$,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:Z}},{completeTorn:!1});if(await z.releaseAll(),!Q){this.firedAtLoad.delete($);return}await X.hold?.("pull-before-request",$);let B;try{B=await this.hook?.(Q)}catch(W){throw new b({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,V,H)=>R4(J,W,V,H)))($,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(Q){this.firedAtLoad.delete($);let B=Q2(Q,"pull",$,G);if(this.onFailure)try{await this.onFailure($,B)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:$,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:$,kind:B.kind})}finally{await z.releaseAll()}}}var h5=100,v4=128;class O9{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=v5){this.rt=$,this.timeoutMs=Z,this.clock=J,this.logger=$.ctx.logger??d("store")}async record($,Z,J){try{this.assertOpen($),P9($,Z);let X=structuredClone({id:$,attribution:Z,observation:J}),{row:z,result:G}=await _0(this.rt,"pull",$);_1($,X.attribution,z),S1(this.rt.ctx,$,this.overlayRow({...z,quota:f0(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>=v4)this.flushNow();else this.schedule(h5)}catch(X){throw Q2(X,"pull",$,{writes:0})}}queued($){return this.pending.get($)?.length??0}async room($){if(this.queued($)<v4)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($)>=v4){this.assertOpen($),this.flushNow();let z=X-performance.now();if(z<=0)throw S("pull",$,"lock-contention",`pool quota queue for ${$} is full (${v4} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let Q=()=>{clearTimeout(B),this.wake.delete(Q),G()},B=setTimeout(Q,z);this.wake.add(Q)})}}assertOpen($){if(this.closed)throw S("pull",$,"invalid-input","pool quota writer is closed")}overlayRow($){let Z=$;for(let J of this.pending.get($.id)??[])try{_1($.id,J.attribution,$),Z={...Z,quota:S1(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)+g5-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 d0(Z.lockDefaults,Z.lockEnv);return this.running=(async()=>{try{await l(Z,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let Q of $){let{id:B,attribution:Y,observation:W}=Q,V=JSON.stringify([B,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(B),_1(B,Y,z.row(B))}catch(j){if(!(j instanceof b))throw j;if(!this.warned.has(V))this.warned.add(V),this.warn("pool quota publication dropped; account binding changed",{id:B,kind:j.kind});continue}let H=z.entry(B);if(!H)continue;let q;try{q=S1(Z,B,H.quota,W)}catch(j){let U=`codec:${V}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:B,error:j instanceof Error?j.message:String(j)});continue}z.setEntry(B,{...H,quota:q,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((B)=>!X.has(B));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()):h5;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 tz}from"node:crypto";function T9($,Z){if(D2("refresh",$,Z?.staged),!Z)throw S("refresh",$,"unknown-row",`no row ${$} in the pool`);if(Z.invalid)throw S("refresh",$,"invalid-row",`row ${$} is invalid`);if(Z.type!=="oauth"||Z.credential?.type!=="oauth")throw S("refresh",$,"no-credential",`row ${$} holds no OAuth credential`);if(!Z.enabled)throw S("refresh",$,"row-disabled",`row ${$} is disabled`);return Z}function w5($){return S("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 m5($,Z,J,X={}){o("refresh");let{ctx:z}=$;return i(z,"refresh",Z,X.onFailure,async(G,Q)=>{let{row:B}=await _0($,"refresh",Z);T9(Z,B);let Y=await X.refuse?.(B);if(Y!==void 0)return{status:"refused",rowId:Z,reason:Y};let W=w(B),V;for(let U=0;;U++){await G.acquire(B0($,{id:Z,identity:W===Z?void 0:W})),await G.acquire(X.providerLock??$.providerLock);for(let D of X.extraLocks??[])await G.acquire(D);let N=await l(z,G,{writes:0},{operation:"refresh",rowId:Z},async(D)=>{let P=T9(Z,D.row(Z));if(J0("refresh",P),!P.hasEntry)D.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await D.commitConfig(),P=T9(Z,D.row(Z));if(w(P)!==W)return{keyNow:w(P)};let O=await X.refuse?.(P);if(O!==void 0)return{refused:O};return{row:P,credential:P.credential,credentialEpoch:P.credentialEpoch,identity:P.identity}});if("refused"in N)return{status:"refused",rowId:Z,reason:N.refused};if("keyNow"in N){if(await G.releaseAll(),U>=1)throw S("refresh",Z,"row-key-changed",`row ${Z}'s wire identity changed twice while its lock was held`,!0);W=N.keyNow;continue}V=N;break}if(H9(V.credential.lastRefreshedAt,z.now()))throw w5(Z);await z.hold?.("refresh-before-provider",Z),await G.assertAll();let H;try{H=await J(V.credential,V.row)}catch(U){throw new b({operation:"refresh",rowId:Z,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof H?.refresh!=="string"||!H.refresh.trim())throw S("refresh",Z,"provider","the provider returned no refresh token",!0);let q=H.providerState===void 0?void 0:n0(z.providerState,"refresh",Z,H.providerState,"the provider state the provider returned"),j=await l(z,G,Q,{operation:"refresh",rowId:Z},async(U)=>{let F=U.row(Z),N=U.entry(Z);if(!F||F.invalid||!N||N.credentialEpoch!==V.credentialEpoch||F.identity!==V.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`});J0("refresh",F);let D=await X.refuse?.(F);if(D!==void 0)return{refused:D};let P=z.now(),O=F.credential?.type==="oauth"?F.credential.lastRefreshedAt:void 0;if(H9(O,P))throw w5(Z);let L={type:"oauth",access:H.access,refresh:H.refresh,expires:H.expires},C=F.identity!==void 0&&H.identity!==void 0&&F.identity!==H.identity?{expectedIdentity:F.identity,returnedIdentity:H.identity}:void 0,T=C?{mark:tz(),enabled:!1,reason:`${v2}${JSON.stringify(C)}`}:void 0,K=F.identity===void 0&&H.identity?H.identity:void 0,M=await f4($,U,Z,L,{stamp:L1(O,P),transition:T,identity:K,...q!==void 0?{providerState:A1(z.providerState,"refresh",Z,F.providerState,q)}:{}});if(T!==void 0)O1(U,Z,T),await U.commitConfig();let _=F.identity;if(K!==void 0)N2(U,Z,K),_=K,await U.commitConfig();return{stored:M,identity:_,contradiction:C,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 U=X.onPersisted;await H0("refresh",()=>U(Z,j.stored),!0)}catch(U){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:U})}return{status:"rotated",rowId:Z,credential:j.stored,...j.identity!==void 0?{identity:j.identity}:{}}})}import{isDeepStrictEqual as u5}from"node:util";var u4=Object.freeze(["version","accounts",v]);function w4($){let Z={};for(let[J,X]of Object.entries($))if(!u4.includes(J))m4(Z,J,X);return Z}function m4($,Z,J){Object.defineProperty($,Z,{value:J,enumerable:!0,writable:!0,configurable:!0})}function ez($,Z){let J={};for(let[X,z]of Object.entries($))if(u4.includes(X)||X==="commonAuthLimits")m4(J,X,z);else if(Object.hasOwn(Z,X))m4(J,X,Z[X]);for(let[X,z]of Object.entries(Z))if(!Object.hasOwn($,X))m4(J,X,z);return J}function _9($){return new b({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:$})}var $G=new p5;function l5($){return c5($.ctx.configPath)}async function c5($){let Z=async([X=$]=[])=>{let z=await H5(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:w4(z.config)}},J=z0?await Z():await $G.read([$],Z);return structuredClone(J)}async function d5($,Z,J={}){o("updateSettings");let{ctx:X}=$,z=J.onFailure;return i(X,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let B=G.held.length;try{for(let N of X.storeLocks)await G.acquire(N);let Y=await t(X);if(Y.status!=="ready")throw Y0(Y,"updateSettings",void 0);let W=w4(Y.config),V=structuredClone(W),H=await H0("updateSettings",()=>Z(V)),q=H===void 0?V:H;if(!A(q))throw _9("the settings mutator must produce an object");let j=u4.filter((N)=>Object.hasOwn(q,N));if(j.length>0)throw _9(`settings cannot set the pool-owned key(s) ${j.join(", ")}`);if(Object.hasOwn(q,"commonAuthLimits")&&(!Object.hasOwn(W,"commonAuthLimits")||!u5(q.commonAuthLimits,W.commonAuthLimits)))throw _9("settings cannot alter commonAuthLimits; use updateLimitsNamespace");let U=ez(Y.config,q);if(u5(w4(U),W))return{settings:W,outcome:"unchanged"};let F={operation:"updateSettings",rowId:void 0};return await q0(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",F),await G.assertAll()}}),Q.writes++,await X.onStep?.("after-config-write",F),{settings:w4(U),outcome:"updated"}}finally{await G.releaseTo(B)}})}var n5=new Map;function ZG($){let Z=n5.get($);if(!Z)Z={removedIds:new Set,firedAtLoad:new Set},n5.set($,Z);return Z}function s5($){if($.status==="ready")return{status:"ready",schemaVersion:z2,rows:$.rows};if($.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray($.config.accounts)?$.config.accounts:[]};return $}function R1($){let Z=ZG($.configPath),J={...S9,...$.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 L9(()=>G,$.pull,$.onPullFailure,Z.firedAtLoad,$.logger),G={ctx:X,providerLock:$.providerLock??{name:`provider-${encodeURIComponent($.provider)}`,path:$.statePath},rowLockOptions:$.rowLockOptions??{},firePull:(W,V)=>z.fire(W,V)},Q=$.coalesceQuota?new O9(G,$.quotaDrainTimeoutMs,$.quotaCommitTimer):void 0,B=(W,V,H)=>Q?Q.record(W,V,H):R4(G,W,V,H);G.publishQuota=B;let Y=(W)=>{if(W.status==="ready"&&Q)return{...W,rows:Q.overlay(W.rows)};return W};return{async load(){let W=Y(await t(X));if(W.status==="ready"){for(let V of W.rows)if((V.candidate||V.torn&&V.enabled)&&V.type==="oauth"&&V.needsFirstReading)z.fire(V.id,"load")}return s5(W)},async read(){return s5(Y(await t(X)))},async initialize(W={}){return{status:await U5(X,W.dropKeys??[])}},add:(W,V)=>M5(G,W,V),publishRoster:(W,V)=>y5(G,W,V),publication:(W)=>b5(G,W),replace:(W,V,H,q)=>L5(G,W,V,H,q),rotate:(W,V,H,q)=>O5(G,W,V,H,q),updateProviderState:(W,V,H,q)=>D5(G,W,V,H,q),disable:(W,V,H)=>_5(G,W,V,H),enable:(W,V)=>S5(G,W,V),remove:(W,V)=>A5(G,W,V),reorder:(W,V)=>E5(G,W,V),readSettings:()=>l5(G),updateSettings:(W,V)=>d5(G,W,V),updateLimitsNamespace:(W,V)=>j5(G,W,V),recordIdentity:(W,V,H,q)=>R5(G,W,V,H,q),refresh:(W,V,H)=>m5(G,W,V,H),recordQuota:B,close:()=>Q?.close()??Promise.resolve(),dispose:()=>Q?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var JG=[/\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 R9($={}){let{redactStrings:Z}=p4({...$,extraValuePatterns:[...JG,...$.extraValuePatterns??[]]});return(J)=>Z(J)}class n extends Error{code;constructor($,Z,J){super(Z,J);this.name="CommandError",this.code=$}}var i5=/^[a-z][a-z0-9-]{0,63}$/,A9={code:"action-failed",text:"That action failed."},XG=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 I1($){if($ instanceof n)return{code:i5.test($.code)?$.code:A9.code,text:$.message};if($ instanceof b)return{code:`pool-${$.kind}`,text:XG.has($.kind)?$.message:`The account pool could not do that (${$.kind}).`};return A9}var a5="This cannot be undone. Continue?",zG=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function GG($){let Z=$.toLowerCase().replace(/[-_]/g,"");return zG.has(Z)||Z.endsWith("token")||Z.endsWith("key")||Z.endsWith("secret")}function QG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function E9($,Z,J){if(typeof $==="string"){let z=J.redact($);if(z!==$)J.redacted.push(Z);return z}if(Array.isArray($))return $.map((z,G)=>E9(z,`${Z}[${G}]`,J));if(!QG($))return $;let X={};for(let[z,G]of Object.entries($)){if(GG(z)){J.dropped.push(`${Z}.${z}`);continue}Object.defineProperty(X,z,{value:E9(G,`${Z}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function r5($,Z,J){let X={redact:J.redact,dropped:[],redacted:[]},z=E9($,"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 YG($){return{value:String($.value),label:String($.label)}}function BG($){switch($.kind){case"choice":return{kind:"choice",id:$.id,label:$.label,choices:($.choices??[]).map(YG),...$.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 I9($){if($.irreversible===!0)return{message:$.confirm||a5,irreversible:!0};if($.confirm)return{message:$.confirm,irreversible:!1};return}function o5($){let Z=I9($);return{id:$.id,label:$.label,...$.description!==void 0?{description:$.description}:{},...$.group!==void 0?{group:String($.group)}:{},knobs:($.knobs??[]).map(BG),...Z?{confirm:Z}:{}}}function WG($){return{id:$.id,...$.label!==void 0?{label:$.label}:{},enabled:$.enabled,type:$.type,...$.identity!==void 0?{identity:$.identity}:{}}}function VG($){return{id:$.id,label:$.label,...$.detail!==void 0?{detail:$.detail}:{},...$.group!==void 0?{group:String($.group)}:{},...$.status!==void 0?{status:String($.status)}:{},...$.account?{account:WG($.account)}:{},...$.facts!==void 0?{facts:$.facts}:{},actions:($.actions??[]).map(o5)}}function HG($){let{content:Z}=$;return{id:$.id,slot:$.slot,title:$.title,lines:(Z.lines??[]).map(String),items:(Z.items??[]).map(VG),actions:(Z.actions??[]).map(o5),...Z.facts!==void 0?{facts:Z.facts}:{}}}function t5($,Z,J){return{command:$,title:Z,sections:J.map(HG)}}function e5($,Z,J,X){return r5({command:$,menu:t5($,Z,J)},$,X)}function $Z($,Z,J,X,z){return r5({command:$,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:i5.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:t5($,Z,J)},$,z)}var YZ="disabled from the command menu";function qG($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function S0($){return qG($)?{...$}:{}}function UG($){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 jG($,Z){return $.label??Z??$.id}function l4($,Z){return Y2($.quota)?h0($.quota,Z):void 0}function BZ($,Z){return`${$} ${Z}${$===1?"":"s"}`}var n2="Actions";function FG($){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 ZZ($,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 JZ($){return I1($).text}function x9($){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 NG($){let{store:Z}=$,J=await Z.read(),X=await x9($).read(),z=await $.routing?.vaultOrder?.();return{load:J,rows:UG(J),settings:X,...z?{vault:z}:{}}}function c4($,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:jG($,J)}}function DG($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=Z.rows.map((H)=>H.id),Q=FG(Z.load),B=Z.rows.filter((H)=>H.enabled).length,Y=Z.rows.map((H,q)=>{let{account:j,name:U}=c4(H,$),F=[H.type==="api"?"API key":"OAuth",...j.identity!==void 0?[j.identity]:[],...!H.invalid&&!H.enabled&&H.disabledReason?[`disabled: ${H.disabledReason}`]:[]].join(" · "),N=H.invalid?"invalid":H.enabled?"enabled":"disabled",D=[];if(!H.invalid&&H.enabled)D.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(H.id,YZ,z),`Disabled ${U}.`}});if(!H.invalid&&!H.enabled)D.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(H.id,z),`Enabled ${U}.`}});if(G.length>1)D.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((P,O)=>({value:String(O+1),label:String(O+1)})),value:String(q+1)}],run:async({values:P})=>{let O=Number(P.position),L=G.filter((T)=>T!==H.id);return L.splice(O-1,0,H.id),(await J.reorder(L,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return D.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(H.id,{...z,...$.accounts?.protect?{protect:$.accounts.protect}:{}}),`Removed ${U}.`}}),{id:H.id,label:U,detail:F,group:"Accounts",status:N,account:j,actions:D}}),W=$.accounts?.login,V=[];if(W&&!Q)V.push({id:"add",label:W.label??"Add account",group:n2,knobs:W.knobs??[],run:async({values:H,invocation:q})=>{let j=await W.run(H,q);if(j.status==="cancelled")return{ok:!1,text:j.message??"Login cancelled."};if(j.status==="ready"){let U=await J.add(j.account,z);return ZZ(j.account.label??U.id,U)}return j.completion.then(async(U)=>{if(!U){q.notify("Login cancelled.","warning");return}let F=await J.add(U,z);q.notify(ZZ(U.label??F.id,F))},(U)=>{q.notify(`Adding the account failed: ${JZ(U)}`,"error")}).catch((U)=>{q.notify(`Adding the account failed: ${JZ(U)}`,"error")}),j.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[Z.rows.length===0?"No accounts yet":`${BZ(Z.rows.length,"account")}, ${B} enabled`],items:Q?[]:Y,actions:V}}}function PG($,Z){let J=$.quota?.scope??"all",X=$.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(V,H)=>{if($.quota?.check)await $.quota.check(V,H);else{for(let q of V)$.store.requestReading(q);await $.store.pullsSettled()}},Q=Z.rows.filter((V)=>V.candidate),B=Q.map((V)=>{let{account:H,name:q}=c4(V,$),j=l4(V,J);return{id:V.id,label:q,group:z,status:y0(j,{now:X,form:"compact"}),detail:y0(j,{now:X,form:"full"}),account:H,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([V.id],U),`Checked quota for ${q}.`}}]}}),Y=Z.rows.filter((V)=>!V.candidate).map((V)=>{let{name:H}=c4(V,$),q=V.invalid?"invalid":!V.enabled?"disabled":V.credential===void 0?"no credential":"unavailable",j=y0(l4(V,J),{now:X,form:"compact"});return`${H} (${q}): ${j}`}),W=[];if(Q.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:n2,run:async({invocation:V})=>{let H=Q.map((q)=>q.id);return await G(H,V),`Checked quota for ${BZ(H.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:Z.rows.length===0?["No accounts yet"]:Y,items:B,actions:W}}}async function KG($,Z){try{return await $.reorder(Z)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new n("vault-invalid-order",J.message,{cause:J});throw J}}function k9($){return new n("vault-invalid-order",$)}function CG($){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 k9(`"${G}" is not a vault account.`);if(Q.length>1)throw k9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let B=Q[0].id;if(z.includes(B))throw k9(`"${G}" names an account already in the order.`);z.push(B)}return z}}}function MG($,Z){let{store:J,extraLocks:X}=$,z=X?{extraLocks:X}:{},G=x9($),Q=[{value:"ordered",label:"Ordered (roster order)"},...$.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=S0(Z.settings.routing).mode,Y=typeof B==="string"&&Q.some((D)=>D.value===B)?B:"ordered",W=GZ(Y),V=Z.vault?CG(Z.vault):void 0,H=V?V.ids:Z.rows.map((D)=>D.id),q=(D)=>V?V.nameOf(D):D,j=QZ(H,W.placement,$.routing?.formerMainId??zZ),F=[`Mode: ${Q.find((D)=>D.value===Y)?.label??Y}`];if(H.length>0)F.push(`${V?"Vault account order":"Roster order"}: ${H.map(q).join(", ")}`);if(W.mode==="ordered"&&j.join()!==H.join())F.push(`Tried in order: ${j.map(q).join(", ")}`);let N=[{id:"mode",label:"Change mode",group:n2,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:Q,value:Y}],run:async({values:D})=>{let P=String(D.mode);return await G.update((O)=>{O.routing={...S0(O.routing),mode:P};return}),`Routing mode set to ${Q.find((O)=>O.value===P)?.label??P}.`}}];if(H.length>1)N.push({id:"order",label:"Set order",group:n2,knobs:[{kind:"text",id:"order",label:V?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:V?H.map(V.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:D})=>{let O=String(D.order).split(V?/[,\n]+/:/[\s,]+/).map((C)=>C.trim()).filter((C)=>C.length>0),L=Z.vault&&V?await KG(Z.vault,V.resolve(O)):await J.reorder(O,z);return L.outcome==="unchanged"?"The order is unchanged.":`Order set to ${L.ids.map(q).join(", ")}.`}});if($.routing?.sameAccountWait){let P=[{value:"0",label:"Don't wait"},{value:"15",label:"15 minutes"},{value:"max",label:"Until the cache expires"}],O=S0(Z.settings.routing).maxSameAccountWait,L=String(O===0||O==="max"?O:15),C=(T)=>P.find((K)=>K.value===T)?.label??T;F.push(`Longest wait on the same account: ${C(L)}`),N.push({id:"maxSameAccountWait",label:"Longest wait on the same account",group:n2,knobs:[{kind:"choice",id:"maxSameAccountWait",label:"Longest wait on the same account",choices:P,value:L}],run:async({values:T})=>{let K=String(T.maxSameAccountWait),M=K==="max"?"max":Number(K);return await G.update((_)=>{_.routing={...S0(_.routing),maxSameAccountWait:M};return}),`Longest wait on the same account set to ${C(K)}.`}})}return{id:"routing",slot:"routing",title:"Routing",content:{lines:F,actions:N}}}function LG($,Z){if($.limits?.labels)return[...$.limits.labels];let J=$.quota?.scope??"all",X=[];for(let z of Z.rows)for(let G of l4(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function OG($,Z){let J=$.quota?.scope??"all",X=new Map;for(let z of Z.rows)for(let G of l4(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,XZ(G));return(z)=>X.get(z)??z}function TG($,Z){let J=x9($),X=S0(Z.settings.killswitch),z=X.enabled===!0,G=S0(X.accounts),Q=LG($,Z),B=OG($,Z),Y=z?"on":"off",W=Z.rows.map((V)=>{let{account:H,name:q}=c4(V,$),j=S0(G[V.id]),U=Q.filter((F)=>typeof j[F]==="number");return{id:V.id,label:q,group:`Floors · killswitch ${Y}`,status:U.length===0?"no floors":U.map((F)=>`${B(F)} ≥${j[F]}%`).join(" · "),account:H,actions:[{id:"floors",label:"Set floors",knobs:Q.map((F)=>({kind:"number",id:F,label:`Minimum % left for ${B(F)}`,min:0,max:100,...typeof j[F]==="number"?{value:j[F]}:{}})),run:async({values:F})=>{return await J.update((N)=>{let D=S0(N.killswitch),P=S0(D.accounts),O=S0(P[V.id]);for(let L of Q){let C=F[L];if(typeof C==="number")O[L]=C;else if(C===null)delete O[L]}if(Object.keys(O).length>0)P[V.id]=O;else delete P[V.id];if(Object.keys(P).length>0)D.accounts=P;else delete D.accounts;N.killswitch=D;return}),`Floors updated for ${q}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${Y}`],items:W,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:n2,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!z}],run:async({values:V})=>{let H=V.enabled===!0;return await J.update((q)=>{q.killswitch={...S0(q.killswitch),enabled:H};return}),`Killswitch ${H?"on":"off"}.`}}]}}}async function WZ($){let Z=await NG($);return[DG($,Z),PG($,Z),MG($,Z),TG($,Z)]}var _G=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),b9=["accounts","quota","routing","limits"];function VZ($,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 SG($,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 AG($,Z){let J={};for(let X of $){let z=Z&&Object.hasOwn(Z,X.id)?Z[X.id]:void 0,G=SG(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function EG($,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 K2($){let Z=$.logger??d("commands"),J=R9($.redaction),X={logger:Z,redact:J},z=$.now??Date.now,G=$.extras??[],Q=$.replace??{},B=b9.filter((q)=>!Q[q]);for(let q of b9)if(Q[q]&&$[q]!==void 0)throw Error(`the ${q} section is replaced; its built-in options cannot also be given`);let Y=$.store;if(B.length>0&&!Y)throw Error(`a store is required for the built-in ${B.join(", ")} section${B.length>1?"s":""}`);let W=new Set;for(let q of G){if(_G.has(q.id)||W.has(q.id))throw Error(`extra section id ${q.id} is taken`);W.add(q.id)}async function V(q,j,U,F){try{return{id:q,slot:j,title:U.title,content:await U.build(F)}}catch(N){return Z.warn("command menu section failed to build",{command:$.command,section:q,error:J(N instanceof Error?N.message:String(N))}),{id:q,slot:j,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function H(q){let j=Y&&B.length>0?await WZ({store:Y,now:z,...$.extraLocks?{extraLocks:$.extraLocks}:{},...$.settings?{settings:$.settings}:{},...$.accounts?{accounts:$.accounts}:{},...$.quota?{quota:$.quota}:{},...$.routing?{routing:$.routing}:{},...$.limits?{limits:$.limits}:{}}):[],U=[];for(let F of b9){let N=Q[F];if(N)U.push(await V(F,F,N,q));else{let D=j.find((P)=>P.slot===F);if(D)U.push(D)}}if($.cache)U.push(await V("cache","cache",$.cache,q));if($.diagnostics)U.push(await V("diagnostics","diagnostics",$.diagnostics,q));for(let F of G)U.push(await V(F.id,"extra",F,q));return U}return{command:$.command,async open(q){let j=VZ(q,J);return e5($.command,$.title,await H(j),X)},async apply(q,j){let U=VZ(j,J),F=async(L)=>$Z($.command,$.title,await H(U),L,X),N=q.command===$.command?EG(await H(U),q):void 0;if(!N)return F({ok:!1,code:"unavailable",text:"That action is no longer available."});let D=I9(N);if(D&&q.confirmed!==!0)return F({ok:!1,code:"needs-confirmation",text:D.message,needsConfirmation:!0});let P=AG(N.knobs??[],q.values);if("problem"in P)return F({ok:!1,code:"invalid-input",text:P.problem});let O;try{let L=await N.run({values:P.values,...q.itemId!==void 0?{itemId:q.itemId}:{},invocation:U});O=typeof L==="string"?{ok:!0,text:L}:{ok:L.ok,text:L.text,...L.ok?{}:{code:L.code??"refused"}}}catch(L){let C=I1(L);Z.warn("command menu action failed",{command:$.command,section:q.sectionId,action:q.actionId,code:C.code,error:J(L instanceof Error?L.message:String(L))}),O={ok:!1,...C}}return F(O)}}}function RG($){return $===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($)}function IG($){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(!RG(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 x($,Z){return $.namespace===Z.namespace&&$.accountId===Z.accountId&&$.incarnation===Z.incarnation}function HZ($,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 kG($){return{requestId:$.requestId,originalUrl:$.originalUrl,requestStartedAt:$.clockNow,saw429:!1,tried:[],excludedForRequest:[],retains:[],retainedAttempts:[],excludedAttempts:[],switchedAttempts:[],switches:0}}function d4($,Z,J){return $.excludedForRequest.some((X)=>x(X.account,Z)&&HZ(X.scope,J))}function s2($,Z){switch(Z.type){case"response":{let J=$.tried.some((X)=>x(X.account,Z.account)&&HZ(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)=>x(X.account,Z.account));return{...$,retainedAttempts:[...$.retainedAttempts,Z.attemptId],retains:[...$.retains.filter((X)=>!x(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:d4($,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 f9=Object.freeze({refundHybridToken:!0,cancelDiscardedBody:!0,addMark:!1,addCooldown:!1,penalizeHealth:!1,chargeSwitch:!1});function C2($){return $!==void 0&&Number.isFinite($)&&$>=0?$:300000}function n4(){let $=new Map;return{get size(){return $.size},recordAccepted(Z){if(!x(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(C2)):C2(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[B,Y]of $)if(Y.lastAcceptedAt<Q)G=B,Q=Y.lastAcceptedAt;if(G!==void 0)$.delete(G)}return!0},get(Z){return $.get(Z)},forgetSession(Z){$.delete(Z)}}}function s4($,Z,J){switch($.kind){case"pool":return!0;case"family":return J(Z)===$.family;case"model":return $.model===Z}}var k1=3621000;function s0($){return $===0||$===15||$==="max"?$:15}function x1($){let Z=s0($.maxSameAccountWait),J=$.activity;if(Z===0||!J||!x(J.accountKey,$.accountKey)||!Number.isFinite(J.lastAcceptedAt))return;let X=C2(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 xG}from"node:crypto";function y9($,Z){let J=xG("sha256").update($).digest().readUInt32BE(0);return 1000*(Math.max(1,Math.ceil(Z/1000))+J%21)}var qZ=691200000;function i4($,Z){return UZ($,Z,!1)}function UZ($,Z,J){if(!Number.isFinite($.maxAgeMs)||$.maxAgeMs<0)return;let X;for(let z of $.candidates){if(!x(z.account,z.readingAccount)||z.identity!==void 0&&z.readingIdentity!==void 0&&z.identity!==z.readingIdentity){if(J)return;continue}let G=z.windows.filter((W)=>W.blockedBy&&s4(W.scope,$.effectiveModel,$.familyOf));if(!G.length){if(J)return;continue}let Q=G.map((W)=>{let V=W.reset,H=V?.observedAt??V?.checkedAt;return V&&H!==void 0&&Number.isFinite(H)&&Z-H<=$.maxAgeMs&&Number.isFinite(V.at)&&V.at>Z?V.at:void 0});if(Q.some((W)=>W===void 0)){if(J)return;continue}let B=Math.max(...Q);if(X&&X.resetAt<=B)continue;let Y=G.some((W)=>W.blockedBy!=="exhausted"&&W.reset?.at===B);X={account:z.account,resetAt:B,checkpoint:{accountKey:{...z.account},decidedAt:Z,blockers:Y?[]:G.flatMap((W)=>W.blockedBy==="exhausted"&&W.reset?[{window:W.window,resetAt:W.reset.at}]:[])}}}return X}function jZ($,Z){return $.source==="pool"&&$.reason==="quota"&&Z.terminalMetadata==="setting-capped-fresh"}function FZ($,Z){let J=$.scan,X=J?.waitForReset?.jitterMs;if($.reason!=="quota"||!J||X===void 0||!Number.isInteger(X)||X<0)return;let z=UZ(J,Z,!0);if(!z)return;return{kept:z,delayMs:Math.ceil((z.resetAt-Z)/1000)*1000+X}}function NZ($,Z,J){return jZ($,Z)&&s0($.scan?.maxSameAccountWait)===0&&!FZ($,J)}function DZ($,Z,J,X){let z=FZ(X,$.now);if(!z&&!jZ(X,Z))return;let G=X.scan,Q=s0(G?.maxSameAccountWait),B=z?.kept??(G&&i4(G,$.now)),Y=B?B.resetAt-$.now:300000,W=G?.activity,V=G?.accountKey??$.attempted,H=W&&V&&x(W.accountKey,V)?C2(W.ttlMs)||300000:300000,q=z?.delayMs??Math.min(Y,Q==="max"?H:900000),j=!z&&Q===0||$.host==="pi"&&$.wake?.kind==="terminal",U=j?B?Y:void 0:q,F=Z.refusals.quota[$.host],N={action:"refuse",reason:"quota",family:$.host==="pi"?"pi-final":j?"json-412":F.family,messageKey:X.messageKey??F.messageKey,retryable:$.host!=="pi"&&!j,hostRetry:$.host==="pi"||j?"veto":"leave",history:J,...U===void 0?{}:{retryAfterMs:U},...B?{resetAt:B.resetAt}:{}};if(!B||j||$.host==="opencode1")return N;let D={delayMs:q,retryAfterMs:q,resetAt:B.resetAt,target:$.now+q,checkpoint:B.checkpoint,waitKind:"terminal",reason:"terminal-quota",retryable:!0,hostRetry:"leave",history:J};if($.host==="pi")return{...D,action:"wait-then-reselect"};if($.hostPhase!=="retry")return N;if($.remainingRetries!==void 0&&$.remainingRetries<1)return{action:"pass",reason:"host-retries-exhausted",retryable:!0,hostRetry:"leave",history:J};if($.remainingRetries===void 0||z&&Number.isNaN($.remainingRetries)||q>(z?qZ:k1))return N;return{...D,action:"hold",account:B.account}}function h9($,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 PZ($,Z,J,X){let{checkpoint:z,target:G}=$;if(!x(Z,z.accountKey)||!Number.isFinite(G)||!Number.isFinite(z.decidedAt)||G<z.decidedAt||!Number.isFinite(X)||X<G)return[];let Q=(B)=>{let Y=B.resetAt;return B.confirmed&&Y!==void 0&&Number.isFinite(Y)&&Y<=G&&z.blockers.some((W)=>W.window===B.window&&Number.isFinite(W.resetAt)&&Y<=W.resetAt)};return J.filter((B)=>Q(B)&&J.filter((Y)=>Y.confirmed&&Y.window===B.window).every(Q)).map((B)=>B.window)}function a4($,Z){return $!==void 0&&Number.isFinite($)&&$>Z}function i2($,Z){return Z.execution==="engine"&&$.phase==="after-limit"?"veto":"leave"}function g0($,Z,J,X,z){let G=z&&DZ($,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 bG($,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((W)=>!a4(W.resetAt,$.now)))return;let Q=Math.max(...z.map((W)=>W.resetAt)),B=Z.shortLimit.jitter==="session-sha256"?y9($.sessionId,Q-$.now):Q-$.now,Y=$.now+B;if(!Number.isFinite(Y)||Y>Math.min(G.cacheExpiresAt,$.now+G.maxWaitMs)||$.host==="opencode2"&&B>k1||G.maxDelayMs!==void 0&&B>G.maxDelayMs)return;return{action:"hold",account:X.account,delayMs:B,retryAfterMs:B,target:Y,checkpoint:h9(X.account,$.now,z),reason:"confirmed-limit",retryable:!0,hostRetry:$.phase==="pre-send"?"leave":i2($,Z),history:J}}function fG($,Z,J,X){let z=Z.poolWaiting;if(z.kind==="off"||!X.length)return;J=s2(J,{type:"blocked",clockNow:$.clockNow});let Q=X.map((j)=>{let U=j.blockers.filter((F)=>!(F.kind==="soft"&&X.length===1&&z.singleEligibleSoftExemption));if(U.some((F)=>!a4(F.until,$.now)))return;return U.length?{candidate:j,time:Math.max(...U.map((F)=>F.until))}:void 0}).filter((j)=>j!==void 0).reduce((j,U)=>!j||U.time<j.time?U:j,void 0),B=Q?Q.time-$.now:X.some((j)=>j.blockers.some((U)=>U.kind!=="soft"))?z.hardFallbackMs:void 0,Y=$.poolWaitBudgetMs??z.budgetMs,W=$.clockNow-(J.blockedSince??$.clockNow);if(Y>0&&(W>=Y||B!==void 0&&B>Y))return g0($,Z,J,"quota",$.terminal);let V=z.requestDeadlineMs-($.clockNow-J.requestStartedAt);if(V<=0)return g0($,Z,J,"incomplete");if(B===void 0)return g0($,Z,J,"quota",$.terminal);let H=Math.min(B,V,Y>0?Y-W:Number.POSITIVE_INFINITY),q=Q?.candidate??X[0];if(!q)return;return{action:"wait-then-reselect",delayMs:H,target:$.now+H,checkpoint:h9(q.account,$.now,q.confirmedBlockers??[]),reason:"pool-blocked",retryable:!0,hostRetry:i2($,Z),history:J}}function g9($,Z){let J=$.history,X=(K,M=$.phase==="pre-send"?!0:$.failureRetryable??!0,_="leave")=>({action:"pass",reason:K,retryable:M,hostRetry:_,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=s2(J,{type:"response",account:$.attempted,scope:$.requestScope,status:z,kind:Z.terminalStatusHistory?.paymentBalance&&$.signalApplicable!==!1&&$.signal&&x($.signal.account,$.attempted)?$.signal.kind:void 0});if($.phase==="after-limit"&&!$.delivery.replayable)return X("unsafe-output",!1,"veto");let G=$.candidates.filter((K)=>K.admitted),Q=G.filter((K)=>!d4(J,K.account,$.requestScope)),B=Q.find((K)=>$.attempted&&x(K.account,$.attempted)),Y=$.signalApplicable!==!1&&$.signal&&$.attempted&&x($.signal.account,$.attempted)?$.signal:void 0;if(Z.requestExclusion==="on"&&Y?.kind==="model-unavailable"&&B)return{action:"exclude-for-request",account:B.account,scope:$.requestScope,effects:f9,reason:"model-unavailable",retryable:!0,hostRetry:i2($,Z),history:J};if(G.length&&!Q.length)return g0($,Z,J,"model-unavailable");if($.host==="opencode2"&&$.hostPhase==="retry"&&Z.execution==="host"&&$.remainingRetries!==void 0&&$.remainingRetries<1)return $.terminal&&($.terminal.retryable===!1||NZ($.terminal,Z,$.now))?g0($,Z,J,$.terminal.reason,$.terminal):X("host-retries-exhausted");if($.wake&&$.phase==="pre-send"){let K=$.wake,M=Q.find((g)=>x(g.account,K.checkpoint.accountKey)),_=M?.confirmedBlockers??(M&&Y&&x(Y.account,M.account)?Y.windows:[]),R=M?PZ(K,M.account,_,$.now):[],I=$.hold,k=K.kind==="terminal"||I!==void 0&&Number.isFinite(I.cacheExpiresAt)&&$.now<=I.cacheExpiresAt&&K.target<=I.cacheExpiresAt&&I.maxWaitMs>0&&K.target-K.checkpoint.decidedAt<=I.maxWaitMs;if(M&&Number.isFinite(K.target)&&K.target>=K.checkpoint.decidedAt&&$.now>=K.target&&k&&M.blockers.every((g)=>g.until!==void 0&&Number.isFinite(g.until)&&g.until<=$.now)&&(M.ready||_.some((g)=>g.confirmed))&&_.filter((g)=>g.confirmed).every((g)=>R.includes(g.window)))return{action:"retain",account:M.account,liftedWindows:R,reason:"wait-elapsed",retryable:!0,hostRetry:"leave",history:s2(J,{type:"selected"})}}if($.credentialRecovery&&B)return{action:"retain",account:B.account,reason:"credential-recovery",...$.credentialRecovery.retryMs===void 0?{}:{retryMs:$.credentialRecovery.retryMs},retryable:!0,hostRetry:i2($,Z),history:J};let W=Z.unconfirmedRetainLimit,V=$.unconfirmedRetainCount,H=z===429&&W!==void 0&&V!==void 0,q=Z.advance[$.host];if($.phase==="after-limit"&&Z.terminalStatusHistory?.paymentBalance&&(Y?.kind==="payment-cap"||z===402&&Y?.kind!=="payment-balance"))return X("unhandled-failure");if($.phase==="after-limit"&&!Y&&!H&&!$.terminal&&(q.attributedLimitOnly||z===void 0||!q.statuses.includes(z)))return X("unhandled-failure");let j=Q.find((K)=>$.selection&&x(K.account,$.selection.account)&&K.placementEligible),U=j&&(j.ready||Z.poolWaiting.kind==="earliest"&&Z.poolWaiting.singleEligibleSoftExemption&&Q.length===1&&j.blockers.length>0&&j.blockers.every((K)=>K.kind==="soft")),F=U&&(!$.attempted||!x(j.account,$.attempted))?j:void 0,N=(K,M="ready-alternative")=>({action:"reroute",account:K.account,pin:$.selection?.pin??"preserve",reason:M,retryable:!0,hostRetry:i2($,Z),history:s2(J,{type:"selected"})}),D=$.phase==="pre-send"?B??Q.find((K)=>$.selection&&x(K.account,$.selection.account)):B,P=(D?.confirmedBlockers??($.phase==="after-limit"?Y?.windows:void 0)??[]).filter((K)=>K.confirmed);if(P.length){if(Z.shortLimit.preference==="ready-alternative-first"&&F)return N(F);let K=bG($,Z,J,D,P);if(K)return K}let O=Z.unknown[$.host],L=$.phase==="after-limit"&&!P.length&&(z===429||Y?.kind==="rate-limit"||Y?.kind==="quota-exhausted"||Y?.kind==="capacity"),C=H&&V>=W;if(L&&B&&(O.affinity==="always"||$.affinity==="sticky")){if(H&&C){if(F)return N(F,"unconfirmed-retry-limit")}else if(H||O.action==="retain"){let K=[...$.retryHintsMs??[],Y?.retryAfterMs].filter((M)=>M!==void 0&&Number.isFinite(M)&&(H||M>=0));return{action:"retain",account:B.account,reason:"unconfirmed-limit",...H?{retryMs:Math.min(60000,...K.map((M)=>Math.max(0,M))),incrementUnconfirmedRetain:!0}:O.hint==="minimum"?{retryMs:Math.min(O.defaultMs,...K)}:{},retryable:!0,hostRetry:i2($,Z),history:J}}else if(O.action==="pass")return X("unconfirmed-limit")}if(F)return N(F);if($.phase==="pre-send"&&U)return N(j);if($.host==="opencode2"&&$.hostPhase==="request"&&Z.markedPool.requestEscape==="ignore-timed-marks-if-all-marked"&&j&&Q.every((K)=>!K.ready)&&Q.every((K)=>K.blockers.length>0&&K.blockers.every((M)=>M.kind==="hard")))return N(j);let T=fG($,Z,J,Q);if(T)return T;if($.phase==="pre-send"&&!Q.length)return g0($,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"&&B)return{action:"retain",account:B.account,reason:"host-delay",retryable:!0,hostRetry:"leave",history:J}}if(Z.terminalPolicy==="status-history"&&Z.terminalStatusHistory&&$.host!=="opencode2"&&!$.terminal){let K=$.phase==="pre-send"&&Q.length>0&&Q.every((R)=>!R.ready),M=Q.filter((R)=>R.placementEligible),_=$.phase==="pre-send"&&Z.terminalStatusHistory.paymentBalance&&M.length>0&&M.every((R)=>!R.ready&&R.blockers.length>0&&R.blockers.every((I)=>I.cause==="payment-balance"&&a4(I.until,$.now)));if(_||K||z===401&&J.saw429||Z.terminalStatusHistory.paymentBalance&&J.saw429&&J.sawPaymentBalance){let R=(_?M:Q).flatMap((I)=>I.blockers.map((k)=>k.until)).filter((I)=>a4(I,$.now));return g0($,Z,J,"quota",{source:"pool",reason:"quota",..._?Z.terminalStatusHistory.paymentBalance:{},retryAfterMs:R.length?Math.max(Z.terminalStatusHistory.minRetryMs,Math.min(...R)-$.now):Z.terminalStatusHistory.defaultRetryMs})}return X("original-response")}if($.terminal)return g0($,Z,J,$.terminal.reason,$.terminal);if(Y?.kind==="auth"||Y?.kind==="account-access")return g0($,Z,J,"auth");if(Y||z===429||Q.some((K)=>K.blockers.length))return g0($,Z,J,"quota");return X("no-override")}function a2($){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 r2=({resetAt:$,now:Z})=>a2($-Z);var w9=Symbol.for("@cortexkit/common-auth/limits-envelope-error");class f1 extends Error{[w9]="conflict";constructor(){super("Conflicting limits envelope writers");this.name="LimitsEnvelopeConflictError"}}class y1 extends Error{[w9]="unsupported";constructor(){super("Invalid or unsupported limits namespace schema");this.name="LimitsEnvelopeUnsupportedError"}}function m9($){let Z=$&&typeof $==="object"&&Reflect.get($,w9);return Z==="conflict"||Z==="unsupported"?Z:void 0}function i0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}var M2=($)=>Number.isSafeInteger($)&&$>=0,v9=($)=>typeof $==="number"&&Number.isFinite($),KZ=($)=>$===void 0||$==="rate-limit"||$==="payment-balance",b1=($,Z)=>Array.isArray($)&&$.every(Z);function MZ($,Z){return i0($)&&$.namespace===Z&&typeof $.accountId==="string"&&typeof $.incarnation==="string"}function CZ($,Z){if(!i0($)||!i0($.scope))return!1;let J=$.scope;return MZ($.account,Z)&&typeof $.window==="string"&&(J.kind==="pool"||J.kind==="family"&&typeof J.family==="string"||J.kind==="model"&&typeof J.model==="string")}function yG($,Z){return $.namespace===Z&&typeof $.generation==="string"&&M2($.revision)&&M2($.lowWatermark)&&b1($.marks,(J)=>i0(J)&&CZ(J.key,Z)&&["latest-evidence","max-until","overwrite"].includes(J.mergeLaw)&&b1(J.entries,(X)=>i0(X)&&KZ(X.cause)&&v9(X.until)&&v9(X.evidenceAt)&&M2(X.baseRevision)&&M2(X.committedRevision)))&&b1($.tombstones,(J)=>i0(J)&&CZ(J.key,Z)&&M2(J.revision)&&KZ(J.cause))&&b1($.operationIds,(J)=>i0(J)&&typeof J.producerId==="string"&&typeof J.operationId==="string"&&M2(J.revision))&&b1($.access,(J)=>i0(J)&&MZ(J.account,Z)&&v9(J.eligibilityStateUpdatedAt)&&M2(J.committedRevision))}class h1{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(!i0($))Z="malformed";else if($.schemaVersion!==1)throw this.terminal=new y1,this.terminal;else if(typeof $.namespace==="string"&&$.namespace!==this.namespace)Z="foreign-namespace";else if(!yG($,this.namespace))Z="malformed";if(!Z)return{snapshot:$};if(this.replaced)throw this.terminal=new f1,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 hG=[/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],gG=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 o2($){let Z=$.toLowerCase();return Z.includes("too_many_requests")||Z.includes("exhausted")||Z.includes("unavailable")||hG.some((J)=>J.test($))||gG.test($)}class r4 extends Error{messageKey;code="unsafe-wording";constructor($){super(`Unsafe refusal template: ${$}`);this.messageKey=$,this.name="UnsafeWordingError"}}function u9($){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 B=Object.freeze({labels:Object.freeze(Q),reset:G}),Y;try{Y=z(B)}catch{throw new r4(X)}if(typeof Y!=="string"||o2(Y))throw new r4(X)}return Object.freeze({formatReset:$.formatReset,render:(X,z,G)=>(G?Z:J).get(X)?.(z)})}var vG=/[^\s@]+@[^\s@]+\.[^\s@]+/;function p9($){return vG.test($)}function l9($){return p9($)||o2($)?"this account":$}class c9 extends Error{code="ECONNRESET";syscall="sticky-routing";isRetryable=!0;constructor($){super($,{cause:{code:"ECONNRESET",syscall:"sticky-routing"}});this.name="ClaudeIncompleteError"}}function o4($,Z=0){if($===void 0||!Number.isFinite($)||$<0)return;let J=$-d9(Z);return J>=0?Math.ceil(J/1000):void 0}function d9($){return Number.isFinite($)&&$>=0?$:0}function OZ($){return $.resetAt!==void 0&&Number.isFinite($.resetAt)?$.resetAt:void 0}function wG($){return $===void 0?"The reset is unknown.":`Reset at ${$}.`}function TZ($,Z,J,X){let z=!X&&J!==void 0?` Retry in ${a2(J*1000)}.`:"";return`${$==="pi-final"?"The request cannot continue.":"No account is available."}${z} ${wG(Z)}`}function _Z($,Z,J){let X=OZ($),z=X===void 0?void 0:r2({resetAt:X,now:Z}),G=o4($.retryAfterMs,$.noticeDelayMs);return TZ($.family,z,G,J)}function mG($,Z){let J=$.now+d9($.noticeDelayMs??0),X=()=>_Z($,J,Z);try{let z=OZ($),G=z===void 0?void 0:($.messages?.formatReset??r2)({resetAt:z,now:J}),Q=o4($.retryAfterMs,$.noticeDelayMs),B=Object.freeze({labels:Object.freeze($.labelPolicy==="relogin"?($.parameters?.labels??[]).map(l9):[]),reset:G,retryIn:!Z&&Q!==void 0?a2(Q*1000):void 0}),Y=$.messages?.render($.messageKey,B,Z);return typeof Y==="string"?Y:TZ($.family,G,Q,Z)}catch{return X()}}function LZ($,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 n9($){let Z=$.family==="json-412"||$.family==="pi-final",J={family:$.family,disposition:"refuse",retryable:!Z,hostRetry:Z||$.host==="opencode2"?"veto":"leave"},X=LZ($.family,mG($,Z));if(Z&&(o2(X)||p9(X))){let Q=$.now+d9($.noticeDelayMs??0);X=LZ($.family,_Z($,Q,!0))}if($.family==="claude-econnreset")return{...J,kind:"throw",error:new c9(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=o4($.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 a0($,Z){return x($.account,Z.account)&&($.identity===void 0||Z.identity===void 0||$.identity===Z.identity)}function s9($,Z){if(!a0($,Z))return Z;return{...Z,identity:Z.identity??$.identity}}function i9($,Z,J){if(!a0($,Z))return"identity-replaced";if(!J($,Z))return"credential-epoch";return}var a9=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 t4($,Z,J,X=0){let z=Z.filter((G)=>G.baseRevision>=X);if($!=="max-until"){let G=z.reduce((Q,B)=>{if(!Q)return B;if($==="latest-evidence"&&B.evidenceAt!==Q.evidenceAt)return B.evidenceAt>Q.evidenceAt?B:Q;return B.committedRevision>Q.committedRevision?B:Q},void 0);return G&&J<G.until?[G]:[]}return z.filter((G,Q)=>J<G.until&&!z.some((B,Y)=>Y!==Q&&B.until>=G.until&&B.baseRevision>=G.baseRevision&&(B.until>G.until||B.baseRevision>G.baseRevision||B.committedRevision>G.committedRevision||B.committedRevision===G.committedRevision&&Y<Q))).sort((G,Q)=>G.committedRevision-Q.committedRevision)}function g1($,Z){if($.eligibilityStateUpdatedAt!==Z.eligibilityStateUpdatedAt)return $.eligibilityStateUpdatedAt>Z.eligibilityStateUpdatedAt?$:Z;return $.committedRevision>Z.committedRevision?$:Z}var AZ=1024;function r9($){return $==="rate-limit"||$==="payment-balance"?$:void 0}function e4($,Z){return r9($.cause)===void 0||$.cause===Z}function EZ($){return JSON.stringify([s($.key),r9($.cause)])}function A0($,Z){return{schemaVersion:1,namespace:$,generation:Z,revision:0,lowWatermark:0,marks:[],tombstones:[],operationIds:[],access:[]}}function pG($){return JSON.stringify([$.namespace,$.accountId,$.incarnation])}function s($){let Z=$.scope;return JSON.stringify([pG($.account),Z.kind,Z.kind==="model"?Z.model:Z.kind==="family"?Z.family:null,$.window])}function SZ($){return JSON.stringify([$.producerId,$.operationId])}function L2($,Z){let J=new Map;for(let Y of $.tombstones){let W=s(Y.key),V=J.get(W);if(V)V.push(Y);else J.set(W,[Y])}let X=$.marks.flatMap((Y)=>{let W=J.get(s(Y.key)),V=t4(Y.mergeLaw,W?Y.entries.filter((H)=>!W.some((q)=>e4(q,H.cause)&&H.baseRevision<q.revision)):Y.entries,Z);return V.length?[{...Y,entries:V}]:[]}),z=$.lowWatermark,G=(Y)=>{let W=[...Y].sort((H,q)=>H.revision-q.revision),V=Math.max(0,W.length-AZ);for(let H of W.slice(0,V))z=Math.max(z,H.revision+1);return W.slice(V)},Q=G($.tombstones),B=G($.operationIds);return{...$,revision:Math.max($.revision,z),marks:X,tombstones:Q,operationIds:B,lowWatermark:z}}function O2($,Z,J){let X=L2($,J.now),z=[];for(let G of Z){let Q=(N)=>{z.push({producerId:G.producerId,operationId:G.operationId,status:"rejected",reason:N})};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 B=J.bindings.find((N)=>x(N.account,G.binding.account));if(!B){Q("unknown-account");continue}let Y=i9(G.binding,B,J.authorizeEpoch);if(Y){Q(Y);continue}let W=X.operationIds.find((N)=>SZ(N)===SZ(G));if(W){z.push({...W,status:"duplicate"});continue}let V=B.account,H=X.revision+1,q=[...X.marks],j=[...X.tombstones],U=[...X.access];if(G.type==="mark"){let N={account:V,scope:G.scope,window:G.window},D=s(N),P=q.find((L)=>s(L.key)===D);if(j.some((L)=>G.baseRevision<L.revision&&e4(L,G.cause)&&s(L.key)===D)){Q("cleared");continue}if(P&&P.mergeLaw!==G.mergeLaw){Q("merge-law-conflict");continue}let O=t4(G.mergeLaw,[...P?.entries??[],{until:G.until,evidenceAt:G.evidenceAt,baseRevision:G.baseRevision,committedRevision:H,...G.cause==="rate-limit"||G.cause==="payment-balance"?{cause:G.cause}:{}}],J.now);if(q=q.filter((L)=>s(L.key)!==D),O.length)q.push({key:N,mergeLaw:G.mergeLaw,entries:O})}else if(G.type==="clear"){let N=r9(G.cause),D=G.keys.map((L)=>({...L,account:V})).filter((L)=>G.cause===void 0||!q.some((C)=>s(C.key)===s(L)&&C.entries.some((T)=>T.cause!==G.cause))),P=new Set(D.map(s)),O=G.evidenceAt;if(O!==void 0&&q.some((L)=>P.has(s(L.key))&&L.entries.some((C)=>C.evidenceAt>O))){Q("newer-evidence");continue}q=q.filter((L)=>!P.has(s(L.key))),j=j.filter((L)=>!P.has(s(L.key))||N!==void 0&&L.cause!==N);for(let L of new Map(D.map((C)=>[s(C),C])).values())j.push({key:L,revision:H,...N===void 0?{}:{cause:N}})}else{let N={account:V,state:G.state,eligibilityStateUpdatedAt:G.eligibilityStateUpdatedAt,committedRevision:H},D=U.find((P)=>x(P.account,V));U=U.filter((P)=>!x(P.account,V)),U.push(D?g1(D,N):N)}let F={producerId:G.producerId,operationId:G.operationId,revision:H};X=L2({...X,revision:H,marks:q,tombstones:j,access:U,operationIds:[...X.operationIds,F]},J.now),z.push({...F,status:"committed"})}return{snapshot:X,outcomes:z}}import{realpathSync as lG}from"node:fs";import{basename as RZ,dirname as IZ,join as cG,resolve as dG}from"node:path";function v1($){let Z=dG($),J=[RZ(Z)],X=IZ(Z);for(;;)try{return cG(lG.native(X),...J.reverse())}catch(z){let G=z.code;if(G!=="ENOENT"&&G!=="ENOTDIR")throw z;let Q=IZ(X);if(Q===X)return Z;J.push(RZ(X)),X=Q}}class E0 extends Error{code;constructor($){super($);this.code=$,this.name="LimitsPersistenceRefusal"}}import{randomUUID as aG}from"node:crypto";import{isDeepStrictEqual as xZ}from"node:util";import{AsyncResource as nG}from"node:async_hooks";import{randomUUID as kZ}from"node:crypto";import{isDeepStrictEqual as sG}from"node:util";var iG=new nG("common-auth-limits-recovery");class w1{logger;running;listeners=new Set;constructor($){this.logger=$}subscribe=($)=>{return this.listeners.add($),()=>this.listeners.delete($)};schedule($){if(this.running)return;this.running=iG.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 T2{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=sG($,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)=>s(z.key)===s(X.key)&&e4(z,X.cause)&&z.revision>=X.revision)))}recover($,Z,J,X){if(!$)this.missingGeneration??=kZ();let z=$??A0(J,this.missingGeneration??kZ()),G=[...this.retained(Z),z],Q=new Map,B=new Map,Y=new Map,W=new Map,V=0;for(let q of G){V=Math.max(V,q.revision,q.lowWatermark);for(let j of q.marks){let U=s(j.key),F=Q.get(U);if(F&&F.mergeLaw!==j.mergeLaw)throw Error("limits-recovery-merge-law-conflict");Q.set(U,{...j,entries:[...F?.entries??[],...j.entries]});for(let N of j.entries)V=Math.max(V,N.baseRevision,N.committedRevision)}for(let j of q.tombstones){let U=EZ(j),F=B.get(U);if(!F||F.revision<j.revision)B.set(U,j);V=Math.max(V,j.revision)}for(let j of q.operationIds){let U=JSON.stringify([j.producerId,j.operationId]),F=Y.get(U);if(!F||F.revision<j.revision)Y.set(U,j);V=Math.max(V,j.revision)}for(let j of q.access){let{namespace:U,accountId:F,incarnation:N}=j.account,D=JSON.stringify([U,F,N]),P=W.get(D);W.set(D,P?g1(P,j):j),V=Math.max(V,j.committedRevision)}}let H=V+1;if(!Number.isSafeInteger(H))throw Error("limits-revision-exhausted");return L2({...z,revision:H,lowWatermark:H,marks:[...Q.values()],tombstones:[...B.values()],operationIds:[...Y.values()],access:[...W.values()]},X)}}function bZ($,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 o9($){let{store:Z,namespace:J}=$;if(!Z.updateLimitsNamespace)throw new E0("limits-unsupported");let X=Z.updateLimitsNamespace.bind(Z),z=aG(),G=new T2,Q=new h1(J,$.logger),B=new w1($.logger),Y=$.now??Date.now,W=async()=>{let j=await Z.read();if(j.status!=="ready"){if(j.status==="error"&&j.kind==="snapshot-contended")throw Error(j.reason);throw new E0("pool-not-ready")}return bZ(J,j.rows)},V=async()=>{let j=await Z.readSettings();if(j.status!=="ready")throw new E0("pool-not-ready");return Q.decode(j.settings.commonAuthLimits)},H=async(j)=>{Q.assertWritable();let U=await W(),F=await V(),N;for(let D=0;D<3;D++){let P=await W(),O=await V(),L=xZ(U,P)&&xZ(F,O);if(N={snapshot:F.snapshot??A0(J,z),bindings:U,authoritative:L},L){if(!F.replacement&&G.lost(F.snapshot,j))return B.schedule(()=>q.commit([],j)),{snapshot:G.recover(F.snapshot,j,J,Y()),bindings:U,authoritative:!1,degradedAgreement:!0};if(F.snapshot)G.remember(F.snapshot);return N}U=P,F=O}return N},q={namespace:J,read:H,subscribe:B.subscribe,async commit(j,U){Q.assertWritable();let F,N,D=()=>{if(Q.didCommit(N)&&F)G=new T2,G.remember(F.snapshot,U)};try{await X((P,O)=>{let L=bZ(J,O),C=Q.decode(P),T=C.snapshot;N=C.replacement;let K=!N&&G.lost(T,U),M=O2(K?G.recover(T,U,J,Y()):T??A0(J,z),j,{now:Y(),bindings:L,authorizeEpoch:(_,R)=>_.credentialEpoch===R.credentialEpoch});return F={...M,bindings:L,authoritative:!0,degradedAgreement:K},M.snapshot},{beforePublish:()=>Q.assertWritable(),onPublished:D})}catch(P){if(Q.assertWritable(),P instanceof b&&(P.kind==="pending-migration"||P.kind==="load-error"))throw new E0("pool-not-ready");throw P}if(!F)throw Error("Pool limits mutator was not called");return D(),G.remember(F.snapshot,U),F}};return await H(),q}function t2($){if($&&typeof $==="object"){for(let Z of Object.values($))t2(Z);Object.freeze($)}return $}function R0($){return{opencode1:$,opencode2:$,pi:$}}var _2={action:"reselect",affinity:"always",hint:"none",defaultMs:60000},fZ={..._2,action:"retain",affinity:"sticky"},hZ={family:"local-auth",messageKey:"auth.no-account",retryable:!1,hostRetry:"leave"};function Z6($,Z){return{auth:R0(hZ),quota:R0($),incomplete:R0(Z),"model-unavailable":R0({family:"json-412",messageKey:"model-unavailable",retryable:!1,hostRetry:"veto"})}}var $6={kind:"off"},gZ={requestEscape:"off",retryExhaustion:"terminal"},vZ={statuses:[],attributedLimitOnly:!0},yZ={family:"json-412",messageKey:"quota.pool-exhausted",retryable:!1,hostRetry:"veto"},wZ=t2({unconfirmedRetainLimit:2,evidence:"per-field-overlay",markers:R0({kind:"reset",mergeLaw:"latest-evidence",defaultMs:60000}),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"on",unknown:{opencode1:{..._2,action:"retain",hint:"minimum"},opencode2:_2,pi:{..._2,action:"pass"}},shortLimit:{holdBound:"cache-ttl",preference:"same-account-first",jitter:"session-sha256"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:R0(vZ),markedPool:gZ,terminalMetadata:"setting-capped-fresh",terminalPolicy:"provided",refusals:Z6({family:"claude-429",messageKey:"quota.all-accounts",retryable:!0,hostRetry:"leave"},{family:"claude-econnreset",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),mZ=t2({evidence:"typed",markers:R0(a9),readingClearsCoveredScopes:"on",successClearsCoveredScopes:"off",unknown:R0(_2),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:R0({statuses:[429,503,529],attributedLimitOnly:!1}),markedPool:gZ,terminalMetadata:"baseline",terminalPolicy:"pool",refusals:Z6(yZ,{...yZ,messageKey:"incomplete.timeout"})}),B2=t2({evidence:"named-window",markers:{opencode1:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},opencode2:{kind:"reset",mergeLaw:"max-until",defaultMs:60000},pi:$6},readingClearsCoveredScopes:"off",successClearsCoveredScopes:"off",unknown:{opencode1:fZ,opencode2:_2,pi:fZ},shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:R0({statuses:[401,403,429],attributedLimitOnly:!1}),markedPool:{requestEscape:"ignore-timed-marks-if-all-marked",retryExhaustion:"same-host-delay"},terminalMetadata:"baseline",terminalPolicy:"provided",refusals:Z6({family:"openai-429",messageKey:"quota.no-route",retryable:!0,hostRetry:"leave"},{family:"openai-429",messageKey:"incomplete.snapshot",retryable:!0,hostRetry:"leave"})}),uZ=t2({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:R0(_2),shortLimit:{holdBound:"disabled",preference:"ready-alternative-first",jitter:"none"},retainBound:"none",poolWaiting:$6,execution:"host",requestExclusion:"off",advance:{opencode1:{statuses:[401,429],attributedLimitOnly:!1},opencode2:vZ,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:Z6({family:"claustrum-429",messageKey:"quota.accounts-rate-limited",retryable:!0,hostRetry:"leave"},{...hZ,messageKey:"incomplete.no-account"})}),rG=t2({"confirmed-affinity":wZ,"earliest-pool-engine":mZ,"window-router":B2,"status-vault-order":uZ});import{AsyncResource as oG}from"node:async_hooks";var X6=Symbol.for("@cortexkit/common-auth/limits-registry/schema-v1"),tG="@cortexkit/common-auth/limits-registry/schema-v",J6=1000,pZ=5000,S2=new oG("common-auth-limits"),eG={now:()=>Date.now(),setTimeout($,Z){let J=setTimeout($,Z);return J.unref?.(),J},clearTimeout:($)=>clearTimeout($)};function $Q(){for(let J of Object.getOwnPropertySymbols(globalThis))if(Symbol.keyFor(J)?.startsWith(tG)&&J!==X6)throw Error("limits-schema-mismatch");let $=Reflect.get(globalThis,X6);if($){if($.schemaVersion!==1||!($.namespaces instanceof Map))throw Error("limits-schema-mismatch");return $}let Z={schemaVersion:1,namespaces:new Map};return Reflect.set(globalThis,X6,Z),Z}function A2($){return JSON.stringify([$.producerId,$.operationId])}class lZ{adapter;clock;restrictive;listeners=new Set;owners=0;activity=n4();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??eG,this.restrictive=$.isAccessRestrictive}fail($){if(this.abandoned)return;let Z=m9($);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)=>x(X.account,Z.account));return J?s9(J,Z):Z});for(let[Z,J]of this.restrictions){let X=J.command,z=this.bindings.find((Q)=>x(Q.account,X.binding.account)),G=this.snapshot.access.find((Q)=>x(Q.account,X.binding.account));if(!z||!a0(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);S2.runInAsyncScope(()=>{this.publicationTimer=this.clock.setTimeout(()=>{this.publicationTimer=void 0,S2.runInAsyncScope(()=>{this.flush()})},$)})}armReload(){if(!this.live||this.reading||this.reloadTimer!==void 0||this.clock.now()-this.lastActivity>=pZ)return;S2.runInAsyncScope(()=>{this.reloadTimer=this.clock.setTimeout(()=>{if(this.reloadTimer=void 0,!this.live||this.clock.now()-this.lastActivity>=pZ)return;S2.runInAsyncScope(()=>{this.reload()})},Math.max(0,this.lastReadAttempt+J6-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,S2.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=S2.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 A0(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=O2(L2($,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=A2($);if(this.journal.has(J)||this.snapshot.operationIds.some((z)=>A2(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:J6)}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=S2.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)=>A2(Q)===A2(z.command));if(!G)throw Error("limits-missing-acknowledgement");this.settle(z,G)}}catch(X){if(m9(X)){this.fail(X);return}if(this.abandoned)return;if(X instanceof E0&&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(A2(z.command)))this.failed.add(A2(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(J6);if(this.degradedAgreement&&this.live)this.armReload()}),this.writing}settle($,Z){let J=$.command,X=A2(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"&&x(z.command.binding.account,$.account));if(Z())await Promise.race([this.flush(),this.abandonment]);if(this.dirty||this.clock.now()-this.lastReloadAt>=J6)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)=>x(z.account,$.account)),X=this.provisional();return{snapshot:X,blocked:Z()||!J||!a0(J,$)||[...this.restrictions.values()].some((z)=>x(z.command.binding.account,$.account))||[...this.snapshot.access,...X.access].some((z)=>x(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=$Q(),J=Z.namespaces.get($.adapter.namespace);if(!J)J=new lZ($),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(Y){throw X.listeners.delete(z),X.owners--,X.live=!1,X.cancelTimers(),Y}let Q=!1,B=()=>{if(Q)throw Error("limits-registry-disposed")};return{get abandoned(){return X.abandoned},get snapshot(){return B(),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(Y){return B(),{binding:structuredClone(Y),baseRevision:X.snapshot.revision}},enqueue(Y,W){B(),X.enqueue(Y,W)},beforeDispatch(Y){return B(),X.beforeDispatch(Y)},flush(){return B(),X.flush()},reload(){return B(),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 W2($){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 e9($){try{let J=W2($.sessionId);if(!J||typeof J.accountFor!=="function")return}catch{return}let Z=x1($);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 XQ}from"node:fs";import{rm as nZ}from"node:fs/promises";import{dirname as zQ,join as X7}from"node:path";import{resolveClaustrumConnectionPath as GQ}from"@cortexkit/claustrum-client";function cZ($,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 $$($){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 ZQ($){let Z=$$($.total),J=$$($.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 JQ($,Z){if(!E($))return;let J=$$($.remaining);return{hasCredits:!0,unlimited:typeof $.unlimited==="boolean"?$.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...$.spendable===!1&&{overageLimitReached:!0},checkedAt:Z}}function Z$($,Z){if($.insulaCreditsUnlimitedUnstated&&$.credits&&$.credits.balance===void 0&&E(Z)&&E(Z.credits)&&Z.credits.unlimited===!0)return{...$,credits:{...$.credits,unlimited:!0}};return $}function dZ($,Z){let J=cZ($.usage?.primary,Z.fetchedAt);if(!J||!Number.isFinite(Z.fetchedAt))return;let X=cZ($.usage?.secondary,Z.fetchedAt),z=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="individual_limit"):void 0,G=E(z)?ZQ(z):void 0,Q=Array.isArray($.spend)?$.spend.find((W)=>E(W)&&W.id==="credits"):void 0,B=JQ(Q,Z.fetchedAt),Y=E($.savedResets)?$.savedResets.availableCount:void 0;return{primary:J,...B&&{credits:B},...B&&E(Q)&&typeof Q.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function z6($){return`ck auth grant --principal enrolled:${$} --selector-kind category --selector openai-native --operation read`}var J$="ck auth reclassify --from-registry";function G6($,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 \`${z6($)}\`.`;return`The vault's grant for ${$} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${J$}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var j0=d("vault"),z7="openai-auth";var QQ={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},G7={opencode:"OpenCode",pi:"Pi"},YQ=[{selector:{category:"openai-native"},operation:"read"}];function z$($){return aZ(z7,$)}function BQ($){return`ChatGPT for ${G7[$]}`}function p1($){return X7(zQ($),"openai-auth-vault")}function r0($,Z){return{...oZ({stateDir:$,host:Z}),rosterPath:X7($,`${Z}-roster.json`)}}var Q7=2000,HD=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],WQ={"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 ${J$} 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 qD($,Z){if($!=="vault-no-grant")return WQ[$];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: ${z6(Z)}`}function UD($){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 VQ($){let Z=$1($);return Z?Z1(Z):void 0}class HQ{host;name;paths;#Z;#$;#B=new Map;#W=new Map;#Q=new Map;#j;#J;#V;#z;#F=!1;#N=!1;#H=Promise.withResolvers();#q="unknown";#U;constructor($){this.#Z=$,this.host=$.host,this.name=z$($.host),this.paths=r0($.stateDir,$.host),this.#$=new Z7({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:QQ,pluginId:z7,connect:()=>this.#M(),isCustodyActive:()=>this.#O(),...$.reservedRouteIds?{reservedRouteIds:$.reservedRouteIds}:{},parseIdentity:VQ,insula:{provider:"codex",normalize:dZ},...$.now?{now:$.now}:{},...$.pollIntervalMs!==void 0?{pollIntervalMs:$.pollIntervalMs}:{},...$.setTimeoutImpl?{setTimeoutImpl:$.setTimeoutImpl}:{},...$.clearTimeoutImpl?{clearTimeoutImpl:$.clearTimeoutImpl}:{},onRoster:(Z)=>{this.#J=void 0;let J=new Set(Z.rows.map((X)=>X.routeId));for(let X of this.#Q.keys())if(!J.has(X))this.#Q.delete(X)},onDiscovery:(Z)=>this.#T(Z),onError:(Z)=>this.#X("vault roster refresh failed",Z),logger:{...j0,warn:(Z,J)=>{if(Z!=="skipped insula provider poll")j0.warn(Z,J)}}})}#D(){return(this.#Z.connectionFile??GQ)()}#P(){return{connectionFile:this.#D(),storagePath:this.paths.tokenPath,logger:($)=>j0.debug("vault transport error",{errorClass:$})}}#M(){return(this.#Z.connectScoped?.()??J7(this.#P())).then(($)=>{return this.#j=$.insula!==void 0,$})}#G($,Z,J){if(!this.owns($))return;let X=this.#Q.get($);if(X?.source===Z&&X.reason===J)return;this.#Q.set($,{source:Z,reason:J}),j0.info("vault background quota source changed",{routeId:$,source:Z,reason:J})}#L(){return this.#Z.connectEnrollment?.()??rZ(this.#P())}#X($,Z){this.#J=v0(Z),j0.warn($,{host:this.host,error:this.#J,...Z instanceof iZ&&Z.reason?{reason:Z.reason}:{}})}#Y(){if(e2())return"host";return[this.paths.tokenPath,this.paths.statePath].map(($)=>{try{let Z=XQ($);return`${Z.ino}:${Z.size}:${Z.mtimeMs}:${Z.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let $=this.#Y(),Z=await tZ(this.paths,this.name);if($===this.#Y()){if(Z!==this.#q)j0.info("vault authority",{host:this.host,authority:Z});return this.#q=Z,this.#U=$,Z}return"unreadable"}enrolled(){return e2()||this.#U!==this.#Y()||this.#q!=="local"}async#O(){if(this.#U!==this.#Y())await this.authority();return this.enrolled()}start(){if(this.#F||this.#N)return;this.#F=!0,this.#$.start()}#T($){if(this.#z===$)return;this.#z=$,$.finally(()=>{if(this.#z===$)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#K(){return this.#$.refresh()}firstRoster(){return this.#H.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.#K()).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.#K();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=Q6(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.#_($,Z).finally(()=>{this.#W.delete($)});return this.#W.set($,X),X}async#_($,Z){if(Z){await this.authority(),await this.#$.refreshInsulaQuota();let J=(await Y6(this.paths.rosterPath))?.rows.find((B)=>B.routeId===$),X,z=await this.#$.pollInsulaQuotaForRoute($,async()=>{this.#G($,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#C($,Z);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let B=Q6(Z$(z,this.routes().find((W)=>W.id===$)?.quota),z.primary.checkedAt,!0);if(!B)return this.#G($,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#$.recordAccountQuota($,J.accountIdentity,B))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.#C($,Z)}async#C($,Z){let J,X=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send($,async(G,Q)=>{try{let B=Z?void 0:await this.#$.cachedInsulaQuota(Q);if(B!==void 0){let W=Q6(Z$(B,this.routes().find((V)=>V.id===$)?.quota),B.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#$.recordQuota($,W,Q),new Response(null,{status:200})}let Y=await u1({accessToken:G,fetchImpl:X,now:this.#Z.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:$,logger:j0});return await this.recordSnapshot($,Y,!0,Q),J=void 0,new Response(null,{status:200})}catch(B){J=v0(B);let Y=B?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw B}},{site:"quota"}).catch((G)=>{J=v0(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)=>{j0.warn("vault quota poll failed",{routeId:$,error:v0(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=qQ(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($),j0.info("vault account declined",{routeId:$})}async accept($){await this.#$.accept($),j0.info("vault account accepted",{routeId:$})}async status(){let $=await this.authority(),Z;try{Z=$==="host"?{state:"idle"}:await m1(this.paths,this.name)}catch(X){this.#X("vault enrollment state unreadable",X),Z={state:"blocked",proposedName:this.name,code:X instanceof sZ?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 n("vault-host",X$);let $=await this.#L().catch((Z)=>{throw new n("vault-unreachable",`Could not reach the Claustrum vault (${this.#D()}): ${v0(Z)}. Is the vault running?`)});try{let Z=new eZ({client:$,paths:this.paths,proposedName:this.name,displayName:BQ(this.host),requestedGrants:YQ,...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(j0.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.#V??=(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.#V=void 0}),this.#V}async disconnect(){if(await this.authority()==="host")throw new n("vault-host",X$);await nZ(this.paths.tokenPath,{force:!0}),await nZ(this.paths.statePath,{force:!0}),await this.#Z.afterDisconnect?.(),await this.authority(),this.#J=void 0,j0.info("vault enrollment forgotten",{host:this.host})}assertHostSlot($){if(this.serves())$7({mode:"custody",auth:$,provider:"openai"})}close(){this.#N=!0,this.#H.resolve(),this.#$.close()}async dispose(){this.close(),await this.#$.dispose()}}function qQ($){if(!$)return;let Z=h0($).limits.map((J)=>J.checkedAt);return Z.length>0?Math.max(...Z):void 0}function B6($,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 ${$}):`,` ${z6($)}`]]}function Y7($,Z,J){let X=`${G7[$]} (${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 G$($,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?`. ${G6(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:[...B6($.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 Q$="/backend-api/wham/rate-limit-reset-credits",UQ=`https://chatgpt.com${Q$}`,U7=`${Q$}/consume`,jQ=`https://chatgpt.com${U7}`,FQ=300000,NQ=60000,DQ=15000,PQ=60000;function J1($){return{configPath:$.configPath,statePath:$.statePath}}class F0 extends Error{kind;cooldownUntil;constructor($,Z,J){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=J}}class E2 extends Error{kind;status;constructor($,Z,J){super(Z);this.name="ResetCreditError",this.kind=$,this.status=J}}function j7($,Z,J){return{authorization:`Bearer ${$}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function V6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function F7($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function H6($){if(!V6($)||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}:{},...N7($.rejectedStatus)?{rejectedStatus:$.rejectedStatus}:{},...typeof $.unknownAnswers==="number"&&Number.isSafeInteger($.unknownAnswers)&&$.unknownAnswers>0?{unknownAnswers:$.unknownAnswers}:{}}}function N7($){return typeof $==="number"&&$>=400&&$<500&&$!==408&&$!==409&&$!==425&&$!==429}function W6($){return $.kind==="http_error"&&N7($.status)}function D7($,Z){return $.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z||$.rejectedStatus!==void 0}function KQ($,Z){if($.chatgptAccountId!==void 0&&$.chatgptAccountId!==Z)throw new F0("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function P7($){return Boolean($&&Object.hasOwn($,"inFlight"))}function K7($,Z){return Z-$.startedAt<FQ}function X1($,Z){if(!o0(Z))return;return $.reset?.[Z]}function C7($){if(!$.reset)$.reset=Object.create(null);return $.reset}function M7($,Z,J){if(!o0(Z))return;let X=C7($),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 L7($,Z){let J=F7($),X=H6($?.inFlight);if(P7($)&&!X)return{kind:"corrupt",beforeState:J};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:J,cooldownUntil:$.cooldownUntil};if(X&&K7(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 CQ($,Z){if(!o0(Z))return{kind:"fresh",beforeState:void 0};let J=await $.loadAccountsFn(J1($));return L7(J?X1(J,Z):void 0,$.now())}async function MQ($,Z){let J;if(await $.mutateAccountsFn((X)=>{let z=$.now(),G=X1(X,Z);if(J=L7(G,z),J.kind==="corrupt")M7(X,Z,z);return X},J1($)),!J)throw Error("corrupt reset state mutation did not run");return J}async function LQ($,Z,J,X){if(!o0(Z))return{kind:"fresh",beforeState:void 0};let z;if(await $.mutateAccountsFn((G)=>{let Q=$.now(),B=X1(G,Z),Y=F7(B),W=H6(B?.inFlight);if(P7(B)&&!W)return M7(G,Z,Q),z={kind:"corrupt",beforeState:Y},G;if(B?.cooldownUntil!==void 0&&B.cooldownUntil>Q)return z={kind:"cooldown",beforeState:Y,cooldownUntil:B.cooldownUntil},G;if(W&&K7(W,Q))return z={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;if(W&&!D7(W,X))return z={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;let V=q6(J);if(!V)return z={kind:"fresh",beforeState:Y},G;let H={redeemRequestId:$.randomUUID(),creditId:V.id,startedAt:Q,...X===void 0?{}:{chatgptAccountId:X}},q=C7(G);return q[Z]={...B,inFlight:H},z={kind:"claim",beforeState:Y,claim:{inFlight:H,selectedCredit:V}},G},J1($)),!z)throw Error("reset claim mutation did not run");return z}async function OQ($,Z,J,X,z){if(!o0(Z))return;if(!W$(X.kind))return TQ($,Z,J,X,z);await $.mutateAccountsFn((G)=>{let Q=X1(G,Z),B=H6(Q?.inFlight);if(!Q||!B||B.redeemRequestId!==J.redeemRequestId||B.creditId!==J.creditId)return G;let Y=$.now();if(delete Q.inFlight,Q.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")Q.cooldownUntil=Y+PQ;else delete Q.cooldownUntil;return G},J1($));return}function B7($,Z){let J=H6($?.inFlight);return J&&J.redeemRequestId===Z.redeemRequestId&&J.creditId===Z.creditId?J:void 0}async function TQ($,Z,J,X,z){let G=W6(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Y=await $.loadAccountsFn(J1($));return B7(Y?X1(Y,Z):void 0,J)}let B;return await $.mutateAccountsFn((Y)=>{B=void 0;let W=X1(Y,Z),V=B7(W,J);if(!W||!V)return Y;let H={...V};if(H.chatgptAccountId===void 0&&z!==void 0)H.chatgptAccountId=z;if(G===void 0)delete H.rejectedStatus,H.unknownAnswers=(V.unknownAnswers??0)+1;else if((V.unknownAnswers??0)===(J.unknownAnswers??0))H.rejectedStatus=G;return W.inFlight=H,B=H,Y},J1($)),B}function l1($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let J=Date.parse($.resetsAt);return!Number.isFinite(J)||J>Z}function Y$($,Z,J){if(!(Z||l1($.primary,J)||l1($.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function W7($,Z){let J=$[Z];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function _Q($){if(!V6($))return;let Z=W7($,"granted_at"),J=W7($,"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 B$($,Z,J){let X;try{X=await $(UQ,{method:"GET",headers:j7(Z,Q$,J),signal:AbortSignal.timeout(DQ)})}catch{throw new E2("http_error","reset credit list request failed")}if(!X.ok)throw new E2("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new E2("invalid_response","reset credit list response was not valid JSON",X.status)}if(!V6(z))throw new E2("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((Q)=>{let B=_Q(Q);return B===void 0?[]:[B]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function q6($){return[...$].filter(O7).sort((Z,J)=>Date.parse(Z.expiresAt)-Date.parse(J.expiresAt))[0]}function O7($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function T7($){return $.filter(O7).length}function W$($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function SQ($,Z,J,X,z){let G;try{G=await $(jQ,{method:"POST",headers:{...j7(Z,U7,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(NQ)})}catch(W){return{kind:"ambiguous",raw:W}}let Q;try{Q=await G.text()}catch(W){return G.ok?{kind:"ambiguous",raw:W}:{kind:"http_error",raw:W,status:G.status}}let B=Q,Y=!1;try{B=JSON.parse(Q),Y=!0}catch{}if(!G.ok)return{kind:"http_error",raw:B,status:G.status};if(!Y||!V6(B)||!W$(B.code))return{kind:"ambiguous",raw:B};return{kind:B.code,raw:B}}function V7($){if($.kind==="cooldown")throw new F0("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function H7(){throw new F0("expired_unreconciled","the previous reset attempt outcome is unknown")}function q7($,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 AQ($){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(W6($))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 EQ($,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 _7($,Z){if(!o0(Z.accountKey))throw new F0("invalid_account_key","the reset account key is reserved");let J=await $.resolveTarget(Z.accountKey);if(J.chatgptAccountId!==Z.expectedChatgptAccountId)throw new F0("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await CQ($,Z.accountKey);if(G.kind==="corrupt"){if(G=await MQ($,Z.accountKey),G.kind==="corrupt")return q7(J,G.beforeState)}if(G.kind==="cooldown")V7(G);let Q;if(G.kind==="claim")Q=G.claim;else if(G.kind==="expired_unreconciled"&&(Z.retry||!D7(G.claim.inFlight,X))){if(!Z.retry)H7();Q=G.claim}else{if(Z.retry)throw new F0("retry_without_inflight","there is no active reset credit redemption to retry");let[q,j]=await Promise.all([$.fetchUsage(J),B$($.fetchImpl,J.accessToken,z)]),U=Y$(q,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!U.ok)throw new F0("not_exhausted",U.reason);if(!q6(j.credits))throw new F0("no_eligible_credit","no eligible reset credit was returned");let F=await LQ($,Z.accountKey,j.credits,X);if(F.kind==="corrupt")return q7(J,F.beforeState);if(F.kind==="cooldown")V7(F);if(F.kind==="expired_unreconciled")H7();if(F.kind!=="claim")throw new F0("no_eligible_credit","no eligible reset credit was available while claiming");Q=F.claim}KQ(Q.inFlight,X);let B=await SQ($.fetchImpl,J.accessToken,z,Q.inFlight.creditId,Q.inFlight.redeemRequestId),Y,W=!1;try{Y=await OQ($,Z.accountKey,Q.inFlight,B,X)}catch{W=!0}let V=W&&W$(B.kind),H=W6(B)&&!W&&Y?.rejectedStatus!==void 0;return{target:J,selectedCredit:Q.selectedCredit,beforeState:G.beforeState,outcome:B,retrySafety:V?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":W6(B)&&!H?EQ(W,Y):AQ(B),...H?{refused:!0}:{},...V?{finalizeStateWriteFailed:!0}:{}}}async function S7($){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 A7($,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 E7($,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 V$($){let Z=$.title??"Auth doctor";return{id:"doctor",label:$.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await S7($.checks);for(let Q of A7(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 E7(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as RQ}from"node:child_process";import{win32 as IQ}from"node:path";function I7($,Z=process.platform,J=RQ){try{if(Z==="win32"){let z=`Start-Process '${$.replaceAll("'","''")}'`,G=J(IQ.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 R7($,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 U6($,Z){let J=new AbortController,X=await $.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),R7(Z,X);let z=!1;try{z=await($.openBrowser??I7)(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}),R7(Z,X);return X.completion}var f={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 H$($){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 Y={A:"up",B:"down",C:"right",D:"left"}[Q];if(Y)J.push(Y);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 k7=`${String.fromCharCode(27)}\\[[0-9;]*m`,kQ=new RegExp(k7,"g"),xQ=new RegExp(`^${k7}`);function x7($){return $.replace(kQ,"")}function R2($,Z){if(Z<=0)return"";if(x7($).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 B=$.slice(G).match(xQ);if(B){z+=B[0],G+=B[0].length;continue}}z+=$[G],G+=1,Q+=1}return z.includes("\x1B[")?`${z}${f.reset}${J}`:z+J}function q$(){return{input:process.stdin,output:process.stdout,signals:process}}function I2($){return $.input.isTTY===!0}function U$($,Z=""){$.output.write(`${Z}
|
|
4
4
|
`)}var bQ=50;function fQ($){if($==="red")return f.red;if($==="cyan")return f.cyan;return""}async function z1($,Z,J){if(!I2($))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,B=null,Y=!1,W=0,V=()=>{let H=z.columns??80,q=z.rows??24,j=W;if(J.clearScreen)z.write(f.clearScreen+f.moveTo(1,1));else if(j>0)z.write(f.up(j));let U=0,F=(T)=>{z.write(`${f.clearLine}${T}
|