@cortexkit/opencode-openai-auth 1.8.5 → 1.8.6
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-g5hv0tda.js → index-25p8t63g.js} +1 -1
- package/dist/{index-8x42xzxb.js → index-a8wbqm6a.js} +1 -1
- package/dist/{index-rmc6hwg6.js → index-pnvp8hvs.js} +1 -1
- package/dist/{index-a7xv52hy.js → index-v6jcz0hz.js} +21 -21
- package/dist/index.js +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/v2/server.js +2 -2
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$c as A7,Ad as F6,Bd as K6,Cd as N6,Dd as D6,Ed as x1,Fc as fZ,Gc as m7,Hc as i5,Hd as E1,Ic as t4,Jd as D0,Kc as y5,Lc as PZ,Ld as M0,Mc as V7,Md as f1,Nc as CZ,Oc as e4,Od as g1,Pc as Z6,Pd as RZ,Qc as $6,Rd as r5,Sc as f7,Tc as x7,Uc as y4,Ud as P0,Vc as k4,Wc as f4,Yc as w7,Zc as w1,_c as u7,_d as v1,ad as S7,de as I7,ed as T5,fd as _5,fe as R7,ge as E7,ie as C0,je as T0,le as C5,oe as U7,rd as Y6,ud as H6,vd as V6,wd as U6,xd as L5,yd as j6,zd as q6}from"./index-zne9tzy9.js";import{Ae as z4,Be as AZ,Ce as G4,De as L9,Ee as QZ,Ge as t1,He as B4}from"./index-n12zjwh9.js";import{Re as a7}from"./index-g5hv0tda.js";import{Ye as p4,af as s,bf as v7,df as P$,ef as u1,ff as C$,gf as TZ}from"./index-zf649dj2.js";import{jf as G5,pf as X4}from"./index-95s2mw9w.js";class R extends Error{operation;rowId;phase;retryable;kind;committed;constructor(Z){super(Z.message??`${Z.operation} failed (${Z.kind}, ${Z.phase})`,Z.cause===void 0?void 0:{cause:Z.cause});this.name="PoolOperationError",this.operation=Z.operation,this.rowId=Z.rowId,this.phase=Z.phase,this.retryable=Z.retryable,this.kind=Z.kind,this.committed=Z.committed}}class o1 extends Error{operation;constructor(Z){super(`${Z} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=Z}}var rZ="identity-contradicted: ",j9="duplicate-identity";function kZ(Z,$,J){let X=Z.rosterRow($);if(!X)return;X.enabled=!1;let z=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...z,disabledReason:G?z.disabledReason:J})}function N1(Z,$){let J=Z.rosterRow($);if(!J)return;J.enabled=!0;let X=Z.entry($);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,Z.setEntry($,z)}}function oZ(Z,$){let J=Z.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===$),X=[];for(let z of J.slice(1))kZ(Z,z.id,"duplicate-identity"),X.push(z.id);return X}function mZ(Z,$,J){let X=Z.rosterRow($);if(!X)return[];return X.accountId=J,oZ(Z,J)}import{setTimeout as S3}from"node:timers/promises";import{AsyncLocalStorage as H3}from"node:async_hooks";var l$=new H3;function p(Z){if(l$.getStore()!==void 0)throw new o1(Z)}function KZ(Z,$){return l$.run(Z,async()=>await $())}async function d$(Z,$,J,X,z){if(!$)return;try{await KZ(Z,()=>$(J,X))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:J,error:G instanceof Error?G.message:String(G)})}}var q9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function V3(Z,$,J){let X=(B)=>{try{let Q=J.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},z={...$,...U3(Z)},G=performance.now();for(;;){let B=await QZ({name:Z.name,path:Z.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(W)=>J.onRenewalTimer?.({name:Z.name,path:Z.path},W)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(W)=>J.onLockStep?.({name:Z.name,path:Z.path},W)}:{}});if(B){X("acquired");let W={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await W.assertOwned()}catch(H){throw await W.release(),H}return W}let Q=z.timeoutMs-(performance.now()-G);if(Q<=0)throw new t1({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((W)=>setTimeout(W,Math.min(z.retryMs+Y,Q)))}}function U3(Z){let $={};if(Z.ttlMs!==void 0)$.ttlMs=Z.ttlMs;if(Z.timeoutMs!==void 0)$.timeoutMs=Z.timeoutMs;if(Z.retryMs!==void 0)$.retryMs=Z.retryMs;if(Z.renew!==void 0)$.renew=Z.renew;if(Z.renewIntervalMs!==void 0)$.renewIntervalMs=Z.renewIntervalMs;return $}class NZ{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await V3(Z,this.defaults,this.env);return this.held.push($),await this.assertAll(),$}async assertAll(){for(let Z of this.held)await Z.assertOwned()}async releaseTo(Z){while(this.held.length>Z)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function wZ(Z,$,J){if(J!==void 0)throw new R({operation:Z,rowId:$,kind:"row-staged",phase:Z==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${$} is reserved for roster publication`})}import{createHash as D1}from"node:crypto";var y="commonAuthPool",vZ=1,WZ="rows",e1="retiredEpochs",M1=1,F9=300000,E=y;function j3(Z){let $=JSON.parse(JSON.stringify(Z)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(C(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J($)}function uZ(Z){return D1("sha256").update(j3(Z)).digest("hex")}function c$(Z){if(!C(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function q3(Z){if(!C(Z)||typeof Z.reservation!=="string"||!Z.reservation||typeof Z.disabledReason!=="string")return;if(Object.keys(Z).some(($)=>!["reservation","label","disabledReason","providerState"].includes($)))return;if("label"in Z&&typeof Z.label!=="string")return;if("providerState"in Z&&(typeof Z.providerState!=="string"||!/^[a-f0-9]{64}$/.test(Z.providerState)))return;return Z}var d="commonAuthProviderState";function C(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var F3=new Set(["__proto__","constructor","prototype"]);function tZ(Z){if(typeof Z!=="string"||Z.length===0)return"id must be non-empty";if(Z.trim()!==Z)return"id must not carry surrounding whitespace";if(F3.has(Z))return"id is a reserved object key";return}function K9(Z){let $=typeof Z==="string"?Z.trim():"";if(!$)return!1;try{let J=new URL($);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function s$(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function YZ(Z){return D1("sha256").update(s$(Z)).digest("hex")}function DZ(Z){return D1("sha256").update(`credential-stamp\x00${s$(Z)}`).digest("hex")}function OZ(Z){let $=Z.type==="oauth"?["oauth",typeof Z.access==="string"?Z.access:null,Z.refresh,typeof Z.expires==="number"&&Number.isFinite(Z.expires)?Z.expires:null]:["api",Z.apiKey,Z.baseURL.trim(),Z.authHeader??"authorization-bearer"];return D1("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function N9(Z,$,J,X={}){return{credentialEpoch:$,digest:DZ(Z),dispatch:OZ(Z),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function eZ(Z,$){let J=Z?.credentialBound?Z.credentialBound($):$;return D1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function P1(Z,$,J,X){if(!$||J===void 0)return;if(!C(Z)||!Object.hasOwn(Z,d))return;let z=a(Z[E]);if(!z||z.providerState===void 0||z.digest!==DZ($)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function w(Z){return Number.isSafeInteger(Z)&&Z>=1}function a(Z){if(!C(Z))return;let $=Z.credentialEpoch;if(!w($))return;if(typeof Z.digest!=="string")return;if("dispatch"in Z&&typeof Z.dispatch!=="string")return;if("replace"in Z&&Z.replace!==!0)return;if("providerState"in Z&&typeof Z.providerState!=="string")return;let J="staged"in Z?q3(Z.staged):void 0;if("staged"in Z&&!J)return;let X={...J?{staged:J}:{},...typeof Z.dispatch==="string"?{dispatch:Z.dispatch}:{},...Z.replace===!0?{replace:!0}:{},...typeof Z.providerState==="string"?{providerState:Z.providerState}:{}};if(!("binding"in Z))return"dispatch"in Z||"replace"in Z||"providerState"in Z||"staged"in Z?void 0:{credentialEpoch:$,digest:Z.digest};let z=Z.binding;if(!C(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!K9(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.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 K3(Z,$,J){if(Z.identity!==J)return!1;if(Z.baseURL!==void 0&&($.type!=="api"||$.baseURL!==Z.baseURL))return!1;if(Z.authHeader!==void 0&&($.type!=="api"||$.authHeader!==Z.authHeader))return!1;return!0}function N3(Z,$,J,X){if(!Z)return"none";if(!C(X)||!Object.hasOwn(X,E))return"missing";let z=a(X[E]);if(!z)return"malformed";if(z.digest!==DZ(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!K3(z.binding,Z,J))return"mismatched";if(z.dispatch!==OZ(Z))return"mismatched";return"bound"}function D9(Z){if(!Z.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in Z)return{status:"error",reason:"config file is not valid JSON"};let $=Z.value;if(!C($))return{status:"error",reason:"config root is not an object"};if("accounts"in $&&!Array.isArray($.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(y in $))return Array.isArray($.accounts)?{status:"pending-migration",config:$}:{status:"ready",exists:!0,config:$};let J=$[y];if(!C(J))return{status:"error",reason:`${y} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${y}.schemaVersion is invalid`};if(X>vZ)return{status:"error",reason:`${y}.schemaVersion ${X} is newer than ${vZ}`};if(WZ in J&&!C(J[WZ]))return{status:"error",reason:`${y}.${WZ} is not an object`};return{status:"ready",exists:!0,config:$}}function a$(Z){if(!Z.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in Z)return{status:"error",reason:"state file is not valid JSON"};if(!C(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!C(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function Z1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function n$(Z){let $=Z[y];if(!C($))return{};let J=$[WZ];return C(J)?J:{}}function D3(Z){return C(Z.accounts)?Z.accounts:{}}function M3(Z){if(!C(Z))return"not an object";let $=tZ(Z.id);if($)return $;if(Z.type==="api")return K9(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function P3(Z,$){if(!C(Z))return;let J=Z.credentialEpoch;if(!w(J))return;if("needsFirstReading"in Z&&typeof Z.needsFirstReading!=="boolean")return;if("disabledReason"in Z&&typeof Z.disabledReason!=="string")return;let X="quota"in Z&&$.decode?$.decode(Z.quota):Z.quota;if("quota"in Z&&!$.validate(X))return;if("staged"in Z&&!c$(Z.staged))return;return{credentialEpoch:J,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:X}:{}}}function C3(Z,$){if(!C($))return;if(Z.type==="api"){let X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(Z.corrupt===!0)return;let J=$.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof $.access==="string"?{access:$.access}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.lastRefreshedAt==="number"?{lastRefreshedAt:$.lastRefreshedAt}:{}}}function Z5(Z,$){return Z1(Z).find((J)=>C(J)&&J.id===$)}function i$(Z){if(!C(Z[y]))Z[y]={};return Z[y]}function M9(Z){let $=i$(Z);if(!C($[WZ]))$[WZ]={};return $[WZ]}function MZ(Z,$){let J=n$(Z),X=Object.hasOwn(J,$)?J[$]:void 0;return C(X)?X:void 0}function $5(Z,$,J){Object.defineProperty(M9(Z),$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function r$(Z,$){let J=Z[y];if(!C(J))return;let X=J[e1];if(!C(X)||!Object.hasOwn(X,$))return;let z=X[$];return w(z)?z:void 0}function o$(Z,$){let J=MZ(Z,$)?.credentialEpoch;return w(J)?J:void 0}function J5(Z,$){return Math.max(r$(Z,$)??0,o$(Z,$)??0)+1}function t$(Z,$){let J=[...$];if(J.length===0)return;let X=i$(Z),z=C(X[e1])?X[e1]:{},G={},B=(Q,Y)=>Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[Q,Y]of Object.entries(z))if(w(Y))B(Q,Y);for(let Q of J)B(Q,Math.max(r$(Z,Q)??0,o$(Z,Q)??1));X[e1]=G}function gZ(Z,$,J,X){let z=n$(Z),G=D3($),B=new Set,Q=[];for(let Y of Z1(Z)){let W=M3(Y),H=C(Y)&&typeof Y.id==="string"?Y.id:void 0,V=H===void 0?void 0:z[H],j=C(V)&&Object.hasOwn(V,"staged"),F=j?c$(V.staged):void 0;if(W||!C(Y)||H===void 0||B.has(H)){if(H!==void 0&&!B.has(H))B.add(H);if(H!==void 0)Q.push({id:H,type:C(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(H);let U=Y.type==="api"?"api":"oauth",q=Object.hasOwn(z,H),K=q?P3(z[H],J):void 0,N=C3(Y,G[H]),M=Y.enabled!==!1,O=K?K.credentialEpoch:q?void 0:1,_=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,D={id:H,type:U,enabled:M,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:q,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},..._!==void 0?{identity:_}:{},...N?{credential:N,fingerprint:YZ(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...T3(G[H],N,O,_,X),stamp:N3(N,O,_,G[H])};if(q&&!K)D.invalid="entry";else D.candidate=M&&N!==void 0&&!j;Q.push(D)}return Q}function T3(Z,$,J,X,z){if(!C(Z)||!Object.hasOwn(Z,d))return{};let G=P1(Z,$,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=Z[d];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(eZ(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function v(Z){return Z.identity??Z.id}function C1(Z,$){if(Z===void 0||Z>$+F9)return $;return Math.max($,Z+1)}function P9(Z,$){return C1(Z,$)>$+F9}function $1(Z){let{id:$,credential:J,identity:X,label:z,addedAt:G}=Z;return{id:$,...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 e$(Z,$){if(Z.type==="api")return{apiKey:Z.apiKey};return{...Z.access!==void 0?{access:Z.access}:{},refresh:Z.refresh,...Z.expires!==void 0?{expires:Z.expires}:{},...$!==void 0?{lastRefreshedAt:$}:{}}}function Z4(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function $4(Z,$={}){if(!C(Z))return"credential must be an object";if(Z.type==="oauth"){if(typeof Z.refresh!=="string"||!Z.refresh.trim())return"oauth credential needs a refresh token";return}if(Z.type==="api"){if(typeof Z.apiKey!=="string"||!Z.apiKey.trim())return"api credential needs an api key";if(Z.apiKey.trim()!==Z.apiKey)return"api key must not carry surrounding whitespace";if(!($.baseURLOptional&&Z.baseURL===void 0)&&!K9(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var X5="transition",J4="transitionMark";function _3(Z){if(!C(Z))return;let $=Z[X5];if(!C($))return;if(typeof $.mark!=="string"||$.mark.length===0)return;if($.enabled===!0)return{mark:$.mark,enabled:!0};if($.enabled===!1&&typeof $.reason==="string")return{mark:$.mark,enabled:!1,reason:$.reason};return}function T1(Z,$,J){if(J.enabled)N1(Z,$);else kZ(Z,$,J.reason??"");if(!Z.rosterRow($))return;let X=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...X,[J4]:J.mark}),!J.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)oZ(Z,z.identity)}function L3(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function O3(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function A3(Z,$,J,X={}){let z=C($.accounts)?$.accounts:{},G=new Map;for(let B of gZ(Z,$,J)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!C(Q))continue;let Y=a(Q[E]);if(!Y?.binding)continue;if(Y.digest!==DZ(B.credential))continue;let W=B.credentialEpoch??1;if(Y.credentialEpoch>W){if(!O3(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==OZ(L3(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===OZ(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===B.identity){if(X.requireCredentialStamps&&Y.dispatch!==OZ(B.credential))continue;let H=_3(Q[E]);if(H&&MZ(Z,B.id)?.[J4]!==H.mark)G.set(B.id,{kind:"transition",transition:H})}}return G}function C9(Z,$,J,X){let G={...Z.entry($)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(rZ))delete G.disabledReason;Z.setEntry($,G);let B=Z.rosterRow($);if(!B)return;if(X.identity!==void 0)B.accountId=X.identity;else delete B.accountId;if(X.baseURL!==void 0)B.baseURL=X.baseURL;if(X.authHeader!==void 0)B.authHeader=X.authHeader}function T9(Z,$,J,X={}){let z=A3(Z,$,J,X);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),B={rows:()=>gZ(G,$,J),rosterRow:(Q)=>Z5(G,Q),entry:(Q)=>MZ(G,Q),setEntry:(Q,Y)=>$5(G,Q,Y)};for(let[Q,Y]of z)if(Y.kind==="replace")C9(B,Q,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[Q,Y]of z)if(Y.kind==="identity")mZ(B,Q,Y.identity);else if(Y.kind==="transition")T1(B,Q,Y.transition);else if(Y.stamp.binding.identity!==void 0)oZ(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function _9(Z,$,J,X={}){let{config:z,torn:G}=T9(Z,$,J,X),B=gZ(z,$,J,X.providerState);for(let Q of B){if(G.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(X.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function z5(Z){try{return await X4(Z,G5)}catch($){if($.code==="ENOENT")return;throw $}}function O9(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function Q4(Z){return D9(O9(await z5(Z)))}async function n(Z){for(let $=0;$<3;$++){let J=await z5(Z.configPath),X=await z5(Z.statePath),z=await z5(Z.configPath);if(J!==z){if($<2)await S3(2+Math.floor(Math.random()*4));continue}let G=D9(O9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=a$(O9(X));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:_9(G.config,B.state,Z.codec,{requireCredentialStamps:Z.requireCredentialStamps===!0,...Z.providerState?{providerState:Z.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function HZ(Z,$,J,X="before-first-write"){if(Z.status==="error"&&Z.kind==="snapshot-contended")return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:Z.reason});return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:Z.status==="pending-migration"?"pending-migration":"load-error",message:Z.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${Z.file} file cannot be loaded: ${Z.reason}`})}class W4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,J,X,z){this.ctx=Z,this.snapshot=$,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return _9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row(Z){return this.rows().find(($)=>$.id===Z)}reservation(Z){if(this.rosterRow(Z)){let J=this.entry(Z);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let $=this.stateAccount(Z)?.[E];return C($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){wZ(this.info.operation,Z,this.reservation(Z))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow(Z){return this.roster(),Z5(this.config,Z)}dropRosterRows(Z){let $=this.roster(),J=$.filter((X)=>!(C(X)&&X.id===Z));return this.config.accounts=J,$.length-J.length}entries(){return M9(this.config)}entry(Z){return this.entries(),MZ(this.config,Z)}setEntry(Z,$){$5(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=T9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if($.length===0)return;this.config=Z,await this.commitConfig({counted:!1})}stateAccount(Z){let $=C(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn($,Z)?$[Z]:void 0;return C(J)?J:void 0}dropStateAccount(Z){if(C(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!C(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,Z,{value:$,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(Z={}){let $=this.roster(),J=new Set;for(let Y of $)if(C(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of Z1(this.snapshot.config))if(C(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);t$(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 B=this.config[y],Q={...this.config,version:M1,accounts:$,[y]:{...B,schemaVersion:vZ,[WZ]:G}};await this.write(this.ctx.configPath,Q,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=Q}),this.config=Q}async commitState(Z,$={}){let J={...this.state,version:M1,accounts:C(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,$.durable??!1),this.state=J,Z)this.progress.committed=Z}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await L9(this.ctx.statePath)}catch(Z){throw new R({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:Z})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await L9(this.ctx.configPath)}async write(Z,$,J,X=!0,z=!1,G){await G4(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 Y4(Z,$){let J=new NZ(Z.lockDefaults,Z.lockEnv),X={writes:0};try{for(let Q of Z.storeLocks)await J.acquire(Q);let z=await n(Z);if(z.status==="error")throw HZ(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Q,Y]of Object.entries(z.config))if(!$.includes(Q))G[Q]=Y;G.version=M1,G[y]={schemaVersion:vZ,[WZ]:{}};let B={operation:"initialize",rowId:void 0};return await AZ(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(z){throw hZ(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function f(Z,$,J,X,z,G={}){let B=$.held.length;try{for(let W of Z.storeLocks)await $.acquire(W);let Q=await n(Z);if(Q.status!=="ready")throw HZ(Q,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new W4(Z,Q,$,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 $.releaseTo(B)}}function hZ(Z,$,J,X){let z=$==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if($==="publishRoster"&&X.publicationDecided)return new R({operation:$,...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:Z});if($==="publishRoster"&&Z instanceof z4)return new R({operation:$,...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:Z});if(Z instanceof R){if(Z.phase===z&&Z.rowId===J&&Z.operation===$&&Z.committed===G)return Z;return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:Z.kind==="after-persist-hook"?Z.phase:z,retryable:Z.retryable,kind:Z.kind,...Z.committed??G?{committed:Z.committed??G}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let B={operation:$,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof B4)return new R({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${$} lost a lease after its first write; the intermediate stays on disk`:`${$} lost a lease before writing; nothing was written`});if(Z instanceof t1)return new R({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new R({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function l(Z,$,J,X,z){let G=new NZ(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await z(G,B)}catch(Q){let Y=hZ(Q,$,J,B);if(Y.kind!=="after-persist-hook")await d$($,X,J,Y,Z.logger);throw Y}finally{await G.releaseAll()}}function r(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(v($))}`,path:Z.ctx.statePath}}async function VZ(Z,$,J){let X=await n(Z.ctx);if(X.status!=="ready")throw HZ(X,$,J);let z=X.rows.find((W)=>W.id===J),G=MZ(X.config,J),B=X.state.accounts,Q=C(B)&&Object.hasOwn(B,J)?B[J]:void 0,Y=C(Q)?Q[E]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))wZ($,J,G.staged);if(!z&&C(Y)&&Object.hasOwn(Y,"staged"))wZ($,J,Y.staged);if(!z)throw e($,J);return{result:X,row:z}}function e(Z,$){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${$} in the pool`})}function c(Z,$){if($.unbound)throw P(Z,$.id,"unbound-credential",`row ${$.id}'s credential is not the one this store stamped for it (stamp ${$.stamp}); replace it with fresh material`)}function P(Z,$,J,X,z=!1){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function A9(Z,$){if(!w($?.credentialEpoch))throw P("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function _1(Z,$,J){if(!J)throw e("pull",Z);if(J.invalid)throw P("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!J.credential)throw P("pull",Z,"no-credential",`row ${Z} holds no credential`);if(c("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==$.credentialEpoch||J.identity!==$.identity)throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`})}function L1(Z,$,J,X){let z=Z.codec.merge(J,X);if(!Z.codec.validate(z))throw P("pull",$,"invalid-quota","the quota codec rejected the merged map");return z}async function B5(Z,$,J,X){let{ctx:z}=Z,G=new NZ(z.lockDefaults,z.lockEnv),B={writes:0};try{A9($,J),await f(z,G,B,{operation:"pull",rowId:$},async(Q)=>{Q.assertNotStaged($);let Y=Q.row($);_1($,J,Y);let W=Q.entry($);if(!W)throw e("pull",$);let H=L1(z,$,W.quota,X);Q.setEntry($,{...W,quota:H,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw hZ(Q,"pull",$,B)}finally{await G.releaseAll()}}function SZ(Z,$,J,X,z="the provider state"){if(!Z)throw P($,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(X);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw P($,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw P($,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function O1(Z,$,J,X,z){if(X===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:SZ(Z,$,J,Z.merge(structuredClone(X),structuredClone(z)),"the merged provider state")}}function H4(Z,$,J,X,z){let G=Z?.onReplace,B=G?G($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:J,...$.identity!==void 0?{previousIdentity:$.identity}:{},...X!==void 0?{identity:X}:{},...z!==void 0?{incoming:structuredClone(z)}:{}}):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:SZ(Z,"replace",$.id,B,"the provider state onReplace returned")}}function V4(Z,$,J,X,z){if($.kind==="set")return eZ(Z,$.value);if($.kind==="clear")return;return P1(J,X?.credential,z,X?.identity)}async function U4(Z,$,J,X,z={}){p("updateProviderState");let{ctx:G}=Z,B="updateProviderState";return l(G,B,$,z.onFailure,async(Q,Y)=>{let W=G.providerState;if(!W)throw P(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw P(B,$,"invalid-input","a mutator is required");let H=C(J)?J.credentialEpoch:void 0;if(!w(H))throw P(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await VZ(Z,B,$);await Q.acquire(r(Z,V));for(let j of z.extraLocks??[])await Q.acquire(j);return f(G,Q,Y,{operation:B,rowId:$},async(j)=>{let F=j.row($);if(!F)throw e(B,$);if(v(F)!==v(V))throw P(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw P(B,$,"invalid-row",`row ${$} failed validation`);if(!F.credential)throw P(B,$,"no-credential",`row ${$} holds no credential`);if(c(B,F),(F.credentialEpoch??1)!==H||F.identity!==J.identity)throw P(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await S9(j,W,B,F,X);if(q.kind!=="changed")return{id:$,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount($,q.account),await j.commitState(),q.value===void 0?{id:$,outcome:"cleared"}:{id:$,outcome:"updated",providerState:q.value}})})}var j4=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function S9(Z,$,J,X,z,G=!1){let{id:B,credential:Q}=X;if(!Q)throw P(J,B,"no-credential",`row ${B} holds no credential`);let Y=X.credentialEpoch??1,W=Z.stateAccount(B),H=W?.[E],V=a(H);if(!C(H)||!V?.binding||V.digest!==DZ(Q)||V.credentialEpoch!==Y||V.binding.identity!==X.identity)throw P(J,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let j=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await KZ(J,()=>z(j,X));if(G&&F===j4)return{kind:"declined"};let U=F===void 0?void 0:SZ($,J,B,F,"the provider state the mutator returned"),q=W!==void 0&&Object.hasOwn(W,d);if(U===void 0?!q:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...W};if(U===void 0){delete K[d];let N={...H};delete N.providerState,K[E]=N}else{K[d]=U;let N=eZ($,U);if(V.providerState!==N)K[E]={...H,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as q4}from"node:crypto";async function H5(Z,$,J){if(!J)return;let X=Z.rows().map((G)=>{let{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}=G;return{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}}),z=await KZ(Z.info.operation,()=>J({id:$,row:X.find((G)=>G.id===$),rows:X,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw P(Z.info.operation,$,"row-protected",z)}var I3=["access","refresh","expires","lastRefreshedAt","apiKey"];function R3(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function E3(Z,$,J){if(J.type!=="api")return J;let X=Z.rosterRow($);if(!C(X)){if(J.baseURL===void 0)throw P(Z.info.operation,$,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=Z.row($)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:R3(X),B=J.baseURL?.trim()??G.baseURL,Q=J.authHeader??G.authHeader;if(B!==G.baseURL||Q!==G.authHeader)throw P(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:Q}}function F4(Z,$,J,X){let z=Z.rosterRow($),G=Z.row($),B=X??(G?G.identity:C(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function Q5(Z,$,J,X,z={}){let G=E3($,J,X),B=$.stateAccount(J),Q=z.providerState??{kind:"keep"},Y=$.row(J)?.credentialEpoch??$.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,H=V4(Z.ctx.providerState,Q,B,B&&Object.hasOwn(B,d)?$.row(J):void 0,W),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??C1(V,Z.ctx.now()):void 0,F={...B??{}};for(let K of I3)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(Q.kind==="clear")delete F[d];else if(Q.kind==="set")F[d]=Q.value;let U=Z4(G,j),q={...F,...e$(G,j),[E]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[X5]:z.transition}:{},...N9(U,W,z.binding??F4($,J,U,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:U,account:q}}async function W5(Z,$,J){return Z.setStateAccount($,J.account),await Z.commitState(J.stored),J.stored}async function V5(Z,$,J,X,z={}){return W5($,J,Q5(Z,$,J,X,z))}async function b3(Z,$,J){if(!$.credential||$.stamp!=="bound")return;let X=Z.stateAccount($.id),z=P1(X,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...X??{},[E]:N9($.credential,$.credentialEpoch??1,F4(Z,$.id,$.credential,J),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function R9(Z,$,J){let X=Z==="add"?tZ($):void 0;if(X)throw P(Z,$,"invalid-input",X);let z=$4(J,{baseURLOptional:Z==="rotate"});if(z)throw P(Z,$,"invalid-input",z)}function U5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if(X&&X.type!==J.type)throw P(Z,$,"type-mismatch",`row ${$} holds a ${J.type} credential`);return J}function X1(Z,$,J){if(J!==void 0&&!w(C(J)?J.credentialEpoch:void 0))throw P(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function j5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw P(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function Y5(Z,$){return P(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function A1(Z,$){return P(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function y3(Z,$,J,X){let{id:z,credential:G,identity:B}=J;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!J1($.state,z))return;let Q=()=>{throw P("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=$.stateAccount(z),W=a(Y?.[E]);if(!W?.binding||W.dispatch===void 0||W.replace)return Q();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return Q();let H=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[V]=gZ({accounts:[$1({id:z,credential:H,identity:W.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:J5($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(DZ(G)!==W.digest)return Q();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return Q();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return Q()}else if(OZ(G)!==W.dispatch)return Q();if(W.providerState!==void 0&&V.providerState===void 0)return Q();if(X!==void 0&&eZ(Z.ctx.providerState,X)!==W.providerState)return Q();return V}function k3(Z,$,J,X){let{id:z,credential:G,identity:B,label:Q}=J,Y=$.rosterRow(z),W=()=>{throw P("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=$.stateAccount(z),V=a(H?.[E]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==Q||Y.accountId!==B))return W();if(j.reservation!==J.stage?.reservation||j.label!==Q||j.disabledReason!==J.disabled?.reason||V.binding.identity!==B)return W();let F=X===void 0?void 0:uZ(X),U=H?.[d],q=U===void 0?void 0:uZ(U);if(j.providerState!==F||j.providerState!==q)return W();if(DZ(G)!==V.digest||OZ(G)!==V.dispatch)return W();let K=Y?$.config:{accounts:[{...$1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=gZ(K,$.state,Z.ctx.codec,Z.ctx.providerState).find((M)=>M.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==j.label||N.identity!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(J5($.config,z)!==V.credentialEpoch)return W();return $.roster().push({...$1({id:z,credential:G,identity:B,label:Q,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function K4(Z,$,J={}){p("add");let{ctx:X}=Z,{id:z,credential:G,identity:B,label:Q}=$,Y=$.stage!==void 0||$.disabled!==void 0,W=await l(X,"add",z,J.onFailure,async(H,V)=>{R9("add",z,G);let j=J.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw P("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!C($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!C($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw P("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=$.providerState===void 0?void 0:SZ(X.providerState,"add",z,$.providerState);if(await H.acquire(r(Z,{id:z,identity:B})),G.type==="oauth")await H.acquire(J.providerLock??Z.providerLock);for(let U of J.extraLocks??[])await H.acquire(U);return f(X,H,V,{operation:"add",rowId:z},async(U)=>{await H5(U,z,J.protect);let q=C(U.state.accounts)?U.state.accounts:{},K=Object.entries(q).find(([b,g])=>{if(b===z||U.rosterRow(b)||!C(g))return!1;let K1=g[E];if(!C(K1)||!Object.hasOwn(K1,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(K)throw P("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw P("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(U.rosterRow(z)||J1(U.state,z)))return k3(Z,U,$,F);if(j==="rotate"){U.assertNotStaged(z);let b=U.rows().find((g)=>g.fingerprint===YZ(G));if(b)U.assertNotStaged(b.id)}if(j==="refuse"){let b=U.rows().find((yZ)=>yZ.fingerprint===YZ(G)||yZ.id===z&&yZ.credential),g=C(U.state.accounts)?U.state.accounts:{},K1=Object.entries(g).find(([,yZ])=>{if(!C(yZ))return!1;if(G.type==="oauth")return yZ.refresh===G.refresh;return typeof yZ.apiKey==="string"&&yZ.apiKey.trim()===G.apiKey.trim()})?.[0],p$=b?.id??K1??z;if(b||K1!==void 0||J1(U.state,z))throw P("add",p$,"credential-exists",`row ${p$} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||J1(U.state,z)))throw P("add",z,"id-exists",`row ${z} already exists`);let N=y3(Z,U,$,F),M=U.rows(),O=YZ(G),_=j==="rotate"&&!N&&M.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(_){if(U.assertNotStaged(_.id),c("add",_),B!==void 0&&_.identity!==void 0&&B!==_.identity)throw Y5("add",_.id);let b=Q5(Z,U,_.id,G,{...F!==void 0?{providerState:O1(X.providerState,"add",_.id,_.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(_.id);let g=await W5(U,_.id,b);return{id:_.id,outcome:"rotated",credential:g,credentialEpoch:_.credentialEpoch??1}}let D=M.find((b)=>b.id===z);if(D){if(D.invalid)throw P("add",z,"invalid-row",`row ${z} is invalid`);if(D.credential)throw P("add",z,"id-exists",`row ${z} already holds a credential`);if(c("add",D),D.type!==G.type)throw P("add",z,"type-mismatch",`row ${z} is a ${D.type} row`);if(B!==void 0&&D.identity!==void 0&&B!==D.identity)throw Y5("add",z);if(!D.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let b=Q5(Z,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let g=await W5(U,z,b);if(!D.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:D.credentialEpoch??1}}let T=J5(U.config,z);if(!w(T))throw P("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??B;U.roster().push($1({id:z,credential:G,...A!==void 0?{identity:A}:{},...Q!==void 0?{label:Q}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let L="added";if($.disabled)kZ(U,z,$.disabled.reason),L="added-disabled";if(!$.disabled&&A!==void 0&&G.type==="oauth"){if(M.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===A))kZ(U,z,j9),L="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??T};U.dropStateAccount(z);let I=Q5(Z,U,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...Q!==void 0?{label:Q}:{},...F!==void 0?{providerState:uZ(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(j==="rotate")await U.completeTorn();let x=await W5(U,z,I);return await U.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))Z.firePull(W.id,"add");return W}async function N4(Z,$,J,X={},z={}){p("replace");let{ctx:G}=Z,B=await l(G,"replace",$,z.onFailure,async(Q,Y)=>{R9("replace",$,J),X1("replace",$,z.attribution);let W=X.providerState===void 0?void 0:SZ(G.providerState,"replace",$,X.providerState),{row:H}=await VZ(Z,"replace",$);if(await Q.acquire(r(Z,H)),J.type==="oauth")await Q.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return f(G,Q,Y,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)j5("replace",$,V.row($),z.attribution),await V.completeTorn();let j=U5("replace",$,V.row($),J);if(v(j)!==v(H))throw A1("replace",$);let F=V.entry($)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!w(U))throw P("replace",$,"invalid-row",`row ${$}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let q=H4(G.providerState,j,U,X.identity,W),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(C9(V,$,U,K),X.identity!==void 0)oZ(V,X.identity);let N=await V5(Z,V,$,J,{clearErrors:!0,binding:K,providerState:q});return await V.commitConfig(),{id:$,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")Z.firePull($,"replace");return B}async function D4(Z,$,J,X={},z={}){p("rotate");let{ctx:G}=Z;return l(G,"rotate",$,z.onFailure,async(B,Q)=>{R9("rotate",$,J),X1("rotate",$,z.attribution);let Y=X.providerState===void 0?void 0:SZ(G.providerState,"rotate",$,X.providerState),{row:W}=await VZ(Z,"rotate",$);if(await B.acquire(r(Z,W)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let H of z.extraLocks??[])await B.acquire(H);return f(G,B,Q,{operation:"rotate",rowId:$},async(H)=>{if(z.attribution!==void 0)j5("rotate",$,H.row($),z.attribution),await H.completeTorn();let V=U5("rotate",$,H.row($),J);if(v(V)!==v(W))throw A1("rotate",$);if(c("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw Y5("rotate",$);let j=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,F=await V5(Z,H,$,J,{identity:j,...Y!==void 0?{providerState:O1(G.providerState,"rotate",$,V.providerState,Y)}:{}}),U=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(X.identity!==void 0&&V.identity!==X.identity)mZ(H,$,X.identity),U=!0;if(U)await H.commitConfig();return{id:$,credential:F}},{completeTorn:z.attribution===void 0})})}async function M4(Z,$,J,X,z){p($);let{ctx:G}=Z,B=G.providerState,Q=z.attribution,Y=z.providerState;return l(G,$,J,z.onFailure,async(W,H)=>{if(X1($,J,Q),Y!==void 0){if(typeof Y!=="function")throw P($,J,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw P($,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw P($,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await VZ(Z,$,J);await W.acquire(r(Z,V));for(let j of z.extraLocks??[])await W.acquire(j);return f(G,W,H,{operation:$,rowId:J},async(j)=>{await H5(j,J,z.protect),j.assertNotStaged(J);let F=j.row(J),U=X.enabled?U5("enable",J,F):F;if(!U||!j.rosterRow(J))throw e($,J);if(v(U)!==v(V))throw A1($,J);if(Q!==void 0)j5($,J,U,Q);if(X.enabled&&U.disabledReason?.startsWith(rZ))throw P("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let q=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&q&&U.type==="oauth"){let _=U.identity===void 0?void 0:j.rows().find((D)=>D.id!==J&&D.invalid===void 0&&D.type==="oauth"&&D.enabled&&D.identity===U.identity);if(_)throw P("enable",J,"duplicate-identity",`row ${_.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:J};if(X.enabled)N1(j,J);else kZ(j,J,X.reason);return await j.commitConfig(),{id:J}}if(!U.credential)throw P($,J,"no-credential",`row ${J} holds no credential`);c($,U);let K=await S9(j,B,$,U,Y,!0);if(K.kind==="declined")return{id:J,declined:!0};await j.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(q){if(X.enabled)N1(j,J);else kZ(j,J,X.reason);await j.commitConfig()}return N}if(!q)return j.setStateAccount(J,K.account),await j.commitState(),N;let M=X.enabled?{mark:q4(),enabled:!0}:{mark:q4(),enabled:!1,reason:X.reason},O=K.account[E];return j.setStateAccount(J,{...K.account,[E]:{...O,[X5]:M}}),await j.commitState(),T1(j,J,M),await j.commitConfig(),N},{completeTorn:!1})})}function P4(Z,$,J,X={}){return M4(Z,"disable",$,{enabled:!1,reason:J},X)}function C4(Z,$,J={}){return M4(Z,"enable",$,{enabled:!0},J)}async function T4(Z,$,J={}){p("remove");let{ctx:X}=Z;return l(X,"remove",$,J.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw P("remove",$,"invalid-input","id must be non-empty");let B=J.attribution;if(X1("remove",$,B),J.staged!==void 0&&(!C(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw P("remove",$,"invalid-input","a staged removal needs a reservation");let Q=await n(X);if(Q.status!=="ready")throw HZ(Q,"remove",$);let Y=Q.rows.find((H)=>H.id===$);if(!Y&&!J1(Q.state,$))throw e("remove",$);let W=v(Y??{id:$});await z.acquire(r(Z,Y??{id:$}));for(let H of J.extraLocks??[])await z.acquire(H);return f(X,z,G,{operation:"remove",rowId:$},async(H)=>{let V=H.reservation($);if(V!==void 0){if(!C(V)||!J.staged||V.reservation!==J.staged.reservation)throw P("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(J.staged)throw P("remove",$,"attribution",`row ${$} is no longer reserved`);let j=H.row($),F=J1(H.state,$);if(!j&&!F)throw e("remove",$);if(v(j??{id:$})!==W)throw A1("remove",$);if(B!==void 0)if(j)q5($,j,B);else v3(Z,H,$,B);let U=J.protect;if(U){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},K=await KZ("remove",()=>U($,q));if(K!==void 0)throw P("remove",$,"row-protected",K)}if(j){if(B===void 0)await H.completeTorn();H.dropRosterRows($),await H.commitConfig()}if(F)H.dropStateAccount($),await H.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function q5(Z,$,J,X="remove"){if(j5(X,Z,$,J),$.torn)throw P(X,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw P(X,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function v3(Z,$,J,X){let z=()=>P("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=$.stateAccount(J),B=a(G?.[E]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let Q;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();Q={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")Q={type:"oauth",refresh:G.refresh};else throw z();let[Y]=gZ({accounts:[$1({id:J,credential:Q,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw P("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function J1(Z,$){let J=Z.accounts;return C(J)&&Object.hasOwn(J,$)}function I9(Z){return C(Z)&&typeof Z.id==="string"?Z.id:void 0}function g3(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let J=new Set;for(let G of Z){let B=I9(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of $){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 h3(Z,$){let J=new Map;for(let G of Z){let B=I9(G);if(B===void 0)continue;let Q=J.get(B);if(Q)Q.push(G);else J.set(B,[G])}let X=$.flatMap((G)=>J.get(G)??[]),z=0;return Z.map((G)=>I9(G)===void 0?G:X[z++])}async function _4(Z,$,J={}){p("reorder");let{ctx:X}=Z,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);return f(X,G,B,{operation:"reorder",rowId:void 0},async(Q)=>{let Y=Q.roster(),W=g3(Y,$);if(W)throw new R({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let H=[...$],V=h3(Y,H);if(V.every((j,F)=>j===Y[F]))return{ids:H,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function L4(Z,$,J,X,z={}){return p("recordIdentity"),l(Z.ctx,"recordIdentity",$,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw P("recordIdentity",$,"invalid-input","identity must be non-empty");let Q=C(X)?X.credentialEpoch:void 0;if(!w(Q))throw P("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await VZ(Z,"recordIdentity",$);await G.acquire(r(Z,Y)),await G.acquire(z.providerLock??Z.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return f(Z.ctx,G,B,{operation:"recordIdentity",rowId:$},async(W)=>{let H=U5("recordIdentity",$,W.row($));if(v(H)!==v(Y))throw A1("recordIdentity",$);if(c("recordIdentity",H),(H.credentialEpoch??1)!==Q)throw P("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw Y5("recordIdentity",$);if(H.identity===void 0)await b3(W,H,J);let V=mZ(W,$,J);return await W.commitConfig(),{id:$,disabled:V}})})}function A4(Z){let $=Z[y];return C($)&&C($.publications)?$.publications:{}}function S4(Z,$){let J=A4(Z);if(!Object.hasOwn(J,$))return;let X=J[$];if(!C(X)||X.operationId!==$||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)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch))||X.finalized.some((z)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw P("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function I4(Z,$){let J=await n(Z.ctx);if(J.status!=="ready")throw HZ(J,"publishRoster",$);return S4(J.config,$)}function f3(Z,$){let J=()=>{throw P("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!C($)||typeof $.operationId!=="string"||!$.operationId||!Array.isArray($.remove)||!Array.isArray($.finalize)||!Array.isArray($.order))J();let X=new Set;for(let z of[...$.remove,...$.finalize]){if(!C(z)||typeof z.id!=="string"||tZ(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),X1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of $.remove)if(Z.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of $.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if($.order.some((z)=>typeof z!=="string"||tZ(z))||new Set($.order).size!==$.order.length)J()}function R4(Z,$){Z.entries();let J=Z.config[y],X={...A4(Z.config)};Object.defineProperty(X,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function x3(Z,$,J){let X=new Set;for(let B of Z1(Z.config)){if(!C(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw P("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set($.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==$.order.length||$.order.some((B)=>!G.some((Q)=>Q.id===B))||G.some((B)=>!$.order.includes(B.id)))throw P("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function O4(Z,$){await Z.assertAll();for(let X of $.removed)if(a(Z.stateAccount(X.id)?.[E])?.credentialEpoch===X.credentialEpoch&&!Z.rosterRow(X.id))Z.dropStateAccount(X.id);for(let X of $.finalized){let z=Z.stateAccount(X.id),G=a(z?.[E]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[E]};delete B.staged,Z.setStateAccount(X.id,{...z,[E]:B})}}await Z.commitState(void 0,{durable:!0});let J={...$,phase:"cleaned"};return R4(Z,J),await Z.commitConfig({durable:!0}),J}async function E4(Z,$,J={}){return p("publishRoster"),l(Z.ctx,"publishRoster",$?.operationId??"",J.onFailure,async(X,z)=>{if(!C($)||typeof $.operationId!=="string"||!$.operationId)throw P("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=uZ($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((Q)=>C(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let Y=await n(Z.ctx);if(Y.status!=="ready")throw HZ(Y,"publishRoster",$.operationId);let W=new Map(B.map(({id:V})=>[V,v(Y.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(W.values())].sort())await X.acquire(r(Z,{id:V}));await X.acquire(J.providerLock??Z.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await f(Z.ctx,X,z,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(B.some(({id:D})=>v(j.find((T)=>T.id===D)??{id:D})!==W.get(D)))return;let F=S4(V.config,$.operationId);if(F){if(F.planDigest!==G)throw P("publishRoster",$.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await O4(V,F)}}f3(Z,$);let U=x3(V,$,j),q=[];for(let D of $.remove){V.assertNotStaged(D.id);let T=j.find((A)=>A.id===D.id);if(!T)throw P("publishRoster",D.id,"attribution","the removed row no longer exists");if(q5(D.id,T,D.attribution,"publishRoster"),!T.credential||D.fingerprint!==void 0&&YZ(T.credential)!==D.fingerprint)throw P("publishRoster",D.id,"attribution","the removed secret no longer matches");q.push(T)}let K=[];for(let D of $.finalize){let T=j.find((g)=>g.id===D.id),A=a(V.stateAccount(D.id)?.[E]);if(!T||T.staged?.reservation!==D.reservation||A?.staged?.reservation!==D.reservation||T.enabled)throw P("publishRoster",D.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(D.id),I=V.rosterRow(D.id),x=L?.[d],b=x===void 0?void 0:uZ(x);if(!A?.staged||A.staged.label!==I?.label||A.staged.disabledReason!==T.disabledReason||A.staged.providerState!==b)throw P("publishRoster",D.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");q5(D.id,T,D.attribution,"publishRoster"),K.push(T)}let N=U.find((D)=>D.torn);if(N)throw P("publishRoster",$.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let M=new Set;for(let D of U){if(!($.finalize.find((A)=>A.id===D.id)?.enabled??D.enabled)||D.type!=="oauth"||D.identity===void 0)continue;if(M.has(D.identity))throw P("publishRoster",D.id,"invalid-input","the final enabled roster repeats a known identity");M.add(D.identity)}for(let D of U)if(D.identity!==void 0&&D.fingerprint!==void 0&&U.some((T)=>T.id!==D.id&&T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the resulting pool gives the same secret different known identities");for(let D of K)if(D.identity!==void 0&&q.some((T)=>T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the staged secret belonged to a different known identity");await H5(V,$.operationId,J.protect);let O={operationId:$.operationId,planDigest:G,phase:"committed",removed:q.map((D)=>({id:D.id,credentialEpoch:D.credentialEpoch??1})),finalized:$.finalize.map((D,T)=>({id:D.id,credentialEpoch:K[T]?.credentialEpoch??1,reservation:D.reservation,enabled:D.enabled}))};for(let D of $.remove)V.dropRosterRows(D.id);for(let D of $.finalize){let T=V.rosterRow(D.id);T.enabled=D.enabled;let A={...V.entry(D.id)};if(delete A.staged,D.enabled)delete A.disabledReason;else A.disabledReason=D.disabledReason;V.setEntry(D.id,A)}let _=V.roster().filter((D)=>!C(D)||typeof D.id!=="string"||j.find((T)=>T.id===D.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((D)=>V.rosterRow(D)),..._],R4(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await O4(V,O)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),Q>=1)throw P("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class E9{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,J,X,z){this.rt=Z,this.hook=$,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire(Z,$){if(!this.hook)return;if($==="load"){if(this.firedAtLoad.has(Z))return;this.firedAtLoad.add(Z)}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 NZ(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await f(X,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let H=W.row(Z);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)c("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let V=W.row(Z);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:Z,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:$}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await X.hold?.("pull-before-request",Z);let Q;try{Q=await this.hook?.(B)}catch(W){throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,H,V)=>B5(J,W,H,V)))(Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete(Z);let Q=hZ(B,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,Q)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:Z,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:Q.kind})}finally{await z.releaseAll()}}}var b4=100,F5=128;class b9{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=k4){this.rt=Z,this.timeoutMs=$,this.clock=J,this.logger=Z.ctx.logger??s("store")}async record(Z,$,J){try{this.assertOpen(Z),A9(Z,$);let X=structuredClone({id:Z,attribution:$,observation:J}),{row:z,result:G}=await VZ(this.rt,"pull",Z);_1(Z,X.attribution,z),L1(this.rt.ctx,Z,this.overlayRow({...z,quota:MZ(G.config,Z)?.quota}).quota,X.observation),await this.room(Z),this.assertOpen(Z);let B=this.pending.get(Z)??[];if(B.push(X),this.pending.set(Z,B),B.length>=F5)this.flushNow();else this.schedule(b4)}catch(X){throw hZ(X,"pull",Z,{writes:0})}}queued(Z){return this.pending.get(Z)?.length??0}async room(Z){if(this.queued(Z)<F5)return;let{ctx:$}=this.rt,J=Math.max(0,...$.storeLocks.map((z)=>z.timeoutMs??$.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued(Z)>=F5){this.assertOpen(Z),this.flushNow();let z=X-performance.now();if(z<=0)throw P("pull",Z,"lock-contention",`pool quota queue for ${Z} is full (${F5} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(Q),this.wake.delete(B),G()},Q=setTimeout(B,z);this.wake.add(B)})}}assertOpen(Z){if(this.closed)throw P("pull",Z,"invalid-input","pool quota writer is closed")}overlayRow(Z){let $=Z;for(let J of this.pending.get(Z.id)??[])try{_1(Z.id,J.attribution,Z),$={...$,quota:L1(this.rt.ctx,Z.id,$.quota,J.observation),needsFirstReading:!1}}catch{}return $}overlay(Z){return Z.map(($)=>this.overlayRow($))}schedule(Z){if(this.running||this.timer||!this.pending.size||this.stopped)return;let $=this.closed?0:(this.committedAt??-1/0)+y4-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 Z=[...this.pending.values()].flat(),$={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new NZ($.lockDefaults,$.lockEnv);return this.running=(async()=>{try{await f($,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of Z){let{id:Q,attribution:Y,observation:W}=B,H=JSON.stringify([Q,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(Q),_1(Q,Y,z.row(Q))}catch(F){if(!(F instanceof R))throw F;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:Q,kind:F.kind});continue}let V=z.entry(Q);if(!V)continue;let j;try{j=L1($,Q,V.quota,W)}catch(F){let U=`codec:${H}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:Q,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(Q,{...V,quota:j,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set(Z);for(let[z,G]of this.pending){let B=G.filter((Q)=>!X.has(Q));if(B.length)this.pending.set(z,B);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()):b4;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)=>{$=()=>{if(!this.pending.size)X()},this.wake.add($),$()});try{this.flush(),await Promise.race([J,new Promise((X)=>{Z=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout(Z),this.cancelTimer(),this.wake.delete($),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 m3}from"node:crypto";function y9(Z,$){if(wZ("refresh",Z,$?.staged),!$)throw P("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw P("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw P("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw P("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function v4(Z){return P("refresh",Z,"refresh-stamp-ahead",`row ${Z}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function g4(Z,$,J,X={}){p("refresh");let{ctx:z}=Z;return l(z,"refresh",$,X.onFailure,async(G,B)=>{let{row:Q}=await VZ(Z,"refresh",$);y9($,Q);let Y=await X.refuse?.(Q);if(Y!==void 0)return{status:"refused",rowId:$,reason:Y};let W=v(Q),H;for(let U=0;;U++){await G.acquire(r(Z,{id:$,identity:W===$?void 0:W})),await G.acquire(X.providerLock??Z.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await f(z,G,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let M=y9($,N.row($));if(c("refresh",M),!M.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),M=y9($,N.row($));if(v(M)!==W)return{keyNow:v(M)};let O=await X.refuse?.(M);if(O!==void 0)return{refused:O};return{row:M,credential:M.credential,credentialEpoch:M.credentialEpoch,identity:M.identity}});if("refused"in K)return{status:"refused",rowId:$,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw P("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);W=K.keyNow;continue}H=K;break}if(P9(H.credential.lastRefreshedAt,z.now()))throw v4($);await z.hold?.("refresh-before-provider",$),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(U){throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw P("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:SZ(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),F=await f(z,G,B,{operation:"refresh",rowId:$},async(U)=>{let q=U.row($),K=U.entry($);if(!q||q.invalid||!K||K.credentialEpoch!==H.credentialEpoch||q.identity!==H.identity)throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${$} changed credential while its refresh was in flight; the rotation is discarded`});c("refresh",q);let N=await X.refuse?.(q);if(N!==void 0)return{refused:N};let M=z.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(P9(O,M))throw v4($);let _={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},D=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,T=D?{mark:m3(),enabled:!1,reason:`${rZ}${JSON.stringify(D)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,L=await V5(Z,U,$,_,{stamp:C1(O,M),transition:T,identity:A,...j!==void 0?{providerState:O1(z.providerState,"refresh",$,q.providerState,j)}:{}});if(T!==void 0)T1(U,$,T),await U.commitConfig();let I=q.identity;if(A!==void 0)mZ(U,$,A),I=A,await U.commitConfig();return{stored:L,identity:I,contradiction:D,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:$,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:$,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await KZ("refresh",()=>U($,F.stored))}catch(U){throw new R({operation:"refresh",rowId:$,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:F.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:$,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as w3}from"node:util";var N5=Object.freeze(["version","accounts",y]);function k9(Z){let $={};for(let[J,X]of Object.entries(Z))if(!N5.includes(J))K5($,J,X);return $}function K5(Z,$,J){Object.defineProperty(Z,$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function u3(Z,$){let J={};for(let[X,z]of Object.entries(Z))if(N5.includes(X))K5(J,X,z);else if(Object.hasOwn($,X))K5(J,X,$[X]);for(let[X,z]of Object.entries($))if(!Object.hasOwn(Z,X))K5(J,X,z);return J}function h4(Z){return new R({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}var p3=new f4;async function x4(Z){let $=async([X=Z.ctx.configPath]=[])=>{let z=await Q4(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:k9(z.config)}},J=G5?await $():await p3.read([Z.ctx.configPath],$);return structuredClone(J)}async function m4(Z,$,J={}){p("updateSettings");let{ctx:X}=Z,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let Q=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Y=await n(X);if(Y.status!=="ready")throw HZ(Y,"updateSettings",void 0);let W=k9(Y.config),H=structuredClone(W),V=await KZ("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!C(j))throw h4("the settings mutator must produce an object");let F=N5.filter((K)=>Object.hasOwn(j,K));if(F.length>0)throw h4(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(w3(j,W))return{settings:W,outcome:"unchanged"};let U=u3(Y.config,j),q={operation:"updateSettings",rowId:void 0};return await AZ(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",q),{settings:k9(U),outcome:"updated"}}finally{await G.releaseTo(Q)}})}var w4=new Map;function l3(Z){let $=w4.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},w4.set(Z,$);return $}function u4(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:vZ,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function S1(Z){let $=l3(Z.configPath),J={...q9,...Z.lockOptions},X={provider:Z.provider,configPath:Z.configPath,statePath:Z.statePath,codec:Z.quota,...Z.providerState?{providerState:Z.providerState}:{},now:Z.now??Date.now,storeLocks:Z.storeLocks??[{name:"save",path:Z.configPath},{name:"save",path:Z.statePath}],lockDefaults:J,lockEnv:{...Z.onLockEvent?{onLockEvent:Z.onLockEvent}:{},...Z.onLockStep?{onLockStep:Z.onLockStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}},removedIds:$.removedIds,requireCredentialStamps:Z.requireCredentialStamps===!0,requireRemovedFingerprint:Z.requireRemovedFingerprint===!0,...Z.logger?{logger:Z.logger}:{},...Z.onStep?{onStep:Z.onStep}:{},...Z.hold?{hold:Z.hold}:{}},z=new E9(()=>G,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),G={ctx:X,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(W,H)=>z.fire(W,H)},B=Z.coalesceQuota?new b9(G,Z.quotaDrainTimeoutMs,Z.quotaCommitTimer):void 0,Q=(W,H,V)=>B?B.record(W,H,V):B5(G,W,H,V);G.publishQuota=Q;let Y=(W)=>{if(W.status==="ready"&&B)return{...W,rows:B.overlay(W.rows)};return W};return{async load(){let W=Y(await n(X));if(W.status==="ready"){for(let H of W.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return u4(W)},async read(){return u4(Y(await n(X)))},async initialize(W={}){return{status:await Y4(X,W.dropKeys??[])}},add:(W,H)=>K4(G,W,H),publishRoster:(W,H)=>E4(G,W,H),publication:(W)=>I4(G,W),replace:(W,H,V,j)=>N4(G,W,H,V,j),rotate:(W,H,V,j)=>D4(G,W,H,V,j),updateProviderState:(W,H,V,j)=>U4(G,W,H,V,j),disable:(W,H,V)=>P4(G,W,H,V),enable:(W,H)=>C4(G,W,H),remove:(W,H)=>T4(G,W,H),reorder:(W,H)=>_4(G,W,H),readSettings:()=>x4(G),updateSettings:(W,H)=>m4(G,W,H),recordIdentity:(W,H,V,j)=>L4(G,W,H,V,j),refresh:(W,H,V)=>g4(G,W,H,V),recordQuota:Q,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var d3=[/\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 h9(Z={}){let{redactStrings:$}=p4({...Z,extraValuePatterns:[...d3,...Z.extraValuePatterns??[]]});return(J)=>$(J)}class u extends Error{code;constructor(Z,$,J){super($,J);this.name="CommandError",this.code=Z}}var l4=/^[a-z][a-z0-9-]{0,63}$/,v9={code:"action-failed",text:"That action failed."},c3=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(Z){if(Z instanceof u)return{code:l4.test(Z.code)?Z.code:v9.code,text:Z.message};if(Z instanceof R)return{code:`pool-${Z.kind}`,text:c3.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return v9}var d4="This cannot be undone. Continue?",s3=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function a3(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return s3.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function n3(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function g9(Z,$,J){if(typeof Z==="string"){let z=J.redact(Z);if(z!==Z)J.redacted.push($);return z}if(Array.isArray(Z))return Z.map((z,G)=>g9(z,`${$}[${G}]`,J));if(!n3(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(a3(z)){J.dropped.push(`${$}.${z}`);continue}Object.defineProperty(X,z,{value:g9(G,`${$}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function c4(Z,$,J){let X={redact:J.redact,dropped:[],redacted:[]},z=g9(Z,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:$,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:$,fields:X.redacted});return z}function i3(Z){return{value:String(Z.value),label:String(Z.label)}}function r3(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(i3),...Z.value!==void 0?{value:Z.value}:{}};case"toggle":return{kind:"toggle",id:Z.id,label:Z.label,value:Z.value===!0};case"number":return{kind:"number",id:Z.id,label:Z.label,...Z.value!==void 0?{value:Z.value}:{},...Z.min!==void 0?{min:Z.min}:{},...Z.max!==void 0?{max:Z.max}:{},...Z.required?{required:!0}:{}};case"text":return{kind:"text",id:Z.id,label:Z.label,...Z.value!==void 0&&!Z.masked?{value:Z.value}:{},...Z.placeholder!==void 0?{placeholder:Z.placeholder}:{},...Z.masked?{masked:!0}:{},...Z.required?{required:!0}:{}}}}function f9(Z){if(Z.irreversible===!0)return{message:Z.confirm||d4,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function s4(Z){let $=f9(Z);return{id:Z.id,label:Z.label,...Z.description!==void 0?{description:Z.description}:{},...Z.group!==void 0?{group:String(Z.group)}:{},knobs:(Z.knobs??[]).map(r3),...$?{confirm:$}:{}}}function o3(Z){return{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...Z.identity!==void 0?{identity:Z.identity}:{}}}function t3(Z){return{id:Z.id,label:Z.label,...Z.detail!==void 0?{detail:Z.detail}:{},...Z.group!==void 0?{group:String(Z.group)}:{},...Z.status!==void 0?{status:String(Z.status)}:{},...Z.account?{account:o3(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(s4)}}function e3(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(t3),actions:($.actions??[]).map(s4),...$.facts!==void 0?{facts:$.facts}:{}}}function a4(Z,$,J){return{command:Z,title:$,sections:J.map(e3)}}function n4(Z,$,J,X){return c4({command:Z,menu:a4(Z,$,J)},Z,X)}function i4(Z,$,J,X,z){return c4({command:Z,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:l4.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:a4(Z,$,J)},Z,z)}var J6="disabled from the command menu";function Z8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function IZ(Z){return Z8(Z)?{...Z}:{}}function $8(Z){if(Z.status!=="ready")return[];let $=new Set;return Z.rows.filter((J)=>{if($.has(J.id))return!1;return $.add(J.id),!0})}function J8(Z,$){return Z.label??$??Z.id}function D5(Z,$){return fZ(Z.quota)?CZ(Z.quota,$):void 0}function X6(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var R1="Actions";function X8(Z){if(Z.status==="pending-migration")return"The account pool has not been migrated yet.";if(Z.status==="error")return`The ${Z.file} file cannot be read: ${Z.reason}`;return}function r4(Z,$){switch($.outcome){case"added":return`Added ${Z}.`;case"added-disabled":return`Added ${Z}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${Z}.`;case"rotated":return`${Z} was already in the pool; its credential was updated.`;case"exists":return`${Z} was already in the pool; its credential is unchanged.`}}function o4(Z){return I1(Z).text}async function z8(Z){let{store:$}=Z,J=await $.read(),X=await $.readSettings(),z=await Z.routing?.vaultOrder?.();return{load:J,rows:$8(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function M5(Z,$){let J=$.accounts?.describeIdentity?$.accounts.describeIdentity(Z):Z.identity;return{account:{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...J!==void 0?{identity:J}:{}},name:J8(Z,J)}}function G8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=$.rows.map((V)=>V.id),B=X8($.load),Q=$.rows.filter((V)=>V.enabled).length,Y=$.rows.map((V,j)=>{let{account:F,name:U}=M5(V,Z),q=[V.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,J6,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${U}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((M,O)=>({value:String(O+1),label:String(O+1)})),value:String(j+1)}],run:async({values:M})=>{let O=Number(M.position),_=G.filter((T)=>T!==V.id);return _.splice(O-1,0,V.id),(await J.reorder(_,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(V.id,{...z,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:q,group:"Accounts",status:K,account:F,actions:N}}),W=Z.accounts?.login,H=[];if(W&&!B)H.push({id:"add",label:W.label??"Add account",group:R1,knobs:W.knobs??[],run:async({values:V,invocation:j})=>{let F=await W.run(V,j);if(F.status==="cancelled")return{ok:!1,text:F.message??"Login cancelled."};if(F.status==="ready"){let U=await J.add(F.account,z);return r4(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let q=await J.add(U,z);j.notify(r4(U.label??q.id,q))},(U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${X6($.rows.length,"account")}, ${Q} enabled`],items:B?[]:Y,actions:H}}}function B8(Z,$){let J=Z.quota?.scope??"all",X=Z.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((H)=>H.candidate),Q=B.map((H)=>{let{account:V,name:j}=M5(H,Z),F=D5(H,J);return{id:H.id,label:j,group:z,status:PZ(F,{now:X,form:"compact"}),detail:PZ(F,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([H.id],U),`Checked quota for ${j}.`}}]}}),Y=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=M5(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",F=PZ(D5(H,J),{now:X,form:"compact"});return`${V} (${j}): ${F}`}),W=[];if(B.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R1,run:async({invocation:H})=>{let V=B.map((j)=>j.id);return await G(V,H),`Checked quota for ${X6(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:Y,items:Q,actions:W}}}async function Q8(Z,$){try{return await Z.reorder($)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function x9(Z){return new u("vault-invalid-order",Z)}function W8(Z){let $=Z.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>$.filter((z)=>z.id===X||z.label===X);return{ids:$.map((X)=>X.id),nameOf:(X)=>$.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let 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 B=J(G);if(B.length===0)throw x9(`"${G}" is not a vault account.`);if(B.length>1)throw x9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let Q=B[0].id;if(z.includes(Q))throw x9(`"${G}" names an account already in the order.`);z.push(Q)}return z}}}function Y8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=IZ($.settings.routing).mode,Q=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Y=Z6(Q),W=$.vault?W8($.vault):void 0,H=W?W.ids:$.rows.map((K)=>K.id),V=(K)=>W?W.nameOf(K):K,j=$6(H,Y.placement,Z.routing?.formerMainId??e4),U=[`Mode: ${G.find((K)=>K.value===Q)?.label??Q}`];if(H.length>0)U.push(`${W?"Vault account order":"Roster order"}: ${H.map(V).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==H.join())U.push(`Tried in order: ${j.map(V).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:R1,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Q}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((M)=>{M.routing={...IZ(M.routing),mode:N};return},z),`Routing mode set to ${G.find((M)=>M.value===N)?.label??N}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:R1,knobs:[{kind:"text",id:"order",label:W?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:W?H.map(W.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:K})=>{let M=String(K.order).split(W?/[,\n]+/:/[\s,]+/).map((_)=>_.trim()).filter((_)=>_.length>0),O=$.vault&&W?await Q8($.vault,W.resolve(M)):await J.reorder(M,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:q}}}function H8(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let J=Z.quota?.scope??"all",X=[];for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function V8(Z,$){let J=Z.quota?.scope??"all",X=new Map;for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,t4(G));return(z)=>X.get(z)??z}function U8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=IZ($.settings.killswitch),B=G.enabled===!0,Q=IZ(G.accounts),Y=H8(Z,$),W=V8(Z,$),H=B?"on":"off",V=$.rows.map((j)=>{let{account:F,name:U}=M5(j,Z),q=IZ(Q[j.id]),K=Y.filter((N)=>typeof q[N]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${H}`,status:K.length===0?"no floors":K.map((N)=>`${W(N)} ≥${q[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Y.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${W(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((M)=>{let O=IZ(M.killswitch),_=IZ(O.accounts),D=IZ(_[j.id]);for(let T of Y){let A=N[T];if(typeof A==="number")D[T]=A;else if(A===null)delete D[T]}if(Object.keys(D).length>0)_[j.id]=D;else delete _[j.id];if(Object.keys(_).length>0)O.accounts=_;else delete O.accounts;M.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:R1,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let F=j.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...IZ(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function z6(Z){let $=await z8(Z);return[G8(Z,$),B8(Z,$),Y8(Z,$),U8(Z,$)]}var j8=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),m9=["accounts","quota","routing","limits"];function G6(Z,$){let{sessionId:J}=Z,X=Z.notify.bind(Z);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X($(String(z))):X($(String(z)),G)})}function q8(Z,$){switch(Z.kind){case"choice":{let J=$??Z.value;if(typeof J==="string"&&Z.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${Z.label}.`}}case"toggle":{let J=$??Z.value;return typeof J==="boolean"?{value:J}:{problem:`${Z.label} must be on or off.`}}case"number":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${Z.label} needs a number.`};if(Z.min!==void 0&&X<Z.min)return{problem:`${Z.label} must be at least ${Z.min}.`};if(Z.max!==void 0&&X>Z.max)return{problem:`${Z.label} must be at most ${Z.max}.`};return{value:X}}case"text":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${Z.label} must be text.`}}}}function F8(Z,$){let J={};for(let X of Z){let z=$&&Object.hasOwn($,X.id)?$[X.id]:void 0,G=q8(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function K8(Z,$){let J=Z.find((z)=>z.id===$.sectionId);if(!J)return;return($.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===$.itemId)?.actions)?.find((z)=>z.id===$.actionId)}function pZ(Z){let $=Z.logger??s("commands"),J=h9(Z.redaction),X={logger:$,redact:J},z=Z.now??Date.now,G=Z.extras??[],B=Z.replace??{},Q=m9.filter((j)=>!B[j]);for(let j of m9)if(B[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=Z.store;if(Q.length>0&&!Y)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let W=new Set;for(let j of G){if(j8.has(j.id)||W.has(j.id))throw Error(`extra section id ${j.id} is taken`);W.add(j.id)}async function H(j,F,U,q){try{return{id:j,slot:F,title:U.title,content:await U.build(q)}}catch(K){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:J(K instanceof Error?K.message:String(K))}),{id:j,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let F=Y&&Q.length>0?await z6({store:Y,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],U=[];for(let q of m9){let K=B[q];if(K)U.push(await H(q,q,K,j));else{let N=F.find((M)=>M.slot===q);if(N)U.push(N)}}if(Z.cache)U.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)U.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of G)U.push(await H(q.id,"extra",q,j));return U}return{command:Z.command,async open(j){let F=G6(j,J);return n4(Z.command,Z.title,await V(F),X)},async apply(j,F){let U=G6(F,J),q=async(_)=>i4(Z.command,Z.title,await V(U),_,X),K=j.command===Z.command?K8(await V(U),j):void 0;if(!K)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=f9(K);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let M=F8(K.knobs??[],j.values);if("problem"in M)return q({ok:!1,code:"invalid-input",text:M.problem});let O;try{let _=await K.run({values:M.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});O=typeof _==="string"?{ok:!0,text:_}:{ok:_.ok,text:_.text,..._.ok?{}:{code:_.code??"refused"}}}catch(_){let D=I1(_);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:D.code,error:J(_ instanceof Error?_.message:String(_))}),O={ok:!1,...D}}return q(O)}}}function N8(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function D8(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $=Z;if(typeof $.command!=="string"||typeof $.sectionId!=="string"||typeof $.actionId!=="string")return;if($.itemId!==void 0&&typeof $.itemId!=="string")return;if($.sessionId!==void 0&&typeof $.sessionId!=="string")return;if($.confirmed!==void 0&&typeof $.confirmed!=="boolean")return;let J={};if($.values!==void 0){if($.values===null||typeof $.values!=="object"||Array.isArray($.values))return;for(let[X,z]of Object.entries($.values)){if(!N8(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:$.command,sectionId:$.sectionId,actionId:$.actionId,...typeof $.itemId==="string"?{itemId:$.itemId}:{},...$.values!==void 0?{values:J}:{},...$.confirmed===!0?{confirmed:!0}:{},...typeof $.sessionId==="string"?{sessionId:$.sessionId}:{}}}function k(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as C8}from"node:fs";import{rm as W6}from"node:fs/promises";import{dirname as T8,join as M6}from"node:path";import{resolveClaustrumConnectionPath as _8}from"@cortexkit/claustrum-client";function B6(Z,$){if(!Z)return;let J=Z.rawUsedPercent??Z.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:$,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...typeof Z.windowMinutes==="number"&&Number.isFinite(Z.windowMinutes)&&Z.windowMinutes>0&&{windowMinutes:Z.windowMinutes}}}function w9(Z){if(!k(Z)||typeof Z.minor!=="number"||!Number.isSafeInteger(Z.minor)||typeof Z.exponent!=="number"||!Number.isInteger(Z.exponent))return;let $=Z.minor/10**Z.exponent;return Number.isFinite($)?$:void 0}function M8(Z){let $=w9(Z.total),J=w9(Z.remaining);if($===void 0||J===void 0||$<0||J<0)return;let X=$-J,z=Z.spendable===!1,G=$>0?X/$*100:z?100:0;return{limit:$,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...k(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function P8(Z,$){if(!k(Z))return;let J=w9(Z.remaining);return{hasCredits:!0,unlimited:typeof Z.unlimited==="boolean"?Z.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...Z.spendable===!1&&{overageLimitReached:!0},checkedAt:$}}function u9(Z,$){if(Z.insulaCreditsUnlimitedUnstated&&Z.credits&&Z.credits.balance===void 0&&k($)&&k($.credits)&&$.credits.unlimited===!0)return{...Z,credits:{...Z.credits,unlimited:!0}};return Z}function Q6(Z,$){let J=B6(Z.usage?.primary,$.fetchedAt);if(!J||!Number.isFinite($.fetchedAt))return;let X=B6(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="individual_limit"):void 0,G=k(z)?M8(z):void 0,B=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="credits"):void 0,Q=P8(B,$.fetchedAt),Y=k(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:J,...Q&&{credits:Q},...Q&&k(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function p9(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var l9="ck auth reclassify --from-registry";function P5(Z,$){if($===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($.grants===0)return`The vault has no grant letting ${Z} read OpenAI accounts. Grant it with \`${p9(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${l9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var UZ=s("vault"),L8="openai-auth",P6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},O8={opencode:"OpenCode",pi:"Pi"};function d9(Z){return H6(L8,Z)}function O5(Z){return M6(T8(Z),"openai-auth-vault")}function lZ(Z,$){return{...U6({stateDir:Z,host:$}),rosterPath:M6(Z,`${$}-roster.json`)}}var C6=2000,RB=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],A8={"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 ${l9} 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 EB(Z,$){if(Z!=="vault-no-grant")return A8[Z];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: ${p9($)}`}function bB(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let J=Z.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function S8(Z){let $=T5(Z);return $?_5($):void 0}class I8{host;name;paths;#$;#Z;#Q=new Map;#W=new Map;#U=new Map;#j;#J;#Y;#z;#q=!1;#F=!1;#H=Promise.withResolvers();#K="unknown";#V;constructor(Z){this.#$=Z,this.host=Z.host,this.name=d9(Z.host),this.paths=lZ(Z.stateDir,Z.host),this.#Z=new N6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:P6,connect:()=>this.#C(),isCustodyActive:()=>this.#_(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:S8,insula:{provider:"codex",normalize:Q6},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:($)=>this.#L($),onError:($)=>this.#X("vault roster refresh failed",$),logger:{...UZ,warn:($,J)=>{if($!=="skipped insula provider poll")UZ.warn($,J)}}})}#N(){return(this.#$.connectionFile??_8)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>UZ.debug("vault transport error",{errorClass:Z})}}#C(){return(this.#$.connectScoped?.()??D6(this.#D())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#G(Z,$,J){let X=this.#U.get(Z);if(X?.source===$&&X.reason===J)return;this.#U.set(Z,{source:$,reason:J}),UZ.info("vault background quota source changed",{routeId:Z,source:$,reason:J})}#T(){return this.#$.connectEnrollment?.()??V6(this.#D())}#X(Z,$){this.#J=TZ($),UZ.warn(Z,{host:this.host,error:this.#J})}#B(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=C8(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#B(),$=await j6(this.paths,this.name);if(Z===this.#B())return this.#K=$,this.#V=Z,$;return"unreadable"}enrolled(){return this.#V!==this.#B()||this.#K!=="local"}async#_(){if(this.#V!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#q||this.#F)return;this.#q=!0,this.#Z.start()}#L(Z){if(this.#z===Z)return;this.#z=Z,Z.finally(()=>{if(this.#z===Z)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#M(){return this.#Z.refresh()}firstRoster(){return this.#H.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#z;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#z??this.#M()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let Z=this.#z;if(Z)await Z.catch(()=>{return});let $=await this.#M();return this.#J=void 0,$}catch(Z){return this.#X("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#Z.routingRows().map(($)=>{let J=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,J){let X=!1;try{return await this.#Z.send(Z,(z)=>{return X=!0,$(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.#Z.authorize(Z,$.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot(Z,$,J,X){let z=C5($,(this.#$.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#Z.recordQuota(Z,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}pollQuota(Z,$=!0){let J=this.#W.get(Z);if(J)return J;let X=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,X),X}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let J=(await K6(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===Z),X,z=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#G(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#P(Z,$);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let Q=C5(u9(z,this.routes().find((W)=>W.id===Z)?.quota),z.primary.checkedAt,!0);if(!Q)return this.#G(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,J.accountIdentity,Q))return this.#G(Z,"insula",null),{ok:!0};return this.#G(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute(Z),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G(Z,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#P(Z,$)}async#P(Z,$){let J,X=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,B)=>{try{let Q=$?void 0:await this.#Z.cachedInsulaQuota(B);if(Q!==void 0){let W=C5(u9(Q,this.routes().find((H)=>H.id===Z)?.quota),Q.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,W,B),new Response(null,{status:200})}let Y=await E1({accessToken:G,fetchImpl:X,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:UZ});return await this.recordSnapshot(Z,Y,!0,B),J=void 0,new Response(null,{status:200})}catch(Q){J=TZ(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((G)=>{J=TZ(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading(Z){let $=this.#Q.get(Z);if($)return $;let J=this.pollQuota(Z,!1).catch((X)=>{UZ.warn("vault quota poll failed",{routeId:Z,error:TZ(X)})}).finally(()=>{this.#Q.delete(Z)});return this.#Q.set(Z,J),J}async pollStale(Z){let $=(this.#$.now??Date.now)(),J=[];for(let X of this.routes()){let z=R8(X.quota);if(z!==void 0&&$-z<Z)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder(Z){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder(Z)}async decline(Z){await this.#Z.decline(Z),UZ.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),UZ.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await L5(this.paths,this.name)}catch(J){this.#X("vault enrollment state unreadable",J),Z={state:"blocked",proposedName:this.name,code:J instanceof Y6?J.kind:"unreadable-state"}}let $=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:$!==void 0,accounts:$?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let Z=await this.#T().catch(($)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${TZ($)}. Is the vault running?`)});try{let $=new q6({client:Z,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),J=await $.status();if(J.state==="denied"||J.state==="blocked")await $.resetTerminal();let X=await $.reconcile();if(UZ.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{Z.close()}}waitForApproval(Z={}){return this.#Y??=(async()=>{let $=Z.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=Z.pollIntervalMs??2000,X=Date.now()+(Z.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if(Z.onPending?.(z),Date.now()>=X)return z;await $(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){await W6(this.paths.tokenPath,{force:!0}),await W6(this.paths.statePath,{force:!0}),await this.#$.afterDisconnect?.(),await this.authority(),this.#J=void 0,UZ.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())F6({mode:"custody",auth:Z,provider:"openai"})}close(){this.#F=!0,this.#H.resolve(),this.#Z.close()}}function R8(Z){if(!Z)return;let $=CZ(Z).limits.map((J)=>J.checkedAt);return $.length>0?Math.max(...$):void 0}function A5(Z,$){if($.state!=="pending")return[];if(!$.requestId)return[`The vault did not take the enrollment request yet${$.retryCode?` (${$.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${$.requestId} for ${Z} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${$.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${Z} --selector-kind category --selector ${P6.category} --operation read`]}function T6(Z,$,J){let X=`${O8[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 c9(Z,$){if(($.state==="blocked"||$.state==="unavailable")&&$.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($.state){case"approved":{let J=Z.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${Z.name}. It serves ${J} OpenAI account${J===1?"":"s"} to this host${J===0?`. ${P5(Z.name,Z.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 (${$.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...A5(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
1
|
+
import{$c as A7,Ad as F6,Bd as K6,Cd as N6,Dd as D6,Ed as x1,Fc as fZ,Gc as m7,Hc as i5,Hd as E1,Ic as t4,Jd as D0,Kc as y5,Lc as PZ,Ld as M0,Mc as V7,Md as f1,Nc as CZ,Oc as e4,Od as g1,Pc as Z6,Pd as RZ,Qc as $6,Rd as r5,Sc as f7,Tc as x7,Uc as y4,Ud as P0,Vc as k4,Wc as f4,Yc as w7,Zc as w1,_c as u7,_d as v1,ad as S7,de as I7,ed as T5,fd as _5,fe as R7,ge as E7,ie as C0,je as T0,le as C5,oe as U7,rd as Y6,ud as H6,vd as V6,wd as U6,xd as L5,yd as j6,zd as q6}from"./index-zne9tzy9.js";import{Ae as z4,Be as AZ,Ce as G4,De as L9,Ee as QZ,Ge as t1,He as B4}from"./index-n12zjwh9.js";import{Re as a7}from"./index-25p8t63g.js";import{Ye as p4,af as s,bf as v7,df as P$,ef as u1,ff as C$,gf as TZ}from"./index-zf649dj2.js";import{jf as G5,pf as X4}from"./index-95s2mw9w.js";class R extends Error{operation;rowId;phase;retryable;kind;committed;constructor(Z){super(Z.message??`${Z.operation} failed (${Z.kind}, ${Z.phase})`,Z.cause===void 0?void 0:{cause:Z.cause});this.name="PoolOperationError",this.operation=Z.operation,this.rowId=Z.rowId,this.phase=Z.phase,this.retryable=Z.retryable,this.kind=Z.kind,this.committed=Z.committed}}class o1 extends Error{operation;constructor(Z){super(`${Z} was called from inside a store hook; hand it to the caller's continuation instead`);this.name="PoolReentryError",this.operation=Z}}var rZ="identity-contradicted: ",j9="duplicate-identity";function kZ(Z,$,J){let X=Z.rosterRow($);if(!X)return;X.enabled=!1;let z=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...z,disabledReason:G?z.disabledReason:J})}function N1(Z,$){let J=Z.rosterRow($);if(!J)return;J.enabled=!0;let X=Z.entry($);if(X&&"disabledReason"in X){let z={...X};delete z.disabledReason,Z.setEntry($,z)}}function oZ(Z,$){let J=Z.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===$),X=[];for(let z of J.slice(1))kZ(Z,z.id,"duplicate-identity"),X.push(z.id);return X}function mZ(Z,$,J){let X=Z.rosterRow($);if(!X)return[];return X.accountId=J,oZ(Z,J)}import{setTimeout as S3}from"node:timers/promises";import{AsyncLocalStorage as H3}from"node:async_hooks";var l$=new H3;function p(Z){if(l$.getStore()!==void 0)throw new o1(Z)}function KZ(Z,$){return l$.run(Z,async()=>await $())}async function d$(Z,$,J,X,z){if(!$)return;try{await KZ(Z,()=>$(J,X))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:J,error:G instanceof Error?G.message:String(G)})}}var q9=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function V3(Z,$,J){let X=(B)=>{try{let Q=J.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},z={...$,...U3(Z)},G=performance.now();for(;;){let B=await QZ({name:Z.name,path:Z.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>X("contended"),...J.onRenewalTimer?{onRenewalTimer:(W)=>J.onRenewalTimer?.({name:Z.name,path:Z.path},W)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...J.onLockStep?{onStep:(W)=>J.onLockStep?.({name:Z.name,path:Z.path},W)}:{}});if(B){X("acquired");let W={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),X("released")}};try{await W.assertOwned()}catch(H){throw await W.release(),H}return W}let Q=z.timeoutMs-(performance.now()-G);if(Q<=0)throw new t1({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let Y=Math.floor(Math.random()*(z.retryMs+1));await new Promise((W)=>setTimeout(W,Math.min(z.retryMs+Y,Q)))}}function U3(Z){let $={};if(Z.ttlMs!==void 0)$.ttlMs=Z.ttlMs;if(Z.timeoutMs!==void 0)$.timeoutMs=Z.timeoutMs;if(Z.retryMs!==void 0)$.retryMs=Z.retryMs;if(Z.renew!==void 0)$.renew=Z.renew;if(Z.renewIntervalMs!==void 0)$.renewIntervalMs=Z.renewIntervalMs;return $}class NZ{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await V3(Z,this.defaults,this.env);return this.held.push($),await this.assertAll(),$}async assertAll(){for(let Z of this.held)await Z.assertOwned()}async releaseTo(Z){while(this.held.length>Z)await this.held.pop()?.release().catch(()=>{})}async releaseAll(){await this.releaseTo(0)}}function wZ(Z,$,J){if(J!==void 0)throw new R({operation:Z,rowId:$,kind:"row-staged",phase:Z==="pull"?"pull":"before-first-write",retryable:!1,message:`row ${$} is reserved for roster publication`})}import{createHash as D1}from"node:crypto";var y="commonAuthPool",vZ=1,WZ="rows",e1="retiredEpochs",M1=1,F9=300000,E=y;function j3(Z){let $=JSON.parse(JSON.stringify(Z)),J=(X)=>{if(Array.isArray(X))return`[${X.map(J).join(",")}]`;if(C(X))return`{${Object.keys(X).sort().map((z)=>`${JSON.stringify(z)}:${J(X[z])}`).join(",")}}`;return JSON.stringify(X)};return J($)}function uZ(Z){return D1("sha256").update(j3(Z)).digest("hex")}function c$(Z){if(!C(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function q3(Z){if(!C(Z)||typeof Z.reservation!=="string"||!Z.reservation||typeof Z.disabledReason!=="string")return;if(Object.keys(Z).some(($)=>!["reservation","label","disabledReason","providerState"].includes($)))return;if("label"in Z&&typeof Z.label!=="string")return;if("providerState"in Z&&(typeof Z.providerState!=="string"||!/^[a-f0-9]{64}$/.test(Z.providerState)))return;return Z}var d="commonAuthProviderState";function C(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var F3=new Set(["__proto__","constructor","prototype"]);function tZ(Z){if(typeof Z!=="string"||Z.length===0)return"id must be non-empty";if(Z.trim()!==Z)return"id must not carry surrounding whitespace";if(F3.has(Z))return"id is a reserved object key";return}function K9(Z){let $=typeof Z==="string"?Z.trim():"";if(!$)return!1;try{let J=new URL($);return(J.protocol==="http:"||J.protocol==="https:")&&!J.username&&!J.password}catch{return!1}}function s$(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function YZ(Z){return D1("sha256").update(s$(Z)).digest("hex")}function DZ(Z){return D1("sha256").update(`credential-stamp\x00${s$(Z)}`).digest("hex")}function OZ(Z){let $=Z.type==="oauth"?["oauth",typeof Z.access==="string"?Z.access:null,Z.refresh,typeof Z.expires==="number"&&Number.isFinite(Z.expires)?Z.expires:null]:["api",Z.apiKey,Z.baseURL.trim(),Z.authHeader??"authorization-bearer"];return D1("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function N9(Z,$,J,X={}){return{credentialEpoch:$,digest:DZ(Z),dispatch:OZ(Z),binding:{...J},...X.replace?{replace:!0}:{},...X.providerState!==void 0?{providerState:X.providerState}:{}}}function eZ(Z,$){let J=Z?.credentialBound?Z.credentialBound($):$;return D1("sha256").update(`provider-state\x00${JSON.stringify(J??null)}`).digest("hex")}function P1(Z,$,J,X){if(!$||J===void 0)return;if(!C(Z)||!Object.hasOwn(Z,d))return;let z=a(Z[E]);if(!z||z.providerState===void 0||z.digest!==DZ($)||z.credentialEpoch!==J||z.binding?.identity!==X)return;return z.providerState}function w(Z){return Number.isSafeInteger(Z)&&Z>=1}function a(Z){if(!C(Z))return;let $=Z.credentialEpoch;if(!w($))return;if(typeof Z.digest!=="string")return;if("dispatch"in Z&&typeof Z.dispatch!=="string")return;if("replace"in Z&&Z.replace!==!0)return;if("providerState"in Z&&typeof Z.providerState!=="string")return;let J="staged"in Z?q3(Z.staged):void 0;if("staged"in Z&&!J)return;let X={...J?{staged:J}:{},...typeof Z.dispatch==="string"?{dispatch:Z.dispatch}:{},...Z.replace===!0?{replace:!0}:{},...typeof Z.providerState==="string"?{providerState:Z.providerState}:{}};if(!("binding"in Z))return"dispatch"in Z||"replace"in Z||"providerState"in Z||"staged"in Z?void 0:{credentialEpoch:$,digest:Z.digest};let z=Z.binding;if(!C(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!K9(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.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 K3(Z,$,J){if(Z.identity!==J)return!1;if(Z.baseURL!==void 0&&($.type!=="api"||$.baseURL!==Z.baseURL))return!1;if(Z.authHeader!==void 0&&($.type!=="api"||$.authHeader!==Z.authHeader))return!1;return!0}function N3(Z,$,J,X){if(!Z)return"none";if(!C(X)||!Object.hasOwn(X,E))return"missing";let z=a(X[E]);if(!z)return"malformed";if(z.digest!==DZ(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!K3(z.binding,Z,J))return"mismatched";if(z.dispatch!==OZ(Z))return"mismatched";return"bound"}function D9(Z){if(!Z.exists)return{status:"ready",exists:!1,config:{}};if("parseError"in Z)return{status:"error",reason:"config file is not valid JSON"};let $=Z.value;if(!C($))return{status:"error",reason:"config root is not an object"};if("accounts"in $&&!Array.isArray($.accounts))return{status:"error",reason:"config accounts is not an array"};if(!(y in $))return Array.isArray($.accounts)?{status:"pending-migration",config:$}:{status:"ready",exists:!0,config:$};let J=$[y];if(!C(J))return{status:"error",reason:`${y} is not an object`};let X=J.schemaVersion;if(typeof X!=="number"||!Number.isInteger(X)||X<1)return{status:"error",reason:`${y}.schemaVersion is invalid`};if(X>vZ)return{status:"error",reason:`${y}.schemaVersion ${X} is newer than ${vZ}`};if(WZ in J&&!C(J[WZ]))return{status:"error",reason:`${y}.${WZ} is not an object`};return{status:"ready",exists:!0,config:$}}function a$(Z){if(!Z.exists)return{status:"ready",exists:!1,state:{}};if("parseError"in Z)return{status:"error",reason:"state file is not valid JSON"};if(!C(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!C(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function Z1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function n$(Z){let $=Z[y];if(!C($))return{};let J=$[WZ];return C(J)?J:{}}function D3(Z){return C(Z.accounts)?Z.accounts:{}}function M3(Z){if(!C(Z))return"not an object";let $=tZ(Z.id);if($)return $;if(Z.type==="api")return K9(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function P3(Z,$){if(!C(Z))return;let J=Z.credentialEpoch;if(!w(J))return;if("needsFirstReading"in Z&&typeof Z.needsFirstReading!=="boolean")return;if("disabledReason"in Z&&typeof Z.disabledReason!=="string")return;let X="quota"in Z&&$.decode?$.decode(Z.quota):Z.quota;if("quota"in Z&&!$.validate(X))return;if("staged"in Z&&!c$(Z.staged))return;return{credentialEpoch:J,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:X}:{}}}function C3(Z,$){if(!C($))return;if(Z.type==="api"){let X=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!X)return;return{type:"api",apiKey:X,baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(Z.corrupt===!0)return;let J=$.refresh;if(typeof J!=="string"||!J.trim())return;return{type:"oauth",refresh:J,...typeof $.access==="string"?{access:$.access}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.lastRefreshedAt==="number"?{lastRefreshedAt:$.lastRefreshedAt}:{}}}function Z5(Z,$){return Z1(Z).find((J)=>C(J)&&J.id===$)}function i$(Z){if(!C(Z[y]))Z[y]={};return Z[y]}function M9(Z){let $=i$(Z);if(!C($[WZ]))$[WZ]={};return $[WZ]}function MZ(Z,$){let J=n$(Z),X=Object.hasOwn(J,$)?J[$]:void 0;return C(X)?X:void 0}function $5(Z,$,J){Object.defineProperty(M9(Z),$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function r$(Z,$){let J=Z[y];if(!C(J))return;let X=J[e1];if(!C(X)||!Object.hasOwn(X,$))return;let z=X[$];return w(z)?z:void 0}function o$(Z,$){let J=MZ(Z,$)?.credentialEpoch;return w(J)?J:void 0}function J5(Z,$){return Math.max(r$(Z,$)??0,o$(Z,$)??0)+1}function t$(Z,$){let J=[...$];if(J.length===0)return;let X=i$(Z),z=C(X[e1])?X[e1]:{},G={},B=(Q,Y)=>Object.defineProperty(G,Q,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[Q,Y]of Object.entries(z))if(w(Y))B(Q,Y);for(let Q of J)B(Q,Math.max(r$(Z,Q)??0,o$(Z,Q)??1));X[e1]=G}function gZ(Z,$,J,X){let z=n$(Z),G=D3($),B=new Set,Q=[];for(let Y of Z1(Z)){let W=M3(Y),H=C(Y)&&typeof Y.id==="string"?Y.id:void 0,V=H===void 0?void 0:z[H],j=C(V)&&Object.hasOwn(V,"staged"),F=j?c$(V.staged):void 0;if(W||!C(Y)||H===void 0||B.has(H)){if(H!==void 0&&!B.has(H))B.add(H);if(H!==void 0)Q.push({id:H,type:C(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...F?{staged:F}:{}});continue}B.add(H);let U=Y.type==="api"?"api":"oauth",q=Object.hasOwn(z,H),K=q?P3(z[H],J):void 0,N=C3(Y,G[H]),M=Y.enabled!==!1,O=K?K.credentialEpoch:q?void 0:1,_=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,D={id:H,type:U,enabled:M,needsFirstReading:K?K.needsFirstReading:U==="oauth",hasEntry:q,candidate:!1,...typeof Y.label==="string"?{label:Y.label}:{},...typeof Y.addedAt==="number"?{addedAt:Y.addedAt}:{},..._!==void 0?{identity:_}:{},...N?{credential:N,fingerprint:YZ(N)}:{},...K?{credentialEpoch:K.credentialEpoch}:{},...F?{staged:F}:{},...K?.disabledReason!==void 0?{disabledReason:K.disabledReason}:{},...K&&"quota"in K?{quota:K.quota}:{},...T3(G[H],N,O,_,X),stamp:N3(N,O,_,G[H])};if(q&&!K)D.invalid="entry";else D.candidate=M&&N!==void 0&&!j;Q.push(D)}return Q}function T3(Z,$,J,X,z){if(!C(Z)||!Object.hasOwn(Z,d))return{};let G=P1(Z,$,J,X);if(G===void 0)return{providerStateDropped:"uncovered"};let B=Z[d];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(eZ(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function v(Z){return Z.identity??Z.id}function C1(Z,$){if(Z===void 0||Z>$+F9)return $;return Math.max($,Z+1)}function P9(Z,$){return C1(Z,$)>$+F9}function $1(Z){let{id:$,credential:J,identity:X,label:z,addedAt:G}=Z;return{id:$,...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 e$(Z,$){if(Z.type==="api")return{apiKey:Z.apiKey};return{...Z.access!==void 0?{access:Z.access}:{},refresh:Z.refresh,...Z.expires!==void 0?{expires:Z.expires}:{},...$!==void 0?{lastRefreshedAt:$}:{}}}function Z4(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function $4(Z,$={}){if(!C(Z))return"credential must be an object";if(Z.type==="oauth"){if(typeof Z.refresh!=="string"||!Z.refresh.trim())return"oauth credential needs a refresh token";return}if(Z.type==="api"){if(typeof Z.apiKey!=="string"||!Z.apiKey.trim())return"api credential needs an api key";if(Z.apiKey.trim()!==Z.apiKey)return"api key must not carry surrounding whitespace";if(!($.baseURLOptional&&Z.baseURL===void 0)&&!K9(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var X5="transition",J4="transitionMark";function _3(Z){if(!C(Z))return;let $=Z[X5];if(!C($))return;if(typeof $.mark!=="string"||$.mark.length===0)return;if($.enabled===!0)return{mark:$.mark,enabled:!0};if($.enabled===!1&&typeof $.reason==="string")return{mark:$.mark,enabled:!1,reason:$.reason};return}function T1(Z,$,J){if(J.enabled)N1(Z,$);else kZ(Z,$,J.reason??"");if(!Z.rosterRow($))return;let X=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...X,[J4]:J.mark}),!J.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)oZ(Z,z.identity)}function L3(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function O3(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function A3(Z,$,J,X={}){let z=C($.accounts)?$.accounts:{},G=new Map;for(let B of gZ(Z,$,J)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!C(Q))continue;let Y=a(Q[E]);if(!Y?.binding)continue;if(Y.digest!==DZ(B.credential))continue;let W=B.credentialEpoch??1;if(Y.credentialEpoch>W){if(!O3(Y))continue;if(X.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==OZ(L3(B.credential,Y.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===W&&Y.dispatch!==void 0&&Y.dispatch===OZ(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===W&&Y.binding.identity===B.identity){if(X.requireCredentialStamps&&Y.dispatch!==OZ(B.credential))continue;let H=_3(Q[E]);if(H&&MZ(Z,B.id)?.[J4]!==H.mark)G.set(B.id,{kind:"transition",transition:H})}}return G}function C9(Z,$,J,X){let G={...Z.entry($)??{},credentialEpoch:J,needsFirstReading:!0};if(delete G.quota,X.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(rZ))delete G.disabledReason;Z.setEntry($,G);let B=Z.rosterRow($);if(!B)return;if(X.identity!==void 0)B.accountId=X.identity;else delete B.accountId;if(X.baseURL!==void 0)B.baseURL=X.baseURL;if(X.authHeader!==void 0)B.authHeader=X.authHeader}function T9(Z,$,J,X={}){let z=A3(Z,$,J,X);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),B={rows:()=>gZ(G,$,J),rosterRow:(Q)=>Z5(G,Q),entry:(Q)=>MZ(G,Q),setEntry:(Q,Y)=>$5(G,Q,Y)};for(let[Q,Y]of z)if(Y.kind==="replace")C9(B,Q,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[Q,Y]of z)if(Y.kind==="identity")mZ(B,Q,Y.identity);else if(Y.kind==="transition")T1(B,Q,Y.transition);else if(Y.stamp.binding.identity!==void 0)oZ(B,Y.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function _9(Z,$,J,X={}){let{config:z,torn:G}=T9(Z,$,J,X),B=gZ(z,$,J,X.providerState);for(let Q of B){if(G.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(X.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function z5(Z){try{return await X4(Z,G5)}catch($){if($.code==="ENOENT")return;throw $}}function O9(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function Q4(Z){return D9(O9(await z5(Z)))}async function n(Z){for(let $=0;$<3;$++){let J=await z5(Z.configPath),X=await z5(Z.statePath),z=await z5(Z.configPath);if(J!==z){if($<2)await S3(2+Math.floor(Math.random()*4));continue}let G=D9(O9(J));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=a$(O9(X));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:_9(G.config,B.state,Z.codec,{requireCredentialStamps:Z.requireCredentialStamps===!0,...Z.providerState?{providerState:Z.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function HZ(Z,$,J,X="before-first-write"){if(Z.status==="error"&&Z.kind==="snapshot-contended")return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,kind:"snapshot-contended",retryable:!0,message:Z.reason});return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:X,retryable:!1,kind:Z.status==="pending-migration"?"pending-migration":"load-error",message:Z.status==="pending-migration"?"the config holds a legacy roster that has not been migrated into the pool":`${Z.file} file cannot be loaded: ${Z.reason}`})}class W4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,J,X,z){this.ctx=Z,this.snapshot=$,this.locks=J,this.progress=X,this.info=z,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return _9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0,...this.ctx.providerState?{providerState:this.ctx.providerState}:{}})}row(Z){return this.rows().find(($)=>$.id===Z)}reservation(Z){if(this.rosterRow(Z)){let J=this.entry(Z);return J&&Object.hasOwn(J,"staged")?J.staged:void 0}let $=this.stateAccount(Z)?.[E];return C($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){wZ(this.info.operation,Z,this.reservation(Z))}roster(){if(!Array.isArray(this.config.accounts))this.config.accounts=[];return this.config.accounts}rosterRow(Z){return this.roster(),Z5(this.config,Z)}dropRosterRows(Z){let $=this.roster(),J=$.filter((X)=>!(C(X)&&X.id===Z));return this.config.accounts=J,$.length-J.length}entries(){return M9(this.config)}entry(Z){return this.entries(),MZ(this.config,Z)}setEntry(Z,$){$5(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=T9(this.config,this.state,this.ctx.codec,{requireCredentialStamps:this.ctx.requireCredentialStamps===!0});if($.length===0)return;this.config=Z,await this.commitConfig({counted:!1})}stateAccount(Z){let $=C(this.state.accounts)?this.state.accounts:{},J=Object.hasOwn($,Z)?$[Z]:void 0;return C(J)?J:void 0}dropStateAccount(Z){if(C(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!C(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,Z,{value:$,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(Z={}){let $=this.roster(),J=new Set;for(let Y of $)if(C(Y)&&typeof Y.id==="string")J.add(Y.id);let X=new Set;for(let Y of Z1(this.snapshot.config))if(C(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);t$(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 B=this.config[y],Q={...this.config,version:M1,accounts:$,[y]:{...B,schemaVersion:vZ,[WZ]:G}};await this.write(this.ctx.configPath,Q,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let Y of X)this.ctx.removedIds.add(Y);this.config=Q}),this.config=Q}async commitState(Z,$={}){let J={...this.state,version:M1,accounts:C(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,J,"state",!0,$.durable??!1),this.state=J,Z)this.progress.committed=Z}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await L9(this.ctx.statePath)}catch(Z){throw new R({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:Z})}}markPublicationDecision(){this.progress.publicationDecided=!0}async syncConfig(){await this.assertAll(),await L9(this.ctx.configPath)}async write(Z,$,J,X=!0,z=!1,G){await G4(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 Y4(Z,$){let J=new NZ(Z.lockDefaults,Z.lockEnv),X={writes:0};try{for(let Q of Z.storeLocks)await J.acquire(Q);let z=await n(Z);if(z.status==="error")throw HZ(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Q,Y]of Object.entries(z.config))if(!$.includes(Q))G[Q]=Y;G.version=M1,G[y]={schemaVersion:vZ,[WZ]:{}};let B={operation:"initialize",rowId:void 0};return await AZ(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await J.assertAll()}}),X.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(z){throw hZ(z,"initialize",void 0,X)}finally{await J.releaseAll()}}async function f(Z,$,J,X,z,G={}){let B=$.held.length;try{for(let W of Z.storeLocks)await $.acquire(W);let Q=await n(Z);if(Q.status!=="ready")throw HZ(Q,X.operation,X.rowId,J.writes>0?"after-first-write":"before-first-write");let Y=new W4(Z,Q,$,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 $.releaseTo(B)}}function hZ(Z,$,J,X){let z=$==="pull"?"pull":X.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?X.committed:void 0;if($==="publishRoster"&&X.publicationDecided)return new R({operation:$,...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:Z});if($==="publishRoster"&&Z instanceof z4)return new R({operation:$,...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:Z});if(Z instanceof R){if(Z.phase===z&&Z.rowId===J&&Z.operation===$&&Z.committed===G)return Z;return new R({operation:$,...J!==void 0?{rowId:J}:{},phase:Z.kind==="after-persist-hook"?Z.phase:z,retryable:Z.retryable,kind:Z.kind,...Z.committed??G?{committed:Z.committed??G}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let B={operation:$,...J!==void 0?{rowId:J}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof B4)return new R({...B,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${$} lost a lease after its first write; the intermediate stays on disk`:`${$} lost a lease before writing; nothing was written`});if(Z instanceof t1)return new R({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new R({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function l(Z,$,J,X,z){let G=new NZ(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await z(G,B)}catch(Q){let Y=hZ(Q,$,J,B);if(Y.kind!=="after-persist-hook")await d$($,X,J,Y,Z.logger);throw Y}finally{await G.releaseAll()}}function r(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(v($))}`,path:Z.ctx.statePath}}async function VZ(Z,$,J){let X=await n(Z.ctx);if(X.status!=="ready")throw HZ(X,$,J);let z=X.rows.find((W)=>W.id===J),G=MZ(X.config,J),B=X.state.accounts,Q=C(B)&&Object.hasOwn(B,J)?B[J]:void 0,Y=C(Q)?Q[E]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))wZ($,J,G.staged);if(!z&&C(Y)&&Object.hasOwn(Y,"staged"))wZ($,J,Y.staged);if(!z)throw e($,J);return{result:X,row:z}}function e(Z,$){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:!1,kind:"unknown-row",message:`no row ${$} in the pool`})}function c(Z,$){if($.unbound)throw P(Z,$.id,"unbound-credential",`row ${$.id}'s credential is not the one this store stamped for it (stamp ${$.stamp}); replace it with fresh material`)}function P(Z,$,J,X,z=!1){return new R({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:z,kind:J,message:X})}function A9(Z,$){if(!w($?.credentialEpoch))throw P("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function _1(Z,$,J){if(!J)throw e("pull",Z);if(J.invalid)throw P("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!J.credential)throw P("pull",Z,"no-credential",`row ${Z} holds no credential`);if(c("pull",J),J.torn||!J.hasEntry||J.credentialEpoch!==$.credentialEpoch||J.identity!==$.identity)throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${Z} was issued for a credential the row no longer holds`})}function L1(Z,$,J,X){let z=Z.codec.merge(J,X);if(!Z.codec.validate(z))throw P("pull",$,"invalid-quota","the quota codec rejected the merged map");return z}async function B5(Z,$,J,X){let{ctx:z}=Z,G=new NZ(z.lockDefaults,z.lockEnv),B={writes:0};try{A9($,J),await f(z,G,B,{operation:"pull",rowId:$},async(Q)=>{Q.assertNotStaged($);let Y=Q.row($);_1($,J,Y);let W=Q.entry($);if(!W)throw e("pull",$);let H=L1(z,$,W.quota,X);Q.setEntry($,{...W,quota:H,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw hZ(Q,"pull",$,B)}finally{await G.releaseAll()}}function SZ(Z,$,J,X,z="the provider state"){if(!Z)throw P($,J,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(X);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw P($,J,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw P($,J,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function O1(Z,$,J,X,z){if(X===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:SZ(Z,$,J,Z.merge(structuredClone(X),structuredClone(z)),"the merged provider state")}}function H4(Z,$,J,X,z){let G=Z?.onReplace,B=G?G($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:J,...$.identity!==void 0?{previousIdentity:$.identity}:{},...X!==void 0?{identity:X}:{},...z!==void 0?{incoming:structuredClone(z)}:{}}):z;if(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:SZ(Z,"replace",$.id,B,"the provider state onReplace returned")}}function V4(Z,$,J,X,z){if($.kind==="set")return eZ(Z,$.value);if($.kind==="clear")return;return P1(J,X?.credential,z,X?.identity)}async function U4(Z,$,J,X,z={}){p("updateProviderState");let{ctx:G}=Z,B="updateProviderState";return l(G,B,$,z.onFailure,async(Q,Y)=>{let W=G.providerState;if(!W)throw P(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof X!=="function")throw P(B,$,"invalid-input","a mutator is required");let H=C(J)?J.credentialEpoch:void 0;if(!w(H))throw P(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await VZ(Z,B,$);await Q.acquire(r(Z,V));for(let j of z.extraLocks??[])await Q.acquire(j);return f(G,Q,Y,{operation:B,rowId:$},async(j)=>{let F=j.row($);if(!F)throw e(B,$);if(v(F)!==v(V))throw P(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(F.invalid)throw P(B,$,"invalid-row",`row ${$} failed validation`);if(!F.credential)throw P(B,$,"no-credential",`row ${$} holds no credential`);if(c(B,F),(F.credentialEpoch??1)!==H||F.identity!==J.identity)throw P(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await S9(j,W,B,F,X);if(q.kind!=="changed")return{id:$,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount($,q.account),await j.commitState(),q.value===void 0?{id:$,outcome:"cleared"}:{id:$,outcome:"updated",providerState:q.value}})})}var j4=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function S9(Z,$,J,X,z,G=!1){let{id:B,credential:Q}=X;if(!Q)throw P(J,B,"no-credential",`row ${B} holds no credential`);let Y=X.credentialEpoch??1,W=Z.stateAccount(B),H=W?.[E],V=a(H);if(!C(H)||!V?.binding||V.digest!==DZ(Q)||V.credentialEpoch!==Y||V.binding.identity!==X.identity)throw P(J,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${X.stamp}); rotate or replace it first`);let j=X.providerState===void 0?void 0:structuredClone(X.providerState),F=await KZ(J,()=>z(j,X));if(G&&F===j4)return{kind:"declined"};let U=F===void 0?void 0:SZ($,J,B,F,"the provider state the mutator returned"),q=W!==void 0&&Object.hasOwn(W,d);if(U===void 0?!q:X.providerState!==void 0&&JSON.stringify(X.providerState)===JSON.stringify(U))return{kind:"unchanged",...U!==void 0?{value:U}:{}};let K={...W};if(U===void 0){delete K[d];let N={...H};delete N.providerState,K[E]=N}else{K[d]=U;let N=eZ($,U);if(V.providerState!==N)K[E]={...H,providerState:N}}return{kind:"changed",...U!==void 0?{value:U}:{},account:K}}import{randomUUID as q4}from"node:crypto";async function H5(Z,$,J){if(!J)return;let X=Z.rows().map((G)=>{let{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}=G;return{id:B,type:Q,label:Y,enabled:W,disabledReason:H,identity:V,credentialEpoch:j,stamp:F,staged:U,torn:q,invalid:K}}),z=await KZ(Z.info.operation,()=>J({id:$,row:X.find((G)=>G.id===$),rows:X,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw P(Z.info.operation,$,"row-protected",z)}var I3=["access","refresh","expires","lastRefreshedAt","apiKey"];function R3(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function E3(Z,$,J){if(J.type!=="api")return J;let X=Z.rosterRow($);if(!C(X)){if(J.baseURL===void 0)throw P(Z.info.operation,$,"invalid-input","api credential needs a valid baseURL");return{...J,baseURL:J.baseURL}}let z=Z.row($)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:R3(X),B=J.baseURL?.trim()??G.baseURL,Q=J.authHeader??G.authHeader;if(B!==G.baseURL||Q!==G.authHeader)throw P(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...J,baseURL:B,authHeader:Q}}function F4(Z,$,J,X){let z=Z.rosterRow($),G=Z.row($),B=X??(G?G.identity:C(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...J.type==="api"?{baseURL:J.baseURL,authHeader:J.authHeader??"authorization-bearer"}:{}}}function Q5(Z,$,J,X,z={}){let G=E3($,J,X),B=$.stateAccount(J),Q=z.providerState??{kind:"keep"},Y=$.row(J)?.credentialEpoch??$.entry(J)?.credentialEpoch,W=typeof Y==="number"?Y:1,H=V4(Z.ctx.providerState,Q,B,B&&Object.hasOwn(B,d)?$.row(J):void 0,W),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??C1(V,Z.ctx.now()):void 0,F={...B??{}};for(let K of I3)delete F[K];if(z.clearErrors)delete F.lastRefreshError,delete F.lastQuotaRefreshError,delete F.quota;if(Q.kind==="clear")delete F[d];else if(Q.kind==="set")F[d]=Q.value;let U=Z4(G,j),q={...F,...e$(G,j),[E]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[X5]:z.transition}:{},...N9(U,W,z.binding??F4($,J,U,z.identity),{replace:z.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:U,account:q}}async function W5(Z,$,J){return Z.setStateAccount($,J.account),await Z.commitState(J.stored),J.stored}async function V5(Z,$,J,X,z={}){return W5($,J,Q5(Z,$,J,X,z))}async function b3(Z,$,J){if(!$.credential||$.stamp!=="bound")return;let X=Z.stateAccount($.id),z=P1(X,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...X??{},[E]:N9($.credential,$.credentialEpoch??1,F4(Z,$.id,$.credential,J),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function R9(Z,$,J){let X=Z==="add"?tZ($):void 0;if(X)throw P(Z,$,"invalid-input",X);let z=$4(J,{baseURLOptional:Z==="rotate"});if(z)throw P(Z,$,"invalid-input",z)}function U5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if(X&&X.type!==J.type)throw P(Z,$,"type-mismatch",`row ${$} holds a ${J.type} credential`);return J}function X1(Z,$,J){if(J!==void 0&&!w(C(J)?J.credentialEpoch:void 0))throw P(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function j5(Z,$,J,X){if(!J)throw e(Z,$);if(J.invalid)throw P(Z,$,"invalid-row",`row ${$} failed validation`);if((J.credentialEpoch??1)!==X.credentialEpoch||J.identity!==X.identity)throw P(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function Y5(Z,$){return P(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function A1(Z,$){return P(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function y3(Z,$,J,X){let{id:z,credential:G,identity:B}=J;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!J1($.state,z))return;let Q=()=>{throw P("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=$.stateAccount(z),W=a(Y?.[E]);if(!W?.binding||W.dispatch===void 0||W.replace)return Q();if(G.type==="api"&&(W.binding.baseURL===void 0||W.binding.authHeader===void 0))return Q();let H=G.type==="api"?{...G,baseURL:W.binding.baseURL,authHeader:W.binding.authHeader}:G,[V]=gZ({accounts:[$1({id:z,credential:H,identity:W.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:J5($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(DZ(G)!==W.digest)return Q();if(G.type==="api"){if(G.baseURL.trim()!==W.binding.baseURL)return Q();if((G.authHeader??"authorization-bearer")!==W.binding.authHeader)return Q()}else if(OZ(G)!==W.dispatch)return Q();if(W.providerState!==void 0&&V.providerState===void 0)return Q();if(X!==void 0&&eZ(Z.ctx.providerState,X)!==W.providerState)return Q();return V}function k3(Z,$,J,X){let{id:z,credential:G,identity:B,label:Q}=J,Y=$.rosterRow(z),W=()=>{throw P("add",z,Y?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=$.stateAccount(z),V=a(H?.[E]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return W();if(Y&&(Y.type!==G.type||Y.label!==Q||Y.accountId!==B))return W();if(j.reservation!==J.stage?.reservation||j.label!==Q||j.disabledReason!==J.disabled?.reason||V.binding.identity!==B)return W();let F=X===void 0?void 0:uZ(X),U=H?.[d],q=U===void 0?void 0:uZ(U);if(j.providerState!==F||j.providerState!==q)return W();if(DZ(G)!==V.digest||OZ(G)!==V.dispatch)return W();let K=Y?$.config:{accounts:[{...$1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=gZ(K,$.state,Z.ctx.codec,Z.ctx.providerState).find((M)=>M.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==j.label||N.identity!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return W();if(Y)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(J5($.config,z)!==V.credentialEpoch)return W();return $.roster().push({...$1({id:z,credential:G,identity:B,label:Q,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function K4(Z,$,J={}){p("add");let{ctx:X}=Z,{id:z,credential:G,identity:B,label:Q}=$,Y=$.stage!==void 0||$.disabled!==void 0,W=await l(X,"add",z,J.onFailure,async(H,V)=>{R9("add",z,G);let j=J.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw P("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!C($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!C($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw P("add",z,"invalid-input","staging requires a reservation and a disabled reason");let F=$.providerState===void 0?void 0:SZ(X.providerState,"add",z,$.providerState);if(await H.acquire(r(Z,{id:z,identity:B})),G.type==="oauth")await H.acquire(J.providerLock??Z.providerLock);for(let U of J.extraLocks??[])await H.acquire(U);return f(X,H,V,{operation:"add",rowId:z},async(U)=>{await H5(U,z,J.protect);let q=C(U.state.accounts)?U.state.accounts:{},K=Object.entries(q).find(([b,g])=>{if(b===z||U.rosterRow(b)||!C(g))return!1;let K1=g[E];if(!C(K1)||!Object.hasOwn(K1,"staged"))return!1;return G.type==="oauth"?g.refresh===G.refresh:typeof g.apiKey==="string"&&g.apiKey.trim()===G.apiKey.trim()});if(K)throw P("add",K[0],"row-staged",`orphan ${K[0]} reserves this secret until its staged add is replayed or removed`);if(X.removedIds.has(z))throw P("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(U.rosterRow(z)||J1(U.state,z)))return k3(Z,U,$,F);if(j==="rotate"){U.assertNotStaged(z);let b=U.rows().find((g)=>g.fingerprint===YZ(G));if(b)U.assertNotStaged(b.id)}if(j==="refuse"){let b=U.rows().find((yZ)=>yZ.fingerprint===YZ(G)||yZ.id===z&&yZ.credential),g=C(U.state.accounts)?U.state.accounts:{},K1=Object.entries(g).find(([,yZ])=>{if(!C(yZ))return!1;if(G.type==="oauth")return yZ.refresh===G.refresh;return typeof yZ.apiKey==="string"&&yZ.apiKey.trim()===G.apiKey.trim()})?.[0],p$=b?.id??K1??z;if(b||K1!==void 0||J1(U.state,z))throw P("add",p$,"credential-exists",`row ${p$} already holds this secret or id`)}if(j==="stage-duplicate"&&(U.rosterRow(z)||J1(U.state,z)))throw P("add",z,"id-exists",`row ${z} already exists`);let N=y3(Z,U,$,F),M=U.rows(),O=YZ(G),_=j==="rotate"&&!N&&M.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(_){if(U.assertNotStaged(_.id),c("add",_),B!==void 0&&_.identity!==void 0&&B!==_.identity)throw Y5("add",_.id);let b=Q5(Z,U,_.id,G,{...F!==void 0?{providerState:O1(X.providerState,"add",_.id,_.providerState,F)}:{}});await U.completeTorn(),U.assertNotStaged(_.id);let g=await W5(U,_.id,b);return{id:_.id,outcome:"rotated",credential:g,credentialEpoch:_.credentialEpoch??1}}let D=M.find((b)=>b.id===z);if(D){if(D.invalid)throw P("add",z,"invalid-row",`row ${z} is invalid`);if(D.credential)throw P("add",z,"id-exists",`row ${z} already holds a credential`);if(c("add",D),D.type!==G.type)throw P("add",z,"type-mismatch",`row ${z} is a ${D.type} row`);if(B!==void 0&&D.identity!==void 0&&B!==D.identity)throw Y5("add",z);if(!D.hasEntry)U.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let b=Q5(Z,U,z,G,{clearErrors:!0,...F!==void 0?{providerState:{kind:"set",value:F}}:{}});await U.completeTorn();let g=await W5(U,z,b);if(!D.hasEntry)await U.commitConfig();return{id:z,outcome:"completed",credential:g,credentialEpoch:D.credentialEpoch??1}}let T=J5(U.config,z);if(!w(T))throw P("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??B;U.roster().push($1({id:z,credential:G,...A!==void 0?{identity:A}:{},...Q!==void 0?{label:Q}:{},addedAt:X.now()})),U.setEntry(z,{credentialEpoch:T,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let L="added";if($.disabled)kZ(U,z,$.disabled.reason),L="added-disabled";if(!$.disabled&&A!==void 0&&G.type==="oauth"){if(M.find((g)=>g.invalid===void 0&&g.type==="oauth"&&g.enabled&&g.identity===A))kZ(U,z,j9),L="added-disabled"}if(N?.credential)return await U.commitConfig(),{id:z,outcome:L,credential:N.credential,credentialEpoch:N.credentialEpoch??T};U.dropStateAccount(z);let I=Q5(Z,U,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...Q!==void 0?{label:Q}:{},...F!==void 0?{providerState:uZ(F)}:{}}}:{},...F!==void 0?{providerState:{kind:"set",value:F}}:{}});if(j==="rotate")await U.completeTorn();let x=await W5(U,z,I);return await U.commitConfig(),{id:z,outcome:L,credential:x,credentialEpoch:T}},{completeTorn:!1})});if(!Y&&G.type==="oauth"&&(W.outcome==="added"||W.outcome==="completed"))Z.firePull(W.id,"add");return W}async function N4(Z,$,J,X={},z={}){p("replace");let{ctx:G}=Z,B=await l(G,"replace",$,z.onFailure,async(Q,Y)=>{R9("replace",$,J),X1("replace",$,z.attribution);let W=X.providerState===void 0?void 0:SZ(G.providerState,"replace",$,X.providerState),{row:H}=await VZ(Z,"replace",$);if(await Q.acquire(r(Z,H)),J.type==="oauth")await Q.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return f(G,Q,Y,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)j5("replace",$,V.row($),z.attribution),await V.completeTorn();let j=U5("replace",$,V.row($),J);if(v(j)!==v(H))throw A1("replace",$);let F=V.entry($)?.credentialEpoch,U=(typeof F==="number"?F:1)+1;if(!w(U))throw P("replace",$,"invalid-row",`row ${$}'s credential epoch cannot advance past ${Number.MAX_SAFE_INTEGER}; remove the row and add the new credential as a new row`);let q=H4(G.providerState,j,U,X.identity,W),K={...X.identity!==void 0?{identity:X.identity}:{},...J.type==="api"?{baseURL:J.baseURL.trim(),authHeader:J.authHeader??"authorization-bearer"}:{}};if(C9(V,$,U,K),X.identity!==void 0)oZ(V,X.identity);let N=await V5(Z,V,$,J,{clearErrors:!0,binding:K,providerState:q});return await V.commitConfig(),{id:$,credential:N,credentialEpoch:U}},{completeTorn:z.attribution===void 0})});if(J.type==="oauth")Z.firePull($,"replace");return B}async function D4(Z,$,J,X={},z={}){p("rotate");let{ctx:G}=Z;return l(G,"rotate",$,z.onFailure,async(B,Q)=>{R9("rotate",$,J),X1("rotate",$,z.attribution);let Y=X.providerState===void 0?void 0:SZ(G.providerState,"rotate",$,X.providerState),{row:W}=await VZ(Z,"rotate",$);if(await B.acquire(r(Z,W)),X.identity!==void 0&&J.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let H of z.extraLocks??[])await B.acquire(H);return f(G,B,Q,{operation:"rotate",rowId:$},async(H)=>{if(z.attribution!==void 0)j5("rotate",$,H.row($),z.attribution),await H.completeTorn();let V=U5("rotate",$,H.row($),J);if(v(V)!==v(W))throw A1("rotate",$);if(c("rotate",V),X.identity!==void 0&&V.identity!==void 0&&X.identity!==V.identity)throw Y5("rotate",$);let j=X.identity!==void 0&&V.identity===void 0?X.identity:void 0,F=await V5(Z,H,$,J,{identity:j,...Y!==void 0?{providerState:O1(G.providerState,"rotate",$,V.providerState,Y)}:{}}),U=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),U=!0;if(X.identity!==void 0&&V.identity!==X.identity)mZ(H,$,X.identity),U=!0;if(U)await H.commitConfig();return{id:$,credential:F}},{completeTorn:z.attribution===void 0})})}async function M4(Z,$,J,X,z){p($);let{ctx:G}=Z,B=G.providerState,Q=z.attribution,Y=z.providerState;return l(G,$,J,z.onFailure,async(W,H)=>{if(X1($,J,Q),Y!==void 0){if(typeof Y!=="function")throw P($,J,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw P($,J,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw P($,J,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await VZ(Z,$,J);await W.acquire(r(Z,V));for(let j of z.extraLocks??[])await W.acquire(j);return f(G,W,H,{operation:$,rowId:J},async(j)=>{await H5(j,J,z.protect),j.assertNotStaged(J);let F=j.row(J),U=X.enabled?U5("enable",J,F):F;if(!U||!j.rosterRow(J))throw e($,J);if(v(U)!==v(V))throw A1($,J);if(Q!==void 0)j5($,J,U,Q);if(X.enabled&&U.disabledReason?.startsWith(rZ))throw P("enable",J,"identity-contradicted",`row ${J} needs an identity-validated credential replacement before it can be enabled`);let q=!X.enabled||!U.enabled||U.disabledReason!==void 0;if(X.enabled&&q&&U.type==="oauth"){let _=U.identity===void 0?void 0:j.rows().find((D)=>D.id!==J&&D.invalid===void 0&&D.type==="oauth"&&D.enabled&&D.identity===U.identity);if(_)throw P("enable",J,"duplicate-identity",`row ${_.id} is enabled with the same identity as row ${J}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:J};if(X.enabled)N1(j,J);else kZ(j,J,X.reason);return await j.commitConfig(),{id:J}}if(!U.credential)throw P($,J,"no-credential",`row ${J} holds no credential`);c($,U);let K=await S9(j,B,$,U,Y,!0);if(K.kind==="declined")return{id:J,declined:!0};await j.completeTorn();let N={id:J,providerStateOutcome:K.kind==="unchanged"?"unchanged":K.value===void 0?"cleared":"updated",...K.value!==void 0?{providerState:K.value}:{}};if(K.kind==="unchanged"){if(q){if(X.enabled)N1(j,J);else kZ(j,J,X.reason);await j.commitConfig()}return N}if(!q)return j.setStateAccount(J,K.account),await j.commitState(),N;let M=X.enabled?{mark:q4(),enabled:!0}:{mark:q4(),enabled:!1,reason:X.reason},O=K.account[E];return j.setStateAccount(J,{...K.account,[E]:{...O,[X5]:M}}),await j.commitState(),T1(j,J,M),await j.commitConfig(),N},{completeTorn:!1})})}function P4(Z,$,J,X={}){return M4(Z,"disable",$,{enabled:!1,reason:J},X)}function C4(Z,$,J={}){return M4(Z,"enable",$,{enabled:!0},J)}async function T4(Z,$,J={}){p("remove");let{ctx:X}=Z;return l(X,"remove",$,J.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw P("remove",$,"invalid-input","id must be non-empty");let B=J.attribution;if(X1("remove",$,B),J.staged!==void 0&&(!C(J.staged)||typeof J.staged.reservation!=="string"||!J.staged.reservation))throw P("remove",$,"invalid-input","a staged removal needs a reservation");let Q=await n(X);if(Q.status!=="ready")throw HZ(Q,"remove",$);let Y=Q.rows.find((H)=>H.id===$);if(!Y&&!J1(Q.state,$))throw e("remove",$);let W=v(Y??{id:$});await z.acquire(r(Z,Y??{id:$}));for(let H of J.extraLocks??[])await z.acquire(H);return f(X,z,G,{operation:"remove",rowId:$},async(H)=>{let V=H.reservation($);if(V!==void 0){if(!C(V)||!J.staged||V.reservation!==J.staged.reservation)throw P("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(J.staged)throw P("remove",$,"attribution",`row ${$} is no longer reserved`);let j=H.row($),F=J1(H.state,$);if(!j&&!F)throw e("remove",$);if(v(j??{id:$})!==W)throw A1("remove",$);if(B!==void 0)if(j)q5($,j,B);else v3(Z,H,$,B);let U=J.protect;if(U){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},K=await KZ("remove",()=>U($,q));if(K!==void 0)throw P("remove",$,"row-protected",K)}if(j){if(B===void 0)await H.completeTorn();H.dropRosterRows($),await H.commitConfig()}if(F)H.dropStateAccount($),await H.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function q5(Z,$,J,X="remove"){if(j5(X,Z,$,J),$.torn)throw P(X,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw P(X,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function v3(Z,$,J,X){let z=()=>P("remove",J,"unbound-credential",`orphan ${J} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=$.stateAccount(J),B=a(G?.[E]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let Q;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();Q={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")Q={type:"oauth",refresh:G.refresh};else throw z();let[Y]=gZ({accounts:[$1({id:J,credential:Q,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[J]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw z();if(B.credentialEpoch!==X.credentialEpoch||B.binding.identity!==X.identity)throw P("remove",J,"attribution",`orphan ${J} was written for a credential or account other than the one this removal was decided for`,!0)}function J1(Z,$){let J=Z.accounts;return C(J)&&Object.hasOwn(J,$)}function I9(Z){return C(Z)&&typeof Z.id==="string"?Z.id:void 0}function g3(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let J=new Set;for(let G of Z){let B=I9(G);if(B!==void 0)J.add(B)}let X=new Set;for(let G of $){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 h3(Z,$){let J=new Map;for(let G of Z){let B=I9(G);if(B===void 0)continue;let Q=J.get(B);if(Q)Q.push(G);else J.set(B,[G])}let X=$.flatMap((G)=>J.get(G)??[]),z=0;return Z.map((G)=>I9(G)===void 0?G:X[z++])}async function _4(Z,$,J={}){p("reorder");let{ctx:X}=Z,z=J.onFailure;return l(X,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of J.extraLocks??[])await G.acquire(Q);return f(X,G,B,{operation:"reorder",rowId:void 0},async(Q)=>{let Y=Q.roster(),W=g3(Y,$);if(W)throw new R({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:W});let H=[...$],V=h3(Y,H);if(V.every((j,F)=>j===Y[F]))return{ids:H,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function L4(Z,$,J,X,z={}){return p("recordIdentity"),l(Z.ctx,"recordIdentity",$,z.onFailure,async(G,B)=>{if(typeof J!=="string"||J.length===0)throw P("recordIdentity",$,"invalid-input","identity must be non-empty");let Q=C(X)?X.credentialEpoch:void 0;if(!w(Q))throw P("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await VZ(Z,"recordIdentity",$);await G.acquire(r(Z,Y)),await G.acquire(z.providerLock??Z.providerLock);for(let W of z.extraLocks??[])await G.acquire(W);return f(Z.ctx,G,B,{operation:"recordIdentity",rowId:$},async(W)=>{let H=U5("recordIdentity",$,W.row($));if(v(H)!==v(Y))throw A1("recordIdentity",$);if(c("recordIdentity",H),(H.credentialEpoch??1)!==Q)throw P("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==J)throw Y5("recordIdentity",$);if(H.identity===void 0)await b3(W,H,J);let V=mZ(W,$,J);return await W.commitConfig(),{id:$,disabled:V}})})}function A4(Z){let $=Z[y];return C($)&&C($.publications)?$.publications:{}}function S4(Z,$){let J=A4(Z);if(!Object.hasOwn(J,$))return;let X=J[$];if(!C(X)||X.operationId!==$||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)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch))||X.finalized.some((z)=>!C(z)||typeof z.id!=="string"||!w(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw P("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(X)}async function I4(Z,$){let J=await n(Z.ctx);if(J.status!=="ready")throw HZ(J,"publishRoster",$);return S4(J.config,$)}function f3(Z,$){let J=()=>{throw P("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!C($)||typeof $.operationId!=="string"||!$.operationId||!Array.isArray($.remove)||!Array.isArray($.finalize)||!Array.isArray($.order))J();let X=new Set;for(let z of[...$.remove,...$.finalize]){if(!C(z)||typeof z.id!=="string"||tZ(z.id)||X.has(z.id)||!z.attribution)J();if(X.add(z.id),X1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))J()}for(let z of $.remove)if(Z.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")J();for(let z of $.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))J();if($.order.some((z)=>typeof z!=="string"||tZ(z))||new Set($.order).size!==$.order.length)J()}function R4(Z,$){Z.entries();let J=Z.config[y],X={...A4(Z.config)};Object.defineProperty(X,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),J.publications=X,delete J.publicationOrder}function x3(Z,$,J){let X=new Set;for(let B of Z1(Z.config)){if(!C(B)||typeof B.id!=="string")continue;if(X.has(B.id))throw P("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");X.add(B.id)}let z=new Set($.remove.map((B)=>B.id)),G=J.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==$.order.length||$.order.some((B)=>!G.some((Q)=>Q.id===B))||G.some((B)=>!$.order.includes(B.id)))throw P("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function O4(Z,$){await Z.assertAll();for(let X of $.removed)if(a(Z.stateAccount(X.id)?.[E])?.credentialEpoch===X.credentialEpoch&&!Z.rosterRow(X.id))Z.dropStateAccount(X.id);for(let X of $.finalized){let z=Z.stateAccount(X.id),G=a(z?.[E]);if(z&&G?.credentialEpoch===X.credentialEpoch&&G.staged?.reservation===X.reservation){let B={...z[E]};delete B.staged,Z.setStateAccount(X.id,{...z,[E]:B})}}await Z.commitState(void 0,{durable:!0});let J={...$,phase:"cleaned"};return R4(Z,J),await Z.commitConfig({durable:!0}),J}async function E4(Z,$,J={}){return p("publishRoster"),l(Z.ctx,"publishRoster",$?.operationId??"",J.onFailure,async(X,z)=>{if(!C($)||typeof $.operationId!=="string"||!$.operationId)throw P("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=uZ($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((Q)=>C(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let Y=await n(Z.ctx);if(Y.status!=="ready")throw HZ(Y,"publishRoster",$.operationId);let W=new Map(B.map(({id:V})=>[V,v(Y.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(W.values())].sort())await X.acquire(r(Z,{id:V}));await X.acquire(J.providerLock??Z.providerLock);for(let V of J.extraLocks??[])await X.acquire(V);let H=await f(Z.ctx,X,z,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(B.some(({id:D})=>v(j.find((T)=>T.id===D)??{id:D})!==W.get(D)))return;let F=S4(V.config,$.operationId);if(F){if(F.planDigest!==G)throw P("publishRoster",$.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(F.phase==="cleaned")return{outcome:"already-cleaned",receipt:F};return V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await O4(V,F)}}f3(Z,$);let U=x3(V,$,j),q=[];for(let D of $.remove){V.assertNotStaged(D.id);let T=j.find((A)=>A.id===D.id);if(!T)throw P("publishRoster",D.id,"attribution","the removed row no longer exists");if(q5(D.id,T,D.attribution,"publishRoster"),!T.credential||D.fingerprint!==void 0&&YZ(T.credential)!==D.fingerprint)throw P("publishRoster",D.id,"attribution","the removed secret no longer matches");q.push(T)}let K=[];for(let D of $.finalize){let T=j.find((g)=>g.id===D.id),A=a(V.stateAccount(D.id)?.[E]);if(!T||T.staged?.reservation!==D.reservation||A?.staged?.reservation!==D.reservation||T.enabled)throw P("publishRoster",D.id,"row-staged","the finalized row is not disabled under this reservation");let L=V.stateAccount(D.id),I=V.rosterRow(D.id),x=L?.[d],b=x===void 0?void 0:uZ(x);if(!A?.staged||A.staged.label!==I?.label||A.staged.disabledReason!==T.disabledReason||A.staged.providerState!==b)throw P("publishRoster",D.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");q5(D.id,T,D.attribution,"publishRoster"),K.push(T)}let N=U.find((D)=>D.torn);if(N)throw P("publishRoster",$.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let M=new Set;for(let D of U){if(!($.finalize.find((A)=>A.id===D.id)?.enabled??D.enabled)||D.type!=="oauth"||D.identity===void 0)continue;if(M.has(D.identity))throw P("publishRoster",D.id,"invalid-input","the final enabled roster repeats a known identity");M.add(D.identity)}for(let D of U)if(D.identity!==void 0&&D.fingerprint!==void 0&&U.some((T)=>T.id!==D.id&&T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the resulting pool gives the same secret different known identities");for(let D of K)if(D.identity!==void 0&&q.some((T)=>T.identity!==void 0&&T.identity!==D.identity&&T.fingerprint===D.fingerprint))throw P("publishRoster",D.id,"attribution","the staged secret belonged to a different known identity");await H5(V,$.operationId,J.protect);let O={operationId:$.operationId,planDigest:G,phase:"committed",removed:q.map((D)=>({id:D.id,credentialEpoch:D.credentialEpoch??1})),finalized:$.finalize.map((D,T)=>({id:D.id,credentialEpoch:K[T]?.credentialEpoch??1,reservation:D.reservation,enabled:D.enabled}))};for(let D of $.remove)V.dropRosterRows(D.id);for(let D of $.finalize){let T=V.rosterRow(D.id);T.enabled=D.enabled;let A={...V.entry(D.id)};if(delete A.staged,D.enabled)delete A.disabledReason;else A.disabledReason=D.disabledReason;V.setEntry(D.id,A)}let _=V.roster().filter((D)=>!C(D)||typeof D.id!=="string"||j.find((T)=>T.id===D.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((D)=>V.rosterRow(D)),..._],R4(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await O4(V,O)}},{completeTorn:!1});if(H)return H;if(await X.releaseAll(),Q>=1)throw P("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class E9{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,J,X,z){this.rt=Z,this.hook=$,this.onFailure=J,this.firedAtLoad=X,this.logger=z}fire(Z,$){if(!this.hook)return;if($==="load"){if(this.firedAtLoad.has(Z))return;this.firedAtLoad.add(Z)}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 NZ(X.lockDefaults,X.lockEnv),G={writes:0};try{let B=await f(X,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let H=W.row(Z);if(H?.unbound&&H.enabled&&H.type==="oauth"&&H.credential&&!H.invalid)c("pull",H);if(!H?.candidate||H.type!=="oauth")return;if(!H.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let V=W.row(Z);if(!V?.credential||V.credentialEpoch===void 0)return;return{id:Z,credential:V.credential,credentialEpoch:V.credentialEpoch,...V.identity!==void 0?{identity:V.identity}:{},reason:$}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await X.hold?.("pull-before-request",Z);let Q;try{Q=await this.hook?.(B)}catch(W){throw new R({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await(J.publishQuota??((W,H,V)=>B5(J,W,H,V)))(Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete(Z);let Q=hZ(B,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,Q)}catch(Y){this.logger?.warn("pull failure hook threw",{rowId:Z,error:Y instanceof Error?Y.message:String(Y)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:Q.kind})}finally{await z.releaseAll()}}}var b4=100,F5=128;class b9{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=k4){this.rt=Z,this.timeoutMs=$,this.clock=J,this.logger=Z.ctx.logger??s("store")}async record(Z,$,J){try{this.assertOpen(Z),A9(Z,$);let X=structuredClone({id:Z,attribution:$,observation:J}),{row:z,result:G}=await VZ(this.rt,"pull",Z);_1(Z,X.attribution,z),L1(this.rt.ctx,Z,this.overlayRow({...z,quota:MZ(G.config,Z)?.quota}).quota,X.observation),await this.room(Z),this.assertOpen(Z);let B=this.pending.get(Z)??[];if(B.push(X),this.pending.set(Z,B),B.length>=F5)this.flushNow();else this.schedule(b4)}catch(X){throw hZ(X,"pull",Z,{writes:0})}}queued(Z){return this.pending.get(Z)?.length??0}async room(Z){if(this.queued(Z)<F5)return;let{ctx:$}=this.rt,J=Math.max(0,...$.storeLocks.map((z)=>z.timeoutMs??$.lockDefaults.timeoutMs)),X=performance.now()+J;while(this.queued(Z)>=F5){this.assertOpen(Z),this.flushNow();let z=X-performance.now();if(z<=0)throw P("pull",Z,"lock-contention",`pool quota queue for ${Z} is full (${F5} readings) and the store locks stayed held`,!0);await new Promise((G)=>{let B=()=>{clearTimeout(Q),this.wake.delete(B),G()},Q=setTimeout(B,z);this.wake.add(B)})}}assertOpen(Z){if(this.closed)throw P("pull",Z,"invalid-input","pool quota writer is closed")}overlayRow(Z){let $=Z;for(let J of this.pending.get(Z.id)??[])try{_1(Z.id,J.attribution,Z),$={...$,quota:L1(this.rt.ctx,Z.id,$.quota,J.observation),needsFirstReading:!1}}catch{}return $}overlay(Z){return Z.map(($)=>this.overlayRow($))}schedule(Z){if(this.running||this.timer||!this.pending.size||this.stopped)return;let $=this.closed?0:(this.committedAt??-1/0)+y4-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 Z=[...this.pending.values()].flat(),$={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((X)=>({...X,timeoutMs:Math.min(X.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},J=new NZ($.lockDefaults,$.lockEnv);return this.running=(async()=>{try{await f($,J,{writes:0},{operation:"pull",rowId:void 0},async(z)=>{if(this.stopped)return;let G=!1;for(let B of Z){let{id:Q,attribution:Y,observation:W}=B,H=JSON.stringify([Q,Y.credentialEpoch,Y.identity]);try{z.assertNotStaged(Q),_1(Q,Y,z.row(Q))}catch(F){if(!(F instanceof R))throw F;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:Q,kind:F.kind});continue}let V=z.entry(Q);if(!V)continue;let j;try{j=L1($,Q,V.quota,W)}catch(F){let U=`codec:${H}`;if(!this.warned.has(U))this.warned.add(U),this.warn("pool quota publication dropped; the quota codec refused it",{id:Q,error:F instanceof Error?F.message:String(F)});continue}z.setEntry(Q,{...V,quota:j,needsFirstReading:!1}),G=!0}if(G&&!this.stopped)await z.commitConfig(),this.committedAt=this.clock.now()},{completeTorn:!1});let X=new Set(Z);for(let[z,G]of this.pending){let B=G.filter((Q)=>!X.has(Q));if(B.length)this.pending.set(z,B);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()):b4;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)=>{$=()=>{if(!this.pending.size)X()},this.wake.add($),$()});try{this.flush(),await Promise.race([J,new Promise((X)=>{Z=setTimeout(X,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout(Z),this.cancelTimer(),this.wake.delete($),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 m3}from"node:crypto";function y9(Z,$){if(wZ("refresh",Z,$?.staged),!$)throw P("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw P("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw P("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw P("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function v4(Z){return P("refresh",Z,"refresh-stamp-ahead",`row ${Z}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`,!0)}async function g4(Z,$,J,X={}){p("refresh");let{ctx:z}=Z;return l(z,"refresh",$,X.onFailure,async(G,B)=>{let{row:Q}=await VZ(Z,"refresh",$);y9($,Q);let Y=await X.refuse?.(Q);if(Y!==void 0)return{status:"refused",rowId:$,reason:Y};let W=v(Q),H;for(let U=0;;U++){await G.acquire(r(Z,{id:$,identity:W===$?void 0:W})),await G.acquire(X.providerLock??Z.providerLock);for(let N of X.extraLocks??[])await G.acquire(N);let K=await f(z,G,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let M=y9($,N.row($));if(c("refresh",M),!M.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),M=y9($,N.row($));if(v(M)!==W)return{keyNow:v(M)};let O=await X.refuse?.(M);if(O!==void 0)return{refused:O};return{row:M,credential:M.credential,credentialEpoch:M.credentialEpoch,identity:M.identity}});if("refused"in K)return{status:"refused",rowId:$,reason:K.refused};if("keyNow"in K){if(await G.releaseAll(),U>=1)throw P("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);W=K.keyNow;continue}H=K;break}if(P9(H.credential.lastRefreshedAt,z.now()))throw v4($);await z.hold?.("refresh-before-provider",$),await G.assertAll();let V;try{V=await J(H.credential,H.row)}catch(U){throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:U})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw P("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:SZ(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),F=await f(z,G,B,{operation:"refresh",rowId:$},async(U)=>{let q=U.row($),K=U.entry($);if(!q||q.invalid||!K||K.credentialEpoch!==H.credentialEpoch||q.identity!==H.identity)throw new R({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"attribution",message:`row ${$} changed credential while its refresh was in flight; the rotation is discarded`});c("refresh",q);let N=await X.refuse?.(q);if(N!==void 0)return{refused:N};let M=z.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(P9(O,M))throw v4($);let _={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},D=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,T=D?{mark:m3(),enabled:!1,reason:`${rZ}${JSON.stringify(D)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,L=await V5(Z,U,$,_,{stamp:C1(O,M),transition:T,identity:A,...j!==void 0?{providerState:O1(z.providerState,"refresh",$,q.providerState,j)}:{}});if(T!==void 0)T1(U,$,T),await U.commitConfig();let I=q.identity;if(A!==void 0)mZ(U,$,A),I=A,await U.commitConfig();return{stored:L,identity:I,contradiction:D,refused:void 0}});if(F.refused!==void 0)return{status:"refused",rowId:$,reason:F.refused};if(F.contradiction!==void 0)return{status:"identity-contradicted",rowId:$,...F.contradiction,credential:F.stored};if(X.onPersisted)try{let U=X.onPersisted;await KZ("refresh",()=>U($,F.stored))}catch(U){throw new R({operation:"refresh",rowId:$,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:F.stored,message:"the after-persist hook threw; the rotation stays committed",cause:U})}return{status:"rotated",rowId:$,credential:F.stored,...F.identity!==void 0?{identity:F.identity}:{}}})}import{isDeepStrictEqual as w3}from"node:util";var N5=Object.freeze(["version","accounts",y]);function k9(Z){let $={};for(let[J,X]of Object.entries(Z))if(!N5.includes(J))K5($,J,X);return $}function K5(Z,$,J){Object.defineProperty(Z,$,{value:J,enumerable:!0,writable:!0,configurable:!0})}function u3(Z,$){let J={};for(let[X,z]of Object.entries(Z))if(N5.includes(X))K5(J,X,z);else if(Object.hasOwn($,X))K5(J,X,$[X]);for(let[X,z]of Object.entries($))if(!Object.hasOwn(Z,X))K5(J,X,z);return J}function h4(Z){return new R({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}var p3=new f4;async function x4(Z){let $=async([X=Z.ctx.configPath]=[])=>{let z=await Q4(X);if(z.status==="error")return{status:"error",file:"config",reason:z.reason};return{status:z.status,settings:k9(z.config)}},J=G5?await $():await p3.read([Z.ctx.configPath],$);return structuredClone(J)}async function m4(Z,$,J={}){p("updateSettings");let{ctx:X}=Z,z=J.onFailure;return l(X,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Y of J.extraLocks??[])await G.acquire(Y);let Q=G.held.length;try{for(let K of X.storeLocks)await G.acquire(K);let Y=await n(X);if(Y.status!=="ready")throw HZ(Y,"updateSettings",void 0);let W=k9(Y.config),H=structuredClone(W),V=await KZ("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!C(j))throw h4("the settings mutator must produce an object");let F=N5.filter((K)=>Object.hasOwn(j,K));if(F.length>0)throw h4(`settings cannot set the pool-owned key(s) ${F.join(", ")}`);if(w3(j,W))return{settings:W,outcome:"unchanged"};let U=u3(Y.config,j),q={operation:"updateSettings",rowId:void 0};return await AZ(X.configPath,U,{beforeRename:async()=>{await X.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await X.onStep?.("after-config-write",q),{settings:k9(U),outcome:"updated"}}finally{await G.releaseTo(Q)}})}var w4=new Map;function l3(Z){let $=w4.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},w4.set(Z,$);return $}function u4(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:vZ,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function S1(Z){let $=l3(Z.configPath),J={...q9,...Z.lockOptions},X={provider:Z.provider,configPath:Z.configPath,statePath:Z.statePath,codec:Z.quota,...Z.providerState?{providerState:Z.providerState}:{},now:Z.now??Date.now,storeLocks:Z.storeLocks??[{name:"save",path:Z.configPath},{name:"save",path:Z.statePath}],lockDefaults:J,lockEnv:{...Z.onLockEvent?{onLockEvent:Z.onLockEvent}:{},...Z.onLockStep?{onLockStep:Z.onLockStep}:{},...Z.onRenewalTimer?{onRenewalTimer:Z.onRenewalTimer}:{}},removedIds:$.removedIds,requireCredentialStamps:Z.requireCredentialStamps===!0,requireRemovedFingerprint:Z.requireRemovedFingerprint===!0,...Z.logger?{logger:Z.logger}:{},...Z.onStep?{onStep:Z.onStep}:{},...Z.hold?{hold:Z.hold}:{}},z=new E9(()=>G,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),G={ctx:X,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(W,H)=>z.fire(W,H)},B=Z.coalesceQuota?new b9(G,Z.quotaDrainTimeoutMs,Z.quotaCommitTimer):void 0,Q=(W,H,V)=>B?B.record(W,H,V):B5(G,W,H,V);G.publishQuota=Q;let Y=(W)=>{if(W.status==="ready"&&B)return{...W,rows:B.overlay(W.rows)};return W};return{async load(){let W=Y(await n(X));if(W.status==="ready"){for(let H of W.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)z.fire(H.id,"load")}return u4(W)},async read(){return u4(Y(await n(X)))},async initialize(W={}){return{status:await Y4(X,W.dropKeys??[])}},add:(W,H)=>K4(G,W,H),publishRoster:(W,H)=>E4(G,W,H),publication:(W)=>I4(G,W),replace:(W,H,V,j)=>N4(G,W,H,V,j),rotate:(W,H,V,j)=>D4(G,W,H,V,j),updateProviderState:(W,H,V,j)=>U4(G,W,H,V,j),disable:(W,H,V)=>P4(G,W,H,V),enable:(W,H)=>C4(G,W,H),remove:(W,H)=>T4(G,W,H),reorder:(W,H)=>_4(G,W,H),readSettings:()=>x4(G),updateSettings:(W,H)=>m4(G,W,H),recordIdentity:(W,H,V,j)=>L4(G,W,H,V,j),refresh:(W,H,V)=>g4(G,W,H,V),recordQuota:Q,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(W)=>z.fire(W,"admission"),pullsSettled:()=>z.settled()}}var d3=[/\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 h9(Z={}){let{redactStrings:$}=p4({...Z,extraValuePatterns:[...d3,...Z.extraValuePatterns??[]]});return(J)=>$(J)}class u extends Error{code;constructor(Z,$,J){super($,J);this.name="CommandError",this.code=Z}}var l4=/^[a-z][a-z0-9-]{0,63}$/,v9={code:"action-failed",text:"That action failed."},c3=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(Z){if(Z instanceof u)return{code:l4.test(Z.code)?Z.code:v9.code,text:Z.message};if(Z instanceof R)return{code:`pool-${Z.kind}`,text:c3.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return v9}var d4="This cannot be undone. Continue?",s3=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function a3(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return s3.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function n3(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function g9(Z,$,J){if(typeof Z==="string"){let z=J.redact(Z);if(z!==Z)J.redacted.push($);return z}if(Array.isArray(Z))return Z.map((z,G)=>g9(z,`${$}[${G}]`,J));if(!n3(Z))return Z;let X={};for(let[z,G]of Object.entries(Z)){if(a3(z)){J.dropped.push(`${$}.${z}`);continue}Object.defineProperty(X,z,{value:g9(G,`${$}.${z}`,J),enumerable:!0,writable:!0,configurable:!0})}return X}function c4(Z,$,J){let X={redact:J.redact,dropped:[],redacted:[]},z=g9(Z,"payload",X);if(X.dropped.length>0)J.logger.warn("credential-shaped field dropped from a command payload",{command:$,fields:X.dropped});if(X.redacted.length>0)J.logger.warn("secret-shaped text masked in a command payload",{command:$,fields:X.redacted});return z}function i3(Z){return{value:String(Z.value),label:String(Z.label)}}function r3(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(i3),...Z.value!==void 0?{value:Z.value}:{}};case"toggle":return{kind:"toggle",id:Z.id,label:Z.label,value:Z.value===!0};case"number":return{kind:"number",id:Z.id,label:Z.label,...Z.value!==void 0?{value:Z.value}:{},...Z.min!==void 0?{min:Z.min}:{},...Z.max!==void 0?{max:Z.max}:{},...Z.required?{required:!0}:{}};case"text":return{kind:"text",id:Z.id,label:Z.label,...Z.value!==void 0&&!Z.masked?{value:Z.value}:{},...Z.placeholder!==void 0?{placeholder:Z.placeholder}:{},...Z.masked?{masked:!0}:{},...Z.required?{required:!0}:{}}}}function f9(Z){if(Z.irreversible===!0)return{message:Z.confirm||d4,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function s4(Z){let $=f9(Z);return{id:Z.id,label:Z.label,...Z.description!==void 0?{description:Z.description}:{},...Z.group!==void 0?{group:String(Z.group)}:{},knobs:(Z.knobs??[]).map(r3),...$?{confirm:$}:{}}}function o3(Z){return{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...Z.identity!==void 0?{identity:Z.identity}:{}}}function t3(Z){return{id:Z.id,label:Z.label,...Z.detail!==void 0?{detail:Z.detail}:{},...Z.group!==void 0?{group:String(Z.group)}:{},...Z.status!==void 0?{status:String(Z.status)}:{},...Z.account?{account:o3(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(s4)}}function e3(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(t3),actions:($.actions??[]).map(s4),...$.facts!==void 0?{facts:$.facts}:{}}}function a4(Z,$,J){return{command:Z,title:$,sections:J.map(e3)}}function n4(Z,$,J,X){return c4({command:Z,menu:a4(Z,$,J)},Z,X)}function i4(Z,$,J,X,z){return c4({command:Z,ok:X.ok,text:String(X.text),...!X.ok&&X.code!==void 0?{code:l4.test(X.code)?X.code:"refused"}:{},...X.needsConfirmation?{needsConfirmation:!0}:{},menu:a4(Z,$,J)},Z,z)}var J6="disabled from the command menu";function Z8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function IZ(Z){return Z8(Z)?{...Z}:{}}function $8(Z){if(Z.status!=="ready")return[];let $=new Set;return Z.rows.filter((J)=>{if($.has(J.id))return!1;return $.add(J.id),!0})}function J8(Z,$){return Z.label??$??Z.id}function D5(Z,$){return fZ(Z.quota)?CZ(Z.quota,$):void 0}function X6(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var R1="Actions";function X8(Z){if(Z.status==="pending-migration")return"The account pool has not been migrated yet.";if(Z.status==="error")return`The ${Z.file} file cannot be read: ${Z.reason}`;return}function r4(Z,$){switch($.outcome){case"added":return`Added ${Z}.`;case"added-disabled":return`Added ${Z}, disabled: another enabled account has the same identity.`;case"completed":return`Finished adding ${Z}.`;case"rotated":return`${Z} was already in the pool; its credential was updated.`;case"exists":return`${Z} was already in the pool; its credential is unchanged.`}}function o4(Z){return I1(Z).text}async function z8(Z){let{store:$}=Z,J=await $.read(),X=await $.readSettings(),z=await Z.routing?.vaultOrder?.();return{load:J,rows:$8(J),settings:X.status==="error"?{}:X.settings,...z?{vault:z}:{}}}function M5(Z,$){let J=$.accounts?.describeIdentity?$.accounts.describeIdentity(Z):Z.identity;return{account:{id:Z.id,...Z.label!==void 0?{label:Z.label}:{},enabled:Z.enabled,type:Z.type,...J!==void 0?{identity:J}:{}},name:J8(Z,J)}}function G8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=$.rows.map((V)=>V.id),B=X8($.load),Q=$.rows.filter((V)=>V.enabled).length,Y=$.rows.map((V,j)=>{let{account:F,name:U}=M5(V,Z),q=[V.type==="api"?"API key":"OAuth",...F.identity!==void 0?[F.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),K=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await J.disable(V.id,J6,z),`Disabled ${U}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await J.enable(V.id,z),`Enabled ${U}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((M,O)=>({value:String(O+1),label:String(O+1)})),value:String(j+1)}],run:async({values:M})=>{let O=Number(M.position),_=G.filter((T)=>T!==V.id);return _.splice(O-1,0,V.id),(await J.reorder(_,z)).outcome==="unchanged"?`${U} is already at position ${O}.`:`Moved ${U} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${U}? Its stored credential is deleted.`,run:async()=>{return await J.remove(V.id,{...z,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${U}.`}}),{id:V.id,label:U,detail:q,group:"Accounts",status:K,account:F,actions:N}}),W=Z.accounts?.login,H=[];if(W&&!B)H.push({id:"add",label:W.label??"Add account",group:R1,knobs:W.knobs??[],run:async({values:V,invocation:j})=>{let F=await W.run(V,j);if(F.status==="cancelled")return{ok:!1,text:F.message??"Login cancelled."};if(F.status==="ready"){let U=await J.add(F.account,z);return r4(F.account.label??U.id,U)}return F.completion.then(async(U)=>{if(!U){j.notify("Login cancelled.","warning");return}let q=await J.add(U,z);j.notify(r4(U.label??q.id,q))},(U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}).catch((U)=>{j.notify(`Adding the account failed: ${o4(U)}`,"error")}),F.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${X6($.rows.length,"account")}, ${Q} enabled`],items:B?[]:Y,actions:H}}}function B8(Z,$){let J=Z.quota?.scope??"all",X=Z.now(),z=J==="all"?"Accounts":`Accounts · ${J}`,G=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((H)=>H.candidate),Q=B.map((H)=>{let{account:V,name:j}=M5(H,Z),F=D5(H,J);return{id:H.id,label:j,group:z,status:PZ(F,{now:X,form:"compact"}),detail:PZ(F,{now:X,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:U})=>{return await G([H.id],U),`Checked quota for ${j}.`}}]}}),Y=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=M5(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",F=PZ(D5(H,J),{now:X,form:"compact"});return`${V} (${j}): ${F}`}),W=[];if(B.length>0)W.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:R1,run:async({invocation:H})=>{let V=B.map((j)=>j.id);return await G(V,H),`Checked quota for ${X6(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:Y,items:Q,actions:W}}}async function Q8(Z,$){try{return await Z.reorder($)}catch(J){if(J instanceof Error&&J.name==="ClaustrumConsumerError"&&J.kind==="invalid-order")throw new u("vault-invalid-order",J.message,{cause:J});throw J}}function x9(Z){return new u("vault-invalid-order",Z)}function W8(Z){let $=Z.rows.map((X)=>({id:X.id,label:X.label.trim()||X.id})),J=(X)=>$.filter((z)=>z.id===X||z.label===X);return{ids:$.map((X)=>X.id),nameOf:(X)=>$.find((z)=>z.id===X)?.label??X,entryOf:(X)=>{let 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 B=J(G);if(B.length===0)throw x9(`"${G}" is not a vault account.`);if(B.length>1)throw x9(`"${G}" matches more than one vault account; enter those accounts by route id.`);let Q=B[0].id;if(z.includes(Q))throw x9(`"${G}" names an account already in the order.`);z.push(Q)}return z}}}function Y8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=IZ($.settings.routing).mode,Q=typeof B==="string"&&G.some((K)=>K.value===B)?B:"ordered",Y=Z6(Q),W=$.vault?W8($.vault):void 0,H=W?W.ids:$.rows.map((K)=>K.id),V=(K)=>W?W.nameOf(K):K,j=$6(H,Y.placement,Z.routing?.formerMainId??e4),U=[`Mode: ${G.find((K)=>K.value===Q)?.label??Q}`];if(H.length>0)U.push(`${W?"Vault account order":"Roster order"}: ${H.map(V).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==H.join())U.push(`Tried in order: ${j.map(V).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:R1,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Q}],run:async({values:K})=>{let N=String(K.mode);return await J.updateSettings((M)=>{M.routing={...IZ(M.routing),mode:N};return},z),`Routing mode set to ${G.find((M)=>M.value===N)?.label??N}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:R1,knobs:[{kind:"text",id:"order",label:W?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:W?H.map(W.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:K})=>{let M=String(K.order).split(W?/[,\n]+/:/[\s,]+/).map((_)=>_.trim()).filter((_)=>_.length>0),O=$.vault&&W?await Q8($.vault,W.resolve(M)):await J.reorder(M,z);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(V).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:U,actions:q}}}function H8(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let J=Z.quota?.scope??"all",X=[];for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(!X.includes(G.label))X.push(G.label);return X.length>0?X:["primary"]}function V8(Z,$){let J=Z.quota?.scope??"all",X=new Map;for(let z of $.rows)for(let G of D5(z,J)?.limits??[])if(G.windowMinutes!==void 0&&!X.has(G.label))X.set(G.label,t4(G));return(z)=>X.get(z)??z}function U8(Z,$){let{store:J,extraLocks:X}=Z,z=X?{extraLocks:X}:{},G=IZ($.settings.killswitch),B=G.enabled===!0,Q=IZ(G.accounts),Y=H8(Z,$),W=V8(Z,$),H=B?"on":"off",V=$.rows.map((j)=>{let{account:F,name:U}=M5(j,Z),q=IZ(Q[j.id]),K=Y.filter((N)=>typeof q[N]==="number");return{id:j.id,label:U,group:`Floors · killswitch ${H}`,status:K.length===0?"no floors":K.map((N)=>`${W(N)} ≥${q[N]}%`).join(" · "),account:F,actions:[{id:"floors",label:"Set floors",knobs:Y.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${W(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await J.updateSettings((M)=>{let O=IZ(M.killswitch),_=IZ(O.accounts),D=IZ(_[j.id]);for(let T of Y){let A=N[T];if(typeof A==="number")D[T]=A;else if(A===null)delete D[T]}if(Object.keys(D).length>0)_[j.id]=D;else delete _[j.id];if(Object.keys(_).length>0)O.accounts=_;else delete O.accounts;M.killswitch=O;return},z),`Floors updated for ${U}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:R1,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let F=j.enabled===!0;return await J.updateSettings((U)=>{U.killswitch={...IZ(U.killswitch),enabled:F};return},z),`Killswitch ${F?"on":"off"}.`}}]}}}async function z6(Z){let $=await z8(Z);return[G8(Z,$),B8(Z,$),Y8(Z,$),U8(Z,$)]}var j8=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),m9=["accounts","quota","routing","limits"];function G6(Z,$){let{sessionId:J}=Z,X=Z.notify.bind(Z);return Object.freeze({...J!==void 0?{sessionId:J}:{},notify:(z,G)=>G===void 0?X($(String(z))):X($(String(z)),G)})}function q8(Z,$){switch(Z.kind){case"choice":{let J=$??Z.value;if(typeof J==="string"&&Z.choices.some((X)=>X.value===J))return{value:J};return{problem:`Choose one of the options for ${Z.label}.`}}case"toggle":{let J=$??Z.value;return typeof J==="boolean"?{value:J}:{problem:`${Z.label} must be on or off.`}}case"number":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} needs a number.`}:{value:null};let X=typeof J==="number"?J:Number(J);if(typeof J==="boolean"||!Number.isFinite(X))return{problem:`${Z.label} needs a number.`};if(Z.min!==void 0&&X<Z.min)return{problem:`${Z.label} must be at least ${Z.min}.`};if(Z.max!==void 0&&X>Z.max)return{problem:`${Z.label} must be at most ${Z.max}.`};return{value:X}}case"text":{let J=$===void 0?Z.value??null:$;if(J===null||J==="")return Z.required?{problem:`${Z.label} cannot be empty.`}:{value:null};return typeof J==="string"?{value:J}:{problem:`${Z.label} must be text.`}}}}function F8(Z,$){let J={};for(let X of Z){let z=$&&Object.hasOwn($,X.id)?$[X.id]:void 0,G=q8(X,z);if("problem"in G)return G;J[X.id]=G.value}return{values:J}}function K8(Z,$){let J=Z.find((z)=>z.id===$.sectionId);if(!J)return;return($.itemId===void 0?J.content.actions:J.content.items?.find((z)=>z.id===$.itemId)?.actions)?.find((z)=>z.id===$.actionId)}function pZ(Z){let $=Z.logger??s("commands"),J=h9(Z.redaction),X={logger:$,redact:J},z=Z.now??Date.now,G=Z.extras??[],B=Z.replace??{},Q=m9.filter((j)=>!B[j]);for(let j of m9)if(B[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let Y=Z.store;if(Q.length>0&&!Y)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let W=new Set;for(let j of G){if(j8.has(j.id)||W.has(j.id))throw Error(`extra section id ${j.id} is taken`);W.add(j.id)}async function H(j,F,U,q){try{return{id:j,slot:F,title:U.title,content:await U.build(q)}}catch(K){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:J(K instanceof Error?K.message:String(K))}),{id:j,slot:F,title:U.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let F=Y&&Q.length>0?await z6({store:Y,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],U=[];for(let q of m9){let K=B[q];if(K)U.push(await H(q,q,K,j));else{let N=F.find((M)=>M.slot===q);if(N)U.push(N)}}if(Z.cache)U.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)U.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of G)U.push(await H(q.id,"extra",q,j));return U}return{command:Z.command,async open(j){let F=G6(j,J);return n4(Z.command,Z.title,await V(F),X)},async apply(j,F){let U=G6(F,J),q=async(_)=>i4(Z.command,Z.title,await V(U),_,X),K=j.command===Z.command?K8(await V(U),j):void 0;if(!K)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=f9(K);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let M=F8(K.knobs??[],j.values);if("problem"in M)return q({ok:!1,code:"invalid-input",text:M.problem});let O;try{let _=await K.run({values:M.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:U});O=typeof _==="string"?{ok:!0,text:_}:{ok:_.ok,text:_.text,..._.ok?{}:{code:_.code??"refused"}}}catch(_){let D=I1(_);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:D.code,error:J(_ instanceof Error?_.message:String(_))}),O={ok:!1,...D}}return q(O)}}}function N8(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function D8(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $=Z;if(typeof $.command!=="string"||typeof $.sectionId!=="string"||typeof $.actionId!=="string")return;if($.itemId!==void 0&&typeof $.itemId!=="string")return;if($.sessionId!==void 0&&typeof $.sessionId!=="string")return;if($.confirmed!==void 0&&typeof $.confirmed!=="boolean")return;let J={};if($.values!==void 0){if($.values===null||typeof $.values!=="object"||Array.isArray($.values))return;for(let[X,z]of Object.entries($.values)){if(!N8(z))return;Object.defineProperty(J,X,{value:z,enumerable:!0,writable:!0,configurable:!0})}}return{command:$.command,sectionId:$.sectionId,actionId:$.actionId,...typeof $.itemId==="string"?{itemId:$.itemId}:{},...$.values!==void 0?{values:J}:{},...$.confirmed===!0?{confirmed:!0}:{},...typeof $.sessionId==="string"?{sessionId:$.sessionId}:{}}}function k(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as C8}from"node:fs";import{rm as W6}from"node:fs/promises";import{dirname as T8,join as M6}from"node:path";import{resolveClaustrumConnectionPath as _8}from"@cortexkit/claustrum-client";function B6(Z,$){if(!Z)return;let J=Z.rawUsedPercent??Z.usedPercent;if(!Number.isFinite(J)||J<0||J>100)return;return{usedPercent:J,remainingPercent:100-J,checkedAt:$,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...typeof Z.windowMinutes==="number"&&Number.isFinite(Z.windowMinutes)&&Z.windowMinutes>0&&{windowMinutes:Z.windowMinutes}}}function w9(Z){if(!k(Z)||typeof Z.minor!=="number"||!Number.isSafeInteger(Z.minor)||typeof Z.exponent!=="number"||!Number.isInteger(Z.exponent))return;let $=Z.minor/10**Z.exponent;return Number.isFinite($)?$:void 0}function M8(Z){let $=w9(Z.total),J=w9(Z.remaining);if($===void 0||J===void 0||$<0||J<0)return;let X=$-J,z=Z.spendable===!1,G=$>0?X/$*100:z?100:0;return{limit:$,used:X,remaining:J,usedPercent:G,remainingPercent:100-G,reached:z,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...k(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function P8(Z,$){if(!k(Z))return;let J=w9(Z.remaining);return{hasCredits:!0,unlimited:typeof Z.unlimited==="boolean"?Z.unlimited:!1,...J!==void 0&&J>=0&&{balance:J},...Z.spendable===!1&&{overageLimitReached:!0},checkedAt:$}}function u9(Z,$){if(Z.insulaCreditsUnlimitedUnstated&&Z.credits&&Z.credits.balance===void 0&&k($)&&k($.credits)&&$.credits.unlimited===!0)return{...Z,credits:{...Z.credits,unlimited:!0}};return Z}function Q6(Z,$){let J=B6(Z.usage?.primary,$.fetchedAt);if(!J||!Number.isFinite($.fetchedAt))return;let X=B6(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="individual_limit"):void 0,G=k(z)?M8(z):void 0,B=Array.isArray(Z.spend)?Z.spend.find((W)=>k(W)&&W.id==="credits"):void 0,Q=P8(B,$.fetchedAt),Y=k(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:J,...Q&&{credits:Q},...Q&&k(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...X&&{secondary:X},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function p9(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var l9="ck auth reclassify --from-registry";function P5(Z,$){if($===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($.grants===0)return`The vault has no grant letting ${Z} read OpenAI accounts. Grant it with \`${p9(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${l9}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var UZ=s("vault"),L8="openai-auth",P6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},O8={opencode:"OpenCode",pi:"Pi"};function d9(Z){return H6(L8,Z)}function O5(Z){return M6(T8(Z),"openai-auth-vault")}function lZ(Z,$){return{...U6({stateDir:Z,host:$}),rosterPath:M6(Z,`${$}-roster.json`)}}var C6=2000,RB=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],A8={"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 ${l9} 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 EB(Z,$){if(Z!=="vault-no-grant")return A8[Z];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: ${p9($)}`}function bB(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let J=Z.grantReach();if(J!==void 0)return J.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function S8(Z){let $=T5(Z);return $?_5($):void 0}class I8{host;name;paths;#$;#Z;#Q=new Map;#W=new Map;#U=new Map;#j;#J;#Y;#z;#q=!1;#F=!1;#H=Promise.withResolvers();#K="unknown";#V;constructor(Z){this.#$=Z,this.host=Z.host,this.name=d9(Z.host),this.paths=lZ(Z.stateDir,Z.host),this.#Z=new N6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:P6,connect:()=>this.#C(),isCustodyActive:()=>this.#_(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:S8,insula:{provider:"codex",normalize:Q6},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#J=void 0},onDiscovery:($)=>this.#L($),onError:($)=>this.#X("vault roster refresh failed",$),logger:{...UZ,warn:($,J)=>{if($!=="skipped insula provider poll")UZ.warn($,J)}}})}#N(){return(this.#$.connectionFile??_8)()}#D(){return{connectionFile:this.#N(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>UZ.debug("vault transport error",{errorClass:Z})}}#C(){return(this.#$.connectScoped?.()??D6(this.#D())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#G(Z,$,J){let X=this.#U.get(Z);if(X?.source===$&&X.reason===J)return;this.#U.set(Z,{source:$,reason:J}),UZ.info("vault background quota source changed",{routeId:Z,source:$,reason:J})}#T(){return this.#$.connectEnrollment?.()??V6(this.#D())}#X(Z,$){this.#J=TZ($),UZ.warn(Z,{host:this.host,error:this.#J})}#B(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=C8(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#B(),$=await j6(this.paths,this.name);if(Z===this.#B())return this.#K=$,this.#V=Z,$;return"unreadable"}enrolled(){return this.#V!==this.#B()||this.#K!=="local"}async#_(){if(this.#V!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#q||this.#F)return;this.#q=!0,this.#Z.start()}#L(Z){if(this.#z===Z)return;this.#z=Z,Z.finally(()=>{if(this.#z===Z)this.#z=void 0;this.#H.resolve()}).catch(()=>{})}#M(){return this.#Z.refresh()}firstRoster(){return this.#H.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#z;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#z??this.#M()).catch((J)=>{this.#X("vault roster refresh failed",J)})}async refresh(){try{await this.authority();let Z=this.#z;if(Z)await Z.catch(()=>{return});let $=await this.#M();return this.#J=void 0,$}catch(Z){return this.#X("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#Z.routingRows().map(($)=>{let J=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...J!==void 0?{identity:J}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,J){let X=!1;try{return await this.#Z.send(Z,(z)=>{return X=!0,$(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.#Z.authorize(Z,$.signal)}catch(J){this.#X("vault refused to serve an account",J);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(J){this.#X("vault failure report failed",J)}await this.refresh()}recordSnapshot(Z,$,J,X){let z=C5($,(this.#$.now??Date.now)(),J);if(!z)return Promise.resolve();return this.#Z.recordQuota(Z,z,X).then(()=>{},(G)=>this.#X("vault quota write failed",G))}pollQuota(Z,$=!0){let J=this.#W.get(Z);if(J)return J;let X=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,X),X}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let J=(await K6(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===Z),X,z=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#G(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),X=await this.#P(Z,$);return});if(X)return X;if(z!==void 0&&J?.accountIdentity){let Q=C5(u9(z,this.routes().find((W)=>W.id===Z)?.quota),z.primary.checkedAt,!0);if(!Q)return this.#G(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,J.accountIdentity,Q))return this.#G(Z,"insula",null),{ok:!0};return this.#G(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute(Z),B=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G(Z,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#P(Z,$)}async#P(Z,$){let J,X=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,B)=>{try{let Q=$?void 0:await this.#Z.cachedInsulaQuota(B);if(Q!==void 0){let W=C5(u9(Q,this.routes().find((H)=>H.id===Z)?.quota),Q.primary.checkedAt,!0);if(!W)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,W,B),new Response(null,{status:200})}let Y=await E1({accessToken:G,fetchImpl:X,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:UZ});return await this.recordSnapshot(Z,Y,!0,B),J=void 0,new Response(null,{status:200})}catch(Q){J=TZ(Q);let Y=Q?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw Q}},{site:"quota"}).catch((G)=>{J=TZ(G);return});if(!z)return{ok:!1,error:J??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:J??`status ${z.status}`}}requestReading(Z){let $=this.#Q.get(Z);if($)return $;let J=this.pollQuota(Z,!1).catch((X)=>{UZ.warn("vault quota poll failed",{routeId:Z,error:TZ(X)})}).finally(()=>{this.#Q.delete(Z)});return this.#Q.set(Z,J),J}async pollStale(Z){let $=(this.#$.now??Date.now)(),J=[];for(let X of this.routes()){let z=R8(X.quota);if(z!==void 0&&$-z<Z)continue;J.push({id:X.id,...await this.pollQuota(X.id)})}return J}async reorder(Z){if(await this.authority()!=="vault")throw Error("Vault order can only be changed in vault mode.");return this.#Z.reorder(Z)}async decline(Z){await this.#Z.decline(Z),UZ.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),UZ.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await L5(this.paths,this.name)}catch(J){this.#X("vault enrollment state unreadable",J),Z={state:"blocked",proposedName:this.name,code:J instanceof Y6?J.kind:"unreadable-state"}}let $=this.enrolled()?this.snapshot():void 0;return{host:this.host,name:this.name,enrollment:Z,discovered:$!==void 0,accounts:$?.rows??[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let Z=await this.#T().catch(($)=>{throw new u("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${TZ($)}. Is the vault running?`)});try{let $=new q6({client:Z,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),J=await $.status();if(J.state==="denied"||J.state==="blocked")await $.resetTerminal();let X=await $.reconcile();if(UZ.info("vault enrollment step",{host:this.host,state:X.state}),X.state==="approved")this.#J=void 0,await this.refresh();return X}finally{Z.close()}}waitForApproval(Z={}){return this.#Y??=(async()=>{let $=Z.sleep??((G)=>new Promise((B)=>setTimeout(B,G))),J=Z.pollIntervalMs??2000,X=Date.now()+(Z.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if(Z.onPending?.(z),Date.now()>=X)return z;await $(J),z=await this.connectStep()}return z})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){await W6(this.paths.tokenPath,{force:!0}),await W6(this.paths.statePath,{force:!0}),await this.#$.afterDisconnect?.(),await this.authority(),this.#J=void 0,UZ.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())F6({mode:"custody",auth:Z,provider:"openai"})}close(){this.#F=!0,this.#H.resolve(),this.#Z.close()}}function R8(Z){if(!Z)return;let $=CZ(Z).limits.map((J)=>J.checkedAt);return $.length>0?Math.max(...$):void 0}function A5(Z,$){if($.state!=="pending")return[];if(!$.requestId)return[`The vault did not take the enrollment request yet${$.retryCode?` (${$.retryCode})`:""}. Run Connect again in a moment.`];return[`Enrollment request ${$.requestId} for ${Z} is waiting for approval. Approve it with:`,` ck auth enroll approve --request-id ${$.requestId}`,"and let it read your OpenAI accounts with:",` ck auth grant --principal enrolled:${Z} --selector-kind category --selector ${P6.category} --operation read`]}function T6(Z,$,J){let X=`${O8[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 c9(Z,$){if(($.state==="blocked"||$.state==="unavailable")&&$.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($.state){case"approved":{let J=Z.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${Z.name}. It serves ${J} OpenAI account${J===1?"":"s"} to this host${J===0?`. ${P5(Z.name,Z.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 (${$.code}). Resolve the refusal before running Connect again.`};case"pending":case"busy":return{ok:!1,text:[...A5(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
|
|
2
2
|
`)};default:return{ok:!1,text:`Enrollment is ${$.state}.`}}}var s9="/backend-api/wham/rate-limit-reset-credits",E8=`https://chatgpt.com${s9}`,I6=`${s9}/consume`,b8=`https://chatgpt.com${I6}`,y8=300000,k8=60000,v8=15000,g8=60000;function z1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class ZZ extends Error{kind;cooldownUntil;constructor(Z,$,J){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=J}}class dZ extends Error{kind;status;constructor(Z,$,J){super($);this.name="ResetCreditError",this.kind=Z,this.status=J}}function R6(Z,$,J){return{authorization:`Bearer ${Z}`,...J?{"chatgpt-account-id":J}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function I5(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function E6(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function R5(Z){if(!I5(Z)||typeof Z.redeemRequestId!=="string"||Z.redeemRequestId.length===0||typeof Z.creditId!=="string"||Z.creditId.length===0||typeof Z.startedAt!=="number"||!Number.isFinite(Z.startedAt)||Z.chatgptAccountId!==void 0&&(typeof Z.chatgptAccountId!=="string"||Z.chatgptAccountId.length===0))return;return{redeemRequestId:Z.redeemRequestId,creditId:Z.creditId,startedAt:Z.startedAt,...typeof Z.chatgptAccountId==="string"?{chatgptAccountId:Z.chatgptAccountId}:{},...b6(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function b6(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function S5(Z){return Z.kind==="http_error"&&b6(Z.status)}function y6(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function h8(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new ZZ("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function k6(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function v6(Z,$){return $-Z.startedAt<y8}function G1(Z,$){if(!RZ($))return;return Z.reset?.[$]}function g6(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function h6(Z,$,J){if(!RZ($))return;let X=g6(Z),z=X[$]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:J,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[$]=z}function f6(Z,$){let J=E6(Z),X=R5(Z?.inFlight);if(k6(Z)&&!X)return{kind:"corrupt",beforeState:J};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:J,cooldownUntil:Z.cooldownUntil};if(X&&v6(X,$))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 f8(Z,$){if(!RZ($))return{kind:"fresh",beforeState:void 0};let J=await Z.loadAccountsFn(z1(Z));return f6(J?G1(J,$):void 0,Z.now())}async function x8(Z,$){let J;if(await Z.mutateAccountsFn((X)=>{let z=Z.now(),G=G1(X,$);if(J=f6(G,z),J.kind==="corrupt")h6(X,$,z);return X},z1(Z)),!J)throw Error("corrupt reset state mutation did not run");return J}async function m8(Z,$,J,X){if(!RZ($))return{kind:"fresh",beforeState:void 0};let z;if(await Z.mutateAccountsFn((G)=>{let B=Z.now(),Q=G1(G,$),Y=E6(Q),W=R5(Q?.inFlight);if(k6(Q)&&!W)return h6(G,$,B),z={kind:"corrupt",beforeState:Y},G;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>B)return z={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},G;if(W&&v6(W,B))return z={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;if(W&&!y6(W,X))return z={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},G;let H=E5(J);if(!H)return z={kind:"fresh",beforeState:Y},G;let V={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:B,...X===void 0?{}:{chatgptAccountId:X}},j=g6(G);return j[$]={...Q,inFlight:V},z={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:H}},G},z1(Z)),!z)throw Error("reset claim mutation did not run");return z}async function w8(Z,$,J,X,z){if(!RZ($))return;if(!i9(X.kind))return u8(Z,$,J,X,z);await Z.mutateAccountsFn((G)=>{let B=G1(G,$),Q=R5(B?.inFlight);if(!B||!Q||Q.redeemRequestId!==J.redeemRequestId||Q.creditId!==J.creditId)return G;let Y=Z.now();if(delete B.inFlight,B.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")B.cooldownUntil=Y+g8;else delete B.cooldownUntil;return G},z1(Z));return}function _6(Z,$){let J=R5(Z?.inFlight);return J&&J.redeemRequestId===$.redeemRequestId&&J.creditId===$.creditId?J:void 0}async function u8(Z,$,J,X,z){let G=S5(X)?X.status:void 0;if(!(J.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===J.rejectedStatus){let Y=await Z.loadAccountsFn(z1(Z));return _6(Y?G1(Y,$):void 0,J)}let Q;return await Z.mutateAccountsFn((Y)=>{Q=void 0;let W=G1(Y,$),H=_6(W,J);if(!W||!H)return Y;let V={...H};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(J.unknownAnswers??0))V.rejectedStatus=G;return W.inFlight=V,Q=V,Y},z1(Z)),Q}function b1(Z,$){if(!Z||Z.usedPercent<100)return!1;if(!Z.resetsAt)return!0;let J=Date.parse(Z.resetsAt);return!Number.isFinite(J)||J>$}function a9(Z,$,J){if(!($||b1(Z.primary,J)||b1(Z.secondary,J)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function L6(Z,$){let J=Z[$];if(J===void 0||J===null)return;return typeof J==="string"?J:null}function p8(Z){if(!I5(Z))return;let $=L6(Z,"granted_at"),J=L6(Z,"reset_type");if(typeof Z.id!=="string"||typeof Z.status!=="string"||typeof Z.expires_at!=="string"||Number.isNaN(Date.parse(Z.expires_at))||typeof Z.is_supported_by_plan!=="boolean"||$===null||J===null)return;return{id:Z.id,status:Z.status,...$===void 0?{}:{grantedAt:$},expiresAt:Z.expires_at,...J===void 0?{}:{resetType:J},isSupportedByPlan:Z.is_supported_by_plan}}async function n9(Z,$,J){let X;try{X=await Z(E8,{method:"GET",headers:R6($,s9,J),signal:AbortSignal.timeout(v8)})}catch{throw new dZ("http_error","reset credit list request failed")}if(!X.ok)throw new dZ("http_error",`reset credit list request failed: ${X.status}`,X.status);let z;try{z=await X.json()}catch{throw new dZ("invalid_response","reset credit list response was not valid JSON",X.status)}if(!I5(z))throw new dZ("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let Q=p8(B);return Q===void 0?[]:[Q]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function E5(Z){return[...Z].filter(x6).sort(($,J)=>Date.parse($.expiresAt)-Date.parse(J.expiresAt))[0]}function x6(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function m6(Z){return Z.filter(x6).length}function i9(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function l8(Z,$,J,X,z){let G;try{G=await Z(b8,{method:"POST",headers:{...R6($,I6,J),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:X}),signal:AbortSignal.timeout(k8)})}catch(W){return{kind:"ambiguous",raw:W}}let B;try{B=await G.text()}catch(W){return G.ok?{kind:"ambiguous",raw:W}:{kind:"http_error",raw:W,status:G.status}}let Q=B,Y=!1;try{Q=JSON.parse(B),Y=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Q,status:G.status};if(!Y||!I5(Q)||!i9(Q.code))return{kind:"ambiguous",raw:Q};return{kind:Q.code,raw:Q}}function O6(Z){if(Z.kind==="cooldown")throw new ZZ("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function A6(){throw new ZZ("expired_unreconciled","the previous reset attempt outcome is unknown")}function S6(Z,$){return{target:Z,selectedCredit:void 0,beforeState:$,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function d8(Z){if(Z.kind==="reset"||Z.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if(Z.kind==="nothing_to_reset"||Z.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(S5(Z))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 c8(Z,$){if(Z)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($)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 w6(Z,$){if(!RZ($.accountKey))throw new ZZ("invalid_account_key","the reset account key is reserved");let J=await Z.resolveTarget($.accountKey);if(J.chatgptAccountId!==$.expectedChatgptAccountId)throw new ZZ("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=J.chatgptAccountId,z=J.accountKey==="main"?void 0:X,G=await f8(Z,$.accountKey);if(G.kind==="corrupt"){if(G=await x8(Z,$.accountKey),G.kind==="corrupt")return S6(J,G.beforeState)}if(G.kind==="cooldown")O6(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&($.retry||!y6(G.claim.inFlight,X))){if(!$.retry)A6();B=G.claim}else{if($.retry)throw new ZZ("retry_without_inflight","there is no active reset credit redemption to retry");let[j,F]=await Promise.all([Z.fetchUsage(J),n9(Z.fetchImpl,J.accessToken,z)]),U=a9(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!U.ok)throw new ZZ("not_exhausted",U.reason);if(!E5(F.credits))throw new ZZ("no_eligible_credit","no eligible reset credit was returned");let q=await m8(Z,$.accountKey,F.credits,X);if(q.kind==="corrupt")return S6(J,q.beforeState);if(q.kind==="cooldown")O6(q);if(q.kind==="expired_unreconciled")A6();if(q.kind!=="claim")throw new ZZ("no_eligible_credit","no eligible reset credit was available while claiming");B=q.claim}h8(B.inFlight,X);let Q=await l8(Z.fetchImpl,J.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),Y,W=!1;try{Y=await w8(Z,$.accountKey,B.inFlight,Q,X)}catch{W=!0}let H=W&&i9(Q.kind),V=S5(Q)&&!W&&Y?.rejectedStatus!==void 0;return{target:J,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:Q,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":S5(Q)&&!V?c8(W,Y):d8(Q),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function u6(Z){let $=[];for(let J of Z)try{$.push(...await J.run())}catch(X){$.push({code:"doctor-check-failed",message:`Check ${J.id} failed: ${X instanceof Error?X.message:String(X)}`})}return{findings:$}}function p6(Z,$){let J=[Z];if($.findings.length===0)return J.push("No problems found."),J;for(let X of $.findings){let z=X.repair?" (repair available)":"";J.push(`- ${X.message}${z}`)}return J}async function l6(Z,$){let J={applied:[],declined:[],failed:[]};for(let X of $.findings){let z=X.repair;if(!z)continue;if(!await Z.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}),Z.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return J}function r9(Z){let $=Z.title??"Auth doctor";return{id:"doctor",label:Z.label??"Auth doctor",hint:"check accounts and offer repairs",async run(J){let X=await u6(Z.checks);for(let B of p6($,X))J.print(B);let z=X.findings.filter((B)=>B.repair);if(z.length===0){if(X.findings.length>0)J.print("No repairs are available.");return}let G=await l6(J,X);J.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as s8}from"node:child_process";function c6(Z,$=process.platform,J=s8){try{if($==="win32"){let z=`Start-Process '${Z.replaceAll("'","''")}'`,G=J("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($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore"});return X.on("error",()=>{}),X.unref(),X.pid!==void 0}catch{return!1}}function d6(Z,$){if(Z.print(""),Z.print("Open this URL in your browser and complete sign-in:"),Z.print(""),Z.print($.url),Z.print(""),$.instructions)Z.print($.instructions),Z.print("")}async function b5(Z,$){let J=new AbortController,X=await Z.begin({headless:!1,signal:J.signal});X.completion.catch(()=>{}),d6($,X);let z=!1;try{z=await(Z.openBrowser??c6)(X.url)!==!1}catch{z=!1}if(!z)J.abort(),$.print("Could not open a browser. Switching to device authorization."),$.print(""),X=await Z.begin({headless:!0}),d6($,X);return X.completion}var S={hide:"\x1B[?25l",show:"\x1B[?25h",up:(Z=1)=>`\x1B[${Z}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 o9(Z){let $=Z.toString(),J=[];for(let X=0;X<$.length;){let z=$[X];if(z==="\x1B"){let G=$.slice(X,X+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let Y={A:"up",B:"down",C:"right",D:"left"}[B];if(Y)J.push(Y);X+=3}else if(X+1===$.length){if(X===0)J.push("escape-start");X+=1}else if(($[X+1]==="["||$[X+1]==="O")&&X+2>=$.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 s6=`${String.fromCharCode(27)}\\[[0-9;]*m`,a8=new RegExp(s6,"g"),n8=new RegExp(`^${s6}`);function a6(Z){return Z.replace(a8,"")}function cZ(Z,$){if($<=0)return"";if(a6(Z).length<=$)return Z;let J=$>=3?"...":".".repeat($),X=Math.max(0,$-J.length),z="",G=0,B=0;while(G<Z.length&&B<X){if(Z[G]==="\x1B"){let Q=Z.slice(G).match(n8);if(Q){z+=Q[0],G+=Q[0].length;continue}}z+=Z[G],G+=1,B+=1}return z.includes("\x1B[")?`${z}${S.reset}${J}`:z+J}function t9(){return{input:process.stdin,output:process.stdout,signals:process}}function sZ(Z){return Z.input.isTTY===!0}function e9(Z,$=""){Z.output.write(`${$}
|
|
4
4
|
`)}var i8=50;function r8(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function B1(Z,$,J){if(!sZ(Z))throw Error("Interactive select requires a TTY terminal");if($.length===0)throw Error("No menu items provided");let{input:X,output:z,signals:G}=Z,B=0,Q=null,Y=!1,W=0,H=()=>{let V=z.columns??80,j=z.rows??24,F=W;if(J.clearScreen)z.write(S.clearScreen+S.moveTo(1,1));else if(F>0)z.write(S.up(F));let U=0,q=(T)=>{z.write(`${S.clearLine}${T}
|