@cortexkit/opencode-openai-auth 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{codex-request-BjGT9yWg.d.ts → codex-request-D_In8uaR.d.ts} +43 -26
  3. package/dist/{index-gmmakhbt.js → index-1qxz4s8a.js} +2 -2
  4. package/dist/{index-2rw81dtm.js → index-79y7w9bz.js} +1 -1
  5. package/dist/{index-2yszc75z.js → index-7nmdsmpp.js} +2 -2
  6. package/dist/{index-3y453wg4.js → index-8xq099qf.js} +2 -2
  7. package/dist/index-agaatt62.js +65 -0
  8. package/dist/{index-mhfja8yr.js → index-b0ty9qam.js} +2 -2
  9. package/dist/index-ge60xry3.js +90 -0
  10. package/dist/{index-krcqvyqf.js → index-jkpg9d1p.js} +1 -1
  11. package/dist/index-k5anexvs.js +69 -0
  12. package/dist/{index-e416r885.js → index-rf0ht3gc.js} +2 -2
  13. package/dist/{index-4w0nsq5s.js → index-x9nffaye.js} +1 -1
  14. package/dist/{index-7vkn2e46.js → index-ya9c5e4m.js} +1 -1
  15. package/dist/{index-djnfq652.js → index-z8bptbrk.js} +2 -2
  16. package/dist/index.d.ts +2 -2
  17. package/dist/index.js +1 -1
  18. package/dist/{model-BMq5SCUB.d.ts → model-D22uj0OB.d.ts} +1 -1
  19. package/dist/{port-file-CjMFUWcX.d.ts → port-file-8ElfwDcq.d.ts} +1 -1
  20. package/dist/{protocol-BC3ndToM.d.ts → protocol-CK9guiFy.d.ts} +1 -1
  21. package/dist/rpc/port-file.d.ts +1 -1
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/protocol.d.ts +1 -1
  24. package/dist/rpc/protocol.js +1 -1
  25. package/dist/rpc/rpc-client.d.ts +3 -3
  26. package/dist/rpc/rpc-client.js +1 -1
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{sidebar-state-DfYyqiOH.d.ts → sidebar-state-Bb9L9oPq.d.ts} +4 -4
  29. package/dist/sidebar-state.d.ts +1 -1
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/token-util-nyvn9866.js +1 -0
  32. package/dist/{token-ycw7dyev.js → token-xtq3457d.js} +1 -1
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +2 -2
  35. package/dist/v2/server.d.ts +2 -2
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +2 -2
  38. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +4 -54
  39. package/src/tui-compiled/raw/shared/a62a27a204266acd-attribution.js +39 -25
  40. package/src/tui-compiled/raw/shared/a910277ac43a8626-pull.js +3 -1
  41. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +18 -3
  42. package/src/tui-compiled/raw/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
  43. package/src/tui-compiled/raw/shared/e1c5e56df0ba4053-pending.js +48 -0
  44. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +4 -54
  45. package/src/tui-compiled/runtime/shared/a62a27a204266acd-attribution.js +39 -25
  46. package/src/tui-compiled/runtime/shared/a910277ac43a8626-pull.js +3 -1
  47. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +18 -3
  48. package/src/tui-compiled/runtime/shared/c911dbb64c9d85c7-quota-writer.js +298 -0
  49. package/src/tui-compiled/runtime/shared/e1c5e56df0ba4053-pending.js +48 -0
  50. package/dist/index-2p3gcjsa.js +0 -69
  51. package/dist/index-6fdmqk6p.js +0 -90
  52. package/dist/index-fztcacjr.js +0 -65
  53. package/dist/token-util-ed4az5gg.js +0 -1
@@ -0,0 +1,69 @@
1
+ import{Ac as L3,Bc as m5,Bd as e7,Cd as _Z,Dc as H3,Ec as j1,Ed as LZ,Fc as Z7,Fd as P1,Gc as q1,Hc as w5,Hd as C3,Ic as u5,Jc as p5,Jd as Z8,Lc as A7,Mc as S7,Oc as E7,Pc as AZ,Pd as PZ,Qc as I7,Rc as D7,Sc as F7,Ud as N7,Wc as X3,Wd as M7,Xc as J3,Xd as K7,Zd as $8,_d as X8,ae as $3,de as $7,hd as r5,kd as o5,ld as t5,md as e5,nd as Z6,od as $6,pd as X6,qd as J6,rd as G6,sd as z6,td as B6,ud as TZ,xd as FZ,yc as A1,zc as R7,zd as t7}from"./index-ge60xry3.js";import{pe as i4,qe as y1,re as r4,se as g3,te as E1,ue as fZ,ve as o4}from"./index-8xq099qf.js";import{Ke as E5,Oe as i,Pe as _7,Re as h7,Se as g7,Te as D1}from"./index-b0ty9qam.js";import{We as a4,af as n4}from"./index-7nmdsmpp.js";class E 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 kZ 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 w1="identity-contradicted: ",O3="duplicate-identity";function C1(Z,$,X){let J=Z.rosterRow($);if(!J)return;J.enabled=!1;let G=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},z=typeof G.disabledReason==="string"&&G.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...G,disabledReason:z?G.disabledReason:X})}function JZ(Z,$){let X=Z.rosterRow($);if(!X)return;X.enabled=!0;let J=Z.entry($);if(J&&"disabledReason"in J){let G={...J};delete G.disabledReason,Z.setEntry($,G)}}function u1(Z,$){let X=Z.rows().filter((G)=>G.invalid===void 0&&!G.staged&&G.type==="oauth"&&G.enabled&&G.identity===$),J=[];for(let G of X.slice(1))C1(Z,G.id,"duplicate-identity"),J.push(G.id);return J}function R1(Z,$,X){let J=Z.rosterRow($);if(!J)return[];return J.accountId=X,u1(Z,X)}import{setTimeout as R8}from"node:timers/promises";import{AsyncLocalStorage as U8}from"node:async_hooks";var b4=new U8;function u(Z){if(b4.getStore()!==void 0)throw new kZ(Z)}function Y1(Z,$){return b4.run(Z,async()=>await $())}async function y4(Z,$,X,J,G){if(!$)return;try{await Y1(Z,()=>$(X,J))}catch(z){G?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:X,error:z instanceof Error?z.message:String(z)})}}var A3=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function V8(Z,$,X){let J=(B)=>{try{let W=X.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(W&&(typeof W==="object"||typeof W==="function")&&"then"in W&&typeof W.then==="function")Promise.resolve(W).catch(()=>{})}catch{}},G={...$,...j8(Z)},z=performance.now();for(;;){let B=await E1({name:Z.name,path:Z.path,ttlMs:G.ttlMs,renew:G.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(Q)=>X.onRenewalTimer?.({name:Z.name,path:Z.path},Q)}:{},...G.renewIntervalMs!==void 0?{renewIntervalMs:G.renewIntervalMs}:{},...X.onLockStep?{onStep:(Q)=>X.onLockStep?.({name:Z.name,path:Z.path},Q)}:{}});if(B){J("acquired");let Q={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),J("released")}};try{await Q.assertOwned()}catch(H){throw await Q.release(),H}return Q}let W=G.timeoutMs-(performance.now()-z);if(W<=0)throw new fZ({target:Z.path,name:Z.name,timeoutMs:G.timeoutMs});let Y=Math.floor(Math.random()*(G.retryMs+1));await new Promise((Q)=>setTimeout(Q,Math.min(G.retryMs+Y,W)))}}function j8(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 H1{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await V8(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 I1(Z,$,X){if(X!==void 0)throw new E({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 GZ}from"node:crypto";var y="commonAuthPool",_1=1,X1="rows",hZ="retiredEpochs",zZ=1,S3=300000,I=y;function q8(Z){let $=JSON.parse(JSON.stringify(Z)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(P(J))return`{${Object.keys(J).sort().map((G)=>`${JSON.stringify(G)}:${X(J[G])}`).join(",")}}`;return JSON.stringify(J)};return X($)}function b1(Z){return GZ("sha256").update(q8(Z)).digest("hex")}function k4(Z){if(!P(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function D8(Z){if(!P(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 l="commonAuthProviderState";function P(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var F8=new Set(["__proto__","constructor","prototype"]);function p1(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(F8.has(Z))return"id is a reserved object key";return}function R3(Z){let $=typeof Z==="string"?Z.trim():"";if(!$)return!1;try{let X=new URL($);return(X.protocol==="http:"||X.protocol==="https:")&&!X.username&&!X.password}catch{return!1}}function f4(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function J1(Z){return GZ("sha256").update(f4(Z)).digest("hex")}function U1(Z){return GZ("sha256").update(`credential-stamp\x00${f4(Z)}`).digest("hex")}function N1(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 GZ("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function E3(Z,$,X,J={}){return{credentialEpoch:$,digest:U1(Z),dispatch:N1(Z),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function l1(Z,$){let X=Z?.credentialBound?Z.credentialBound($):$;return GZ("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function BZ(Z,$,X,J){if(!$||X===void 0)return;if(!P(Z)||!Object.hasOwn(Z,l))return;let G=s(Z[I]);if(!G||G.providerState===void 0||G.digest!==U1($)||G.credentialEpoch!==X||G.binding?.identity!==J)return;return G.providerState}function m(Z){return Number.isSafeInteger(Z)&&Z>=1}function s(Z){if(!P(Z))return;let $=Z.credentialEpoch;if(!m($))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 X="staged"in Z?D8(Z.staged):void 0;if("staged"in Z&&!X)return;let J={...X?{staged:X}:{},...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 G=Z.binding;if(!P(G))return;if("identity"in G&&(typeof G.identity!=="string"||!G.identity))return;if("baseURL"in G&&!R3(G.baseURL))return;if("authHeader"in G&&G.authHeader!=="authorization-bearer"&&G.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.digest,...J,binding:{...typeof G.identity==="string"?{identity:G.identity}:{},...typeof G.baseURL==="string"?{baseURL:G.baseURL.trim()}:{},...G.authHeader==="authorization-bearer"||G.authHeader==="x-api-key"?{authHeader:G.authHeader}:{}}}}function N8(Z,$,X){if(Z.identity!==X)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 M8(Z,$,X,J){if(!Z)return"none";if(!P(J)||!Object.hasOwn(J,I))return"missing";let G=s(J[I]);if(!G)return"malformed";if(G.digest!==U1(Z))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==$)return"mismatched";if(!G.binding||!N8(G.binding,Z,X))return"mismatched";if(G.dispatch!==N1(Z))return"mismatched";return"bound"}function h4(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(!P($))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 X=$[y];if(!P(X))return{status:"error",reason:`${y} is not an object`};let J=X.schemaVersion;if(typeof J!=="number"||!Number.isInteger(J)||J<1)return{status:"error",reason:`${y}.schemaVersion is invalid`};if(J>_1)return{status:"error",reason:`${y}.schemaVersion ${J} is newer than ${_1}`};if(X1 in X&&!P(X[X1]))return{status:"error",reason:`${y}.${X1} is not an object`};return{status:"ready",exists:!0,config:$}}function g4(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(!P(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!P(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function d1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function v4(Z){let $=Z[y];if(!P($))return{};let X=$[X1];return P(X)?X:{}}function K8(Z){return P(Z.accounts)?Z.accounts:{}}function P8(Z){if(!P(Z))return"not an object";let $=p1(Z.id);if($)return $;if(Z.type==="api")return R3(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function L8(Z,$){if(!P(Z))return;let X=Z.credentialEpoch;if(!m(X))return;if("needsFirstReading"in Z&&typeof Z.needsFirstReading!=="boolean")return;if("disabledReason"in Z&&typeof Z.disabledReason!=="string")return;let J="quota"in Z&&$.decode?$.decode(Z.quota):Z.quota;if("quota"in Z&&!$.validate(J))return;if("staged"in Z&&!k4(Z.staged))return;return{credentialEpoch:X,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:J}:{}}}function C8(Z,$){if(!P($))return;if(Z.type==="api"){let J=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!J)return;return{type:"api",apiKey:J,baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}if(Z.corrupt===!0)return;let X=$.refresh;if(typeof X!=="string"||!X.trim())return;return{type:"oauth",refresh:X,...typeof $.access==="string"?{access:$.access}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.lastRefreshedAt==="number"?{lastRefreshedAt:$.lastRefreshedAt}:{}}}function gZ(Z,$){return d1(Z).find((X)=>P(X)&&X.id===$)}function x4(Z){if(!P(Z[y]))Z[y]={};return Z[y]}function I3(Z){let $=x4(Z);if(!P($[X1]))$[X1]={};return $[X1]}function V1(Z,$){let X=v4(Z),J=Object.hasOwn(X,$)?X[$]:void 0;return P(J)?J:void 0}function vZ(Z,$,X){Object.defineProperty(I3(Z),$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function m4(Z,$){let X=Z[y];if(!P(X))return;let J=X[hZ];if(!P(J)||!Object.hasOwn(J,$))return;let G=J[$];return m(G)?G:void 0}function w4(Z,$){let X=V1(Z,$)?.credentialEpoch;return m(X)?X:void 0}function xZ(Z,$){return Math.max(m4(Z,$)??0,w4(Z,$)??0)+1}function u4(Z,$){let X=[...$];if(X.length===0)return;let J=x4(Z),G=P(J[hZ])?J[hZ]:{},z={},B=(W,Y)=>Object.defineProperty(z,W,{value:Y,enumerable:!0,writable:!0,configurable:!0});for(let[W,Y]of Object.entries(G))if(m(Y))B(W,Y);for(let W of X)B(W,Math.max(m4(Z,W)??0,w4(Z,W)??1));J[hZ]=z}function T1(Z,$,X,J){let G=v4(Z),z=K8($),B=new Set,W=[];for(let Y of d1(Z)){let Q=P8(Y),H=P(Y)&&typeof Y.id==="string"?Y.id:void 0,U=H===void 0?void 0:G[H],j=P(U)&&Object.hasOwn(U,"staged"),D=j?k4(U.staged):void 0;if(Q||!P(Y)||H===void 0||B.has(H)){if(H!==void 0&&!B.has(H))B.add(H);if(H!==void 0)W.push({id:H,type:P(Y)&&Y.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(G,H),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}B.add(H);let V=Y.type==="api"?"api":"oauth",q=Object.hasOwn(G,H),F=q?L8(G[H],X):void 0,N=C8(Y,z[H]),L=Y.enabled!==!1,O=F?F.credentialEpoch:q?void 0:1,_=typeof Y.accountId==="string"&&Y.accountId?Y.accountId:void 0,M={id:H,type:V,enabled:L,needsFirstReading:F?F.needsFirstReading:V==="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:J1(N)}:{},...F?{credentialEpoch:F.credentialEpoch}:{},...D?{staged:D}:{},...F?.disabledReason!==void 0?{disabledReason:F.disabledReason}:{},...F&&"quota"in F?{quota:F.quota}:{},..._8(z[H],N,O,_,J),stamp:M8(N,O,_,z[H])};if(q&&!F)M.invalid="entry";else M.candidate=L&&N!==void 0&&!j;W.push(M)}return W}function _8(Z,$,X,J,G){if(!P(Z)||!Object.hasOwn(Z,l))return{};let z=BZ(Z,$,X,J);if(z===void 0)return{providerStateDropped:"uncovered"};let B=Z[l];if(!G?.validate(B))return{providerStateDropped:"invalid"};if(l1(G,B)!==z)return{providerStateDropped:"uncovered"};return{providerState:B}}function k(Z){return Z.identity??Z.id}function QZ(Z,$){if(Z===void 0||Z>$+S3)return $;return Math.max($,Z+1)}function b3(Z,$){return QZ(Z,$)>$+S3}function c1(Z){let{id:$,credential:X,identity:J,label:G,addedAt:z}=Z;return{id:$,...G!==void 0?{label:G}:{},type:X.type,addedAt:z,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function p4(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 l4(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function d4(Z,$={}){if(!P(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)&&!R3(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var mZ="transition",c4="transitionMark";function T8(Z){if(!P(Z))return;let $=Z[mZ];if(!P($))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 WZ(Z,$,X){if(X.enabled)JZ(Z,$);else C1(Z,$,X.reason??"");if(!Z.rosterRow($))return;let J=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...J,[c4]:X.mark}),!X.enabled)return;let G=Z.rows().find((z)=>z.id===$);if(G?.type==="oauth"&&G.identity!==void 0)u1(Z,G.identity)}function O8(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function A8(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function S8(Z,$,X,J={}){let G=P($.accounts)?$.accounts:{},z=new Map;for(let B of T1(Z,$,X)){if(B.invalid||B.staged||!B.credential)continue;let W=Object.hasOwn(G,B.id)?G[B.id]:void 0;if(!P(W))continue;let Y=s(W[I]);if(!Y?.binding)continue;if(Y.digest!==U1(B.credential))continue;let Q=B.credentialEpoch??1;if(Y.credentialEpoch>Q){if(!A8(Y))continue;if(J.requireCredentialStamps){if(Y.dispatch===void 0)continue;if(Y.dispatch!==N1(O8(B.credential,Y.binding)))continue}z.set(B.id,{kind:"replace",stamp:{...Y,binding:Y.binding}})}else if(Y.credentialEpoch===Q&&Y.dispatch!==void 0&&Y.dispatch===N1(B.credential)&&Y.binding.identity!==void 0&&B.identity===void 0)z.set(B.id,{kind:"identity",identity:Y.binding.identity});else if(Y.credentialEpoch===Q&&Y.binding.identity===B.identity){if(J.requireCredentialStamps&&Y.dispatch!==N1(B.credential))continue;let H=T8(W[I]);if(H&&V1(Z,B.id)?.[c4]!==H.mark)z.set(B.id,{kind:"transition",transition:H})}}return z}function y3(Z,$,X,J){let z={...Z.entry($)??{},credentialEpoch:X,needsFirstReading:!0};if(delete z.quota,J.identity!==void 0&&typeof z.disabledReason==="string"&&z.disabledReason.startsWith(w1))delete z.disabledReason;Z.setEntry($,z);let B=Z.rosterRow($);if(!B)return;if(J.identity!==void 0)B.accountId=J.identity;else delete B.accountId;if(J.baseURL!==void 0)B.baseURL=J.baseURL;if(J.authHeader!==void 0)B.authHeader=J.authHeader}function k3(Z,$,X,J={}){let G=S8(Z,$,X,J);if(G.size===0)return{config:Z,torn:[]};let z=structuredClone(Z),B={rows:()=>T1(z,$,X),rosterRow:(W)=>gZ(z,W),entry:(W)=>V1(z,W),setEntry:(W,Y)=>vZ(z,W,Y)};for(let[W,Y]of G)if(Y.kind==="replace")y3(B,W,Y.stamp.credentialEpoch,Y.stamp.binding);for(let[W,Y]of G)if(Y.kind==="identity")R1(B,W,Y.identity);else if(Y.kind==="transition")WZ(B,W,Y.transition);else if(Y.stamp.binding.identity!==void 0)u1(B,Y.stamp.binding.identity);return{config:z,torn:[...G.keys()]}}function f3(Z,$,X,J={}){let{config:G,torn:z}=k3(Z,$,X,J),B=T1(G,$,X,J.providerState);for(let W of B){if(z.includes(W.id))W.torn=!0,W.candidate=!1;if(J.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return B}async function h3(Z){try{return await n4(Z,a4)}catch($){if($.code==="ENOENT")return;throw $}}function s4(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function d(Z){for(let $=0;$<3;$++){let X=await h3(Z.configPath),J=await h3(Z.statePath),G=await h3(Z.configPath);if(X!==G){if($<2)await R8(2+Math.floor(Math.random()*4));continue}let z=h4(s4(X));if(z.status==="error")return{status:"error",file:"config",reason:z.reason};let B=g4(s4(J));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(z.status==="pending-migration")return{status:"pending-migration",config:z.config};return{status:"ready",configExists:z.exists,stateExists:B.exists,config:z.config,state:B.state,rows:f3(z.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 G1(Z,$,X,J="before-first-write"){if(Z.status==="error"&&Z.kind==="snapshot-contended")return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:J,kind:"snapshot-contended",retryable:!0,message:Z.reason});return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:J,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 t4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,X,J,G){this.ctx=Z,this.snapshot=$,this.locks=X,this.progress=J,this.info=G,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return f3(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 X=this.entry(Z);return X&&Object.hasOwn(X,"staged")?X.staged:void 0}let $=this.stateAccount(Z)?.[I];return P($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){I1(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(),gZ(this.config,Z)}dropRosterRows(Z){let $=this.roster(),X=$.filter((J)=>!(P(J)&&J.id===Z));return this.config.accounts=X,$.length-X.length}entries(){return I3(this.config)}entry(Z){return this.entries(),V1(this.config,Z)}setEntry(Z,$){vZ(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=k3(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 $=P(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn($,Z)?$[Z]:void 0;return P(X)?X:void 0}dropStateAccount(Z){if(P(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!P(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(),X=new Set;for(let Y of $)if(P(Y)&&typeof Y.id==="string")X.add(Y.id);let J=new Set;for(let Y of d1(this.snapshot.config))if(P(Y)&&typeof Y.id==="string"&&!X.has(Y.id))J.add(Y.id);for(let Y of Object.keys(this.entries()))if(!X.has(Y))J.add(Y);u4(this.config,J);let G=this.entries(),z={};for(let[Y,Q]of Object.entries(G))if(X.has(Y))Object.defineProperty(z,Y,{value:Q,enumerable:!0,writable:!0,configurable:!0});let B=this.config[y],W={...this.config,version:zZ,accounts:$,[y]:{...B,schemaVersion:_1,[X1]:z}};await this.write(this.ctx.configPath,W,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let Y of J)this.ctx.removedIds.add(Y);this.config=W}),this.config=W}async commitState(Z,$={}){let X={...this.state,version:zZ,accounts:P(this.state.accounts)?this.state.accounts:{}};if(await this.write(this.ctx.statePath,X,"state",!0,$.durable??!1),this.state=X,Z)this.progress.committed=Z}async assertAll(){await this.locks.assertAll()}async syncState(){await this.assertAll();try{if(this.snapshot.stateExists)await g3(this.ctx.statePath)}catch(Z){throw new E({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 g3(this.ctx.configPath)}async write(Z,$,X,J=!0,G=!1,z){await r4(Z,$,{durable:G,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;z?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function e4(Z,$){let X=new H1(Z.lockDefaults,Z.lockEnv),J={writes:0};try{for(let W of Z.storeLocks)await X.acquire(W);let G=await d(Z);if(G.status==="error")throw G1(G,"initialize",void 0);if(G.status==="ready")return"already-ready";let z={};for(let[W,Y]of Object.entries(G.config))if(!$.includes(W))z[W]=Y;z.version=zZ,z[y]={schemaVersion:_1,[X1]:{}};let B={operation:"initialize",rowId:void 0};return await y1(Z.configPath,z,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await X.assertAll()}}),J.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(G){throw O1(G,"initialize",void 0,J)}finally{await X.releaseAll()}}async function g(Z,$,X,J,G,z={}){let B=$.held.length;try{for(let Q of Z.storeLocks)await $.acquire(Q);let W=await d(Z);if(W.status!=="ready")throw G1(W,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let Y=new t4(Z,W,$,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))Y.assertNotStaged(J.rowId);if(z.completeTorn??!0)await Y.completeTorn();return await G(Y)}finally{await $.releaseTo(B)}}function O1(Z,$,X,J){let G=$==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",z=G==="after-first-write"?J.committed:void 0;if($==="publishRoster"&&J.publicationDecided)return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:G,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 i4)return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:G,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:Z});if(Z instanceof E){if(Z.phase===G&&Z.rowId===X&&Z.operation===$&&Z.committed===z)return Z;return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:Z.kind==="after-persist-hook"?Z.phase:G,retryable:Z.retryable,kind:Z.kind,...Z.committed??z?{committed:Z.committed??z}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let B={operation:$,...X!==void 0?{rowId:X}:{},phase:G,...z?{committed:z}:{},cause:Z};if(Z instanceof o4)return new E({...B,retryable:!0,kind:"lock-ownership",message:G==="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 fZ)return new E({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new E({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function p(Z,$,X,J,G){let z=new H1(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await G(z,B)}catch(W){let Y=O1(W,$,X,B);if(Y.kind!=="after-persist-hook")await y4($,J,X,Y,Z.logger);throw Y}finally{await z.releaseAll()}}function n(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(k($))}`,path:Z.ctx.statePath}}async function z1(Z,$,X){let J=await d(Z.ctx);if(J.status!=="ready")throw G1(J,$,X);let G=J.rows.find((Q)=>Q.id===X),z=V1(J.config,X),B=J.state.accounts,W=P(B)&&Object.hasOwn(B,X)?B[X]:void 0,Y=P(W)?W[I]:void 0;if(G&&!["enable","disable"].includes($)&&z&&Object.hasOwn(z,"staged"))I1($,X,z.staged);if(!G&&P(Y)&&Object.hasOwn(Y,"staged"))I1($,X,Y.staged);if(!G)throw r($,X);return{result:J,row:G}}function r(Z,$){return new E({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 K(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 K(Z,$,X,J,G=!1){return new E({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:G,kind:X,message:J})}function v3(Z,$){if(!m($?.credentialEpoch))throw K("pull",Z,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer")}function YZ(Z,$,X){if(!X)throw r("pull",Z);if(X.invalid)throw K("pull",Z,"invalid-row",`row ${Z} is invalid`);if(!X.credential)throw K("pull",Z,"no-credential",`row ${Z} holds no credential`);if(c("pull",X),X.torn||!X.hasEntry||X.credentialEpoch!==$.credentialEpoch||X.identity!==$.identity)throw new E({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 HZ(Z,$,X,J){let G=Z.codec.merge(X,J);if(!Z.codec.validate(G))throw K("pull",$,"invalid-quota","the quota codec rejected the merged map");return G}async function wZ(Z,$,X,J){let{ctx:G}=Z,z=new H1(G.lockDefaults,G.lockEnv),B={writes:0};try{v3($,X),await g(G,z,B,{operation:"pull",rowId:$},async(W)=>{W.assertNotStaged($);let Y=W.row($);YZ($,X,Y);let Q=W.entry($);if(!Q)throw r("pull",$);let H=HZ(G,$,Q.quota,J);W.setEntry($,{...Q,quota:H,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw O1(W,"pull",$,B)}finally{await z.releaseAll()}}function M1(Z,$,X,J,G="the provider state"){if(!Z)throw K($,X,"invalid-input","the store was opened without a provider-state codec");let z;try{let B=JSON.stringify(J);z=B===void 0?void 0:JSON.parse(B)}catch{z=void 0}if(z===void 0)throw K($,X,"invalid-provider-state",`${G} cannot be stored as JSON`);if(!Z.validate(z))throw K($,X,"invalid-provider-state",`the provider-state codec rejected ${G}`);return z}function UZ(Z,$,X,J,G){if(J===void 0||!Z?.merge)return{kind:"set",value:G};return{kind:"set",value:M1(Z,$,X,Z.merge(structuredClone(J),structuredClone(G)),"the merged provider state")}}function Z5(Z,$,X,J,G){let z=Z?.onReplace,B=z?z($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:X,...$.identity!==void 0?{previousIdentity:$.identity}:{},...J!==void 0?{identity:J}:{},...G!==void 0?{incoming:structuredClone(G)}:{}}):G;if(B===void 0)return{kind:"clear"};if(!z)return{kind:"set",value:B};return{kind:"set",value:M1(Z,"replace",$.id,B,"the provider state onReplace returned")}}function $5(Z,$,X,J,G){if($.kind==="set")return l1(Z,$.value);if($.kind==="clear")return;return BZ(X,J?.credential,G,J?.identity)}async function X5(Z,$,X,J,G={}){u("updateProviderState");let{ctx:z}=Z,B="updateProviderState";return p(z,B,$,G.onFailure,async(W,Y)=>{let Q=z.providerState;if(!Q)throw K(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw K(B,$,"invalid-input","a mutator is required");let H=P(X)?X.credentialEpoch:void 0;if(!m(H))throw K(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:U}=await z1(Z,B,$);await W.acquire(n(Z,U));for(let j of G.extraLocks??[])await W.acquire(j);return g(z,W,Y,{operation:B,rowId:$},async(j)=>{let D=j.row($);if(!D)throw r(B,$);if(k(D)!==k(U))throw K(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(D.invalid)throw K(B,$,"invalid-row",`row ${$} failed validation`);if(!D.credential)throw K(B,$,"no-credential",`row ${$} holds no credential`);if(c(B,D),(D.credentialEpoch??1)!==H||D.identity!==X.identity)throw K(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await x3(j,Q,B,D,J);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 J5=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function x3(Z,$,X,J,G,z=!1){let{id:B,credential:W}=J;if(!W)throw K(X,B,"no-credential",`row ${B} holds no credential`);let Y=J.credentialEpoch??1,Q=Z.stateAccount(B),H=Q?.[I],U=s(H);if(!P(H)||!U?.binding||U.digest!==U1(W)||U.credentialEpoch!==Y||U.binding.identity!==J.identity)throw K(X,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let j=J.providerState===void 0?void 0:structuredClone(J.providerState),D=await Y1(X,()=>G(j,J));if(z&&D===J5)return{kind:"declined"};let V=D===void 0?void 0:M1($,X,B,D,"the provider state the mutator returned"),q=Q!==void 0&&Object.hasOwn(Q,l);if(V===void 0?!q:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(V))return{kind:"unchanged",...V!==void 0?{value:V}:{}};let F={...Q};if(V===void 0){delete F[l];let N={...H};delete N.providerState,F[I]=N}else{F[l]=V;let N=l1($,V);if(U.providerState!==N)F[I]={...H,providerState:N}}return{kind:"changed",...V!==void 0?{value:V}:{},account:F}}import{randomUUID as G5}from"node:crypto";async function dZ(Z,$,X){if(!X)return;let J=Z.rows().map((z)=>{let{id:B,type:W,label:Y,enabled:Q,disabledReason:H,identity:U,credentialEpoch:j,stamp:D,staged:V,torn:q,invalid:F}=z;return{id:B,type:W,label:Y,enabled:Q,disabledReason:H,identity:U,credentialEpoch:j,stamp:D,staged:V,torn:q,invalid:F}}),G=await Y1(Z.info.operation,()=>X({id:$,row:J.find((z)=>z.id===$),rows:J,config:structuredClone(Z.snapshot.config)}));if(G!==void 0)throw K(Z.info.operation,$,"row-protected",G)}var E8=["access","refresh","expires","lastRefreshedAt","apiKey"];function I8(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function b8(Z,$,X){if(X.type!=="api")return X;let J=Z.rosterRow($);if(!P(J)){if(X.baseURL===void 0)throw K(Z.info.operation,$,"invalid-input","api credential needs a valid baseURL");return{...X,baseURL:X.baseURL}}let G=Z.row($)?.credential,z=G?.type==="api"?{baseURL:G.baseURL.trim(),authHeader:G.authHeader??"authorization-bearer"}:I8(J),B=X.baseURL?.trim()??z.baseURL,W=X.authHeader??z.authHeader;if(B!==z.baseURL||W!==z.authHeader)throw K(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:B,authHeader:W}}function z5(Z,$,X,J){let G=Z.rosterRow($),z=Z.row($),B=J??(z?z.identity:P(G)&&typeof G.accountId==="string"&&G.accountId?G.accountId:void 0);return{...B!==void 0?{identity:B}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function uZ(Z,$,X,J,G={}){let z=b8($,X,J),B=$.stateAccount(X),W=G.providerState??{kind:"keep"},Y=$.row(X)?.credentialEpoch??$.entry(X)?.credentialEpoch,Q=typeof Y==="number"?Y:1,H=$5(Z.ctx.providerState,W,B,B&&Object.hasOwn(B,l)?$.row(X):void 0,Q),U=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=z.type==="oauth"?G.stamp??QZ(U,Z.ctx.now()):void 0,D={...B??{}};for(let F of E8)delete D[F];if(G.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(W.kind==="clear")delete D[l];else if(W.kind==="set")D[l]=W.value;let V=l4(z,j),q={...D,...p4(z,j),[I]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[mZ]:G.transition}:{},...E3(V,Q,G.binding??z5($,X,V,G.identity),{replace:G.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:V,account:q}}async function pZ(Z,$,X){return Z.setStateAccount($,X.account),await Z.commitState(X.stored),X.stored}async function cZ(Z,$,X,J,G={}){return pZ($,X,uZ(Z,$,X,J,G))}async function y8(Z,$,X){if(!$.credential||$.stamp!=="bound")return;let J=Z.stateAccount($.id),G=BZ(J,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...J??{},[I]:E3($.credential,$.credentialEpoch??1,z5(Z,$.id,$.credential,X),G!==void 0?{providerState:G}:{})}),await Z.commitState()}function w3(Z,$,X){let J=Z==="add"?p1($):void 0;if(J)throw K(Z,$,"invalid-input",J);let G=d4(X,{baseURLOptional:Z==="rotate"});if(G)throw K(Z,$,"invalid-input",G)}function sZ(Z,$,X,J){if(!X)throw r(Z,$);if(X.invalid)throw K(Z,$,"invalid-row",`row ${$} failed validation`);if(J&&J.type!==X.type)throw K(Z,$,"type-mismatch",`row ${$} holds a ${X.type} credential`);return X}function a1(Z,$,X){if(X!==void 0&&!m(P(X)?X.credentialEpoch:void 0))throw K(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function aZ(Z,$,X,J){if(!X)throw r(Z,$);if(X.invalid)throw K(Z,$,"invalid-row",`row ${$} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw K(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function lZ(Z,$){return K(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function VZ(Z,$){return K(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function k8(Z,$,X,J){let{id:G,credential:z,identity:B}=X;if(!Z.ctx.requireCredentialStamps||$.rosterRow(G)||!s1($.state,G))return;let W=()=>{throw K("add",G,"unbound-credential",`orphan ${G} cannot be bound to this add's material; remove it explicitly before adding different material`)},Y=$.stateAccount(G),Q=s(Y?.[I]);if(!Q?.binding||Q.dispatch===void 0||Q.replace)return W();if(z.type==="api"&&(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0))return W();let H=z.type==="api"?{...z,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}:z,[U]=T1({accounts:[c1({id:G,credential:H,identity:Q.binding.identity,addedAt:0})],[y]:{rows:{[G]:{credentialEpoch:xZ($.config,G)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!U?.credential||U.invalid||U.stamp!=="bound")return W();if(B!==void 0&&B!==U.identity)return W();if(U1(z)!==Q.digest)return W();if(z.type==="api"){if(z.baseURL.trim()!==Q.binding.baseURL)return W();if((z.authHeader??"authorization-bearer")!==Q.binding.authHeader)return W()}else if(N1(z)!==Q.dispatch)return W();if(Q.providerState!==void 0&&U.providerState===void 0)return W();if(J!==void 0&&l1(Z.ctx.providerState,J)!==Q.providerState)return W();return U}function f8(Z,$,X,J){let{id:G,credential:z,identity:B,label:W}=X,Y=$.rosterRow(G),Q=()=>{throw K("add",G,Y?"id-exists":"unbound-credential",`row ${G} does not match this staged add`)},H=$.stateAccount(G),U=s(H?.[I]),j=U?.staged;if(!U?.binding||!j||U.replace||U.dispatch===void 0)return Q();if(Y&&(Y.type!==z.type||Y.label!==W||Y.accountId!==B))return Q();if(j.reservation!==X.stage?.reservation||j.label!==W||j.disabledReason!==X.disabled?.reason||U.binding.identity!==B)return Q();let D=J===void 0?void 0:b1(J),V=H?.[l],q=V===void 0?void 0:b1(V);if(j.providerState!==D||j.providerState!==q)return Q();if(U1(z)!==U.digest||N1(z)!==U.dispatch)return Q();let F=Y?$.config:{accounts:[{...c1({id:G,credential:z.type==="api"?{...z,baseURL:U.binding.baseURL??"",authHeader:U.binding.authHeader}:z,identity:U.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[G]:{credentialEpoch:U.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=T1(F,$.state,Z.ctx.codec,Z.ctx.providerState).find((L)=>L.id===G);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==z.type||N.enabled||N.label!==j.label||N.identity!==U.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return Q();if(Y)return{id:G,outcome:"exists",credential:N.credential,credentialEpoch:U.credentialEpoch};if(xZ($.config,G)!==U.credentialEpoch)return Q();return $.roster().push({...c1({id:G,credential:z,identity:B,label:W,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(G,{credentialEpoch:U.credentialEpoch,needsFirstReading:z.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:G,outcome:"completed",credential:N.credential,credentialEpoch:U.credentialEpoch}))}async function B5(Z,$,X={}){u("add");let{ctx:J}=Z,{id:G,credential:z,identity:B,label:W}=$,Y=$.stage!==void 0||$.disabled!==void 0,Q=await p(J,"add",G,X.onFailure,async(H,U)=>{w3("add",G,z);let j=X.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw K("add",G,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(W!==void 0&&typeof W!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!P($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!P($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw K("add",G,"invalid-input","staging requires a reservation and a disabled reason");let D=$.providerState===void 0?void 0:M1(J.providerState,"add",G,$.providerState);if(await H.acquire(n(Z,{id:G,identity:B})),z.type==="oauth")await H.acquire(X.providerLock??Z.providerLock);for(let V of X.extraLocks??[])await H.acquire(V);return g(J,H,U,{operation:"add",rowId:G},async(V)=>{await dZ(V,G,X.protect);let q=P(V.state.accounts)?V.state.accounts:{},F=Object.entries(q).find(([b,f])=>{if(b===G||V.rosterRow(b)||!P(f))return!1;let XZ=f[I];if(!P(XZ)||!Object.hasOwn(XZ,"staged"))return!1;return z.type==="oauth"?f.refresh===z.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===z.apiKey.trim()});if(F)throw K("add",F[0],"row-staged",`orphan ${F[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(G))throw K("add",G,"id-removed",`id ${G} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(V.rosterRow(G)||s1(V.state,G)))return f8(Z,V,$,D);if(j==="rotate"){V.assertNotStaged(G);let b=V.rows().find((f)=>f.fingerprint===J1(z));if(b)V.assertNotStaged(b.id)}if(j==="refuse"){let b=V.rows().find((L1)=>L1.fingerprint===J1(z)||L1.id===G&&L1.credential),f=P(V.state.accounts)?V.state.accounts:{},XZ=Object.entries(f).find(([,L1])=>{if(!P(L1))return!1;if(z.type==="oauth")return L1.refresh===z.refresh;return typeof L1.apiKey==="string"&&L1.apiKey.trim()===z.apiKey.trim()})?.[0],I4=b?.id??XZ??G;if(b||XZ!==void 0||s1(V.state,G))throw K("add",I4,"credential-exists",`row ${I4} already holds this secret or id`)}if(j==="stage-duplicate"&&(V.rosterRow(G)||s1(V.state,G)))throw K("add",G,"id-exists",`row ${G} already exists`);let N=k8(Z,V,$,D),L=V.rows(),O=J1(z),_=j==="rotate"&&!N&&L.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(_){if(V.assertNotStaged(_.id),c("add",_),B!==void 0&&_.identity!==void 0&&B!==_.identity)throw lZ("add",_.id);let b=uZ(Z,V,_.id,z,{...D!==void 0?{providerState:UZ(J.providerState,"add",_.id,_.providerState,D)}:{}});await V.completeTorn(),V.assertNotStaged(_.id);let f=await pZ(V,_.id,b);return{id:_.id,outcome:"rotated",credential:f,credentialEpoch:_.credentialEpoch??1}}let M=L.find((b)=>b.id===G);if(M){if(M.invalid)throw K("add",G,"invalid-row",`row ${G} is invalid`);if(M.credential)throw K("add",G,"id-exists",`row ${G} already holds a credential`);if(c("add",M),M.type!==z.type)throw K("add",G,"type-mismatch",`row ${G} is a ${M.type} row`);if(B!==void 0&&M.identity!==void 0&&B!==M.identity)throw lZ("add",G);if(!M.hasEntry)V.setEntry(G,{credentialEpoch:1,needsFirstReading:z.type==="oauth"});let b=uZ(Z,V,G,z,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await V.completeTorn();let f=await pZ(V,G,b);if(!M.hasEntry)await V.commitConfig();return{id:G,outcome:"completed",credential:f,credentialEpoch:M.credentialEpoch??1}}let C=xZ(V.config,G);if(!m(C))throw K("add",G,"id-removed",`id ${G} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??B;V.roster().push(c1({id:G,credential:z,...A!==void 0?{identity:A}:{},...W!==void 0?{label:W}:{},addedAt:J.now()})),V.setEntry(G,{credentialEpoch:C,needsFirstReading:z.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let T="added";if($.disabled)C1(V,G,$.disabled.reason),T="added-disabled";if(!$.disabled&&A!==void 0&&z.type==="oauth"){if(L.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===A))C1(V,G,O3),T="added-disabled"}if(N?.credential)return await V.commitConfig(),{id:G,outcome:T,credential:N.credential,credentialEpoch:N.credentialEpoch??C};V.dropStateAccount(G);let R=uZ(Z,V,G,z,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...W!==void 0?{label:W}:{},...D!==void 0?{providerState:b1(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await V.completeTorn();let v=await pZ(V,G,R);return await V.commitConfig(),{id:G,outcome:T,credential:v,credentialEpoch:C}},{completeTorn:!1})});if(!Y&&z.type==="oauth"&&(Q.outcome==="added"||Q.outcome==="completed"))Z.firePull(Q.id,"add");return Q}async function Q5(Z,$,X,J={},G={}){u("replace");let{ctx:z}=Z,B=await p(z,"replace",$,G.onFailure,async(W,Y)=>{w3("replace",$,X),a1("replace",$,G.attribution);let Q=J.providerState===void 0?void 0:M1(z.providerState,"replace",$,J.providerState),{row:H}=await z1(Z,"replace",$);if(await W.acquire(n(Z,H)),X.type==="oauth")await W.acquire(G.providerLock??Z.providerLock);for(let U of G.extraLocks??[])await W.acquire(U);return g(z,W,Y,{operation:"replace",rowId:$},async(U)=>{if(G.attribution!==void 0)aZ("replace",$,U.row($),G.attribution),await U.completeTorn();let j=sZ("replace",$,U.row($),X);if(k(j)!==k(H))throw VZ("replace",$);let D=U.entry($)?.credentialEpoch,V=(typeof D==="number"?D:1)+1;if(!m(V))throw K("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=Z5(z.providerState,j,V,J.identity,Q),F={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(y3(U,$,V,F),J.identity!==void 0)u1(U,J.identity);let N=await cZ(Z,U,$,X,{clearErrors:!0,binding:F,providerState:q});return await U.commitConfig(),{id:$,credential:N,credentialEpoch:V}},{completeTorn:G.attribution===void 0})});if(X.type==="oauth")Z.firePull($,"replace");return B}async function W5(Z,$,X,J={},G={}){u("rotate");let{ctx:z}=Z;return p(z,"rotate",$,G.onFailure,async(B,W)=>{w3("rotate",$,X),a1("rotate",$,G.attribution);let Y=J.providerState===void 0?void 0:M1(z.providerState,"rotate",$,J.providerState),{row:Q}=await z1(Z,"rotate",$);if(await B.acquire(n(Z,Q)),J.identity!==void 0&&X.type==="oauth")await B.acquire(G.providerLock??Z.providerLock);for(let H of G.extraLocks??[])await B.acquire(H);return g(z,B,W,{operation:"rotate",rowId:$},async(H)=>{if(G.attribution!==void 0)aZ("rotate",$,H.row($),G.attribution),await H.completeTorn();let U=sZ("rotate",$,H.row($),X);if(k(U)!==k(Q))throw VZ("rotate",$);if(c("rotate",U),J.identity!==void 0&&U.identity!==void 0&&J.identity!==U.identity)throw lZ("rotate",$);let j=J.identity!==void 0&&U.identity===void 0?J.identity:void 0,D=await cZ(Z,H,$,X,{identity:j,...Y!==void 0?{providerState:UZ(z.providerState,"rotate",$,U.providerState,Y)}:{}}),V=!1;if(!U.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:U.type==="oauth"}),V=!0;if(J.identity!==void 0&&U.identity!==J.identity)R1(H,$,J.identity),V=!0;if(V)await H.commitConfig();return{id:$,credential:D}},{completeTorn:G.attribution===void 0})})}async function Y5(Z,$,X,J,G){u($);let{ctx:z}=Z,B=z.providerState,W=G.attribution,Y=G.providerState;return p(z,$,X,G.onFailure,async(Q,H)=>{if(a1($,X,W),Y!==void 0){if(typeof Y!=="function")throw K($,X,"invalid-input","the provider-state mutator must be a function");if(W===void 0)throw K($,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw K($,X,"invalid-input","the store was opened without a provider-state codec")}let{row:U}=await z1(Z,$,X);await Q.acquire(n(Z,U));for(let j of G.extraLocks??[])await Q.acquire(j);return g(z,Q,H,{operation:$,rowId:X},async(j)=>{await dZ(j,X,G.protect),j.assertNotStaged(X);let D=j.row(X),V=J.enabled?sZ("enable",X,D):D;if(!V||!j.rosterRow(X))throw r($,X);if(k(V)!==k(U))throw VZ($,X);if(W!==void 0)aZ($,X,V,W);if(J.enabled&&V.disabledReason?.startsWith(w1))throw K("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let q=!J.enabled||!V.enabled||V.disabledReason!==void 0;if(J.enabled&&q&&V.type==="oauth"){let _=V.identity===void 0?void 0:j.rows().find((M)=>M.id!==X&&M.invalid===void 0&&M.type==="oauth"&&M.enabled&&M.identity===V.identity);if(_)throw K("enable",X,"duplicate-identity",`row ${_.id} is enabled with the same identity as row ${X}`)}if(Y===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:X};if(J.enabled)JZ(j,X);else C1(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!V.credential)throw K($,X,"no-credential",`row ${X} holds no credential`);c($,V);let F=await x3(j,B,$,V,Y,!0);if(F.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let N={id:X,providerStateOutcome:F.kind==="unchanged"?"unchanged":F.value===void 0?"cleared":"updated",...F.value!==void 0?{providerState:F.value}:{}};if(F.kind==="unchanged"){if(q){if(J.enabled)JZ(j,X);else C1(j,X,J.reason);await j.commitConfig()}return N}if(!q)return j.setStateAccount(X,F.account),await j.commitState(),N;let L=J.enabled?{mark:G5(),enabled:!0}:{mark:G5(),enabled:!1,reason:J.reason},O=F.account[I];return j.setStateAccount(X,{...F.account,[I]:{...O,[mZ]:L}}),await j.commitState(),WZ(j,X,L),await j.commitConfig(),N},{completeTorn:!1})})}function H5(Z,$,X,J={}){return Y5(Z,"disable",$,{enabled:!1,reason:X},J)}function U5(Z,$,X={}){return Y5(Z,"enable",$,{enabled:!0},X)}async function V5(Z,$,X={}){u("remove");let{ctx:J}=Z;return p(J,"remove",$,X.onFailure,async(G,z)=>{if(typeof $!=="string"||$.length===0)throw K("remove",$,"invalid-input","id must be non-empty");let B=X.attribution;if(a1("remove",$,B),X.staged!==void 0&&(!P(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw K("remove",$,"invalid-input","a staged removal needs a reservation");let W=await d(J);if(W.status!=="ready")throw G1(W,"remove",$);let Y=W.rows.find((H)=>H.id===$);if(!Y&&!s1(W.state,$))throw r("remove",$);let Q=k(Y??{id:$});await G.acquire(n(Z,Y??{id:$}));for(let H of X.extraLocks??[])await G.acquire(H);return g(J,G,z,{operation:"remove",rowId:$},async(H)=>{let U=H.reservation($);if(U!==void 0){if(!P(U)||!X.staged||U.reservation!==X.staged.reservation)throw K("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(X.staged)throw K("remove",$,"attribution",`row ${$} is no longer reserved`);let j=H.row($),D=s1(H.state,$);if(!j&&!D)throw r("remove",$);if(k(j??{id:$})!==Q)throw VZ("remove",$);if(B!==void 0)if(j)nZ($,j,B);else h8(Z,H,$,B);let V=X.protect;if(V){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await Y1("remove",()=>V($,q));if(F!==void 0)throw K("remove",$,"row-protected",F)}if(j){if(B===void 0)await H.completeTorn();H.dropRosterRows($),await H.commitConfig()}if(D)H.dropStateAccount($),await H.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function nZ(Z,$,X,J="remove"){if(aZ(J,Z,$,X),$.torn)throw K(J,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw K(J,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function h8(Z,$,X,J){let G=()=>K("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),z=$.stateAccount(X),B=s(z?.[I]);if(!z||!B?.binding||B.dispatch===void 0||B.replace)throw G();let W;if(typeof z.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw G();W={type:"api",apiKey:z.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof z.refresh==="string")W={type:"oauth",refresh:z.refresh};else throw G();let[Y]=T1({accounts:[c1({id:X,credential:W,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[X]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!Y?.credential||Y.invalid||Y.stamp!=="bound")throw G();if(B.credentialEpoch!==J.credentialEpoch||B.binding.identity!==J.identity)throw K("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function s1(Z,$){let X=Z.accounts;return P(X)&&Object.hasOwn(X,$)}function m3(Z){return P(Z)&&typeof Z.id==="string"?Z.id:void 0}function g8(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let X=new Set;for(let z of Z){let B=m3(z);if(B!==void 0)X.add(B)}let J=new Set;for(let z of $){if(typeof z!=="string")return"ids must be an array of roster ids";if(J.has(z))return`id ${z} appears more than once`;if(!X.has(z))return`id ${z} is not in the roster`;J.add(z)}let G=[...X].filter((z)=>!J.has(z));if(G.length>0)return`the order leaves out roster id(s) ${G.join(", ")}`;return}function v8(Z,$){let X=new Map;for(let z of Z){let B=m3(z);if(B===void 0)continue;let W=X.get(B);if(W)W.push(z);else X.set(B,[z])}let J=$.flatMap((z)=>X.get(z)??[]),G=0;return Z.map((z)=>m3(z)===void 0?z:J[G++])}async function j5(Z,$,X={}){u("reorder");let{ctx:J}=Z,G=X.onFailure;return p(J,"reorder",void 0,G&&((z,B)=>G(B)),async(z,B)=>{for(let W of X.extraLocks??[])await z.acquire(W);return g(J,z,B,{operation:"reorder",rowId:void 0},async(W)=>{let Y=W.roster(),Q=g8(Y,$);if(Q)throw new E({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Q});let H=[...$],U=v8(Y,H);if(U.every((j,D)=>j===Y[D]))return{ids:H,outcome:"unchanged"};return W.config.accounts=U,await W.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function q5(Z,$,X,J,G={}){return u("recordIdentity"),p(Z.ctx,"recordIdentity",$,G.onFailure,async(z,B)=>{if(typeof X!=="string"||X.length===0)throw K("recordIdentity",$,"invalid-input","identity must be non-empty");let W=P(J)?J.credentialEpoch:void 0;if(!m(W))throw K("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:Y}=await z1(Z,"recordIdentity",$);await z.acquire(n(Z,Y)),await z.acquire(G.providerLock??Z.providerLock);for(let Q of G.extraLocks??[])await z.acquire(Q);return g(Z.ctx,z,B,{operation:"recordIdentity",rowId:$},async(Q)=>{let H=sZ("recordIdentity",$,Q.row($));if(k(H)!==k(Y))throw VZ("recordIdentity",$);if(c("recordIdentity",H),(H.credentialEpoch??1)!==W)throw K("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(H.identity!==void 0&&H.identity!==X)throw lZ("recordIdentity",$);if(H.identity===void 0)await y8(Q,H,X);let U=R1(Q,$,X);return await Q.commitConfig(),{id:$,disabled:U}})})}function F5(Z){let $=Z[y];return P($)&&P($.publications)?$.publications:{}}function N5(Z,$){let X=F5(Z);if(!Object.hasOwn(X,$))return;let J=X[$];if(!P(J)||J.operationId!==$||typeof J.planDigest!=="string"||!/^[a-f0-9]{64}$/.test(J.planDigest)||!["committed","cleaned"].includes(String(J.phase))||!Array.isArray(J.removed)||!Array.isArray(J.finalized)||J.removed.some((G)=>!P(G)||typeof G.id!=="string"||!m(G.credentialEpoch))||J.finalized.some((G)=>!P(G)||typeof G.id!=="string"||!m(G.credentialEpoch)||typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"))throw K("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function M5(Z,$){let X=await d(Z.ctx);if(X.status!=="ready")throw G1(X,"publishRoster",$);return N5(X.config,$)}function x8(Z,$){let X=()=>{throw K("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!P($)||typeof $.operationId!=="string"||!$.operationId||!Array.isArray($.remove)||!Array.isArray($.finalize)||!Array.isArray($.order))X();let J=new Set;for(let G of[...$.remove,...$.finalize]){if(!P(G)||typeof G.id!=="string"||p1(G.id)||J.has(G.id)||!G.attribution)X();if(J.add(G.id),a1("publishRoster",G.id,G.attribution),G.attribution.identity!==void 0&&(typeof G.attribution.identity!=="string"||!G.attribution.identity))X()}for(let G of $.remove)if(Z.ctx.requireRemovedFingerprint&&!G.fingerprint||G.fingerprint!==void 0&&typeof G.fingerprint!=="string")X();for(let G of $.finalize)if(typeof G.reservation!=="string"||!G.reservation||typeof G.enabled!=="boolean"||(G.enabled?G.disabledReason!==void 0:typeof G.disabledReason!=="string"))X();if($.order.some((G)=>typeof G!=="string"||p1(G))||new Set($.order).size!==$.order.length)X()}function K5(Z,$){Z.entries();let X=Z.config[y],J={...F5(Z.config)};Object.defineProperty(J,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function m8(Z,$,X){let J=new Set;for(let B of d1(Z.config)){if(!P(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw K("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(B.id)}let G=new Set($.remove.map((B)=>B.id)),z=X.filter((B)=>B.invalid!=="roster"&&!G.has(B.id));if(z.length!==$.order.length||$.order.some((B)=>!z.some((W)=>W.id===B))||z.some((B)=>!$.order.includes(B.id)))throw K("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return z}async function D5(Z,$){await Z.assertAll();for(let J of $.removed)if(s(Z.stateAccount(J.id)?.[I])?.credentialEpoch===J.credentialEpoch&&!Z.rosterRow(J.id))Z.dropStateAccount(J.id);for(let J of $.finalized){let G=Z.stateAccount(J.id),z=s(G?.[I]);if(G&&z?.credentialEpoch===J.credentialEpoch&&z.staged?.reservation===J.reservation){let B={...G[I]};delete B.staged,Z.setStateAccount(J.id,{...G,[I]:B})}}await Z.commitState(void 0,{durable:!0});let X={...$,phase:"cleaned"};return K5(Z,X),await Z.commitConfig({durable:!0}),X}async function P5(Z,$,X={}){return u("publishRoster"),p(Z.ctx,"publishRoster",$?.operationId??"",X.onFailure,async(J,G)=>{if(!P($)||typeof $.operationId!=="string"||!$.operationId)throw K("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let z=b1($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((W)=>P(W)&&typeof W.id==="string");for(let W=0;;W++){let Y=await d(Z.ctx);if(Y.status!=="ready")throw G1(Y,"publishRoster",$.operationId);let Q=new Map(B.map(({id:U})=>[U,k(Y.rows.find((j)=>j.id===U)??{id:U})]));for(let U of[...new Set(Q.values())].sort())await J.acquire(n(Z,{id:U}));await J.acquire(X.providerLock??Z.providerLock);for(let U of X.extraLocks??[])await J.acquire(U);let H=await g(Z.ctx,J,G,{operation:"publishRoster",rowId:$.operationId},async(U)=>{let j=U.rows();if(B.some(({id:M})=>k(j.find((C)=>C.id===M)??{id:M})!==Q.get(M)))return;let D=N5(U.config,$.operationId);if(D){if(D.planDigest!==z)throw K("publishRoster",$.operationId,"publication-mismatch","the operation id belongs to a different publication plan");if(D.phase==="cleaned")return{outcome:"already-cleaned",receipt:D};return U.markPublicationDecision(),await U.syncConfig(),{outcome:"cleaned",receipt:await D5(U,D)}}x8(Z,$);let V=m8(U,$,j),q=[];for(let M of $.remove){U.assertNotStaged(M.id);let C=j.find((A)=>A.id===M.id);if(!C)throw K("publishRoster",M.id,"attribution","the removed row no longer exists");if(nZ(M.id,C,M.attribution,"publishRoster"),!C.credential||M.fingerprint!==void 0&&J1(C.credential)!==M.fingerprint)throw K("publishRoster",M.id,"attribution","the removed secret no longer matches");q.push(C)}let F=[];for(let M of $.finalize){let C=j.find((f)=>f.id===M.id),A=s(U.stateAccount(M.id)?.[I]);if(!C||C.staged?.reservation!==M.reservation||A?.staged?.reservation!==M.reservation||C.enabled)throw K("publishRoster",M.id,"row-staged","the finalized row is not disabled under this reservation");let T=U.stateAccount(M.id),R=U.rosterRow(M.id),v=T?.[l],b=v===void 0?void 0:b1(v);if(!A?.staged||A.staged.label!==R?.label||A.staged.disabledReason!==C.disabledReason||A.staged.providerState!==b)throw K("publishRoster",M.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");nZ(M.id,C,M.attribution,"publishRoster"),F.push(C)}let N=V.find((M)=>M.torn);if(N)throw K("publishRoster",$.operationId,"attribution",`Row ${N.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let L=new Set;for(let M of V){if(!($.finalize.find((A)=>A.id===M.id)?.enabled??M.enabled)||M.type!=="oauth"||M.identity===void 0)continue;if(L.has(M.identity))throw K("publishRoster",M.id,"invalid-input","the final enabled roster repeats a known identity");L.add(M.identity)}for(let M of V)if(M.identity!==void 0&&M.fingerprint!==void 0&&V.some((C)=>C.id!==M.id&&C.identity!==void 0&&C.identity!==M.identity&&C.fingerprint===M.fingerprint))throw K("publishRoster",M.id,"attribution","the resulting pool gives the same secret different known identities");for(let M of F)if(M.identity!==void 0&&q.some((C)=>C.identity!==void 0&&C.identity!==M.identity&&C.fingerprint===M.fingerprint))throw K("publishRoster",M.id,"attribution","the staged secret belonged to a different known identity");await dZ(U,$.operationId,X.protect);let O={operationId:$.operationId,planDigest:z,phase:"committed",removed:q.map((M)=>({id:M.id,credentialEpoch:M.credentialEpoch??1})),finalized:$.finalize.map((M,C)=>({id:M.id,credentialEpoch:F[C]?.credentialEpoch??1,reservation:M.reservation,enabled:M.enabled}))};for(let M of $.remove)U.dropRosterRows(M.id);for(let M of $.finalize){let C=U.rosterRow(M.id);C.enabled=M.enabled;let A={...U.entry(M.id)};if(delete A.staged,M.enabled)delete A.disabledReason;else A.disabledReason=M.disabledReason;U.setEntry(M.id,A)}let _=U.roster().filter((M)=>!P(M)||typeof M.id!=="string"||j.find((C)=>C.id===M.id)?.invalid==="roster");return U.config.accounts=[...$.order.map((M)=>U.rosterRow(M)),..._],K5(U,O),await U.syncState(),await U.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await D5(U,O)}},{completeTorn:!1});if(H)return H;if(await J.releaseAll(),W>=1)throw K("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class u3{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,X,J,G){this.rt=Z,this.hook=$,this.onFailure=X,this.firedAtLoad=J,this.logger=G}fire(Z,$){if(!this.hook)return;if($==="load"){if(this.firedAtLoad.has(Z))return;this.firedAtLoad.add(Z)}let X=this.run(Z,$);this.inflight.add(X),X.finally(()=>this.inflight.delete(X))}async settled(){while(this.inflight.size>0)await Promise.allSettled([...this.inflight])}async run(Z,$){let X=this.rt(),{ctx:J}=X,G=new H1(J.lockDefaults,J.lockEnv),z={writes:0};try{let B=await g(J,G,z,{operation:"pull",rowId:Z},async(Q)=>{if(Q.reservation(Z)!==void 0)return;await Q.completeTorn();let H=Q.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)Q.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await Q.commitConfig();let U=Q.row(Z);if(!U?.credential||U.credentialEpoch===void 0)return;return{id:Z,credential:U.credential,credentialEpoch:U.credentialEpoch,...U.identity!==void 0?{identity:U.identity}:{},reason:$}},{completeTorn:!1});if(await G.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await J.hold?.("pull-before-request",Z);let W;try{W=await this.hook?.(B)}catch(Q){throw new E({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:Q})}await(X.publishQuota??((Q,H,U)=>wZ(X,Q,H,U)))(Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(B){this.firedAtLoad.delete(Z);let W=O1(B,"pull",Z,z);if(this.onFailure)try{await this.onFailure(Z,W)}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:W.kind})}finally{await G.releaseAll()}}}var L5=100,iZ=128;class p3{rt;timeoutMs;pending=new Map;warned=new Set;wake=new Set;logger;timer;running;closing;closed=!1;stopped=!1;failures=0;constructor(Z,$=1000){this.rt=Z,this.timeoutMs=$,this.logger=Z.ctx.logger??i("store")}async record(Z,$,X){try{this.assertOpen(Z),v3(Z,$);let J=structuredClone({id:Z,attribution:$,observation:X}),{row:G,result:z}=await z1(this.rt,"pull",Z);YZ(Z,J.attribution,G),HZ(this.rt.ctx,Z,this.overlayRow({...G,quota:V1(z.config,Z)?.quota}).quota,J.observation),await this.room(Z),this.assertOpen(Z);let B=this.pending.get(Z)??[];if(B.push(J),this.pending.set(Z,B),B.length>=iZ)this.flushNow();else this.schedule(L5)}catch(J){throw O1(J,"pull",Z,{writes:0})}}queued(Z){return this.pending.get(Z)?.length??0}async room(Z){if(this.queued(Z)<iZ)return;let{ctx:$}=this.rt,X=Math.max(0,...$.storeLocks.map((G)=>G.timeoutMs??$.lockDefaults.timeoutMs)),J=performance.now()+X;while(this.queued(Z)>=iZ){this.assertOpen(Z),this.flushNow();let G=J-performance.now();if(G<=0)throw K("pull",Z,"lock-contention",`pool quota queue for ${Z} is full (${iZ} readings) and the store locks stayed held`,!0);await new Promise((z)=>{let B=()=>{clearTimeout(W),this.wake.delete(B),z()},W=setTimeout(B,G);this.wake.add(B)})}}assertOpen(Z){if(this.closed)throw K("pull",Z,"invalid-input","pool quota writer is closed")}overlayRow(Z){let $=Z;for(let X of this.pending.get(Z.id)??[])try{YZ(Z.id,X.attribution,Z),$={...$,quota:HZ(this.rt.ctx,Z.id,$.quota,X.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;if(this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},Z),!this.closed)this.timer.unref?.()}flushNow(){if(this.running)return;clearTimeout(this.timer),this.timer=void 0,this.flush()}flush(){if(this.running||this.stopped||!this.pending.size)return;let Z=[...this.pending.values()].flat(),$={...this.rt.ctx,storeLocks:this.rt.ctx.storeLocks.map((J)=>({...J,timeoutMs:Math.min(J.timeoutMs??this.rt.ctx.lockDefaults.timeoutMs,100)}))},X=new H1($.lockDefaults,$.lockEnv);this.running=(async()=>{try{await g($,X,{writes:0},{operation:"pull",rowId:void 0},async(G)=>{if(this.stopped)return;let z=!1;for(let B of Z){let{id:W,attribution:Y,observation:Q}=B,H=JSON.stringify([W,Y.credentialEpoch,Y.identity]);try{G.assertNotStaged(W),YZ(W,Y,G.row(W))}catch(D){if(!(D instanceof E))throw D;if(!this.warned.has(H))this.warned.add(H),this.warn("pool quota publication dropped; account binding changed",{id:W,kind:D.kind});continue}let U=G.entry(W);if(!U)continue;let j;try{j=HZ($,W,U.quota,Q)}catch(D){let V=`codec:${H}`;if(!this.warned.has(V))this.warned.add(V),this.warn("pool quota publication dropped; the quota codec refused it",{id:W,error:D instanceof Error?D.message:String(D)});continue}G.setEntry(W,{...U,quota:j,needsFirstReading:!1}),z=!0}if(z&&!this.stopped)await G.commitConfig()},{completeTorn:!1});let J=new Set(Z);for(let[G,z]of this.pending){let B=z.filter((W)=>!J.has(W));if(B.length)this.pending.set(G,B);else this.pending.delete(G)}this.failures=0}catch(J){if(!this.stopped&&this.failures++===0)this.warn("pool quota publication delayed; retrying",{error:J instanceof Error?J.message:String(J)})}finally{await X.releaseAll(),this.running=void 0;for(let G of this.wake)G();let J=this.failures?Math.min(5000,100*2**Math.min(this.failures,6))*(0.5+Math.random()):L5;this.schedule(J)}})()}warn(Z,$){try{this.logger.warn(Z,$)}catch{}}close(){if(this.closing)return this.closing;return this.closed=!0,this.closing=this.drain(),this.closing}async drain(){clearTimeout(this.timer),this.timer=void 0;let Z,$,X=new Promise((J)=>{$=()=>{if(!this.pending.size)J()},this.wake.add($),$()});try{this.flush(),await Promise.race([X,new Promise((J)=>{Z=setTimeout(J,Math.max(0,this.timeoutMs))})])}finally{if(this.stopped=!0,clearTimeout(Z),clearTimeout(this.timer),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((J,G)=>J+G.length,0)});this.pending.clear();for(let J of this.wake)J()}}}import{randomUUID as w8}from"node:crypto";function l3(Z,$){if(I1("refresh",Z,$?.staged),!$)throw K("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw K("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw K("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw K("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function C5(Z){return K("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 _5(Z,$,X,J={}){u("refresh");let{ctx:G}=Z;return p(G,"refresh",$,J.onFailure,async(z,B)=>{let{row:W}=await z1(Z,"refresh",$);l3($,W);let Y=await J.refuse?.(W);if(Y!==void 0)return{status:"refused",rowId:$,reason:Y};let Q=k(W),H;for(let V=0;;V++){await z.acquire(n(Z,{id:$,identity:Q===$?void 0:Q})),await z.acquire(J.providerLock??Z.providerLock);for(let N of J.extraLocks??[])await z.acquire(N);let F=await g(G,z,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let L=l3($,N.row($));if(c("refresh",L),!L.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),L=l3($,N.row($));if(k(L)!==Q)return{keyNow:k(L)};let O=await J.refuse?.(L);if(O!==void 0)return{refused:O};return{row:L,credential:L.credential,credentialEpoch:L.credentialEpoch,identity:L.identity}});if("refused"in F)return{status:"refused",rowId:$,reason:F.refused};if("keyNow"in F){if(await z.releaseAll(),V>=1)throw K("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);Q=F.keyNow;continue}H=F;break}if(b3(H.credential.lastRefreshedAt,G.now()))throw C5($);await G.hold?.("refresh-before-provider",$),await z.assertAll();let U;try{U=await X(H.credential,H.row)}catch(V){throw new E({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:V})}if(typeof U?.refresh!=="string"||!U.refresh.trim())throw K("refresh",$,"provider","the provider returned no refresh token",!0);let j=U.providerState===void 0?void 0:M1(G.providerState,"refresh",$,U.providerState,"the provider state the provider returned"),D=await g(G,z,B,{operation:"refresh",rowId:$},async(V)=>{let q=V.row($),F=V.entry($);if(!q||q.invalid||!F||F.credentialEpoch!==H.credentialEpoch||q.identity!==H.identity)throw new E({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 J.refuse?.(q);if(N!==void 0)return{refused:N};let L=G.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(b3(O,L))throw C5($);let _={type:"oauth",access:U.access,refresh:U.refresh,expires:U.expires},M=q.identity!==void 0&&U.identity!==void 0&&q.identity!==U.identity?{expectedIdentity:q.identity,returnedIdentity:U.identity}:void 0,C=M?{mark:w8(),enabled:!1,reason:`${w1}${JSON.stringify(M)}`}:void 0,A=q.identity===void 0&&U.identity?U.identity:void 0,T=await cZ(Z,V,$,_,{stamp:QZ(O,L),transition:C,identity:A,...j!==void 0?{providerState:UZ(G.providerState,"refresh",$,q.providerState,j)}:{}});if(C!==void 0)WZ(V,$,C),await V.commitConfig();let R=q.identity;if(A!==void 0)R1(V,$,A),R=A,await V.commitConfig();return{stored:T,identity:R,contradiction:M,refused:void 0}});if(D.refused!==void 0)return{status:"refused",rowId:$,reason:D.refused};if(D.contradiction!==void 0)return{status:"identity-contradicted",rowId:$,...D.contradiction,credential:D.stored};if(J.onPersisted)try{let V=J.onPersisted;await Y1("refresh",()=>V($,D.stored))}catch(V){throw new E({operation:"refresh",rowId:$,phase:"after-first-write",retryable:!1,kind:"after-persist-hook",committed:D.stored,message:"the after-persist hook threw; the rotation stays committed",cause:V})}return{status:"rotated",rowId:$,credential:D.stored,...D.identity!==void 0?{identity:D.identity}:{}}})}import{isDeepStrictEqual as u8}from"node:util";var oZ=Object.freeze(["version","accounts",y]);function d3(Z){let $={};for(let[X,J]of Object.entries(Z))if(!oZ.includes(X))rZ($,X,J);return $}function rZ(Z,$,X){Object.defineProperty(Z,$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function p8(Z,$){let X={};for(let[J,G]of Object.entries(Z))if(oZ.includes(J))rZ(X,J,G);else if(Object.hasOwn($,J))rZ(X,J,$[J]);for(let[J,G]of Object.entries($))if(!Object.hasOwn(Z,J))rZ(X,J,G);return X}function T5(Z){return new E({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}async function O5(Z){let $=await d(Z.ctx);if($.status==="error")return $;return{status:$.status,settings:d3($.config)}}async function A5(Z,$,X={}){u("updateSettings");let{ctx:J}=Z,G=X.onFailure;return p(J,"updateSettings",void 0,G&&((z,B)=>G(B)),async(z,B)=>{for(let Y of X.extraLocks??[])await z.acquire(Y);let W=z.held.length;try{for(let F of J.storeLocks)await z.acquire(F);let Y=await d(J);if(Y.status!=="ready")throw G1(Y,"updateSettings",void 0);let Q=d3(Y.config),H=structuredClone(Q),U=await Y1("updateSettings",()=>$(H)),j=U===void 0?H:U;if(!P(j))throw T5("the settings mutator must produce an object");let D=oZ.filter((F)=>Object.hasOwn(j,F));if(D.length>0)throw T5(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(u8(j,Q))return{settings:Q,outcome:"unchanged"};let V=p8(Y.config,j),q={operation:"updateSettings",rowId:void 0};return await y1(J.configPath,V,{beforeRename:async()=>{await J.onStep?.("before-config-write",q),await z.assertAll()}}),B.writes++,await J.onStep?.("after-config-write",q),{settings:d3(V),outcome:"updated"}}finally{await z.releaseTo(W)}})}var S5=new Map;function l8(Z){let $=S5.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},S5.set(Z,$);return $}function R5(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:_1,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function jZ(Z){let $=l8(Z.configPath),X={...A3,...Z.lockOptions},J={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:X,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}:{}},G=new u3(()=>z,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),z={ctx:J,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(Q,H)=>G.fire(Q,H)},B=Z.coalesceQuota?new p3(z,Z.quotaDrainTimeoutMs):void 0,W=(Q,H,U)=>B?B.record(Q,H,U):wZ(z,Q,H,U);z.publishQuota=W;let Y=(Q)=>{if(Q.status==="ready"&&B)return{...Q,rows:B.overlay(Q.rows)};return Q};return{async load(){let Q=Y(await d(J));if(Q.status==="ready"){for(let H of Q.rows)if((H.candidate||H.torn&&H.enabled)&&H.type==="oauth"&&H.needsFirstReading)G.fire(H.id,"load")}return R5(Q)},async read(){return R5(Y(await d(J)))},async initialize(Q={}){return{status:await e4(J,Q.dropKeys??[])}},add:(Q,H)=>B5(z,Q,H),publishRoster:(Q,H)=>P5(z,Q,H),publication:(Q)=>M5(z,Q),replace:(Q,H,U,j)=>Q5(z,Q,H,U,j),rotate:(Q,H,U,j)=>W5(z,Q,H,U,j),updateProviderState:(Q,H,U,j)=>X5(z,Q,H,U,j),disable:(Q,H,U)=>H5(z,Q,H,U),enable:(Q,H)=>U5(z,Q,H),remove:(Q,H)=>V5(z,Q,H),reorder:(Q,H)=>j5(z,Q,H),readSettings:()=>O5(z),updateSettings:(Q,H)=>A5(z,Q,H),recordIdentity:(Q,H,U,j)=>q5(z,Q,H,U,j),refresh:(Q,H,U)=>_5(z,Q,H,U),recordQuota:W,close:()=>B?.close()??Promise.resolve(),dispose:()=>B?.close()??Promise.resolve(),requestReading:(Q)=>G.fire(Q,"admission"),pullsSettled:()=>G.settled()}}var d8=[/\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 a3(Z={}){let{redactStrings:$}=E5({...Z,extraValuePatterns:[...d8,...Z.extraValuePatterns??[]]});return(X)=>$(X)}class w extends Error{code;constructor(Z,$,X){super($,X);this.name="CommandError",this.code=Z}}var I5=/^[a-z][a-z0-9-]{0,63}$/,c3={code:"action-failed",text:"That action failed."},c8=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 qZ(Z){if(Z instanceof w)return{code:I5.test(Z.code)?Z.code:c3.code,text:Z.message};if(Z instanceof E)return{code:`pool-${Z.kind}`,text:c8.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return c3}var b5="This cannot be undone. Continue?",s8=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function a8(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return s8.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function n8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function s3(Z,$,X){if(typeof Z==="string"){let G=X.redact(Z);if(G!==Z)X.redacted.push($);return G}if(Array.isArray(Z))return Z.map((G,z)=>s3(G,`${$}[${z}]`,X));if(!n8(Z))return Z;let J={};for(let[G,z]of Object.entries(Z)){if(a8(G)){X.dropped.push(`${$}.${G}`);continue}Object.defineProperty(J,G,{value:s3(z,`${$}.${G}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function y5(Z,$,X){let J={redact:X.redact,dropped:[],redacted:[]},G=s3(Z,"payload",J);if(J.dropped.length>0)X.logger.warn("credential-shaped field dropped from a command payload",{command:$,fields:J.dropped});if(J.redacted.length>0)X.logger.warn("secret-shaped text masked in a command payload",{command:$,fields:J.redacted});return G}function i8(Z){return{value:String(Z.value),label:String(Z.label)}}function r8(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(i8),...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 n3(Z){if(Z.irreversible===!0)return{message:Z.confirm||b5,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function k5(Z){let $=n3(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(r8),...$?{confirm:$}:{}}}function o8(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 t8(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:o8(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(k5)}}function e8(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(t8),actions:($.actions??[]).map(k5),...$.facts!==void 0?{facts:$.facts}:{}}}function f5(Z,$,X){return{command:Z,title:$,sections:X.map(e8)}}function h5(Z,$,X,J){return y5({command:Z,menu:f5(Z,$,X)},Z,J)}function g5(Z,$,X,J,G){return y5({command:Z,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:I5.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:f5(Z,$,X)},Z,G)}var l5="disabled from the command menu";function Z9(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function K1(Z){return Z9(Z)?{...Z}:{}}function $9(Z){if(Z.status!=="ready")return[];let $=new Set;return Z.rows.filter((X)=>{if($.has(X.id))return!1;return $.add(X.id),!0})}function X9(Z,$){return Z.label??$??Z.id}function tZ(Z,$){return A1(Z.quota)?q1(Z.quota,$):void 0}function d5(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var DZ="Actions";function J9(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 v5(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 x5(Z){return qZ(Z).text}async function G9(Z){let{store:$}=Z,X=await $.read(),J=await $.readSettings(),G=await Z.routing?.vaultOrder?.();return{load:X,rows:$9(X),settings:J.status==="error"?{}:J.settings,...G?{vault:G}:{}}}function eZ(Z,$){let X=$.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,...X!==void 0?{identity:X}:{}},name:X9(Z,X)}}function z9(Z,$){let{store:X,extraLocks:J}=Z,G=J?{extraLocks:J}:{},z=$.rows.map((U)=>U.id),B=J9($.load),W=$.rows.filter((U)=>U.enabled).length,Y=$.rows.map((U,j)=>{let{account:D,name:V}=eZ(U,Z),q=[U.type==="api"?"API key":"OAuth",...D.identity!==void 0?[D.identity]:[],...!U.invalid&&!U.enabled&&U.disabledReason?[`disabled: ${U.disabledReason}`]:[]].join(" · "),F=U.invalid?"invalid":U.enabled?"enabled":"disabled",N=[];if(!U.invalid&&U.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(U.id,l5,G),`Disabled ${V}.`}});if(!U.invalid&&!U.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(U.id,G),`Enabled ${V}.`}});if(z.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:z.map((L,O)=>({value:String(O+1),label:String(O+1)})),value:String(j+1)}],run:async({values:L})=>{let O=Number(L.position),_=z.filter((C)=>C!==U.id);return _.splice(O-1,0,U.id),(await X.reorder(_,G)).outcome==="unchanged"?`${V} is already at position ${O}.`:`Moved ${V} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${V}? Its stored credential is deleted.`,run:async()=>{return await X.remove(U.id,{...G,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${V}.`}}),{id:U.id,label:V,detail:q,group:"Accounts",status:F,account:D,actions:N}}),Q=Z.accounts?.login,H=[];if(Q&&!B)H.push({id:"add",label:Q.label??"Add account",group:DZ,knobs:Q.knobs??[],run:async({values:U,invocation:j})=>{let D=await Q.run(U,j);if(D.status==="cancelled")return{ok:!1,text:D.message??"Login cancelled."};if(D.status==="ready"){let V=await X.add(D.account,G);return v5(D.account.label??V.id,V)}return D.completion.then(async(V)=>{if(!V){j.notify("Login cancelled.","warning");return}let q=await X.add(V,G);j.notify(v5(V.label??q.id,q))},(V)=>{j.notify(`Adding the account failed: ${x5(V)}`,"error")}).catch((V)=>{j.notify(`Adding the account failed: ${x5(V)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${d5($.rows.length,"account")}, ${W} enabled`],items:B?[]:Y,actions:H}}}function B9(Z,$){let X=Z.quota?.scope??"all",J=Z.now(),G=X==="all"?"Accounts":`Accounts · ${X}`,z=async(H,U)=>{if(Z.quota?.check)await Z.quota.check(H,U);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((H)=>H.candidate),W=B.map((H)=>{let{account:U,name:j}=eZ(H,Z),D=tZ(H,X);return{id:H.id,label:j,group:G,status:j1(D,{now:J,form:"compact"}),detail:j1(D,{now:J,form:"full"}),account:U,actions:[{id:"check",label:"Check this account",run:async({invocation:V})=>{return await z([H.id],V),`Checked quota for ${j}.`}}]}}),Y=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:U}=eZ(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",D=j1(tZ(H,X),{now:J,form:"compact"});return`${U} (${j}): ${D}`}),Q=[];if(B.length>0)Q.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:DZ,run:async({invocation:H})=>{let U=B.map((j)=>j.id);return await z(U,H),`Checked quota for ${d5(U.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:Y,items:W,actions:Q}}}async function Q9(Z,$){try{return await Z.reorder($)}catch(X){if(X instanceof Error&&X.name==="ClaustrumConsumerError"&&X.kind==="invalid-order")throw new w("vault-invalid-order",X.message,{cause:X});throw X}}function i3(Z){return new w("vault-invalid-order",Z)}function W9(Z){let $=Z.rows.map((J)=>({id:J.id,label:J.label.trim()||J.id})),X=(J)=>$.filter((G)=>G.id===J||G.label===J);return{ids:$.map((J)=>J.id),nameOf:(J)=>$.find((G)=>G.id===J)?.label??J,entryOf:(J)=>{let G=$.find((z)=>z.id===J);return G&&!/[,\n]/.test(G.label)&&X(G.label).length===1?G.label:J},resolve:(J)=>{let G=[];for(let z of J){let B=X(z);if(B.length===0)throw i3(`"${z}" is not a vault account.`);if(B.length>1)throw i3(`"${z}" matches more than one vault account; enter those accounts by route id.`);let W=B[0].id;if(G.includes(W))throw i3(`"${z}" names an account already in the order.`);G.push(W)}return G}}}function Y9(Z,$){let{store:X,extraLocks:J}=Z,G=J?{extraLocks:J}:{},z=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],B=K1($.settings.routing).mode,W=typeof B==="string"&&z.some((F)=>F.value===B)?B:"ordered",Y=u5(W),Q=$.vault?W9($.vault):void 0,H=Q?Q.ids:$.rows.map((F)=>F.id),U=(F)=>Q?Q.nameOf(F):F,j=p5(H,Y.placement,Z.routing?.formerMainId??w5),V=[`Mode: ${z.find((F)=>F.value===W)?.label??W}`];if(H.length>0)V.push(`${Q?"Vault account order":"Roster order"}: ${H.map(U).join(", ")}`);if(Y.mode==="ordered"&&j.join()!==H.join())V.push(`Tried in order: ${j.map(U).join(", ")}`);let q=[{id:"mode",label:"Change mode",group:DZ,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:z,value:W}],run:async({values:F})=>{let N=String(F.mode);return await X.updateSettings((L)=>{L.routing={...K1(L.routing),mode:N};return},G),`Routing mode set to ${z.find((L)=>L.value===N)?.label??N}.`}}];if(H.length>1)q.push({id:"order",label:"Set order",group:DZ,knobs:[{kind:"text",id:"order",label:Q?"Vault accounts, first to last, separated by commas":"Account ids, first to last",value:Q?H.map(Q.entryOf).join(", "):H.join(", "),required:!0}],run:async({values:F})=>{let L=String(F.order).split(Q?/[,\n]+/:/[\s,]+/).map((_)=>_.trim()).filter((_)=>_.length>0),O=$.vault&&Q?await Q9($.vault,Q.resolve(L)):await X.reorder(L,G);return O.outcome==="unchanged"?"The order is unchanged.":`Order set to ${O.ids.map(U).join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:V,actions:q}}}function H9(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let X=Z.quota?.scope??"all",J=[];for(let G of $.rows)for(let z of tZ(G,X)?.limits??[])if(!J.includes(z.label))J.push(z.label);return J.length>0?J:["primary"]}function U9(Z,$){let X=Z.quota?.scope??"all",J=new Map;for(let G of $.rows)for(let z of tZ(G,X)?.limits??[])if(z.windowMinutes!==void 0&&!J.has(z.label))J.set(z.label,m5(z));return(G)=>J.get(G)??G}function V9(Z,$){let{store:X,extraLocks:J}=Z,G=J?{extraLocks:J}:{},z=K1($.settings.killswitch),B=z.enabled===!0,W=K1(z.accounts),Y=H9(Z,$),Q=U9(Z,$),H=B?"on":"off",U=$.rows.map((j)=>{let{account:D,name:V}=eZ(j,Z),q=K1(W[j.id]),F=Y.filter((N)=>typeof q[N]==="number");return{id:j.id,label:V,group:`Floors · killswitch ${H}`,status:F.length===0?"no floors":F.map((N)=>`${Q(N)} ≥${q[N]}%`).join(" · "),account:D,actions:[{id:"floors",label:"Set floors",knobs:Y.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${Q(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await X.updateSettings((L)=>{let O=K1(L.killswitch),_=K1(O.accounts),M=K1(_[j.id]);for(let C of Y){let A=N[C];if(typeof A==="number")M[C]=A;else if(A===null)delete M[C]}if(Object.keys(M).length>0)_[j.id]=M;else delete _[j.id];if(Object.keys(_).length>0)O.accounts=_;else delete O.accounts;L.killswitch=O;return},G),`Floors updated for ${V}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:U,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:DZ,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let D=j.enabled===!0;return await X.updateSettings((V)=>{V.killswitch={...K1(V.killswitch),enabled:D};return},G),`Killswitch ${D?"on":"off"}.`}}]}}}async function c5(Z){let $=await G9(Z);return[z9(Z,$),B9(Z,$),Y9(Z,$),V9(Z,$)]}var j9=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),r3=["accounts","quota","routing","limits"];function s5(Z,$){let{sessionId:X}=Z,J=Z.notify.bind(Z);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(G,z)=>z===void 0?J($(String(G))):J($(String(G)),z)})}function q9(Z,$){switch(Z.kind){case"choice":{let X=$??Z.value;if(typeof X==="string"&&Z.choices.some((J)=>J.value===X))return{value:X};return{problem:`Choose one of the options for ${Z.label}.`}}case"toggle":{let X=$??Z.value;return typeof X==="boolean"?{value:X}:{problem:`${Z.label} must be on or off.`}}case"number":{let X=$===void 0?Z.value??null:$;if(X===null||X==="")return Z.required?{problem:`${Z.label} needs a number.`}:{value:null};let J=typeof X==="number"?X:Number(X);if(typeof X==="boolean"||!Number.isFinite(J))return{problem:`${Z.label} needs a number.`};if(Z.min!==void 0&&J<Z.min)return{problem:`${Z.label} must be at least ${Z.min}.`};if(Z.max!==void 0&&J>Z.max)return{problem:`${Z.label} must be at most ${Z.max}.`};return{value:J}}case"text":{let X=$===void 0?Z.value??null:$;if(X===null||X==="")return Z.required?{problem:`${Z.label} cannot be empty.`}:{value:null};return typeof X==="string"?{value:X}:{problem:`${Z.label} must be text.`}}}}function D9(Z,$){let X={};for(let J of Z){let G=$&&Object.hasOwn($,J.id)?$[J.id]:void 0,z=q9(J,G);if("problem"in z)return z;X[J.id]=z.value}return{values:X}}function F9(Z,$){let X=Z.find((G)=>G.id===$.sectionId);if(!X)return;return($.itemId===void 0?X.content.actions:X.content.items?.find((G)=>G.id===$.itemId)?.actions)?.find((G)=>G.id===$.actionId)}function k1(Z){let $=Z.logger??i("commands"),X=a3(Z.redaction),J={logger:$,redact:X},G=Z.now??Date.now,z=Z.extras??[],B=Z.replace??{},W=r3.filter((j)=>!B[j]);for(let j of r3)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(W.length>0&&!Y)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let Q=new Set;for(let j of z){if(j9.has(j.id)||Q.has(j.id))throw Error(`extra section id ${j.id} is taken`);Q.add(j.id)}async function H(j,D,V,q){try{return{id:j,slot:D,title:V.title,content:await V.build(q)}}catch(F){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:X(F instanceof Error?F.message:String(F))}),{id:j,slot:D,title:V.title,content:{lines:["This section could not be loaded."]}}}}async function U(j){let D=Y&&W.length>0?await c5({store:Y,now:G,...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}:{}}):[],V=[];for(let q of r3){let F=B[q];if(F)V.push(await H(q,q,F,j));else{let N=D.find((L)=>L.slot===q);if(N)V.push(N)}}if(Z.cache)V.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)V.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of z)V.push(await H(q.id,"extra",q,j));return V}return{command:Z.command,async open(j){let D=s5(j,X);return h5(Z.command,Z.title,await U(D),J)},async apply(j,D){let V=s5(D,X),q=async(_)=>g5(Z.command,Z.title,await U(V),_,J),F=j.command===Z.command?F9(await U(V),j):void 0;if(!F)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=n3(F);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let L=D9(F.knobs??[],j.values);if("problem"in L)return q({ok:!1,code:"invalid-input",text:L.problem});let O;try{let _=await F.run({values:L.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:V});O=typeof _==="string"?{ok:!0,text:_}:{ok:_.ok,text:_.text,..._.ok?{}:{code:_.code??"refused"}}}catch(_){let M=qZ(_);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:M.code,error:X(_ instanceof Error?_.message:String(_))}),O={ok:!1,...M}}return q(O)}}}function N9(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function M9(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 X={};if($.values!==void 0){if($.values===null||typeof $.values!=="object"||Array.isArray($.values))return;for(let[J,G]of Object.entries($.values)){if(!N9(G))return;Object.defineProperty(X,J,{value:G,enumerable:!0,writable:!0,configurable:!0})}}return{command:$.command,sectionId:$.sectionId,actionId:$.actionId,...typeof $.itemId==="string"?{itemId:$.itemId}:{},...$.values!==void 0?{values:X}:{},...$.confirmed===!0?{confirmed:!0}:{},...typeof $.sessionId==="string"?{sessionId:$.sessionId}:{}}}function h(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as L9}from"node:fs";import{rm as i5}from"node:fs/promises";import{dirname as C9,join as Q6}from"node:path";import{resolveClaustrumConnectionPath as _9}from"@cortexkit/claustrum-client";function a5(Z,$){if(!Z)return;let X=Z.rawUsedPercent??Z.usedPercent;if(!Number.isFinite(X)||X<0||X>100)return;return{usedPercent:X,remainingPercent:100-X,checkedAt:$,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...typeof Z.windowMinutes==="number"&&Number.isFinite(Z.windowMinutes)&&Z.windowMinutes>0&&{windowMinutes:Z.windowMinutes}}}function o3(Z){if(!h(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 K9(Z){let $=o3(Z.total),X=o3(Z.remaining);if($===void 0||X===void 0||$<0||X<0)return;let J=$-X,G=Z.spendable===!1,z=$>0?J/$*100:G?100:0;return{limit:$,used:J,remaining:X,usedPercent:z,remainingPercent:100-z,reached:G,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...h(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function P9(Z,$){if(!h(Z))return;let X=o3(Z.remaining);return{hasCredits:!0,unlimited:typeof Z.unlimited==="boolean"?Z.unlimited:!1,...X!==void 0&&X>=0&&{balance:X},...Z.spendable===!1&&{overageLimitReached:!0},checkedAt:$}}function t3(Z,$){if(Z.insulaCreditsUnlimitedUnstated&&Z.credits&&Z.credits.balance===void 0&&h($)&&h($.credits)&&$.credits.unlimited===!0)return{...Z,credits:{...Z.credits,unlimited:!0}};return Z}function n5(Z,$){let X=a5(Z.usage?.primary,$.fetchedAt);if(!X||!Number.isFinite($.fetchedAt))return;let J=a5(Z.usage?.secondary,$.fetchedAt),G=Array.isArray(Z.spend)?Z.spend.find((Q)=>h(Q)&&Q.id==="individual_limit"):void 0,z=h(G)?K9(G):void 0,B=Array.isArray(Z.spend)?Z.spend.find((Q)=>h(Q)&&Q.id==="credits"):void 0,W=P9(B,$.fetchedAt),Y=h(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:X,...W&&{credits:W},...W&&h(B)&&typeof B.unlimited!=="boolean"&&{insulaCreditsUnlimitedUnstated:!0},...J&&{secondary:J},...typeof Y==="number"&&Number.isFinite(Y)&&Y>=0&&{resetCreditsAvailable:Y},...z&&{spendControl:z},...!G&&{spendControlCleared:!0}}}function e3(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var Z4="ck auth reclassify --from-registry";function Z3(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 \`${e3(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${Z4}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var B1=i("vault"),T9="openai-auth",W6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},O9={opencode:"OpenCode",pi:"Pi"};function A9(Z){return o5(T9,Z)}function LJ(Z){return Q6(C9(Z),"openai-auth-vault")}function S9(Z,$){return{...e5({stateDir:Z,host:$}),rosterPath:Q6(Z,`${$}-roster.json`)}}var Y6=2000,CJ=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],R9={"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 ${Z4} 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 _J(Z,$){if(Z!=="vault-no-grant")return R9[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: ${e3($)}`}function TJ(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let X=Z.grantReach();if(X!==void 0)return X.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function E9(Z){let $=X3(Z);return $?J3($):void 0}class H6 extends z6{#$;constructor(Z,$){super(Z);this.#$=$}refresh(){let Z=super.refresh();return this.#$(Z),Z}}class I9{host;name;paths;#$;#Z;#Q=new Map;#W=new Map;#V=new Map;#j;#X;#Y;#G;#q=!1;#D=!1;#H=Promise.withResolvers();#F="unknown";#U;constructor(Z){this.#$=Z,this.host=Z.host,this.name=A9(Z.host),this.paths=S9(Z.stateDir,Z.host),this.#Z=new H6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:W6,connect:()=>this.#L(),isCustodyActive:()=>this.#_(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:E9,insula:{provider:"codex",normalize:n5},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#X=void 0},onError:($)=>this.#J("vault roster refresh failed",$),logger:{...B1,warn:($,X)=>{if($!=="skipped insula provider poll")B1.warn($,X)}}},($)=>this.#T($))}#N(){return(this.#$.connectionFile??_9)()}#M(){return{connectionFile:this.#N(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>B1.debug("vault transport error",{errorClass:Z})}}#L(){return(this.#$.connectScoped?.()??B6(this.#M())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#z(Z,$,X){let J=this.#V.get(Z);if(J?.source===$&&J.reason===X)return;this.#V.set(Z,{source:$,reason:X}),B1.info("vault background quota source changed",{routeId:Z,source:$,reason:X})}#C(){return this.#$.connectEnrollment?.()??t5(this.#M())}#J(Z,$){this.#X=D1($),B1.warn(Z,{host:this.host,error:this.#X})}#B(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=L9(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#B(),$=await $6(this.paths,this.name);if(Z===this.#B())return this.#F=$,this.#U=Z,$;return"unreadable"}enrolled(){return this.#U!==this.#B()||this.#F!=="local"}async#_(){if(this.#U!==this.#B())await this.authority();return this.enrolled()}start(){if(this.#q||this.#D)return;this.#q=!0,this.#Z.start()}#T(Z){if(this.#G===Z)return;this.#G=Z,Z.finally(()=>{if(this.#G===Z)this.#G=void 0;this.#H.resolve()}).catch(()=>{})}#K(){return this.#Z.refresh()}firstRoster(){return this.#H.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#G;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#G??this.#K()).catch((X)=>{this.#J("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let Z=this.#G;if(Z)await Z.catch(()=>{return});let $=await this.#K();return this.#X=void 0,$}catch(Z){return this.#J("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 X=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...X!==void 0?{identity:X}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,X){let J=!1;try{return await this.#Z.send(Z,(G)=>{return J=!0,$(G.accessToken,G)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(G){if(J)throw G;this.#J("vault refused to serve an account",G);return}}async authorize(Z,$={}){try{return await this.#Z.authorize(Z,$.signal)}catch(X){this.#J("vault refused to serve an account",X);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(X){this.#J("vault failure report failed",X)}await this.refresh()}recordSnapshot(Z,$,X,J){let G=$3($,(this.#$.now??Date.now)(),X);if(!G)return Promise.resolve();return this.#Z.recordQuota(Z,G,J).then(()=>{},(z)=>this.#J("vault quota write failed",z))}pollQuota(Z,$=!0){let X=this.#W.get(Z);if(X)return X;let J=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,J),J}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let X=(await G6(this.paths.rosterPath))?.rows.find((W)=>W.routeId===Z),J,G=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#z(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),J=await this.#P(Z,$);return});if(J)return J;if(G!==void 0&&X?.accountIdentity){let W=$3(t3(G,this.routes().find((Q)=>Q.id===Z)?.quota),G.primary.checkedAt,!0);if(!W)return this.#z(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,X.accountIdentity,W))return this.#z(Z,"insula",null),{ok:!0};return this.#z(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:z}=await this.#Z.lookupInsulaQuotaForRoute(Z),B=z==="cold"||z==="upstream-failed"?z:"no-insula-reading";return this.#z(Z,"insula",B),{ok:!1,error:`insula ${B}`}}return this.#P(Z,$)}async#P(Z,$){let X,J=this.#$.fetchImpl?.()??globalThis.fetch,G=await this.send(Z,async(z,B)=>{try{let W=$?void 0:await this.#Z.cachedInsulaQuota(B);if(W!==void 0){let Q=$3(t3(W,this.routes().find((H)=>H.id===Z)?.quota),W.primary.checkedAt,!0);if(!Q)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,Q,B),new Response(null,{status:200})}let Y=await FZ({accessToken:z,fetchImpl:J,now:this.#$.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:B1});return await this.recordSnapshot(Z,Y,!0,B),X=void 0,new Response(null,{status:200})}catch(W){X=D1(W);let Y=W?.status;if(typeof Y==="number")return new Response(null,{status:Y});throw W}},{site:"quota"}).catch((z)=>{X=D1(z);return});if(!G)return{ok:!1,error:X??"vault refused"};return G.ok?{ok:!0}:{ok:!1,error:X??`status ${G.status}`}}requestReading(Z){let $=this.#Q.get(Z);if($)return $;let X=this.pollQuota(Z,!1).catch((J)=>{B1.warn("vault quota poll failed",{routeId:Z,error:D1(J)})}).finally(()=>{this.#Q.delete(Z)});return this.#Q.set(Z,X),X}async pollStale(Z){let $=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let G=b9(J.quota);if(G!==void 0&&$-G<Z)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}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),B1.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),B1.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await Z6(this.paths,this.name)}catch($){this.#J("vault enrollment state unreadable",$),Z={state:"blocked",proposedName:this.name,code:$ instanceof r5?$.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:Z,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#X?{lastError:this.#X}:{}}}async connectStep(){let Z=await this.#C().catch(($)=>{throw new w("vault-unreachable",`Could not reach the Claustrum vault (${this.#N()}): ${D1($)}. Is the vault running?`)});try{let $=new X6({client:Z,paths:this.paths,proposedName:this.name,...this.#$.now?{now:this.#$.now}:{}}),X=await $.status();if(X.state==="denied"||X.state==="blocked")await $.resetTerminal();let J=await $.reconcile();if(B1.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#X=void 0,await this.refresh();return J}finally{Z.close()}}waitForApproval(Z={}){return this.#Y??=(async()=>{let $=Z.sleep??((z)=>new Promise((B)=>setTimeout(B,z))),X=Z.pollIntervalMs??2000,J=Date.now()+(Z.timeoutMs??600000),G=await this.connectStep();while(G.state==="pending"||G.state==="busy"){if(Z.onPending?.(G),Date.now()>=J)return G;await $(X),G=await this.connectStep()}return G})().finally(()=>{this.#Y=void 0}),this.#Y}async disconnect(){await i5(this.paths.tokenPath,{force:!0}),await i5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,B1.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())J6({mode:"custody",auth:Z,provider:"openai"})}close(){this.#D=!0,this.#H.resolve(),this.#Z.close()}}function b9(Z){if(!Z)return;let $=q1(Z).limits.map((X)=>X.checkedAt);return $.length>0?Math.max(...$):void 0}function G3(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 ${W6.category} --operation read`]}function U6(Z,$,X){let J=`${O9[Z]} (${$})`;switch(X.state){case"approved":return`${J}: connected to the Claustrum vault.`;case"idle":return`${J}: not connected to the Claustrum vault.`;case"pending":return X.requestId?`${J}: waiting for approval of request ${X.requestId}.`:`${J}: enrollment request not taken yet${X.retryCode?` (${X.retryCode})`:""}.`;case"denied":return`${J}: the vault denied the enrollment request.`;case"blocked":return`${J}: enrollment stopped (${X.code}).`;case"unavailable":return`${J}: the vault is unavailable (${X.code}).`;case"busy":return`${J}: another process is enrolling right now.`}}function $4(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 X=Z.snapshot()?.rows.length??0;return{ok:!0,text:`Connected: the vault approved ${Z.name}. It serves ${X} OpenAI account${X===1?"":"s"} to this host${X===0?`. ${Z3(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:[...G3(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
2
+ `)};default:return{ok:!1,text:`Enrollment is ${$.state}.`}}}var X4="/backend-api/wham/rate-limit-reset-credits",y9=`https://chatgpt.com${X4}`,N6=`${X4}/consume`,k9=`https://chatgpt.com${N6}`,f9=300000,h9=60000,g9=15000,v9=60000;function n1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class o extends Error{kind;cooldownUntil;constructor(Z,$,X){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=X}}class f1 extends Error{kind;status;constructor(Z,$,X){super($);this.name="ResetCreditError",this.kind=Z,this.status=X}}function M6(Z,$,X){return{authorization:`Bearer ${Z}`,...X?{"chatgpt-account-id":X}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function B3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function K6(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function Q3(Z){if(!B3(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}:{},...P6(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function P6(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function z3(Z){return Z.kind==="http_error"&&P6(Z.status)}function L6(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function x9(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new o("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function C6(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function _6(Z,$){return $-Z.startedAt<f9}function i1(Z,$){if(!P1($))return;return Z.reset?.[$]}function T6(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function O6(Z,$,X){if(!P1($))return;let J=T6(Z),G=J[$]??{},z=G.lastOutcome;delete G.inFlight,G.lastOutcome={code:"ambiguous_local",at:X,...z?{previousOutcome:{code:z.code,at:z.at}}:{}},J[$]=G}function A6(Z,$){let X=K6(Z),J=Q3(Z?.inFlight);if(C6(Z)&&!J)return{kind:"corrupt",beforeState:X};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:X,cooldownUntil:Z.cooldownUntil};if(J&&_6(J,$))return{kind:"claim",beforeState:X,claim:{inFlight:J,selectedCredit:{id:J.creditId}}};if(J)return{kind:"expired_unreconciled",beforeState:X,claim:{inFlight:J,selectedCredit:{id:J.creditId}}};return{kind:"fresh",beforeState:X}}async function m9(Z,$){if(!P1($))return{kind:"fresh",beforeState:void 0};let X=await Z.loadAccountsFn(n1(Z));return A6(X?i1(X,$):void 0,Z.now())}async function w9(Z,$){let X;if(await Z.mutateAccountsFn((J)=>{let G=Z.now(),z=i1(J,$);if(X=A6(z,G),X.kind==="corrupt")O6(J,$,G);return J},n1(Z)),!X)throw Error("corrupt reset state mutation did not run");return X}async function u9(Z,$,X,J){if(!P1($))return{kind:"fresh",beforeState:void 0};let G;if(await Z.mutateAccountsFn((z)=>{let B=Z.now(),W=i1(z,$),Y=K6(W),Q=Q3(W?.inFlight);if(C6(W)&&!Q)return O6(z,$,B),G={kind:"corrupt",beforeState:Y},z;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>B)return G={kind:"cooldown",beforeState:Y,cooldownUntil:W.cooldownUntil},z;if(Q&&_6(Q,B))return G={kind:"claim",beforeState:Y,claim:{inFlight:Q,selectedCredit:{id:Q.creditId}}},z;if(Q&&!L6(Q,J))return G={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:Q,selectedCredit:{id:Q.creditId}}},z;let H=W3(X);if(!H)return G={kind:"fresh",beforeState:Y},z;let U={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:B,...J===void 0?{}:{chatgptAccountId:J}},j=T6(z);return j[$]={...W,inFlight:U},G={kind:"claim",beforeState:Y,claim:{inFlight:U,selectedCredit:H}},z},n1(Z)),!G)throw Error("reset claim mutation did not run");return G}async function p9(Z,$,X,J,G){if(!P1($))return;if(!z4(J.kind))return l9(Z,$,X,J,G);await Z.mutateAccountsFn((z)=>{let B=i1(z,$),W=Q3(B?.inFlight);if(!B||!W||W.redeemRequestId!==X.redeemRequestId||W.creditId!==X.creditId)return z;let Y=Z.now();if(delete B.inFlight,B.lastOutcome={code:J.kind,at:Y},J.kind==="reset"||J.kind==="already_redeemed")B.cooldownUntil=Y+v9;else delete B.cooldownUntil;return z},n1(Z));return}function V6(Z,$){let X=Q3(Z?.inFlight);return X&&X.redeemRequestId===$.redeemRequestId&&X.creditId===$.creditId?X:void 0}async function l9(Z,$,X,J,G){let z=z3(J)?J.status:void 0;if(!(X.chatgptAccountId===void 0&&G!==void 0)&&z!==void 0&&z===X.rejectedStatus){let Y=await Z.loadAccountsFn(n1(Z));return V6(Y?i1(Y,$):void 0,X)}let W;return await Z.mutateAccountsFn((Y)=>{W=void 0;let Q=i1(Y,$),H=V6(Q,X);if(!Q||!H)return Y;let U={...H};if(U.chatgptAccountId===void 0&&G!==void 0)U.chatgptAccountId=G;if(z===void 0)delete U.rejectedStatus,U.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(X.unknownAnswers??0))U.rejectedStatus=z;return Q.inFlight=U,W=U,Y},n1(Z)),W}function NZ(Z,$){if(!Z||Z.usedPercent<100)return!1;if(!Z.resetsAt)return!0;let X=Date.parse(Z.resetsAt);return!Number.isFinite(X)||X>$}function J4(Z,$,X){if(!($||NZ(Z.primary,X)||NZ(Z.secondary,X)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function j6(Z,$){let X=Z[$];if(X===void 0||X===null)return;return typeof X==="string"?X:null}function d9(Z){if(!B3(Z))return;let $=j6(Z,"granted_at"),X=j6(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||X===null)return;return{id:Z.id,status:Z.status,...$===void 0?{}:{grantedAt:$},expiresAt:Z.expires_at,...X===void 0?{}:{resetType:X},isSupportedByPlan:Z.is_supported_by_plan}}async function G4(Z,$,X){let J;try{J=await Z(y9,{method:"GET",headers:M6($,X4,X),signal:AbortSignal.timeout(g9)})}catch{throw new f1("http_error","reset credit list request failed")}if(!J.ok)throw new f1("http_error",`reset credit list request failed: ${J.status}`,J.status);let G;try{G=await J.json()}catch{throw new f1("invalid_response","reset credit list response was not valid JSON",J.status)}if(!B3(G))throw new f1("invalid_response","reset credit list response was not an object",J.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((B)=>{let W=d9(B);return W===void 0?[]:[W]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function W3(Z){return[...Z].filter(S6).sort(($,X)=>Date.parse($.expiresAt)-Date.parse(X.expiresAt))[0]}function S6(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function R6(Z){return Z.filter(S6).length}function z4(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function c9(Z,$,X,J,G){let z;try{z=await Z(k9,{method:"POST",headers:{...M6($,N6,X),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:J}),signal:AbortSignal.timeout(h9)})}catch(Q){return{kind:"ambiguous",raw:Q}}let B;try{B=await z.text()}catch(Q){return z.ok?{kind:"ambiguous",raw:Q}:{kind:"http_error",raw:Q,status:z.status}}let W=B,Y=!1;try{W=JSON.parse(B),Y=!0}catch{}if(!z.ok)return{kind:"http_error",raw:W,status:z.status};if(!Y||!B3(W)||!z4(W.code))return{kind:"ambiguous",raw:W};return{kind:W.code,raw:W}}function q6(Z){if(Z.kind==="cooldown")throw new o("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function D6(){throw new o("expired_unreconciled","the previous reset attempt outcome is unknown")}function F6(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 s9(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(z3(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 a9(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 E6(Z,$){if(!P1($.accountKey))throw new o("invalid_account_key","the reset account key is reserved");let X=await Z.resolveTarget($.accountKey);if(X.chatgptAccountId!==$.expectedChatgptAccountId)throw new o("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let J=X.chatgptAccountId,G=X.accountKey==="main"?void 0:J,z=await m9(Z,$.accountKey);if(z.kind==="corrupt"){if(z=await w9(Z,$.accountKey),z.kind==="corrupt")return F6(X,z.beforeState)}if(z.kind==="cooldown")q6(z);let B;if(z.kind==="claim")B=z.claim;else if(z.kind==="expired_unreconciled"&&($.retry||!L6(z.claim.inFlight,J))){if(!$.retry)D6();B=z.claim}else{if($.retry)throw new o("retry_without_inflight","there is no active reset credit redemption to retry");let[j,D]=await Promise.all([Z.fetchUsage(X),G4(Z.fetchImpl,X.accessToken,G)]),V=J4(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!V.ok)throw new o("not_exhausted",V.reason);if(!W3(D.credits))throw new o("no_eligible_credit","no eligible reset credit was returned");let q=await u9(Z,$.accountKey,D.credits,J);if(q.kind==="corrupt")return F6(X,q.beforeState);if(q.kind==="cooldown")q6(q);if(q.kind==="expired_unreconciled")D6();if(q.kind!=="claim")throw new o("no_eligible_credit","no eligible reset credit was available while claiming");B=q.claim}x9(B.inFlight,J);let W=await c9(Z.fetchImpl,X.accessToken,G,B.inFlight.creditId,B.inFlight.redeemRequestId),Y,Q=!1;try{Y=await p9(Z,$.accountKey,B.inFlight,W,J)}catch{Q=!0}let H=Q&&z4(W.kind),U=z3(W)&&!Q&&Y?.rejectedStatus!==void 0;return{target:X,selectedCredit:B.selectedCredit,beforeState:z.beforeState,outcome:W,retrySafety:H?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":z3(W)&&!U?a9(Q,Y):s9(W),...U?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function I6(Z){let $=[];for(let X of Z)try{$.push(...await X.run())}catch(J){$.push({code:"doctor-check-failed",message:`Check ${X.id} failed: ${J instanceof Error?J.message:String(J)}`})}return{findings:$}}function b6(Z,$){let X=[Z];if($.findings.length===0)return X.push("No problems found."),X;for(let J of $.findings){let G=J.repair?" (repair available)":"";X.push(`- ${J.message}${G}`)}return X}async function y6(Z,$){let X={applied:[],declined:[],failed:[]};for(let J of $.findings){let G=J.repair;if(!G)continue;if(!await Z.confirm(`Apply repair: ${G.label}?`)){X.declined.push(J);continue}try{await G.apply(),X.applied.push(J)}catch(z){X.failed.push({finding:J,error:z}),Z.print(`Repair failed: ${G.label}: ${z instanceof Error?z.message:String(z)}`)}}return X}function B4(Z){let $=Z.title??"Auth doctor";return{id:"doctor",label:Z.label??"Auth doctor",hint:"check accounts and offer repairs",async run(X){let J=await I6(Z.checks);for(let B of b6($,J))X.print(B);let G=J.findings.filter((B)=>B.repair);if(G.length===0){if(J.findings.length>0)X.print("No repairs are available.");return}let z=await y6(X,J);X.print(`Applied ${z.applied.length} of ${G.length} repair(s).`)}}}import{spawn as n9}from"node:child_process";function f6(Z,$=process.platform,X=n9){try{if($==="win32"){let G=`Start-Process '${Z.replaceAll("'","''")}'`,z=X("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(G,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return z.on("error",()=>{}),z.unref(),z.pid!==void 0}let J=X($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore"});return J.on("error",()=>{}),J.unref(),J.pid!==void 0}catch{return!1}}function k6(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 Y3(Z,$){let X=new AbortController,J=await Z.begin({headless:!1,signal:X.signal});J.completion.catch(()=>{}),k6($,J);let G=!1;try{G=await(Z.openBrowser??f6)(J.url)!==!1}catch{G=!1}if(!G)X.abort(),$.print("Could not open a browser. Switching to device authorization."),$.print(""),J=await Z.begin({headless:!0}),k6($,J);return J.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 Q4(Z){let $=Z.toString(),X=[];for(let J=0;J<$.length;){let G=$[J];if(G==="\x1B"){let z=$.slice(J,J+3),B=z[1]==="["||z[1]==="O"?z[2]:void 0;if(B&&"ABCD".includes(B)){let Y={A:"up",B:"down",C:"right",D:"left"}[B];if(Y)X.push(Y);J+=3}else if(J+1===$.length){if(J===0)X.push("escape-start");J+=1}else if(($[J+1]==="["||$[J+1]==="O")&&J+2>=$.length)break;else J+=1;continue}if(G==="\r"||G===`
3
+ `)X.push("enter");else if(G==="\x03")X.push("escape");else if(G&&G>=" ")X.push("char");J+=1}return X}var h6=`${String.fromCharCode(27)}\\[[0-9;]*m`,i9=new RegExp(h6,"g"),r9=new RegExp(`^${h6}`);function g6(Z){return Z.replace(i9,"")}function h1(Z,$){if($<=0)return"";if(g6(Z).length<=$)return Z;let X=$>=3?"...":".".repeat($),J=Math.max(0,$-X.length),G="",z=0,B=0;while(z<Z.length&&B<J){if(Z[z]==="\x1B"){let W=Z.slice(z).match(r9);if(W){G+=W[0],z+=W[0].length;continue}}G+=Z[z],z+=1,B+=1}return G.includes("\x1B[")?`${G}${S.reset}${X}`:G+X}function W4(){return{input:process.stdin,output:process.stdout,signals:process}}function g1(Z){return Z.input.isTTY===!0}function Y4(Z,$=""){Z.output.write(`${$}
4
+ `)}var o9=50;function t9(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function r1(Z,$,X){if(!g1(Z))throw Error("Interactive select requires a TTY terminal");if($.length===0)throw Error("No menu items provided");let{input:J,output:G,signals:z}=Z,B=0,W=null,Y=!1,Q=0,H=()=>{let U=G.columns??80,j=G.rows??24,D=Q;if(X.clearScreen)G.write(S.clearScreen+S.moveTo(1,1));else if(D>0)G.write(S.up(D));let V=0,q=(C)=>{G.write(`${S.clearLine}${C}
5
+ `),V+=1},F=X.lines??[],N=1+(X.subtitle?3:0)+F.length+(F.length?1:0),L=Math.max(1,Math.min($.length,j-N-2-1)),O=Math.max(0,Math.min(B-Math.floor(L/2),Math.max(0,$.length-L))),_=$.slice(O,O+L);if(q(`${S.dim}┌ ${S.reset}${h1(X.message,Math.max(1,U-4))}`),X.subtitle)q(`${S.dim}│${S.reset}`),q(`${S.cyan}◆${S.reset} ${h1(X.subtitle,Math.max(1,U-4))}`),q("");for(let C of F)q(`${S.cyan}│${S.reset} ${h1(C,Math.max(1,U-4))}`);if(F.length)q(`${S.cyan}│${S.reset}`);for(let C=0;C<_.length;C++){let A=_[C];if(!A)continue;let T=O+C===B,R=t9(A.color),v=R?`${T?"":S.dim}${R}${A.label}${S.reset}`:T?A.label:`${S.dim}${A.label}${S.reset}`;if(A.hint)v+=` ${S.dim}${A.hint}${S.reset}`;v=h1(v,Math.max(1,U-8)),q(T?`${S.cyan}│${S.reset} ${S.green}●${S.reset} ${v}`:`${S.cyan}│${S.reset} ${S.dim}○${S.reset} ${v}`)}let M=_.length<$.length?` (${O+1}-${O+_.length}/${$.length})`:"";q(`${S.cyan}│${S.reset} ${S.dim}${h1(`Up/Down to select | Enter: confirm | Esc: back${M}`,Math.max(1,U-6))}${S.reset}`),q(`${S.cyan}└${S.reset}`);for(let C=V;C<D;C++)q("");Q=V};return new Promise((U)=>{let j=J.isRaw??!1,D=()=>{if(Y)return;if(Y=!0,W)clearTimeout(W);J.removeListener("data",F);try{J.setRawMode(j),J.pause(),G.write(S.show)}catch{}z?.removeListener("SIGINT",q),z?.removeListener("SIGTERM",q)},V=(N)=>{D(),U(N)},q=()=>V(null),F=(N)=>{for(let L of Q4(N)){if(Y)break;if(W)clearTimeout(W),W=null;switch(L){case"up":B=(B-1+$.length)%$.length,H();break;case"down":B=(B+1)%$.length,H();break;case"enter":V($[B]?.value??null);break;case"escape":V(null);break;case"escape-start":W=setTimeout(()=>V(null),o9);break;default:break}}};z?.once("SIGINT",q),z?.once("SIGTERM",q);try{J.setRawMode(!0)}catch{D(),U(null);return}J.resume(),G.write(S.hide),H(),J.on("data",F)})}async function H4(Z,$,X=!1){if(!g1(Z))return!1;return await r1(Z,X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function v6(Z){let $=g1(Z);return{terminal:Z,interactive:$,print:(X)=>Y4(Z,X),confirm:(X,J)=>H4(Z,X,J),select:async(X,J)=>$&&X.length>0?r1(Z,X,J):null}}function e9(Z,$){if(Z.print($.title),$.subtitle)Z.print($.subtitle);for(let X of $.status??[])Z.print(` ${X}`);Z.print(""),Z.print("Actions:");for(let X of $.actions)Z.print(X.hint?` - ${X.label} (${X.hint})`:` - ${X.label}`);return Z.print(""),Z.print("This menu needs an interactive terminal to choose an action; nothing was changed."),{status:"not-interactive"}}async function MZ(Z){let $=Z.terminal??W4(),X=v6($);if(!X.interactive)return e9(X,Z);if(Z.actions.length===0)return X.print("No actions are available."),{status:"cancelled"};let J=await r1($,Z.actions.map((G)=>({label:G.label,value:G,color:G.destructive?"red":"cyan",...G.hint?{hint:G.hint}:{}})),{message:Z.title,subtitle:Z.subtitle??"Select an account action",...Z.status?{lines:Z.status}:{},clearScreen:!0});if(!J)return{status:"cancelled"};if(J.destructive&&!await X.confirm(J.confirm??`${J.label}?`))return X.print("Cancelled; nothing was changed."),{status:"declined",action:J.id};try{return await J.run(X),{status:"ran",action:J.id}}catch(G){return X.print(`${J.label} failed: ${G instanceof Error?G.message:String(G)}`),{status:"failed",action:J.id,error:G}}}var m6="disabled from the auth menu",x6=8;async function F1(Z){let $=await Z.read();if($.status==="ready")return{rows:$.rows};if($.status==="pending-migration")return{rows:[],problem:"The account store has not been migrated yet."};return{rows:[],problem:`The account store could not be read (${$.file}: ${$.reason}).`}}async function Z$(Z){let{rows:$}=await F1(Z);return $.some((X)=>X.credential!==void 0)}function j4(Z){let $=[];if(Z.label)$.push(Z.label);if(Z.invalid)$.push(`invalid ${Z.invalid}`);else if(!Z.enabled)$.push(Z.disabledReason?`disabled: ${Z.disabledReason}`:"disabled");else $.push("enabled");if(!Z.credential&&!Z.invalid)$.push("no credential");return $.join(", ")}function $$(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,x6).map((J)=>`${J.id}: ${j4(J)}`),X=Z.rows.length-x6;if(X>0)$.push(`... and ${X} more`);return $}function X$(Z){return Z instanceof Error?Z.message:String(Z)}async function q4(Z,$,X){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((J)=>({label:J.id,value:J,hint:j4(J)})),{message:X})}function J$(Z,$){let X=new Set($.map((J)=>J.id));if(Z.id&&!X.has(Z.id))return Z.id;for(let J=1;;J++){let G=`account-${J}`;if(!X.has(G))return G}}function w6(Z,$=Date.now()){let X=A1(Z.quota)?q1(Z.quota):void 0,J=H3(X,{now:$,form:"full"});return(J.length>0?J:[j1(X,{now:$})]).map((G)=>` ${G}`)}function u6(Z){return{id:"add-account",label:"Add account",hint:"sign in to another account",async run($){let X=Z.login;if(!X)throw Error("No login is configured");let J=await Y3(X,$),{rows:G}=await F1(Z.store),z=(Z.newAccountId??J$)(J,G),B=await Z.store.add({id:z,credential:J.credential,...J.identity!==void 0?{identity:J.identity}:{},...J.label!==void 0?{label:J.label}:{}},Z.extraLocks?{extraLocks:Z.extraLocks}:{});if(B.outcome==="rotated")$.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")$.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")$.print(`Finished adding account ${B.id}.`);else $.print(`Added account ${B.id}.`)}}}function p6(Z){return{id:"reauthenticate",label:"Re-authenticate account",hint:"sign an account in again",async run($){let X=Z.login;if(!X)throw Error("No login is configured");let{rows:J}=await F1(Z.store),G=await q4($,J,"Re-authenticate which account?");if(!G)return;let z=await Y3(X,$);if(z.identity!==void 0&&G.identity!==void 0&&z.identity!==G.identity){$.print(`That sign-in is a different account from ${G.id}; nothing was changed. Use Add account to add it.`);return}let B=z.identity??G.identity;await Z.store.replace(G.id,z.credential,B!==void 0?{identity:B}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${G.id}.`)}}}function l6(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function d6(Z){return Z instanceof E&&Z.kind==="row-protected"?Z.message:void 0}function c6(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:X}=await F1(Z.store),J=await q4($,X,"Remove which account?");if(!J)return;if(!await $.confirm(`Remove account ${J.id}?`)){$.print("Cancelled; nothing was changed.");return}try{await Z.store.remove(J.id,l6(Z))}catch(G){let z=d6(G);if(z===void 0)throw G;$.print(`Account ${J.id} was kept: ${z}`);return}$.print(`Removed account ${J.id}.`)}}}function U4(Z){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run($){let{rows:X}=await F1(Z.store),J=await q4($,X,"Enable or disable which account?");if(!J)return;let G=Z.extraLocks?{extraLocks:Z.extraLocks}:{};if(J.enabled){await Z.store.disable(J.id,Z.disableReason??m6,G),$.print(`Disabled account ${J.id}.`);return}try{await Z.store.enable(J.id,G)}catch(z){if(z instanceof E&&z.kind==="duplicate-identity"){$.print(`Account ${J.id} stays disabled: another enabled account is the same provider account.`);return}throw z}$.print(`Enabled account ${J.id}.`)}}}function s6(Z){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run($){let X=await F1(Z.store);if(X.problem){$.print(X.problem);return}if(X.rows.length===0)$.print("No accounts yet.");for(let J of X.rows)$.print(`${J.id}: ${j4(J)}`)}}}function V4(Z){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run($){let X=await F1(Z.store);if(X.problem){$.print(X.problem);return}let J=new Map,G=Z.pollQuota;if(G)for(let B of X.rows){if(B.invalid||!B.credential||B.credentialEpoch===void 0){J.set(B.id,"no usable credential");continue}try{let W=await G(B);await Z.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},W)}catch(W){J.set(B.id,X$(W))}}let z=await F1(Z.store);if(z.rows.length===0)$.print("No accounts yet.");for(let B of z.rows){$.print(`${B.id}:`);let W=J.get(B.id);if(W)$.print(` quota check failed: ${W}`);for(let Y of w6(B,(Z.now??Date.now)()))$.print(Y)}}}}function a6(Z){return{id:"delete-all",label:"Delete all accounts",destructive:!0,confirm:"Delete every account? Accounts the plugin keeps are not deleted.",async run($){let X=await F1(Z.store);if(X.problem){$.print(X.problem);return}let J=[],G=[];for(let z of X.rows)try{await Z.store.remove(z.id,l6(Z)),J.push(z.id)}catch(B){let W=d6(B);if(W===void 0)throw B;G.push(`${z.id} (${W})`)}if($.print(`Deleted ${J.length} account(s).`),G.length>0)$.print(`Kept: ${G.join(", ")}.`)}}}async function D4(Z){return n6(Z,await Z.custody?.()===!0)}function n6(Z,$){let X=Z.doctor?.length?[B4({checks:Z.doctor})]:[],J=[...Z.extraActions??[]];if($)return[s6(Z),U4(Z),V4(Z),...X,...J];return[...Z.login?[u6(Z),p6(Z)]:[],c6(Z),U4(Z),V4(Z),...X,...J,a6(Z)]}async function G$(Z){let $=await Z.custody?.()===!0,X=n6(Z,$),[J,G]=await Promise.all([F1(Z.store),Z.status?.()??[]]);return MZ({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...$$(J)],actions:X,...Z.terminal?{terminal:Z.terminal}:{}})}function i6(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function r6(Z){return Z!==void 0}function z$(Z){return async($)=>{if(!r6($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),i6()}}function t(Z){return Z.authority!=="local"}async function a(Z){return{authority:await Z.authority(),status:await Z.status(),identities:Z.identities(),routes:new Set(Z.routes().map(($)=>$.id))}}async function U3(Z){let $;try{return await Promise.race([Promise.resolve().then(()=>Z.refresh()).then(()=>{return},(X)=>X instanceof Error?X.message:String(X)),new Promise((X)=>{$=setTimeout(()=>X("Vault roster refresh did not finish within the roster wait budget."),Y6)})])}finally{clearTimeout($)}}function Q1(Z){return Z.email||Z.label||Z.routeId}function o6(Z,$){let X=q1(A1(Z.quota)?Z.quota:void 0),J=H3(X,{now:$});return(J.length>0?J:[j1(X,{now:$})]).map((G)=>` ${G}`)}var KZ="Accounts are managed in the vault with ck. Disconnect to use local accounts.",v1="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function t6(Z){let $=[...Z.label?[Z.label]:[],Z.invalid?`invalid ${Z.invalid}`:Z.enabled?"enabled":`disabled${Z.disabledReason?`: ${Z.disabledReason}`:""}`];return`${Z.id}: ${$.join(", ")}`}async function B$(Z,$){let X=await U3($),J=await a($),{status:G}=J,z=t(J)?void 0:await Z.store.read(),B=await D4(Z),W=new Set(["check-quotas",...(Z.extraActions??[]).map((H)=>H.id)]),Y=B.filter((H)=>!t(J)||W.has(H.id)).map((H)=>({...H,run:async(U)=>{if(!W.has(H.id)&&t(await a($))){U.print(v1);return}await $.authority(),await H.run(U)}})),Q=Y.find((H)=>H.id==="check-quotas");if(Q)Q.run=async(H)=>{await U3($);let U=await a($),j=t(U)?void 0:await Z.store.read();if(!j)H.print(KZ);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(t6(q));try{if(Z.pollQuota&&q.credentialEpoch!==void 0){let L=await Z.pollQuota(q);await Z.store.recordQuota(q.id,{credentialEpoch:q.credentialEpoch,...q.identity!==void 0?{identity:q.identity}:{}},L)}}catch(L){H.print(` quota check failed: ${L instanceof Error?L.message:String(L)}`)}let F=await Z.store.read(),N=F.status==="ready"?F.rows.find((L)=>L.id===q.id):void 0;for(let L of o6(N??q,(Z.now??Date.now)()))H.print(L)}let D=U.routes;for(let q of $.snapshot()?.rows??[]){if(H.print(`Vault ${Q1(q)}: ${q.enabled?q.state:"declined"}`),!D.has(q.routeId)){H.print(" quota check skipped: account is not enabled and active");continue}let F=await $.pollQuota(q.routeId);if(!F.ok)H.print(` quota check failed: ${F.error??"vault unavailable"}`);let N=$.snapshot()?.rows.find((L)=>L.routeId===q.routeId);for(let L of o6({quota:N?.quota},(Z.now??Date.now)()))H.print(L)}let V=await $.status();if(V.lastError)H.print(`Claustrum vault unreachable: ${V.lastError}`)};return MZ({title:Z.title,subtitle:"Select an account action",status:[...await Z.status?.()??[],...X?[`Last error: ${X}`]:[],...G.lastError?[`Claustrum vault unreachable: ${G.lastError}`]:[],...G.accounts.map((H)=>`Vault ${Q1(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!z?[KZ]:z.status==="ready"?z.rows.map((H)=>t6(H)):["The local account store could not be read."]],actions:Y,...Z.terminal?{terminal:Z.terminal}:{}})}function e6(Z){return h(Z)?{...Z}:{}}function F4(Z,$){let X=A1($)?Z7($.credits):void 0;return X?`${Z} · prepaid ${X}`:Z}function X7(Z,$){return{...Z,sections:Z.sections.map((X)=>X.id!=="quota"?X:{...X,items:X.items.map((J)=>J.detail===void 0?J:{...J,detail:F4(J.detail,$.get(J.id))})})}}function V3(Z,$,X,J){let G=X.confirm?.irreversible?{irreversible:!0,confirm:X.confirm.message}:{...X.confirm?{confirm:X.confirm.message}:{}};return{id:X.id,label:X.label,...X.description?{description:X.description}:{},...X.group?{group:X.group}:{},knobs:X.knobs,...G,run:async({values:z,invocation:B})=>{let W=await Z.apply({command:Z.command,sectionId:$,...J?{itemId:J}:{},actionId:X.id,values:z,confirmed:!0},B);return{ok:W.ok,text:W.text,...W.code?{code:W.code}:{}}}}}function N4(Z,$){return new Proxy(Z,{get(X,J){if(J==="read")return async()=>{let z=await X.read();if(z.status!=="ready")return z;let B={...z,rows:z.rows.map((Q)=>({...Q,label:Q.label??Q.id}))};if(!$)return B;let W=await a($);if(!t(W))return B;let Y=[...W.status.accounts.map((Q)=>({id:Q.routeId,label:Q1(Q),type:"oauth",enabled:Q.enabled,identity:Q.accountIdentity,quota:Q.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...z,rows:Y}};if(J==="readSettings")return async()=>{let z=await X.readSettings();if(z.status==="error"||!$)return z;let B=await a($),W=e6(z.settings.killswitch);if(!t(B)||!z.settings.killswitch)return z;let Y=e6(W.accounts);for(let Q of B.status.accounts)Y[Q.routeId]=PZ({version:1,accounts:[],...z.settings},Q.routeId);return{...z,settings:{...z.settings,killswitch:{...W,accounts:Y}}}};let G=Reflect.get(X,J);return typeof G==="function"?G.bind(X):G}})}function M4(Z,$,X={}){let J=k1(Z),G=(Q)=>k1({command:Z.command,title:Z.title,store:N4(Z.store,$),accounts:Z.accounts,quota:Z.quota,limits:Z.limits,routing:{...Z.routing,formerMainId:Q??"",vaultOrder:async()=>{let H=await a($);if(!t(H))return;return{rows:H.status.accounts.map((U)=>({id:U.routeId,label:Q1(U)})),reorder:async(U)=>{if(!t(await a($)))throw new w("vault-local-action",v1);return $.reorder(U)}}}},...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.now?{now:Z.now}:{}}),z=async(Q,H)=>{let U=await a($),j=t(U),D=$7(U.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),V=j?G(D):J,F=(await V.open(H)).menu.sections.find((T)=>T.id===Q);if(!F)throw new w("unavailable","The account menu is unavailable.");if(!j)return{lines:F.lines,items:F.items.map((T)=>({...T,actions:T.actions.map((R)=>V3(V,Q,R,T.id))})),actions:F.actions.map((T)=>V3(V,Q,T))};let N=new Map(U.status.accounts.map((T)=>[T.routeId,T])),L=(Z.now??Date.now)(),O=(T)=>({id:"check",label:T?"Check this account":"Check now",group:"Actions",run:async()=>{let v=[...(await a($)).routes].filter((b)=>!T||b===T);if(T&&v.length===0)throw new w("unavailable","This vault account cannot be checked right now.");for(let b of v){let f=await $.pollQuota(b);if(!f.ok)throw new w("quota-check-failed",`${b}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${v.length} account${v.length===1?"":"s"}.`}});if(Q==="quota"){let T=(R,v)=>j1(q1(R.quota,Z.quota?.scope),{now:L,form:v});return{lines:U.status.accounts.filter((R)=>!U.routes.has(R.routeId)).map((R)=>`${Q1(R)} (${R.enabled?R.state:"disabled"}): ${F4(T(R,"compact"),R.quota)}`),items:U.status.accounts.filter((R)=>U.routes.has(R.routeId)).map((R)=>({id:R.routeId,label:Q1(R),group:"Accounts",status:T(R,"compact"),detail:F4(T(R,"full"),R.quota),actions:[O(R.routeId)]})),actions:U.routes.size>0?[O()]:[]}}let _=F.items.map((T)=>{let R=N.get(T.id),v=R&&Q==="accounts"?`Vault · ${R.credentialType==="oauth"?"login":"API key"} · ${R.state} · ${R.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:v,group:T.group,status:R&&Q==="accounts"?R.enabled?R.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:R&&Q!=="limits"?[]:T.actions.map((b)=>V3(V,Q,b,T.id))}}),M=F.actions.filter((T)=>Q==="limits"||Q==="routing"&&(T.id==="mode"||T.id==="order")).map((T)=>V3(V,Q,T)),C=F.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),A=Q==="routing"&&D===null&&C?.kind==="choice"&&(C.value==="main-first"||C.value==="fallback-first");return{lines:Q==="accounts"?[`${U.status.accounts.length} vault account${U.status.accounts.length===1?"":"s"}`,`${U.routes.size} can route`,KZ]:[...F.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:_,actions:M}},B=k1({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(Q)=>z("accounts",Q)},quota:{title:"Quota",build:(Q)=>z("quota",Q)},routing:{title:"Routing",build:(Q)=>z("routing",Q)},limits:{title:"Limits",build:(Q)=>z("limits",Q)}},extras:Z.extras?.map((Q)=>Q.id!=="reset"?Q:{...Q,build:async(H)=>{let U=await a($);if(t(U))return{lines:[KZ]};return Q.build(H)}})}),W=async()=>{if(!t(await a($)))return{menu:J,error:void 0};let Q=X.refresh===!1?void 0:await U3($);return{menu:B,error:Q}},Y=async(Q,H)=>{let U=await Q.menu.open(H);if(Q.error)U.menu.sections.find((D)=>D.id==="vault")?.lines.push(`Last error: ${Q.error}`);return U};return{command:Z.command,open:async(Q)=>Y(await W(),Q),apply:async(Q,H)=>{let U=await W(),{menu:j}=U;if(j===B&&(Q.sectionId==="accounts"||Q.sectionId==="reset"||Q.sectionId==="quota"&&(await a($)).routes.size===0||Q.sectionId==="limits"&&Q.itemId!==void 0&&!(await a($)).status.accounts.some((D)=>D.routeId===Q.itemId)))return{...await Y(U,H),ok:!1,code:"vault-local-action",text:v1};if(X.refuseApply)return{...await Y(U,H),ok:!1,...X.refuseApply};return j.apply(Q,H)}}}var CZ="openai",Q7="OpenAI accounts",S1="main",W7="that account is already your main account, so it was not added again",Z1=i("commands"),Y7=new Set(["__proto__","constructor","prototype"]);function Q$(Z,$){let X={version:1,accounts:[],killswitch:Z},J=h(Z.accounts)?Object.keys(Z.accounts):[],G={};for(let W of new Set([S1,...$,...J])){if(Y7.has(W))continue;let Y=PZ(X,W===S1?void 0:W);G[W]={primary:Y.primary,secondary:Y.secondary}}let z=PZ(X,void 0),B={...Z};return delete B.main,B.accounts=G,B.defaults={primary:z.primary,secondary:z.secondary},B.schema=_Z,B}function W$(Z,$){let X=h(Z.accounts)?{...Z.accounts}:{};for(let G of new Set([S1,...$])){if(Y7.has(G)||Object.hasOwn(X,G))continue;X[G]={primary:LZ.primary,secondary:LZ.secondary}}let J=h(Z.defaults)?Z.defaults:{primary:LZ.primary,secondary:LZ.secondary};return{...Z,accounts:X,defaults:J,schema:_Z}}function J7(Z,$){let X=!1;if(h(Z.cachekeep))Z.cacheKeep={...Z.cachekeep,...h(Z.cacheKeep)?Z.cacheKeep:{}},delete Z.cachekeep,X=!0;let J=Z.killswitch;if(h(J)&&J.schema!==_Z)Z.killswitch=Q$(J,$),X=!0;return X}async function G7(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((X)=>X.id):[]}function L4(Z){let $=async()=>{let J=await Z.readSettings();if(J.status==="error")return J;let G=structuredClone(J.settings);return J7(G,await G7(Z)),{...J,settings:G}},X=async(J,G)=>{let z=await G7(Z);return Z.updateSettings(async(B)=>{J7(B,z);let W=await J(B)??B;if(h(W.killswitch)&&W.killswitch.schema!==_Z)W.killswitch=W$(W.killswitch,z);return W},G)};return new Proxy(Z,{get(J,G){if(G==="readSettings")return $;if(G==="updateSettings")return X;let z=Reflect.get(J,G,J);return typeof z==="function"?z.bind(J):z}})}function Y$(Z,$){let X=(Y,Q)=>$.rowLocks?$.rowLocks(Y):Q,J=(Y,Q)=>{let H=X(Y,Q?.extraLocks);return{...Q??{},...H?{extraLocks:H}:{}}},G=(Y,Q,H,U)=>Z.replace(Y,Q,H,J(Y,U)),W={add:async(Y,Q)=>{let H=await Z.read(),j=(H.status==="ready"?H.rows:[]).filter((F)=>F.type==="oauth"&&!F.invalid),D=Y.identity?j.find((F)=>F.identity===Y.identity):void 0;if(D?.id===S1)throw new w("main-account",W7);let V=D??j.find((F)=>F.id===Y.id&&F.id!==S1);if(!V||Y.credential.type!=="oauth")return Z.add(Y,Q);let q=await G(V.id,Y.credential,Y.identity!==void 0?{identity:Y.identity}:{},Q?.extraLocks?{extraLocks:Q.extraLocks}:void 0);return Z1.info("account signed in again",{id:V.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:G,enable:(Y,Q)=>Z.enable(Y,J(Y,Q)),disable:(Y,Q,H)=>Z.disable(Y,Q,J(Y,H)),remove:(Y,Q)=>Z.remove(Y,J(Y,Q))};return new Proxy(Z,{get(Y,Q){if(Object.hasOwn(W,Q))return W[Q];let H=Reflect.get(Y,Q,Y);return typeof H==="function"?H.bind(Y):H}})}async function EG(Z,$,X){await L4(Z).updateSettings((J)=>{X(J);return},$?{extraLocks:$}:{})}var H$=["version","accounts","commonAuthPool"];function IG(Z,$){return async(X)=>{let J;if(await L4(Z).updateSettings((G)=>{let z={...G,version:1,accounts:[]},B=X(z)??z;J=B;let W={...B};for(let Y of H$)delete W[Y];return W},$?{extraLocks:$}:{}),!J)throw Error("the settings write did not run");return J}}var U$="migration";function z7(Z){let $=["Accounts move to the new account layout once every OpenCode process on this machine runs this version of OpenAI auth. This menu works on that layout, so it opens after the move.",Z.length>0?"These processes still hold the move back:":"No running process holds the move back."],X={command:CZ,title:Q7,sections:[{id:U$,slot:"extra",title:"Accounts are moving",lines:$,items:Z.map((J,G)=>({id:`blocker-${G}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return P4(X)}var V$=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function j$(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(V$.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function K4(Z,$,X){if(Array.isArray(Z))return Z.map((G,z)=>K4(G,`${$}[${z}]`,X));if(!h(Z))return Z;let J={};for(let[G,z]of Object.entries(Z)){if(j$(G)){X.push(`${$}.${G}`);continue}J[G]=K4(z,`${$}.${G}`,X)}return J}function P4(Z){let $=[],X=K4(Z,"menu",$);if($.length>0)Z1.warn("credential-shaped field stripped before RPC",{fields:$});return X}function q$(Z){return{id:Z.id,credential:{type:"oauth",refresh:Z.refresh,...Z.access!==void 0?{access:Z.access}:{},...Z.expires!==void 0?{expires:Z.expires}:{}},...Z.accountId!==void 0?{identity:Z.accountId}:{},...Z.label!==void 0?{label:Z.label}:{}}}function D$(Z,$){return{label:"Add account",knobs:[{kind:"text",id:"label",label:"Label (optional)"},{kind:"toggle",id:"headless",label:"Sign in with a device code (no browser on this machine)",value:!1}],run:async(X)=>{let J=typeof X.label==="string"&&X.label.trim().length>0?X.label.trim():void 0,G=X.headless===!0,z=await Z.begin({...J!==void 0?{label:J}:{},headless:G}),B=G?`Open this verification URL:
6
+
7
+ ${z.url}
8
+
9
+ Then enter the code: ${z.instructions.match(/Enter code: (.+)/)?.[1]??z.instructions}
10
+
11
+ The account is added when you finish.`:`Open this URL and complete sign-in:
12
+
13
+ ${z.url}
14
+
15
+ ${z.instructions}
16
+
17
+ The account is added when you finish.`,W=z.completion.then(async(Y)=>{if($&&await $.authority()!=="local")throw new w("vault-local-action",v1);let Q=await Z.mainIdentity?.();if(Y.id===S1||Y.accountId&&Q&&Y.accountId===Q)throw Z1.warn("account add rejected (main identity)",{id:Y.id}),new w("main-account",W7);return Z1.info("account added",{id:Y.id}),q$(Y)});return{status:"pending",message:B,completion:W}}}}function bG(Z){return{id:"session",title:"This session",build:async($)=>{let X=$.sessionId;if(!X)return{lines:["No current session"]};let J=await Z.getPin?.(X);return{lines:[J?`Pinned to ${J}`:"No sticky pin"],actions:Z.clearPin?[{id:"clear-pin",label:"Clear this session's pin",description:"The next request may still choose the same account.",run:async({invocation:G})=>{if(!G.sessionId)return"No current session.";return await Z.clearPin?.(G.sessionId),Z1.info("routing session pin cleared"),"This session's pin was cleared. The next request may choose the same account if it remains the best selection."}}]:[]}}}}function yG(Z){let{vault:$}=Z;return{id:"vault",title:"Vault",build:async()=>{let X=await $.status(),J=await $.authority()!=="local",G=$.routes().length;return{lines:[J?`Connected · ${X.accounts.length} account${X.accounts.length===1?"":"s"}`:X.enrollment.state==="idle"?"Not connected":`Enrollment ${X.enrollment.state}`,U6(X.host,X.name,X.enrollment),...G3(X.name,X.enrollment),...J?[X.accounts.length===0?Z3(X.name,$.grantReach()):`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${G} can route now.`]:[],...J&&$.snapshot()?.complete===!1?["The vault's last list had records this host could not read; accounts it did not list are kept as they were until a complete list arrives."]:[],...X.lastError?[`Last error: ${X.lastError}`]:[]],items:X.accounts.map((z)=>({id:z.routeId,label:Q1(z),group:"Accounts",status:z.enabled?z.state:"disabled",detail:[z.credentialType==="api_key"?"API key":"login",z.state==="active"?"active":`vault state ${z.state}`,z.enabled?"enabled":"disabled here"].join(", "),actions:[z.enabled?{id:"disable",label:"Disable on this host",description:"It stays in the vault and in this list, and is never sent from this host until enabled again.",run:async()=>{return await $.decline(z.routeId),await Z.changed?.(),`${Q1(z)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(z.routeId),await Z.changed?.(),`${Q1(z)} is enabled on this host.`}}]})),actions:J?[{id:"disconnect",label:"Disconnect",description:"Forgets this host's vault token; its vault accounts stop routing at once. Revoke the enrollment itself with `ck auth enroll revoke`.",confirm:"Disconnect from the vault? Connecting again needs a new approval with `ck`.",run:async()=>{return await $.disconnect(),await Z.changed?.(),`Disconnected: ${$.name} no longer reads from the vault. Run \`ck auth enroll revoke --name ${$.name}\` to revoke it in the vault too.`}}]:[{id:"connect",label:"Connect",description:"Asks the vault to enroll this host; you approve the request with `ck`.",run:async({invocation:z})=>{let B=await $.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await Z.changed?.(),$4($,B);return $.waitForApproval(Z.wait).then(async(W)=>{await Z.changed?.();let Y=$4($,W);z.notify(Y.text,Y.ok?"info":"warning")}).catch((W)=>{z.notify(`Connecting to the vault failed: ${W instanceof Error?W.message:String(W)}`,"error")}),{ok:!0,text:[...G3($.name,B),"Waiting for the approval; you are told here when it lands."].join(`
18
+ `)}}}]}}}}async function B7(Z,$,X){if(!P1($))return e($,"invalid_account_key","That account cannot take a reset credit.");let J;try{let G=(await Z.loadAccounts({configPath:Z.configPath,statePath:Z.statePath}))?.reset?.[$];if(X||G&&Object.hasOwn(G,"inFlight"))J=(await Z.resolveResetTarget($)).chatgptAccountId;else{let B=await U7($,Z);if(!B.eligible)return e($,"not_eligible",V7(B));J=B.chatgptAccountId}if(!J)return e($,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");Z1.info("reset redemption decision",{accountKey:$,retry:X});let z=await E6({configPath:Z.configPath,statePath:Z.statePath,mutateAccountsFn:Z.mutateAccounts,loadAccountsFn:Z.loadAccounts,now:Z.now,randomUUID:Z.randomUUID,fetchImpl:Z.fetchImpl,resolveTarget:Z.resolveResetTarget,fetchUsage:(B)=>FZ({accessToken:B.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:$,expectedChatgptAccountId:J,retry:X});return Z1.info("reset redemption outcome",{accountKey:$,code:z.outcome.kind}),j7(z,Z,J)}catch(G){let z=L$($,G,J);return Z1.info("reset redemption outcome",{accountKey:$,code:z.code}),z}}function kG(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===S1?"Main account":$,actions:[{id:"preview",label:"Preview",description:"Fetch the account's current quota and reset credits before spending a credit.",run:async()=>{let X=await U7($,Z);return{ok:X.eligible,text:`${P$(X)}
19
+
20
+ ${V7(X)}`}}},{id:"spend",label:"Spend a reset credit",irreversible:!0,confirm:"Spend one reset credit on this account? Its eligibility is checked again first, and nothing is spent when it is not eligible.",run:async()=>{let{ok:X,text:J}=await B7(Z,$,!1);return{ok:X,text:J}}},{id:"retry",label:"Retry the last redemption",irreversible:!0,confirm:"Retry the last redemption? A retry within five minutes reuses the same request and credit identifiers.",run:async()=>{let{ok:X,text:J}=await B7(Z,$,!0);return{ok:X,text:J}}}]}))})}}var F$=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],N$=["primary","secondary"];function fG(Z){let $=new Set(Z.unavailableSections),X=(Q)=>({title:Q,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...Z.extras??[]];if($.has("reset")){let Q={id:"reset",...X("Reset credits")},H=J.findIndex((U)=>U.id==="reset");if(H<0)J.unshift(Q);else J[H]=Q}let G={command:CZ,title:Q7,store:N4(L4(Y$(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:D$(Z.login,Z.vault)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:F$,formerMainId:S1},limits:{labels:N$},...$.has("cache")?{cache:X("Cache")}:Z.cache?{cache:Z.cache}:{},...$.has("diagnostics")?{diagnostics:X("Diagnostics")}:Z.diagnostics?{diagnostics:Z.diagnostics}:{},extras:J,...Z.logger?{logger:Z.logger}:{},...Z.now?{now:Z.now}:{}},z=Z.vault?M4(G,Z.vault,{refresh:!Z.readOnly,...Z.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):k1(G),B=Z.vault?M4(G,Z.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,W=(Q)=>{let{sessionId:H}=Q,U=Q.notify.bind(Q);return{...H!==void 0?{sessionId:H}:{},notify:U}},Y=async(Q)=>{if(Z.vault&&await Z.vault.authority()!=="local")return Q;let H=await Z.store.read().catch(()=>{return});if(H?.status!=="ready")return Q;return{...Q,menu:X7(Q.menu,new Map(H.rows.map((U)=>[U.id,U.quota])))}};return{command:CZ,async open(Q){let H=W(Q),U=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(U&&!U.migrated)return{command:CZ,menu:z7(U.blockers)};let j=await z.open(H);return Y({...j,menu:P4(j.menu)})},async apply(Q,H){let U=W(H),j=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(j&&!j.migrated)return{command:CZ,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:z7(j.blockers)};if(Z.readOnly&&Z.vault)return z.apply(Q,U);if(Z.readOnly||Z.allowAction&&!Z.allowAction(Q)||$.has(Q.sectionId)){if(B)return B.apply(Q,U);return{...await z.open(U),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let D=await z.apply(Q,U);if(D.ok)await Z.afterApply?.();return Y({...D,menu:P4(D.menu)})}}}function H7(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((X)=>X!==void 0);return $.length>0?Math.max(...$):void 0}function M$(Z,$){let X=[Z.primary,Z.secondary].filter((G)=>G!==void 0),J=X.filter((G)=>NZ(G,$));return(J.length>0?J:X).sort((G,z)=>z.usedPercent-G.usedPercent)[0]?.resetsAt}function K$(Z,$){if(!Z)return!1;let X=[Z.primary,Z.secondary].filter((J)=>J!==void 0);if(X.length===0)return!1;return X.every((J)=>!NZ(J,$))}async function U7(Z,$){let X;try{X=await $.resolveResetTarget(Z);let J=X.accountKey==="main"?void 0:X.chatgptAccountId,[G,z]=await Promise.all([FZ({accessToken:X.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:X.chatgptAccountId}),G4($.fetchImpl,X.accessToken,J)]),B=W3(z.credits),W=R6(z.credits),Y=z.availableCount??G.resetCreditsAvailable??(W>0?W:void 0),Q=G.resetCreditsApplicable,H=J4(G,$.quotaManager.isRateLimited(Z),$.now()),U;if(!X.chatgptAccountId)U="stable ChatGPT account identity unavailable";else if(!H.ok)U=H.reason;else if(!B)U="no eligible credit";return{accountKey:X.accountKey,label:X.label,chatgptAccountId:X.chatgptAccountId,usedPercent:H7(G),resetTime:M$(G,$.now()),availableCount:Y,applicableAvailableCount:Q,eligible:U===void 0,reason:U,selectedCreditId:B?.id,selectedCreditExpiresAt:B?.expiresAt}}catch(J){if(J?.status===401)await X?.onAuthFailure?.(401);return Z1.warn("reset preview row failed",{accountKey:Z,error:J?.message??String(J)}),{accountKey:Z,label:Z==="main"?"Main account":Z,eligible:!1,reason:J?.message??String(J)}}}function P$(Z){let $=Z.usedPercent===void 0?"quota unavailable":`${Z.usedPercent}% used`,X=Z.availableCount===void 0?"credits unavailable":`${Z.applicableAvailableCount===void 0?"?":Z.applicableAvailableCount}/${Z.availableCount} applicable/available`,J=Z.eligible?`eligible · credit ${Z.selectedCreditId} expires ${Z.selectedCreditExpiresAt}`:Z.reason;return`${$}; ${X}; ${J}`}function V7(Z){let $=["## Confirm reset credit","",`Account: **${Z.label}** (\`${Z.accountKey}\`)`,`Current quota: **${Z.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Z.availableCount??"unknown"}**`,`Credit expires: **${Z.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Z.resetTime??"unavailable"}**`,""];if((Z.availableCount??0)>0&&Z.applicableAvailableCount===0)$.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),$.push("");if(Z.eligible&&Z.chatgptAccountId)$.push('Eligible: choose "Spend a reset credit" to redeem one.');else $.push(`Cannot reset: **${Z.reason??"not eligible"}**`);return $.join(`
21
+ `)}function e(Z,$,X,J={}){if(Object.keys(J).length>0)Z1.debug("reset step details",{accountKey:Z,code:$,...J});return{ok:$==="reset"||$==="already_redeemed",code:$,text:X}}function L$(Z,$,X){if($ instanceof o){let G={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",pair_identity_mismatch:"Nothing was sent: the saved redemption was started while this account was signed in as a different ChatGPT account. Sign this account back in as that ChatGPT account and retry, or wait until five minutes after the saved redemption started and spend a new credit.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return e(Z,$.kind,`## Reset credit
22
+
23
+ ${G[$.kind]}
24
+
25
+ Code: \`${$.kind}\``,{cooldownUntil:$.cooldownUntil,...$.kind==="expired_unreconciled"?{chatgptAccountId:X,retryGuidance:"Retry replays the same request and credit identifiers from the previous attempt."}:{}})}let J=$?.code;if(J==="unknown_account"||J==="disabled_account"||J==="non_oauth_account"||J==="token_unavailable")return e(Z,J,`## Reset credit
26
+
27
+ ${{unknown_account:"Account unavailable: the selected account no longer exists. Reopen the reset account list.",disabled_account:"Account unavailable: the selected account is disabled. Reopen the reset account list.",non_oauth_account:"Account unavailable: the selected account is not authenticated with OAuth. Reopen the reset account list.",token_unavailable:"Authentication problem: the selected account token is unavailable. Reauthenticate the account before retrying."}[J]}
28
+
29
+ Code: \`${J}\``);if($ instanceof f1)return e(Z,$.kind,`## Reset credit
30
+
31
+ No redemption was attempted: reset credit availability could not be loaded.
32
+
33
+ Code: \`${$.kind}\``);return Z1.warn("reset command failed before a known result",{accountKey:Z,error:$?.message??String($)}),e(Z,"error",`## Reset credit
34
+
35
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function j7(Z,$,X){let{accountKey:J}=Z.target,G=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return e(J,G,`## Reset credit result
36
+
37
+ Account: **${Z.target.label}** (\`${J}\`)
38
+
39
+ The server outcome recorded as \`${G}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:Z.retrySafety,chatgptAccountId:X});if(G==="reset"||G==="already_redeemed"){let B={account:J,ok:!1,error:"targeted quota refresh did not complete"};try{B=await $.refreshResetTargetQuota(J)}catch(D){B.error=D?.message??String(D)}let W=!B.ok&&B.error!==void 0;if(W)Z1.warn("reset quota re-check failed",{accountKey:J,error:B.error});let Y=J==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(J),Q=B.ok&&K$(Y?.quota,$.now()),H=Y?.quota.resetCreditsApplicable,U=Q?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${G}\`).`,j=W?`
40
+
41
+ quota re-check failed — see log.`:"";return e(J,G,`## Reset credit result
42
+
43
+ Account: **${Z.target.label}** (\`${J}\`)
44
+
45
+ Code: \`${G}\`
46
+
47
+ ${U}${j}${H===void 0?"":`
48
+
49
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:Q,afterUsedPercent:H7(Y?.quota??{}),remainingCredits:H})}if(G==="ambiguous_local")return e(J,G,`## Reset credit result
50
+
51
+ Account: **${Z.target.label}** (\`${J}\`)
52
+
53
+ Code: \`${G}\`
54
+
55
+ ${Z.retrySafety}`,{retryGuidance:Z.retrySafety});if(G==="ambiguous"||G==="http_error"){let B=Z.refused?' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.':"";return e(J,G,`## Reset credit result
56
+
57
+ Account: **${Z.target.label}** (\`${J}\`)
58
+
59
+ The redemption outcome is unknown (\`${G}\`).
60
+
61
+ Retry with "Retry the last redemption" on this account. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.${B}`,{retryGuidance:Z.retrySafety,chatgptAccountId:X})}let z={nothing_to_reset:"The server found no exhausted quota window to reset. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions.",no_credit:"The server found no usable reset credit. No reset was confirmed. A new attempt starts fresh and must pass the current preconditions."};return e(J,G,`## Reset credit result
62
+
63
+ Account: **${Z.target.label}** (\`${J}\`)
64
+
65
+ Code: \`${G}\`
66
+
67
+ ${z[G]??"The server returned a no-op result. No reset was confirmed."}`)}var C4=i("quota"),q7="the account holds a tombstone from the removed vault custody, not a credential";function C$(Z){return Z?.status===401}async function uG(Z,$={}){let X=Z.whamFn;if(!X)throw Error("whamFn is required for refreshAllQuota");let J=[],G=Z.logger??C4,z=(V)=>{J.push(V);let q={pid:process.pid,accountId:V.account,status:V.ok?"ok":"error",...V.error?{error:V.error}:{}};if(V.ok)G.debug("quota refresh succeeded",q);else G.warn("quota refresh failed",q)},B=Z.skipFresherThanMs,W=!1,Y;if(B!==void 0)try{Y=await Z.readSidebarState()}catch{}let Q=new Map(Y?.fallbacks.map((V)=>[V.id,V])??[]),H=(...V)=>B!==void 0&&V.some((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=Z.now()&&Z.now()-q<B),U=await Z.loadAccounts(Z.paths).catch(()=>{return}),j=U?.mainAccountId??Z.storageMainAccountId,D;if(!$.accountKey||$.accountKey==="main")try{let V=await Z.getAuth();if(M7(V)){if(D=K7(U),!D)z({account:"main",ok:!1,error:TZ(V)?q7:"main account row is missing from the account pool"})}else if(V.type==="oauth"){let q=Y&&j!==void 0&&Y.main.mainAccountId===j?Y.main.quota:void 0;if(H(Z.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.checkedAt))z({account:"main",ok:!0});else{if(!V.access||(V.expires??0)<Z.now()){let N=await Z.refreshMainWithLease();V={...V,access:N.access,expires:N.expires}}if(V.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())z({account:"main",ok:!0});else{let N=await X({accessToken:V.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:j,accountKey:"main"});Z.quotaManager.setMain(V.access,{quota:N,refreshAfter:Z.now()+300000,checkedAt:Z.now()},j,!0),W=!0,z({account:"main",ok:!0})}else if(!J.some((N)=>N.account==="main"))z({account:"main",ok:!1,error:"no access token"})}}else z({account:"main",ok:!1,error:"auth type is not oauth"})}catch(V){z({account:"main",ok:!1,error:D1(V)})}if(U)for(let V of U.accounts){let q=D!==void 0&&V===D;if(!q&&$.accountKey&&($.accountKey==="main"||V.id!==$.accountKey))continue;if(!q&&Z.isOAuthAccountFn(V)&&N7(U,V)){if($.accountKey)z({account:V.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let F=q?V.accountId??j:void 0,N=(L,O,_)=>{if(q)Z.quotaManager.setMain(O,L,F,!0);else Z.quotaManager.setFallback(V.id,L,O,!0,_)};if(V.enabled===!1||!Z.isOAuthAccountFn(V)){if($.accountKey)z({account:V.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let L=Q.get(V.id),O=V.accountId,_=q?Y&&F!==void 0&&Y.main.mainAccountId===F?Y.main.quota:void 0:L&&O!==void 0&&L.accountId===O?L.quota:void 0;if(H(q?Z.quotaManager.peekMainForPolicy(F)?.checkedAt:Z.quotaManager.peekFallbackForPolicy(V.id,O)?.checkedAt,_?.primary?.checkedAt,_?.secondary?.checkedAt,_?.checkedAt)){z({account:V.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(V.id,V.access))){z({account:V.id,ok:!0});continue}let M=V.lastRefreshError;if(D7(M,V.refresh,Z.now())){z({account:V.id,ok:!1,error:F7(M,Z.now()),permanent:!0});continue}if(TZ(V)){z({account:V.id,ok:!1,error:q7});continue}let C;try{C=q?await Z.fallbackManager.refreshAccount(V,U,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(V,U)}catch(T){C4.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:V.id,error:D1(T)}),C=V}if(!C.access||(C.expires??0)<Z.now()){z({account:V.id,ok:!1,error:"no usable access token"});continue}let A;try{A=await X({accessToken:C.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:C.accountId,accountKey:V.id})}catch(T){if(!C$(T))throw T;if(C4.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:V.id}),C=await Z.fallbackManager.refreshAccount(V,U,q?{force:!0,asPoolMain:!0}:{force:!0}),!C.access){z({account:V.id,ok:!1,error:"no usable access token after forced refresh"});continue}A=await X({accessToken:C.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:C.accountId,accountKey:V.id})}N({quota:A,refreshAfter:Z.now()+300000,checkedAt:Z.now()},C.access,C.accountId),W=!0,z({account:V.id,ok:!0})}catch(L){z({account:V.id,ok:!1,error:D1(L)})}}if($.accountKey&&$.accountKey!=="main"&&!J.some((V)=>V.account===$.accountKey))J.push({account:$.accountKey,ok:!1,error:"account not found"});if(B===void 0||W){let V=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,V)}return J}import{types as _$}from"node:util";var T$=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,O$=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function T7(Z){return Z.replace(/\\(?:u([a-f\d]{4})|(["\\/bfnrt]))/gi,($,X,J)=>{if(X)return String.fromCharCode(Number.parseInt(X,16));return{b:"\b",f:"\f",n:`
68
+ `,r:"\r",t:"\t"}[J]??J??$})}function A$(Z,$){if(!$)return Z;let X=Z.split($).join("[credential]"),J=$.replace(/\s/g,"");if(!J)return X;let G=X.replace(/\s/g,"");if(!G.includes(J))return X;let z=[];for(let Y=0;Y<X.length;Y++){let Q=X[Y]??"";if(!/\s/.test(Q))z.push(Y)}let B=[],W=0;for(let Y=G.indexOf(J);Y>=0;Y=G.indexOf(J,Y+J.length)){let Q=z[Y]??W,H=(z[Y+J.length-1]??Q)+1;B.push(X.slice(W,Q),"[credential]"),W=H}return B.length?B.join("")+X.slice(W):X}function P7(Z,$){let X=A$(Z,$);return _7(X).replaceAll("***REDACTED***","[credential]")}function o1(Z,$){let X=P7(Z,$),J=T7(X),G=P7(J,$);return G===J?X:G}function L7(Z){let $=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(Z);if(!$)return;let X=$[3]??"",J=($[2]??"")+X,G=0;while(J[G]==="0")G++;if(G===J.length)return"0";let z=J.length;while(J[z-1]==="0")z--;let B=$[4]??"0",W=B.startsWith("-")||B.startsWith("+")?1:0;while(B[W]==="0")W++;let Y=B.slice(W)||"0";if(Y.length>16)return;let Q=BigInt((B.startsWith("-")?"-":"")+Y)-BigInt(X.length)+BigInt(J.length-z);return`${$[1]}${J.slice(G,z)}e${Q}`}function O7(Z,$){let X=$?L7($):void 0;return Z.replace(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null/g,(J)=>{if(!J.startsWith('"'))return $&&(J===$||X!==void 0&&L7(J)===X||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===$)?'"[credential]"':J;let G=T7(J.slice(1,-1)),z=o1(G,$);return z===G?J:JSON.stringify(z)})}function T4(Z,$){let X=O7(Z,$);try{return JSON.parse(Z),X}catch{return o1(X,$)}}var S$=16384,R$=65536,E$=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function I$(Z){try{let $=x(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let X=0,J,G=!0,z=!1,B;for(let W of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let Y=W[0];if(Y==="{"||Y==="["){X++;continue}if(Y==="}"||Y==="]"){X--;continue}if(X!==1)continue;if(Y===","){G=!0,z=!1,J=void 0;continue}if(Y===":"){z=!0;continue}if(G&&Y.startsWith('"')){J=JSON.parse(Y),G=!1;continue}if(z&&J==="request_id"&&!Y.startsWith('"'))B=Y;z=!1}return B}catch{return}}function b$(Z,$){let X=T4(Z,$);if(Buffer.byteLength(X,"utf8")<=R$)return X;let J=E$.flatMap((z)=>z.exec(X)?.[0]??[]);for(let z of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(z))J.push(z);let G={retry:J};try{let z=JSON.parse(X);if(x(z,"type")==="error")G.type="error";let B=x(z,"error"),W={};for(let Q of["code","type"]){let H=x(B,Q);if(typeof H==="string")W[Q]=H.slice(0,256)}if(Object.keys(W).length)G.error=W;let Y={};for(let Q of["workspace","limitName"]){let H=x(x(z,"metadata"),Q);if(typeof H==="string")Y[Q]=H.slice(0,256)}if(Object.keys(Y).length)G.metadata=Y}catch{}return JSON.stringify(G)}function j3(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let X=0;$&&X<16;X++){if(_$.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function x(Z,$){if(!j3(Z))return;let X=Object.getOwnPropertyDescriptor(Z,$);return X&&"value"in X?X.value:void 0}function OZ(Z,$){return o1(Z,$).slice(0,S$)}function t1(Z,$){let X=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!X)throw Error(`Missing native ${$} accessor`);return X}var y$=t1(DOMException.prototype,"message"),k$=t1(DOMException.prototype,"name");function _4(Z,$){let X=x(Z,"message"),J=x(Z,"name");if(j3(Z)&&Z instanceof DOMException)try{X=y$.call(Z),J=k$.call(Z)}catch{}let G=Error(OZ(typeof X==="string"?X:typeof Z==="string"?Z:"Provider request failed",$));for(let U of Object.getOwnPropertyNames(G))if(U!=="message")Reflect.deleteProperty(G,U);Object.defineProperty(G,"name",{value:typeof J==="string"?OZ(J,$):"Error",configurable:!0,writable:!0});let z=(U,j,D)=>{let V=x(U,D);if(typeof V==="string"||typeof V==="number"&&Number.isFinite(V)||typeof V==="boolean")Object.defineProperty(j,D,{value:typeof V==="string"?OZ(V,$):V,enumerable:!0,configurable:!0,writable:!0})};for(let U of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=x(Z,U);if(typeof j==="number"&&Number.isFinite(j))z(Z,G,U)}for(let U of["code","type","isRetryable"])z(Z,G,U);for(let U of["error","data"]){let j=x(Z,U),D=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])z(j,D,q);let V=x(j,"error");if(j3(V)){let q=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])z(V,q,F);D.error=q}if(Object.keys(D).length)Object.defineProperty(G,U,{value:D,enumerable:!0})}let B=x(Z,"responseHeaders");if(B&&typeof B==="object"){let U={};for(let j of["retry-after-ms","retry-after"]){let D=x(B,j);if(typeof D==="string")U[j]=OZ(D,$)}Object.defineProperty(G,"responseHeaders",{value:U,enumerable:!0})}let W=x(Z,"responseBody");if(typeof W==="string")Object.defineProperty(G,"responseBody",{value:b$(W,$),enumerable:!0});let Y=x(Z,"request_id"),Q=x(B,"x-request-id"),H=typeof Y==="string"?Y:typeof Q==="string"?Q:typeof W==="string"?I$(T4(W,$)):void 0;if(typeof H==="string")Object.defineProperty(G,"request_id",{value:OZ(H,$),enumerable:!0});for(let U of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(U);if(x(Z,j)===!0)Object.defineProperty(G,j,{value:!0})}return G}function f$(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!T$.test(Z)&&!O$.test(Z)))return Z;let X;try{X=JSON.parse(Z)}catch{return Z}if(X?.type==="error"||X?.error||X?.response?.error)return O7(Z,$);return Z}var h$=t1(Response.prototype,"status"),g$=t1(Response.prototype,"statusText"),v$=t1(Response.prototype,"headers"),x$=t1(Response.prototype,"body"),m$=Response.prototype.text,C7=Headers.prototype.entries;async function cG(Z,$,X="http"){try{let D=function(V){let q=j&&V.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+V.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(F,N)=>F.slice(0,F.length-N.length)+f$(N,$))};if(!j3(Z))throw Error("Invalid provider response");let J=h$.call(Z),G=v$.call(Z),z=x$.call(Z),B=new Headers;for(let[V,q]of C7.call(G))B.append(V,q);let W={status:J,statusText:o1(g$.call(Z),$),headers:B};if(J<200||J>299){for(let[q,F]of C7.call(G)){if(o1(q,$?.toLowerCase())!==q){W.headers.delete(q);continue}try{W.headers.set(q,o1(F,$))}catch{W.headers.delete(q)}}W.headers.delete("content-length");let V=await m$.call(Z);return new Response(T4(V,$),W)}if(!z||X==="http")return Z;W.headers.delete("content-length");let Y=ReadableStream.prototype.getReader.call(z),Q=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,U="",j=!0;return new Response(new ReadableStream({async pull(V){try{for(;;){let q=await Y.read();U+=Q.decode(q.value,{stream:!q.done});let F=!1;for(;;){let N=/\r?\n\r?\n/.exec(U);if(!N)break;let L=N.index+N[0].length;V.enqueue(H.encode(D(U.slice(0,L)))),U=U.slice(L),F=!0}if(q.done){if(U)V.enqueue(H.encode(D(U)));V.close();return}if(F)return}}catch(q){V.error(_4(q,$))}},async cancel(V){try{await Y.cancel(V)}catch(q){throw _4(q,$)}finally{Y.releaseLock()}}}),W)}catch(J){throw _4(J,$)}}function nG(Z,$,X){let J=Z.get($.sessionId),G=new Set($.validPinnedAccountIds);if(J&&!$.excludeAccountIds.includes(J.accountId)&&A7(J,G,$.wireAccountIdByAccount[J.accountId])){if($.persist){let Y=$.quotaCheckedAtByAccount[J.accountId];X($.sessionId,{accountId:J.accountId,inputBytes:$.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...Y!==void 0?{quotaCheckedAt:Y}:{}})}return{accountId:J.accountId}}let z=new Map(Object.entries($.quotaCheckedAtByAccount)),B=S7(Z,z,$.sessionId),W=$.select(B);if(!W)return;if($.persist){let Y=$.wireAccountIdByAccount[W.accountId];X($.sessionId,{accountId:W.accountId,inputBytes:$.requestBytes,...Y!==void 0?{wireIdentity:Y}:{},...W.quotaCheckedAt!==void 0?{quotaCheckedAt:W.quotaCheckedAt}:{}})}return{accountId:W.accountId}}import{statSync as w$}from"node:fs";var b7=30000,u$=8,p$=1800000;function y7(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function eG(Z){try{let $=w$(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function Zz(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function l$(Z,$){try{return R7(Z,$)}catch{return Z}}function $z(Z,$,X){let J=y7($);Z.set(J,[...Z.get(J)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:X}].slice(-u$))}function Xz(Z,$,X){let J=Z;for(let G of $.get(y7(Z))??[]){if(!(X-G.observation.checkedAt<=p$)||G.credentialEpoch!==Z.credentialEpoch||G.identity!==Z.identity)continue;J={...J,quota:l$(J.quota,G.observation)}}return J}function Jz(Z,$,X,J){let G=AZ(Z);if(typeof $?.status==="number"||E7($)){let B=I7({error:$,now:X,refreshToken:Z,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:G,retryCount:B.retryCount}}return{nextRetryAt:X+b7,tokenHash:G,retryCount:J?.tokenHash===G?J.retryCount:0}}function Gz(Z,$,X,J){let G=new Map;for(let z of Z){if(J(z,X))continue;let B=$.get(z.id);G.set(z.id,B&&B.nextRetryAt>X?B.nextRetryAt:X+b7)}return G}import{realpathSync as k7}from"node:fs";import{homedir as d$}from"node:os";import{basename as c$,dirname as s$,join as D3,resolve as v7}from"node:path";function a$(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return D3(process.env.XDG_CONFIG_HOME||D3(d$(),".config"),"opencode")}function x7(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||D3(a$(),h7)}function q3(Z,$){let X=v7(Z);return $==="win32"||$==="darwin"?X.toLowerCase():X}function f7(Z){try{return k7.native(Z)}catch{try{return D3(k7.native(s$(Z)),c$(Z))}catch{return}}}function n$(Z,$,X=process.platform){if(q3(Z,X)===q3($,X))return!0;let J=f7(Z),G=f7($);return J!==void 0&&G!==void 0&&q3(J,X)===q3(G,X)}function i$(Z=x7()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(n$(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${v7(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}return g7(Z)}function hz(Z=x7()){return{configPath:Z,statePath:i$(Z)}}import{createHash as J0}from"node:crypto";import{readFileSync as G0}from"node:fs";import{readFile as z0}from"node:fs/promises";import{resolve as B0}from"node:path";import{createHash as r$}from"node:crypto";import{readFile as o$}from"node:fs/promises";import{homedir as t$}from"node:os";import{join as m7,resolve as e$}from"node:path";var Z0="openai",w7=250,RZ="main-refresh";function A4(Z){if(typeof Z.access!=="string"||typeof Z.refresh!=="string")return;let $=Buffer.from(Z.access),X=Buffer.from(Z.refresh),J=(G)=>{let z=Buffer.alloc(4);return z.writeUInt32BE(G.length),z};return r$("sha256").update(J($)).update($).update(J(X)).update(X).digest("hex")}function s7(Z){if(!Z||typeof Z!=="object")return;let $=Z;if($.type!=="oauth")return;return{type:"oauth",...typeof $.access==="string"?{access:$.access}:{},...typeof $.refresh==="string"?{refresh:$.refresh}:{},...typeof $.expires==="number"?{expires:$.expires}:{},...typeof $.accountId==="string"?{accountId:$.accountId}:{}}}function a7(Z){let $=s7(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function u7(Z){if(x1(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=s7(Z);if(!$)return{kind:"indeterminate"};return TZ($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function p7(Z){return Z.auth.get({path:{id:Z0}})}async function l7(Z){return Object.keys(await Z.auth.all()).length>0}async function n7(Z){let $=await p7(Z.client);if($!==void 0)return u7($);let X=await l7(Z.client),J=Z.now();if(await Z.sleep(w7),Z.now()-J<w7)return{kind:"indeterminate"};let G=await p7(Z.client);if(G!==void 0)return u7(G);let z=await l7(Z.client);return X&&z?{kind:"slot-absent"}:{kind:"indeterminate"}}function F3(Z=process.env,$=t$()){let X=Z.XDG_DATA_HOME||m7($,".local","share");return m7(X,"opencode","auth.json")}function x1(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var d7=(Z)=>Z===void 0||typeof Z==="string";function $0(Z){if(!x1(Z))return!1;switch(Z.type){case"oauth":return typeof Z.refresh==="string"&&typeof Z.access==="string"&&typeof Z.expires==="number"&&Number.isSafeInteger(Z.expires)&&Z.expires>=0&&d7(Z.accountId)&&d7(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||x1(Z.metadata)&&Object.values(Z.metadata).every(($)=>typeof $==="string"));case"wellknown":return typeof Z.key==="string"&&typeof Z.token==="string";default:return!1}}async function O4(Z,$=process.env){let X=$.OPENCODE_AUTH_CONTENT;if(X)try{let G=JSON.parse(X);return x1(G)?G:{}}catch{}let J;try{J=JSON.parse(await o$(Z,"utf8"))}catch{return{}}if(!x1(J))return{};return Object.fromEntries(Object.entries(J).filter(([,G])=>$0(G)))}function c7(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class N3 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function X0(Z){let $=Z.env??process.env,X=Z.path??F3($),J=new Map;return{path:e$(X),migrationDisabledReason:()=>c7($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(G){let z=(await O4(X,$))[G.path.id];return J.set(G.path.id,JSON.stringify(z)),z},async all(){return O4(X,$)},async set(G){if(c7($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let z=(await O4(X,$))[G.path.id];if(SZ(G.body)&&(!J.has(G.path.id)||J.get(G.path.id)!==JSON.stringify(z)))throw new N3;let B=await Z.set(G);if(x1(B)&&"error"in B&&B.error!==void 0)throw Error(`OpenCode refused the write of its ${G.path.id} login: ${JSON.stringify(B.error)}`);return B}}}function lz(Z,$={}){let X=x1(Z)?Z.auth:void 0,J=X&&typeof X==="object"?X.set:void 0;if(typeof J!=="function")return{reason:"the OpenCode client has no auth.set to write its login slot with"};return{slot:X0({...$,set:(G)=>J.call(X,G)})}}var e1="openai",Q0="common-auth-placeholder:v1:openai",EZ=Object.freeze({type:"oauth",access:"",refresh:Q0,expires:0});function SZ(Z){if(!$1(Z))return!1;return Z.type===EZ.type&&Z.access===EZ.access&&Z.refresh===EZ.refresh&&Z.expires===EZ.expires}var M3="openaiAuthPool",W0=120000,J8="pool-migration",Y0="slot-transfer-origin-unknown",H0="Sign in again with `opencode auth login`, or re-enable the row only if this config root is the only one using that auth.json.",_3=Object.freeze({mainRefreshTtlMs:W0,fallbackTtlMs:$8,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function K3(Z,$,X){return Z.kind==="placeholder"&&!$&&!X.pending}class m1 extends Error{constructor(Z){super(`timed out waiting for the legacy ${Z} lock`);this.name="LegacyLockContention"}}function $1(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function U0(Z){let $=Z.now??Date.now;return{paths:Z.paths,slot:Z.slot,now:$,sleep:Z.sleep??((X)=>new Promise((J)=>setTimeout(J,X))),newId:Z.newId??(()=>crypto.randomUUID()),log:Z.log??i("pool-migration"),...Z.vaultServes?{vaultServes:Z.vaultServes}:{},locks:{..._3,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:jZ({provider:e1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:L3,now:$,...Z.store}),onStep:async(X)=>{await Z.onStep?.(X)}}}async function $Z(Z){let $;try{$=await z0(Z,"utf8")}catch(J){if(J.code==="ENOENT")return{};throw J}let X=JSON.parse($);if(!$1(X))throw Error("config root is not an object");return X}async function IZ(Z,$,X,J,G){let z=performance.now();for(;;){if(G?.aborted)throw new m1($);let B=await E1({name:$,path:X,ttlMs:J,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(B){if(!G?.aborted)return B;throw await B.release(),new m1($)}if(performance.now()-z>=Z.locks.timeoutMs)throw new m1($);await Z.sleep(Z.locks.retryMs)}}async function $B(Z,$,X={}){let J={..._3,...X},G=performance.now();for(;;){let z=await E1({name:RZ,path:Z,ttlMs:J.mainRefreshTtlMs,renew:J.renew,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}});if(z)try{return await $()}finally{await z.release().catch(()=>{})}if(performance.now()-G>=J.timeoutMs)throw new m1(RZ);await new Promise((B)=>setTimeout(B,J.retryMs))}}async function bZ(Z,$){let X=Z.locks.saveTtlMs,J=await IZ(Z,"save",Z.paths.configPath,X);try{let G=await IZ(Z,"save",Z.paths.statePath,X);try{let z=await $Z(Z.paths.configPath);if(!await $(z))return;await y1(Z.paths.configPath,z,{beforeRename:async()=>{await J.assertOwned(),await G.assertOwned()}})}finally{await G.release().catch(()=>{})}}finally{await J.release().catch(()=>{})}}function V0(Z){if(!$1(Z))return;let{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:G}=Z,{credentialFingerprint:z,carryLegacyMain:B,recordedAt:W,identity:Y}=Z;if(typeof $!=="string"||!$)return;if(X!=="add"&&X!=="rotate"&&X!=="replace")return;if(J!==null&&typeof J!=="string")return;if(typeof G!=="string")return;if(typeof z!=="string")return;return{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:G,credentialFingerprint:z,...typeof Y==="string"&&Y?{identity:Y}:{},carryLegacyMain:B===!0,recordedAt:typeof W==="number"?W:0}}function G8(Z,$){if(!$1(Z)||!$)return!1;return W1(Z).pending?.credentialFingerprint===J1({type:"oauth",refresh:$})}function XB(Z,$){let X;try{X=JSON.parse(G0(Z,"utf8"))}catch{return!1}return G8(X,$)}class j0 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var q0=600000;async function JB(Z,$,X={}){let J=X.now??Date.now,G=(Y)=>{let Q=W1(Y).pending;return Q&&G8(Y,$)&&J()-Q.recordedAt>=q0?Q:void 0},z=G(await $Z(Z.configPath));if(!z)return!1;let B={..._3,...X.legacyLocks},W=await E1({name:J8,path:Z.configPath,ttlMs:B.mainRefreshTtlMs});if(!W)return!1;try{let Y=await $Z(Z.configPath),Q=W1(Y).migratedAt!==void 0,H=await jZ({provider:e1,configPath:Z.configPath,statePath:Z.statePath,quota:L3,now:J}).read();if(Q&&H.status!=="ready")return!1;let U;if(H.status==="ready"){let D=H.rows.find((q)=>q.id===z.rowId&&!q.invalid),V=D?.fingerprint??null;if(Q&&D&&V===z.credentialFingerprint)return!1;if(D&&V!==z.credentialFingerprint&&V!==z.rowFingerprint)U=X.slotAccess!==void 0?A4({type:"oauth",access:X.slotAccess,refresh:$}):z.slotFingerprint}let j=!1;if(await bZ({paths:Z,locks:B,sleep:(D)=>new Promise((V)=>setTimeout(V,D))},(D)=>{let V=W1(D),q=G(D);if(!q||q.recordedAt!==z.recordedAt)return!1;let{pending:F,...N}=V;return T3(D,U!==void 0?{...N,declinedSlotFingerprint:U}:N),j=!0,!0}),j)(X.log??i("pool-migration")).warn(U!==void 0?"dropped an expired account-pool transfer record whose row was rotated since; the slot login is not adopted unless its refresh renews it":"dropped an expired account-pool transfer record so the slot refresh can resume",{rowId:z.rowId,recordedAt:z.recordedAt});return j}finally{await W.release().catch(()=>{})}}function W1(Z){let $=Z[M3];if(!$1($))return{};let X=V0($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...X?{pending:X}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function T3(Z,$){let J={...$1(Z[M3])?Z[M3]:{}};for(let G of["migratedAt","pending","declinedSlotFingerprint"])delete J[G];Object.assign(J,$),Z[M3]=J}function D0(Z){let $=Z?X3(Z):void 0;return $?J3($):void 0}function F0(Z){let $=A4({type:"oauth",...Z}),X=D0(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:J1({type:"oauth",refresh:Z.refresh}),...X?{identity:X}:{}}}function z8(Z){if(SZ(Z))return{kind:"placeholder",...$1(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=a7(Z);if(!$?.refresh.trim())return{kind:"empty"};return F0($)}async function yZ(Z){let $=await n7({client:{auth:{get:(X)=>Z.slot.get(X),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return z8($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function GB(Z,$){if(!SZ($))return!1;let X=await $Z(Z.configPath),J=await jZ({provider:e1,configPath:Z.configPath,statePath:Z.statePath,quota:L3}).read();if(J.status==="error")return!1;let G=J.status==="ready"?J.rows.some((z)=>z.id==="main"):J.roster.some((z)=>$1(z)&&z.id==="main");return K3({kind:"placeholder"},G,W1(X))}async function N0(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let X=await yZ(Z);if(X.kind!=="real")return X;if(!await B8(Z,X.credential.refresh))return X;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function B8(Z,$){let X=await C3(Z.paths),J=X?.refresh?.mainRefreshLeaseUntil;return Boolean(J&&J>Z.now()&&X?.refresh?.mainRefreshLeaseTokenHash===AZ($))}function M0(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function K0(Z,$,X,J,G){let z=X.identity?{identity:X.identity}:{},B=$.find((H)=>!H.invalid&&H.fingerprint===X.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...z,carryLegacyMain:Z==="migrate"&&B.id==="main"};let W=$.find((H)=>H.id==="main");if(!W||!W.invalid&&!W.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...z,carryLegacyMain:Z==="migrate"};if(X.identity){let H=$.find((U)=>!U.invalid&&U.type==="oauth"&&U.enabled&&U.identity===X.identity);if(H)return{rowId:H.id,operation:"replace",rowFingerprint:H.fingerprint??null,...z,carryLegacyMain:Z==="migrate"&&H.id==="main"}}let Y=new Set($.map((H)=>H.id));return{rowId:J??(X.identity&&M0(X.identity)&&!Y.has(X.identity)?X.identity:G()),operation:"add",rowFingerprint:null,...z,carryLegacyMain:!1}}function P0(Z,$,X,J,G,z,B){let W=$.pending;if(W){let Y=X.find((U)=>U.id===W.rowId&&!U.invalid),Q=Y?.fingerprint??null,H=J.kind==="real"&&J.fingerprint===W.slotFingerprint;if(Y&&Q===W.credentialFingerprint)return{kind:"finish",record:W};if((Y||W.rowFingerprint===null)&&Q===W.rowFingerprint)return H&&J.kind==="real"?{kind:"transfer",record:W,credential:J.credential,fresh:!1}:{kind:"drop-record"};if(!Y)return{kind:"drop-record"};return H?{kind:"ambiguous",record:W}:{kind:"drop-record"}}if(J.kind==="indeterminate")return{kind:"drop-record"};if(J.kind!=="real")return{kind:"nothing",slot:J.kind};if($.declinedSlotFingerprint===J.fingerprint)return{kind:"nothing",slot:"declined"};return{kind:"transfer",record:{...K0(Z,X,J,G,B),slotFingerprint:J.fingerprint,credentialFingerprint:J.credentialFingerprint,recordedAt:z},credential:J.credential,fresh:!0}}async function L0(Z,$,X){let J={type:"oauth",access:X.access,refresh:X.refresh,...X.expires!==void 0?{expires:X.expires}:{}},G=$.identity?{identity:$.identity}:{},z={extraLocks:P3(Z.paths,$.rowId,Z.locks)};if($.operation==="add")await Z.store.add({id:$.rowId,credential:J,...G},z);else if($.operation==="replace")await Z.store.replace($.rowId,J,G,z);else{let B=await Z.store.read(),W=B.status==="ready"?B.rows.find((Y)=>Y.id===$.rowId):void 0;await Z.store.rotate($.rowId,J,W?.identity===void 0?G:{},z)}}async function C0(Z,$){let X=await Z.store.read();if(X.status!=="ready")return;let J=X.rows.find((G)=>G.id===$.rowId&&!G.invalid);return J?.fingerprint===$.credentialFingerprint?J:void 0}function _0(Z,$){let X=[],J=[["primary",Z.primary],["secondary",Z.secondary]],G=0;for(let[W,Y]of J){if(!Y||!Number.isFinite(Y.checkedAt)||!Number.isFinite(Y.usedPercent))continue;G=Math.max(G,Y.checkedAt),X.push({checkedAt:Y.checkedAt,readings:[{label:W,usedPercent:Y.usedPercent,...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{},...Number.isFinite(Y.windowMinutes)?{windowMinutes:Y.windowMinutes}:{}}]})}let z=$??(G||void 0),B=Z.spendControl;if(z!==void 0&&B)X.push({checkedAt:z,budget:{kind:"reading",reached:B.reached,remainingPercent:B.remainingPercent,usedPercent:B.usedPercent,limit:B.limit,used:B.used,remaining:B.remaining,...B.resetsAt!==void 0?{resetsAt:B.resetsAt}:{},...B.unit!==void 0?{unit:B.unit}:{}}});else if(z!==void 0&&Z.spendControlCleared)X.push({checkedAt:z,budget:{kind:"cleared"}});return X.sort((W,Y)=>W.checkedAt-Y.checkedAt)}async function T0(Z,$){let X=await C3(Z.paths);if(!X)return;let J=X.quota?.mainQuotaToken,G=$.credential?.type==="oauth"?$.credential.access:void 0,B=!J||G!==void 0&&J===t7(G)?X.quota?.mainQuota:void 0;if(B&&$.credentialEpoch!==void 0){let H={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let U of _0(B,X.quota?.mainQuotaCheckedAt))try{await Z.store.recordQuota($.id,H,U)}catch(j){Z.log.warn("legacy main quota not carried to the pool row",{rowId:$.id,error:j instanceof Error?j.message:String(j)})}}let W=X.refresh?.mainLastRefreshError,Y=X.accounts.find((H)=>H.id===$.id);if(!Y||!e7(Y)||Y.corrupt)return;if(!W&&!B)return;let Q={...X,accounts:[{...Y,...Y.lastRefreshError||!W?{}:{lastRefreshError:W},...Y.quota||!B?{}:{quota:B}}]};try{await Z8(Q,Z.paths,{accounts:[$.id]})}catch(H){Z.log.warn("legacy main backoff not carried to the pool row",{rowId:$.id,error:H instanceof Error?H.message:String(H)})}}async function ZZ(Z,$,X={}){await bZ(Z,(J)=>{let G=W1(J);if(delete J.mainAccountId,$==="migrate"&&G.migratedAt===void 0)O0(J);return T3(J,{...G.migratedAt!==void 0||$==="migrate"?{migratedAt:G.migratedAt??Z.now()}:{},...X.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:X.declinedSlotFingerprint}:G.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:G.declinedSlotFingerprint}:{}}),!0})}function O0(Z){let $=Z.routing;if($===void 0)Z.routing={mode:"main-first"};else if($1($)&&$.mode===void 0)Z.routing={...$,mode:"main-first"}}async function R4(Z){await bZ(Z,($)=>{let X=W1($);if(!X.pending)return!1;let{pending:J,...G}=X;return T3($,G),!0})}async function A0(Z,$){await bZ(Z,(X)=>{let J=W1(X);if($.identity)X.mainAccountId=$.identity;return T3(X,{...J,pending:$}),!0})}async function S0(Z,$,X,J){let G=await IZ(Z,RZ,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await R0(Z,$,X,J)}finally{await G.release().catch(()=>{})}}async function R0(Z,$,X,J){let G=(Q)=>({status:"completed",rowId:X.rowId,operation:J,placeholder:Q}),z=await yZ(Z);if(z.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(z.kind==="placeholder"){if(z.origin===void 0)return{status:"untagged-placeholder"};if(z.origin!==S4(Z))return{status:"foreign-placeholder"};return await ZZ(Z,$),await Z.onStep("after-record-clear"),G("already-present")}if(Object.keys(await Z.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(z.kind==="real"&&z.fingerprint!==X.slotFingerprint&&X.identity!==void 0&&z.identity===X.identity)return await R4(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return await ZZ(Z,$),await Z.onStep("after-record-clear"),G("slot-moved-on");await Z.onStep("before-placeholder-write");let B=await Z.slot.get({path:{id:e1}}),W=B===void 0||B===null?void 0:z8(B);if(W?.kind!=="real"||W.fingerprint!==X.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:e1},body:{...EZ,accountId:S4(Z)}})}catch(Q){if(Q instanceof N3)return{status:"retry",reason:"slot-changed"};throw Q}await Z.onStep("after-placeholder-write");let Y=await Z.slot.get({path:{id:e1}});if(!SZ(Y))return{status:"retry",reason:"placeholder-overwritten"};if($1(Y)&&Y.accountId===void 0)return{status:"untagged-placeholder"};if($1(Y)&&Y.accountId!==S4(Z))return{status:"foreign-placeholder"};return await ZZ(Z,$),await Z.onStep("after-record-clear"),G("written")}async function E0(Z,$,X){let{record:J}=X;if(X.fresh)await A0(Z,J),await Z.onStep("after-record-write");if(await B8(Z,X.credential.refresh))return{status:"restart"};let G=await yZ(Z);if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return{status:"restart"};return await L0(Z,J,X.credential),await Z.onStep("after-row-write"),Q8(Z,$,J,X.fresh?J.operation:"resumed")}async function Q8(Z,$,X,J){let G=await C0(Z,X);if(!G)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),X.carryLegacyMain)await T0(Z,G),await Z.onStep("after-carry-over");let z=await S0(Z,$,X,J);if(z.status==="untagged-placeholder"){await Z.store.disable(X.rowId,Y0,{extraLocks:P3(Z.paths,X.rowId,Z.locks),attribution:{credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}}}),await ZZ(Z,$);let B=`${Z.paths.configPath}\x00${X.rowId}`;if(!o7.has(B))o7.add(B),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${H0}`,{rowId:X.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(z.status!=="foreign-placeholder")return z;return await Z.store.remove(X.rowId,{extraLocks:P3(Z.paths,X.rowId,Z.locks),protect:(B,W)=>W.row?.fingerprint!==X.credentialFingerprint?"the transfer row changed before rollback":void 0}),await R4(Z),await E4(Z),{status:"refused",reason:"placeholder-without-main"}}var i7=new Set,r7=new Set,o7=new Set;function S4(Z){return`openai-auth-pool:${J0("sha256").update(B0(Z.paths.configPath)).digest("hex")}`}async function I0(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function W8(Z,$,X){let J=U0(Z),G=J.slot.migrationDisabledReason?.();if(G){let Q=J.slot.path??F3();if(!r7.has(Q))r7.add(Q),J.log.info("account pool migration is off: the host login slot is read-only",{reason:G});return{status:"slot-read-only",reason:G}}let z;try{z=await $Z(J.paths.configPath)}catch(Q){return{status:"error",reason:Q instanceof Error?Q.message:String(Q)}}let B=await Y8(J,$,z);if(B){if(B.status==="already-migrated"&&"mainAccountId"in z)await E4(J);return B}if(X){let Q=await I0(X);if(Q.length>0){let H=`${J.paths.configPath}\x00${Q.map((U)=>`${U.pid}@${U.version}`).join(",")}`;if(!i7.has(H))i7.add(H),J.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:Q});return{status:"deferred",reason:"older-version-running",blockers:Q}}}let W,Y;try{Y=await IZ(J,"pool-slot-transfer",J.slot.path??F3(),J.locks.mainRefreshTtlMs,Z.signal),W=await IZ(J,J8,J.paths.configPath,J.locks.mainRefreshTtlMs,Z.signal)}catch(Q){if(await Y?.release().catch(()=>{}),Q instanceof m1)return{status:"retry",reason:"lock-contention"};throw Q}try{return await b0(J,$)}catch(Q){if(Q instanceof m1)return{status:"retry",reason:"lock-contention"};if(Q instanceof E)return{status:"retry",reason:Q.kind==="lock-contention"?"lock-contention":`store-${Q.kind}`};throw Q}finally{await W?.release().catch(()=>{}),await Y?.release().catch(()=>{})}}async function Y8(Z,$,X){let J=W1(X);if(J.pending)return;if($==="migrate"&&J.migratedAt!==void 0){let G=await Z.store.read();if(G.status==="ready"&&!G.rows.some((z)=>z.id==="main")&&!J.pending&&K3(await yZ(Z),G.rows.some((z)=>z.id==="main"),J))return{status:"refused",reason:"placeholder-without-main"};return{status:"already-migrated"}}if($==="adopt"&&J.migratedAt===void 0)return{status:"not-migrated"};return}async function b0(Z,$){let X;for(let J=0;J<4;J++){let G=await $Z(Z.paths.configPath),z=await Y8(Z,$,G);if(z){if(z.status==="already-migrated")await E4(Z);return z}let B=await Z.store.read(),W=W1(G);if(B.status==="pending-migration"){if(K3(await yZ(Z),B.roster.some((U)=>$1(U)&&U.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};await Z.store.initialize(),await Z.onStep("after-pool-key-write"),B=await Z.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let Y=await N0(Z);if(Y.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(Y.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(K3(Y,B.rows.some((U)=>U.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};let Q=P0($,W,B.rows,Y,X,Z.now(),Z.newId);if(Q.kind==="nothing"){if($==="migrate")await ZZ(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:Q.slot}}if(Q.kind==="drop-record"){await R4(Z),await Z.onStep("after-record-clear");continue}if(Q.kind==="ambiguous")return await ZZ(Z,$,{declinedSlotFingerprint:Q.record.slotFingerprint}),await Z.onStep("after-record-clear"),Z.log.warn("interrupted slot transfer left alone: the row was rotated since, so the slot copy may be stale; the next login resolves it",{rowId:Q.record.rowId}),{status:"ambiguous",rowId:Q.record.rowId};if(Q.kind==="transfer"&&Q.fresh)X=Q.record.rowId;let H=Q.kind==="finish"?await Q8(Z,$,Q.record,"resumed"):await E0(Z,$,Q);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function E4(Z){await bZ(Z,($)=>{if(!("mainAccountId"in $))return!1;if(W1($).pending)return!1;return delete $.mainAccountId,!0})}function zB(Z){return W8(Z,"migrate",Z.fence)}function BB(Z){return W8(Z,"adopt")}class H8 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function P3(Z,$,X={}){let J={..._3,...X},G={renew:J.renew,timeoutMs:J.timeoutMs,retryMs:J.retryMs,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}};return[{name:RZ,path:Z.configPath,ttlMs:J.mainRefreshTtlMs,...G},{name:X8($),path:Z.configPath,ttlMs:J.fallbackTtlMs,...G}]}async function QB(Z,$,X,J={}){let G=Z.now??Date.now,z=Z.sleep??((Y)=>new Promise((Q)=>setTimeout(Q,Y))),B=Z.leaseWait??{timeoutMs:4000,pollMs:50},W=async(Y,Q)=>{let H=AZ(Y.refresh),U=async()=>{let j=await C3(Z.paths),D=j?.refresh?.mainRefreshLeaseUntil;return Boolean(D&&D>G()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await U()){let j=G()+B.timeoutMs;while(G()<j&&await U())await z(B.pollMs);throw new H8}return X(Y,Q)};return Z.store.refresh($,W,{...J,extraLocks:P3(Z.paths,$,Z.legacyLocks)})}
69
+ export{jZ as qa,w as ra,M9 as sa,h as ta,W6 as ua,A9 as va,LJ as wa,CJ as xa,R9 as ya,_J as za,TJ as Aa,I9 as Ba,G3 as Ca,U6 as Da,$4 as Ea,B4 as Fa,W4 as Ga,g1 as Ha,Y4 as Ia,r1 as Ja,MZ as Ka,Z$ as La,G$ as Ma,z$ as Na,v1 as Oa,B$ as Pa,CZ as Qa,Y$ as Ra,EG as Sa,IG as Ta,bG as Ua,yG as Va,kG as Wa,fG as Xa,nG as Ya,y7 as Za,eG as _a,Zz as $a,l$ as ab,$z as bb,Xz as cb,Jz as db,Gz as eb,uG as fb,o1 as gb,_4 as hb,f$ as ib,cG as jb,i$ as kb,hz as lb,Q0 as mb,EZ as nb,Y0 as ob,H0 as pb,$B as qb,XB as rb,j0 as sb,JB as tb,W1 as ub,GB as vb,zB as wb,BB as xb,P3 as yb,QB as zb,RZ as Ab,u7 as Bb,F3 as Cb,c7 as Db,N3 as Eb,lz as Fb};