@cortexkit/opencode-openai-auth 1.0.5 → 1.1.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 (102) hide show
  1. package/dist/bin.js +9 -8
  2. package/dist/{pool-lifecycle-C_6YRmsh.d.ts → codex-request-BXDXToyt.d.ts} +158 -27
  3. package/dist/index-0yh85bwb.js +69 -0
  4. package/dist/{index-826s1yxa.js → index-4c8yw54k.js} +2 -2
  5. package/dist/{index-y4gxyxqd.js → index-7c6sxtd6.js} +2 -2
  6. package/dist/index-7eb3dw37.js +90 -0
  7. package/dist/index-8re8rprk.js +2 -0
  8. package/dist/{index-66asrje2.js → index-csky2xpg.js} +1 -1
  9. package/dist/index-edbdscy7.js +65 -0
  10. package/dist/{index-pg305s90.js → index-f2fmb596.js} +1 -1
  11. package/dist/{index-fsxbncpw.js → index-j8v2xwq6.js} +1 -1
  12. package/dist/{index-fsky1rsh.js → index-k6cydkgt.js} +2 -2
  13. package/dist/{index-116q849r.js → index-m5qmvr6c.js} +2 -2
  14. package/dist/index-msx2m78k.js +8 -0
  15. package/dist/{index-nx2qh047.js → index-zpm95mt5.js} +1 -1
  16. package/dist/index.d.ts +15 -7
  17. package/dist/index.js +1 -1
  18. package/dist/{map-m6f5a_IA.d.ts → map-Buq-GW7l.d.ts} +1 -1
  19. package/dist/{protocol-DctqemRI.d.ts → model-YRg7Uowo.d.ts} +67 -25
  20. package/dist/{port-file-ZPlxXB4G.d.ts → port-file-CxEpgSHY.d.ts} +1 -1
  21. package/dist/protocol-CDV1Pc6h.d.ts +29 -0
  22. package/dist/rpc/port-file.d.ts +1 -1
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +1 -1
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -3
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/{sidebar-state-z_M7Trnd.d.ts → sidebar-state-DjTWUbmf.d.ts} +15 -9
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/{token-bzhkgc29.js → token-rz4t3ay6.js} +1 -1
  33. package/dist/token-util-tpy2c7h6.js +1 -0
  34. package/dist/tui-preferences.js +1 -1
  35. package/dist/tui.d.ts +20 -2
  36. package/dist/v2/server.d.ts +73 -1
  37. package/dist/v2/server.js +3 -3
  38. package/package.json +2 -2
  39. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +13 -8
  40. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +354 -0
  41. package/src/tui-compiled/raw/shared/134b008900698fe0-backoff.js +92 -0
  42. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +393 -0
  43. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  44. package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +473 -0
  45. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +566 -0
  46. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  47. package/src/tui-compiled/raw/shared/4593a4d71edf69fd-tombstone.js +25 -0
  48. package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +500 -0
  49. package/src/tui-compiled/raw/shared/6371b24a0573d79e-any-signal.js +42 -0
  50. package/src/tui-compiled/raw/shared/7c140680fc81be92-interlock.js +29 -0
  51. package/src/tui-compiled/raw/shared/85512cc5263ba259-provider.js +87 -0
  52. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +192 -0
  53. package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +806 -0
  54. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  55. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +0 -1
  56. package/src/tui-compiled/raw/shared/ca0fccaba1d87af4-errors.js +8 -0
  57. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +152 -0
  58. package/src/tui-compiled/raw/shared/d9d2892a4c371301-host-slot.js +72 -0
  59. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +1470 -0
  60. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  61. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +24 -0
  62. package/src/tui-compiled/raw/sidebar-state.js +41 -14
  63. package/src/tui-compiled/raw/tui/command-dialogs.tsx +3 -34
  64. package/src/tui-compiled/raw/tui/section-text.js +21 -0
  65. package/src/tui-compiled/raw/tui/v2-dialog.js +137 -0
  66. package/src/tui-compiled/raw/tui/v2.tsx +133 -0
  67. package/src/tui-compiled/raw/tui.tsx +146 -40
  68. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +13 -8
  69. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +354 -0
  70. package/src/tui-compiled/runtime/shared/134b008900698fe0-backoff.js +92 -0
  71. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +393 -0
  72. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +154 -0
  73. package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +473 -0
  74. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +566 -0
  75. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +0 -1
  76. package/src/tui-compiled/runtime/shared/4593a4d71edf69fd-tombstone.js +25 -0
  77. package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +500 -0
  78. package/src/tui-compiled/runtime/shared/6371b24a0573d79e-any-signal.js +42 -0
  79. package/src/tui-compiled/runtime/shared/7c140680fc81be92-interlock.js +29 -0
  80. package/src/tui-compiled/runtime/shared/85512cc5263ba259-provider.js +87 -0
  81. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +192 -0
  82. package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +806 -0
  83. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +85 -0
  84. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +0 -1
  85. package/src/tui-compiled/runtime/shared/ca0fccaba1d87af4-errors.js +8 -0
  86. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +152 -0
  87. package/src/tui-compiled/runtime/shared/d9d2892a4c371301-host-slot.js +72 -0
  88. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +1470 -0
  89. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +26 -12
  90. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +24 -0
  91. package/src/tui-compiled/runtime/sidebar-state.js +41 -14
  92. package/src/tui-compiled/runtime/tui/command-dialogs.js +3 -15
  93. package/src/tui-compiled/runtime/tui/section-text.js +21 -0
  94. package/src/tui-compiled/runtime/tui/v2-dialog.js +137 -0
  95. package/src/tui-compiled/runtime/tui/v2.js +95 -0
  96. package/src/tui-compiled/runtime/tui.js +255 -163
  97. package/dist/index-4fnghj9e.js +0 -65
  98. package/dist/index-a69gr76b.js +0 -2
  99. package/dist/index-h263aftt.js +0 -157
  100. package/dist/index-ssj7m2rd.js +0 -8
  101. package/dist/index-ydz3hbhc.js +0 -2
  102. package/dist/token-util-4a2xxnpg.js +0 -1
@@ -0,0 +1,69 @@
1
+ import{$c as d4,Ac as D6,Ad as MZ,Bc as _Z,Cc as F6,Dc as $6,Ec as X6,Fd as J6,Hd as G6,Ic as eZ,Id as z6,Jc as Z0,Kd as u6,Ld as p6,Nd as tZ,Qd as p5,Wc as m4,Xc as w4,Yc as u4,Zc as p4,_c as l4,ad as c4,bd as s4,cd as a4,dd as n4,ed as i4,fd as LZ,id as jZ,kd as x6,mc as c1,md as m6,nc as q6,nd as PZ,oc as N0,pc as S4,pd as NZ,qc as B0,qd as N1,rc as B1,sc as W1,sd as K0,tc as R4,uc as E4,ud as w6,vc as I4,xc as H6,yc as j6}from"./index-7eb3dw37.js";import{$d as I1,_d as x3,ae as m3,be as k0,ce as S1,de as yZ,ee as w3}from"./index-msx2m78k.js";import{Ae as L6,Be as C6,Ce as V1,te as M4,xe as J1,ye as U6}from"./index-7c6sxtd6.js";import{Fe as v3,Le as g3}from"./index-m5qmvr6c.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 bZ 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 v1="identity-contradicted: ",C0="duplicate-identity";function P1(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 XZ(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 g1(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))P1(Z,G.id,"duplicate-identity"),J.push(G.id);return J}function A1(Z,$,X){let J=Z.rosterRow($);if(!J)return[];return J.accountId=X,g1(Z,X)}import{setTimeout as q7}from"node:timers/promises";import{AsyncLocalStorage as o6}from"node:async_hooks";var P3=new o6;function w(Z){if(P3.getStore()!==void 0)throw new bZ(Z)}function z1(Z,$){return P3.run(Z,async()=>await $())}async function L3(Z,$,X,J,G){if(!$)return;try{await z1(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 _0=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function t6(Z,$,X){let J=(Q)=>{try{let W=X.onLockEvent?.({type:Q,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={...$,...e6(Z)},z=performance.now();for(;;){let Q=await S1({name:Z.name,path:Z.path,ttlMs:G.ttlMs,renew:G.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(U)=>X.onRenewalTimer?.({name:Z.name,path:Z.path},U)}:{},...G.renewIntervalMs!==void 0?{renewIntervalMs:G.renewIntervalMs}:{},...X.onLockStep?{onStep:(U)=>X.onLockStep?.({name:Z.name,path:Z.path},U)}:{}});if(Q){J("acquired");let U={name:Z.name,path:Z.path,assertOwned:()=>Q.assertOwned(),release:async()=>{await Q.release(),J("released")}};try{await U.assertOwned()}catch(H){throw await U.release(),H}return U}let W=G.timeoutMs-(performance.now()-z);if(W<=0)throw new yZ({target:Z.path,name:Z.name,timeoutMs:G.timeoutMs});let B=Math.floor(Math.random()*(G.retryMs+1));await new Promise((U)=>setTimeout(U,Math.min(G.retryMs+B,W)))}}function e6(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 L1{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await t6(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 R1(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 JZ}from"node:crypto";var y="commonAuthPool",C1=1,e="rows",kZ="retiredEpochs",GZ=1,T0=300000,I=y;function Z7(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 E1(Z){return JZ("sha256").update(Z7(Z)).digest("hex")}function C3(Z){if(!P(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function $7(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 p="commonAuthProviderState";function P(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var X7=new Set(["__proto__","constructor","prototype"]);function x1(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(X7.has(Z))return"id is a reserved object key";return}function O0(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 _3(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function Z1(Z){return JZ("sha256").update(_3(Z)).digest("hex")}function Q1(Z){return JZ("sha256").update(`credential-stamp\x00${_3(Z)}`).digest("hex")}function q1(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 JZ("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function A0(Z,$,X,J={}){return{credentialEpoch:$,digest:Q1(Z),dispatch:q1(Z),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function m1(Z,$){let X=Z?.credentialBound?Z.credentialBound($):$;return JZ("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function zZ(Z,$,X,J){if(!$||X===void 0)return;if(!P(Z)||!Object.hasOwn(Z,p))return;let G=c(Z[I]);if(!G||G.providerState===void 0||G.digest!==Q1($)||G.credentialEpoch!==X||G.binding?.identity!==J)return;return G.providerState}function x(Z){return Number.isSafeInteger(Z)&&Z>=1}function c(Z){if(!P(Z))return;let $=Z.credentialEpoch;if(!x($))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?$7(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&&!O0(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 J7(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 G7(Z,$,X,J){if(!Z)return"none";if(!P(J)||!Object.hasOwn(J,I))return"missing";let G=c(J[I]);if(!G)return"malformed";if(G.digest!==Q1(Z))return"mismatched";if(G.dispatch===void 0)return"legacy";if(G.credentialEpoch!==$)return"mismatched";if(!G.binding||!J7(G.binding,Z,X))return"mismatched";if(G.dispatch!==q1(Z))return"mismatched";return"bound"}function T3(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>C1)return{status:"error",reason:`${y}.schemaVersion ${J} is newer than ${C1}`};if(e in X&&!P(X[e]))return{status:"error",reason:`${y}.${e} is not an object`};return{status:"ready",exists:!0,config:$}}function O3(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 w1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function A3(Z){let $=Z[y];if(!P($))return{};let X=$[e];return P(X)?X:{}}function z7(Z){return P(Z.accounts)?Z.accounts:{}}function Q7(Z){if(!P(Z))return"not an object";let $=x1(Z.id);if($)return $;if(Z.type==="api")return O0(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function B7(Z,$){if(!P(Z))return;let X=Z.credentialEpoch;if(!x(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&&!C3(Z.staged))return;return{credentialEpoch:X,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:J}:{}}}function W7(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 fZ(Z,$){return w1(Z).find((X)=>P(X)&&X.id===$)}function S3(Z){if(!P(Z[y]))Z[y]={};return Z[y]}function S0(Z){let $=S3(Z);if(!P($[e]))$[e]={};return $[e]}function _1(Z,$){let X=A3(Z),J=Object.hasOwn(X,$)?X[$]:void 0;return P(J)?J:void 0}function hZ(Z,$,X){Object.defineProperty(S0(Z),$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function R3(Z,$){let X=Z[y];if(!P(X))return;let J=X[kZ];if(!P(J)||!Object.hasOwn(J,$))return;let G=J[$];return x(G)?G:void 0}function E3(Z,$){let X=_1(Z,$)?.credentialEpoch;return x(X)?X:void 0}function vZ(Z,$){return Math.max(R3(Z,$)??0,E3(Z,$)??0)+1}function I3(Z,$){let X=[...$];if(X.length===0)return;let J=S3(Z),G=P(J[kZ])?J[kZ]:{},z={},Q=(W,B)=>Object.defineProperty(z,W,{value:B,enumerable:!0,writable:!0,configurable:!0});for(let[W,B]of Object.entries(G))if(x(B))Q(W,B);for(let W of X)Q(W,Math.max(R3(Z,W)??0,E3(Z,W)??1));J[kZ]=z}function T1(Z,$,X,J){let G=A3(Z),z=z7($),Q=new Set,W=[];for(let B of w1(Z)){let U=Q7(B),H=P(B)&&typeof B.id==="string"?B.id:void 0,V=H===void 0?void 0:G[H],j=P(V)&&Object.hasOwn(V,"staged"),D=j?C3(V.staged):void 0;if(U||!P(B)||H===void 0||Q.has(H)){if(H!==void 0&&!Q.has(H))Q.add(H);if(H!==void 0)W.push({id:H,type:P(B)&&B.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(G,H),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}Q.add(H);let Y=B.type==="api"?"api":"oauth",q=Object.hasOwn(G,H),F=q?B7(G[H],X):void 0,N=W7(B,z[H]),L=B.enabled!==!1,O=F?F.credentialEpoch:q?void 0:1,_=typeof B.accountId==="string"&&B.accountId?B.accountId:void 0,M={id:H,type:Y,enabled:L,needsFirstReading:F?F.needsFirstReading:Y==="oauth",hasEntry:q,candidate:!1,...typeof B.label==="string"?{label:B.label}:{},...typeof B.addedAt==="number"?{addedAt:B.addedAt}:{},..._!==void 0?{identity:_}:{},...N?{credential:N,fingerprint:Z1(N)}:{},...F?{credentialEpoch:F.credentialEpoch}:{},...D?{staged:D}:{},...F?.disabledReason!==void 0?{disabledReason:F.disabledReason}:{},...F&&"quota"in F?{quota:F.quota}:{},...U7(z[H],N,O,_,J),stamp:G7(N,O,_,z[H])};if(q&&!F)M.invalid="entry";else M.candidate=L&&N!==void 0&&!j;W.push(M)}return W}function U7(Z,$,X,J,G){if(!P(Z)||!Object.hasOwn(Z,p))return{};let z=zZ(Z,$,X,J);if(z===void 0)return{providerStateDropped:"uncovered"};let Q=Z[p];if(!G?.validate(Q))return{providerStateDropped:"invalid"};if(m1(G,Q)!==z)return{providerStateDropped:"uncovered"};return{providerState:Q}}function k(Z){return Z.identity??Z.id}function QZ(Z,$){if(Z===void 0||Z>$+T0)return $;return Math.max($,Z+1)}function R0(Z,$){return QZ(Z,$)>$+T0}function u1(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 b3(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 y3(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function k3(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)&&!O0(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var gZ="transition",f3="transitionMark";function V7(Z){if(!P(Z))return;let $=Z[gZ];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 BZ(Z,$,X){if(X.enabled)XZ(Z,$);else P1(Z,$,X.reason??"");if(!Z.rosterRow($))return;let J=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...J,[f3]:X.mark}),!X.enabled)return;let G=Z.rows().find((z)=>z.id===$);if(G?.type==="oauth"&&G.identity!==void 0)g1(Z,G.identity)}function Y7(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function H7(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function j7(Z,$,X,J={}){let G=P($.accounts)?$.accounts:{},z=new Map;for(let Q of T1(Z,$,X)){if(Q.invalid||Q.staged||!Q.credential)continue;let W=Object.hasOwn(G,Q.id)?G[Q.id]:void 0;if(!P(W))continue;let B=c(W[I]);if(!B?.binding)continue;if(B.digest!==Q1(Q.credential))continue;let U=Q.credentialEpoch??1;if(B.credentialEpoch>U){if(!H7(B))continue;if(J.requireCredentialStamps){if(B.dispatch===void 0)continue;if(B.dispatch!==q1(Y7(Q.credential,B.binding)))continue}z.set(Q.id,{kind:"replace",stamp:{...B,binding:B.binding}})}else if(B.credentialEpoch===U&&B.dispatch!==void 0&&B.dispatch===q1(Q.credential)&&B.binding.identity!==void 0&&Q.identity===void 0)z.set(Q.id,{kind:"identity",identity:B.binding.identity});else if(B.credentialEpoch===U&&B.binding.identity===Q.identity){if(J.requireCredentialStamps&&B.dispatch!==q1(Q.credential))continue;let H=V7(W[I]);if(H&&_1(Z,Q.id)?.[f3]!==H.mark)z.set(Q.id,{kind:"transition",transition:H})}}return z}function E0(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(v1))delete z.disabledReason;Z.setEntry($,z);let Q=Z.rosterRow($);if(!Q)return;if(J.identity!==void 0)Q.accountId=J.identity;else delete Q.accountId;if(J.baseURL!==void 0)Q.baseURL=J.baseURL;if(J.authHeader!==void 0)Q.authHeader=J.authHeader}function I0(Z,$,X,J={}){let G=j7(Z,$,X,J);if(G.size===0)return{config:Z,torn:[]};let z=structuredClone(Z),Q={rows:()=>T1(z,$,X),rosterRow:(W)=>fZ(z,W),entry:(W)=>_1(z,W),setEntry:(W,B)=>hZ(z,W,B)};for(let[W,B]of G)if(B.kind==="replace")E0(Q,W,B.stamp.credentialEpoch,B.stamp.binding);for(let[W,B]of G)if(B.kind==="identity")A1(Q,W,B.identity);else if(B.kind==="transition")BZ(Q,W,B.transition);else if(B.stamp.binding.identity!==void 0)g1(Q,B.stamp.binding.identity);return{config:z,torn:[...G.keys()]}}function b0(Z,$,X,J={}){let{config:G,torn:z}=I0(Z,$,X,J),Q=T1(G,$,X,J.providerState);for(let W of Q){if(z.includes(W.id))W.torn=!0,W.candidate=!1;if(J.requireCredentialStamps&&W.stamp!=="bound")W.unbound=!0,W.candidate=!1}return Q}async function y0(Z){try{return await g3(Z,v3)}catch($){if($.code==="ENOENT")return;throw $}}function h3(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function l(Z){for(let $=0;$<3;$++){let X=await y0(Z.configPath),J=await y0(Z.statePath),G=await y0(Z.configPath);if(X!==G){if($<2)await q7(2+Math.floor(Math.random()*4));continue}let z=T3(h3(X));if(z.status==="error")return{status:"error",file:"config",reason:z.reason};let Q=O3(h3(J));if(Q.status==="error")return{status:"error",file:"state",reason:Q.reason};if(z.status==="pending-migration")return{status:"pending-migration",config:z.config};return{status:"ready",configExists:z.exists,stateExists:Q.exists,config:z.config,state:Q.state,rows:b0(z.config,Q.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 $1(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 u3{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 b0(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){R1(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(),fZ(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 S0(this.config)}entry(Z){return this.entries(),_1(this.config,Z)}setEntry(Z,$){hZ(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=I0(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 B of $)if(P(B)&&typeof B.id==="string")X.add(B.id);let J=new Set;for(let B of w1(this.snapshot.config))if(P(B)&&typeof B.id==="string"&&!X.has(B.id))J.add(B.id);for(let B of Object.keys(this.entries()))if(!X.has(B))J.add(B);I3(this.config,J);let G=this.entries(),z={};for(let[B,U]of Object.entries(G))if(X.has(B))Object.defineProperty(z,B,{value:U,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[y],W={...this.config,version:GZ,accounts:$,[y]:{...Q,schemaVersion:C1,[e]:z}};await this.write(this.ctx.configPath,W,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let B of J)this.ctx.removedIds.add(B);this.config=W}),this.config=W}async commitState(Z,$={}){let X={...this.state,version:GZ,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 k0(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 k0(this.ctx.configPath)}async write(Z,$,X,J=!0,G=!1,z){await m3(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 p3(Z,$){let X=new L1(Z.lockDefaults,Z.lockEnv),J={writes:0};try{for(let W of Z.storeLocks)await X.acquire(W);let G=await l(Z);if(G.status==="error")throw $1(G,"initialize",void 0);if(G.status==="ready")return"already-ready";let z={};for(let[W,B]of Object.entries(G.config))if(!$.includes(W))z[W]=B;z.version=GZ,z[y]={schemaVersion:C1,[e]:{}};let Q={operation:"initialize",rowId:void 0};return await I1(Z.configPath,z,{beforeRename:async()=>{await Z.onStep?.("before-config-write",Q),await X.assertAll()}}),J.writes++,await Z.onStep?.("after-config-write",Q),"initialized"}catch(G){throw p1(G,"initialize",void 0,J)}finally{await X.releaseAll()}}async function v(Z,$,X,J,G,z={}){let Q=$.held.length;try{for(let U of Z.storeLocks)await $.acquire(U);let W=await l(Z);if(W.status!=="ready")throw $1(W,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let B=new u3(Z,W,$,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))B.assertNotStaged(J.rowId);if(z.completeTorn??!0)await B.completeTorn();return await G(B)}finally{await $.releaseTo(Q)}}function p1(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 x3)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 Q={operation:$,...X!==void 0?{rowId:X}:{},phase:G,...z?{committed:z}:{},cause:Z};if(Z instanceof w3)return new E({...Q,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 yZ)return new E({...Q,retryable:!0,kind:"lock-contention",message:Z.message});return new E({...Q,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function u(Z,$,X,J,G){let z=new L1(Z.lockDefaults,Z.lockEnv),Q={writes:0};try{return await G(z,Q)}catch(W){let B=p1(W,$,X,Q);if(B.kind!=="after-persist-hook")await L3($,J,X,B,Z.logger);throw B}finally{await z.releaseAll()}}function s(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(k($))}`,path:Z.ctx.statePath}}async function D1(Z,$,X){let J=await l(Z.ctx);if(J.status!=="ready")throw $1(J,$,X);let G=J.rows.find((U)=>U.id===X),z=_1(J.config,X),Q=J.state.accounts,W=P(Q)&&Object.hasOwn(Q,X)?Q[X]:void 0,B=P(W)?W[I]:void 0;if(G&&!["enable","disable"].includes($)&&z&&Object.hasOwn(z,"staged"))R1($,X,z.staged);if(!G&&P(B)&&Object.hasOwn(B,"staged"))R1($,X,B.staged);if(!G)throw X1($,X);return{result:J,row:G}}function X1(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 d(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})}async function xZ(Z,$,X,J){let{ctx:G}=Z,z=new L1(G.lockDefaults,G.lockEnv),Q={writes:0};try{if(!x(X?.credentialEpoch))throw K("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await v(G,z,Q,{operation:"pull",rowId:$},async(W)=>{W.assertNotStaged($);let B=W.row($);if(!B)throw X1("pull",$);if(B.invalid)throw K("pull",$,"invalid-row",`row ${$} is invalid`);if(!B.credential)throw K("pull",$,"no-credential",`row ${$} holds no credential`);d("pull",B);let U=W.entry($);if(B.torn||!U||U.credentialEpoch!==X.credentialEpoch||B.identity!==X.identity)throw new E({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`});let H=G.codec.merge(U.quota,J);if(!G.codec.validate(H))throw K("pull",$,"invalid-quota","the quota codec rejected the merged map");W.setEntry($,{...U,quota:H,needsFirstReading:!1}),await W.commitConfig()},{completeTorn:!1})}catch(W){throw p1(W,"pull",$,Q)}finally{await z.releaseAll()}}function F1(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 Q=JSON.stringify(J);z=Q===void 0?void 0:JSON.parse(Q)}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 WZ(Z,$,X,J,G){if(J===void 0||!Z?.merge)return{kind:"set",value:G};return{kind:"set",value:F1(Z,$,X,Z.merge(structuredClone(J),structuredClone(G)),"the merged provider state")}}function l3(Z,$,X,J,G){let z=Z?.onReplace,Q=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(Q===void 0)return{kind:"clear"};if(!z)return{kind:"set",value:Q};return{kind:"set",value:F1(Z,"replace",$.id,Q,"the provider state onReplace returned")}}function d3(Z,$,X,J,G){if($.kind==="set")return m1(Z,$.value);if($.kind==="clear")return;return zZ(X,J?.credential,G,J?.identity)}async function c3(Z,$,X,J,G={}){w("updateProviderState");let{ctx:z}=Z,Q="updateProviderState";return u(z,Q,$,G.onFailure,async(W,B)=>{let U=z.providerState;if(!U)throw K(Q,$,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw K(Q,$,"invalid-input","a mutator is required");let H=P(X)?X.credentialEpoch:void 0;if(!x(H))throw K(Q,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await D1(Z,Q,$);await W.acquire(s(Z,V));for(let j of G.extraLocks??[])await W.acquire(j);return v(z,W,B,{operation:Q,rowId:$},async(j)=>{let D=j.row($);if(!D)throw X1(Q,$);if(k(D)!==k(V))throw K(Q,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(D.invalid)throw K(Q,$,"invalid-row",`row ${$} failed validation`);if(!D.credential)throw K(Q,$,"no-credential",`row ${$} holds no credential`);if(d(Q,D),(D.credentialEpoch??1)!==H||D.identity!==X.identity)throw K(Q,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await f0(j,U,Q,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 s3=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function f0(Z,$,X,J,G,z=!1){let{id:Q,credential:W}=J;if(!W)throw K(X,Q,"no-credential",`row ${Q} holds no credential`);let B=J.credentialEpoch??1,U=Z.stateAccount(Q),H=U?.[I],V=c(H);if(!P(H)||!V?.binding||V.digest!==Q1(W)||V.credentialEpoch!==B||V.binding.identity!==J.identity)throw K(X,Q,"unbound-credential",`row ${Q}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let j=J.providerState===void 0?void 0:structuredClone(J.providerState),D=await z1(X,()=>G(j,J));if(z&&D===s3)return{kind:"declined"};let Y=D===void 0?void 0:F1($,X,Q,D,"the provider state the mutator returned"),q=U!==void 0&&Object.hasOwn(U,p);if(Y===void 0?!q:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(Y))return{kind:"unchanged",...Y!==void 0?{value:Y}:{}};let F={...U};if(Y===void 0){delete F[p];let N={...H};delete N.providerState,F[I]=N}else{F[p]=Y;let N=m1($,Y);if(V.providerState!==N)F[I]={...H,providerState:N}}return{kind:"changed",...Y!==void 0?{value:Y}:{},account:F}}import{randomUUID as a3}from"node:crypto";async function pZ(Z,$,X){if(!X)return;let J=Z.rows().map((z)=>{let{id:Q,type:W,label:B,enabled:U,disabledReason:H,identity:V,credentialEpoch:j,stamp:D,staged:Y,torn:q,invalid:F}=z;return{id:Q,type:W,label:B,enabled:U,disabledReason:H,identity:V,credentialEpoch:j,stamp:D,staged:Y,torn:q,invalid:F}}),G=await z1(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 D7=["access","refresh","expires","lastRefreshedAt","apiKey"];function F7(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function M7(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"}:F7(J),Q=X.baseURL?.trim()??z.baseURL,W=X.authHeader??z.authHeader;if(Q!==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:Q,authHeader:W}}function n3(Z,$,X,J){let G=Z.rosterRow($),z=Z.row($),Q=J??(z?z.identity:P(G)&&typeof G.accountId==="string"&&G.accountId?G.accountId:void 0);return{...Q!==void 0?{identity:Q}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function mZ(Z,$,X,J,G={}){let z=M7($,X,J),Q=$.stateAccount(X),W=G.providerState??{kind:"keep"},B=$.row(X)?.credentialEpoch??$.entry(X)?.credentialEpoch,U=typeof B==="number"?B:1,H=d3(Z.ctx.providerState,W,Q,Q&&Object.hasOwn(Q,p)?$.row(X):void 0,U),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,j=z.type==="oauth"?G.stamp??QZ(V,Z.ctx.now()):void 0,D={...Q??{}};for(let F of D7)delete D[F];if(G.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(W.kind==="clear")delete D[p];else if(W.kind==="set")D[p]=W.value;let Y=y3(z,j),q={...D,...b3(z,j),[I]:{...G.staged?{staged:G.staged}:{},...G.transition!==void 0?{[gZ]:G.transition}:{},...A0(Y,U,G.binding??n3($,X,Y,G.identity),{replace:G.binding!==void 0,...H!==void 0?{providerState:H}:{}})}};return{stored:Y,account:q}}async function wZ(Z,$,X){return Z.setStateAccount($,X.account),await Z.commitState(X.stored),X.stored}async function lZ(Z,$,X,J,G={}){return wZ($,X,mZ(Z,$,X,J,G))}async function N7(Z,$,X){if(!$.credential||$.stamp!=="bound")return;let J=Z.stateAccount($.id),G=zZ(J,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...J??{},[I]:A0($.credential,$.credentialEpoch??1,n3(Z,$.id,$.credential,X),G!==void 0?{providerState:G}:{})}),await Z.commitState()}function v0(Z,$,X){let J=Z==="add"?x1($):void 0;if(J)throw K(Z,$,"invalid-input",J);let G=k3(X,{baseURLOptional:Z==="rotate"});if(G)throw K(Z,$,"invalid-input",G)}function dZ(Z,$,X,J){if(!X)throw X1(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 d1(Z,$,X){if(X!==void 0&&!x(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 cZ(Z,$,X,J){if(!X)throw X1(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 uZ(Z,$){return K(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function UZ(Z,$){return K(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function K7(Z,$,X,J){let{id:G,credential:z,identity:Q}=X;if(!Z.ctx.requireCredentialStamps||$.rosterRow(G)||!l1($.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`)},B=$.stateAccount(G),U=c(B?.[I]);if(!U?.binding||U.dispatch===void 0||U.replace)return W();if(z.type==="api"&&(U.binding.baseURL===void 0||U.binding.authHeader===void 0))return W();let H=z.type==="api"?{...z,baseURL:U.binding.baseURL,authHeader:U.binding.authHeader}:z,[V]=T1({accounts:[u1({id:G,credential:H,identity:U.binding.identity,addedAt:0})],[y]:{rows:{[G]:{credentialEpoch:vZ($.config,G)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return W();if(Q!==void 0&&Q!==V.identity)return W();if(Q1(z)!==U.digest)return W();if(z.type==="api"){if(z.baseURL.trim()!==U.binding.baseURL)return W();if((z.authHeader??"authorization-bearer")!==U.binding.authHeader)return W()}else if(q1(z)!==U.dispatch)return W();if(U.providerState!==void 0&&V.providerState===void 0)return W();if(J!==void 0&&m1(Z.ctx.providerState,J)!==U.providerState)return W();return V}function P7(Z,$,X,J){let{id:G,credential:z,identity:Q,label:W}=X,B=$.rosterRow(G),U=()=>{throw K("add",G,B?"id-exists":"unbound-credential",`row ${G} does not match this staged add`)},H=$.stateAccount(G),V=c(H?.[I]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return U();if(B&&(B.type!==z.type||B.label!==W||B.accountId!==Q))return U();if(j.reservation!==X.stage?.reservation||j.label!==W||j.disabledReason!==X.disabled?.reason||V.binding.identity!==Q)return U();let D=J===void 0?void 0:E1(J),Y=H?.[p],q=Y===void 0?void 0:E1(Y);if(j.providerState!==D||j.providerState!==q)return U();if(Q1(z)!==V.digest||q1(z)!==V.dispatch)return U();let F=B?$.config:{accounts:[{...u1({id:G,credential:z.type==="api"?{...z,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:z,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[G]:{credentialEpoch:V.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!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return U();if(B)return{id:G,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(vZ($.config,G)!==V.credentialEpoch)return U();return $.roster().push({...u1({id:G,credential:z,identity:Q,label:W,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(G,{credentialEpoch:V.credentialEpoch,needsFirstReading:z.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:G,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function i3(Z,$,X={}){w("add");let{ctx:J}=Z,{id:G,credential:z,identity:Q,label:W}=$,B=$.stage!==void 0||$.disabled!==void 0,U=await u(J,"add",G,X.onFailure,async(H,V)=>{v0("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"||Q!==void 0&&(typeof Q!=="string"||!Q))||$.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:F1(J.providerState,"add",G,$.providerState);if(await H.acquire(s(Z,{id:G,identity:Q})),z.type==="oauth")await H.acquire(X.providerLock??Z.providerLock);for(let Y of X.extraLocks??[])await H.acquire(Y);return v(J,H,V,{operation:"add",rowId:G},async(Y)=>{await pZ(Y,G,X.protect);let q=P(Y.state.accounts)?Y.state.accounts:{},F=Object.entries(q).find(([b,f])=>{if(b===G||Y.rosterRow(b)||!P(f))return!1;let $Z=f[I];if(!P($Z)||!Object.hasOwn($Z,"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"&&(Y.rosterRow(G)||l1(Y.state,G)))return P7(Z,Y,$,D);if(j==="rotate"){Y.assertNotStaged(G);let b=Y.rows().find((f)=>f.fingerprint===Z1(z));if(b)Y.assertNotStaged(b.id)}if(j==="refuse"){let b=Y.rows().find((K1)=>K1.fingerprint===Z1(z)||K1.id===G&&K1.credential),f=P(Y.state.accounts)?Y.state.accounts:{},$Z=Object.entries(f).find(([,K1])=>{if(!P(K1))return!1;if(z.type==="oauth")return K1.refresh===z.refresh;return typeof K1.apiKey==="string"&&K1.apiKey.trim()===z.apiKey.trim()})?.[0],K3=b?.id??$Z??G;if(b||$Z!==void 0||l1(Y.state,G))throw K("add",K3,"credential-exists",`row ${K3} already holds this secret or id`)}if(j==="stage-duplicate"&&(Y.rosterRow(G)||l1(Y.state,G)))throw K("add",G,"id-exists",`row ${G} already exists`);let N=K7(Z,Y,$,D),L=Y.rows(),O=Z1(z),_=j==="rotate"&&!N&&L.find((b)=>b.invalid===void 0&&b.fingerprint===O);if(_){if(Y.assertNotStaged(_.id),d("add",_),Q!==void 0&&_.identity!==void 0&&Q!==_.identity)throw uZ("add",_.id);let b=mZ(Z,Y,_.id,z,{...D!==void 0?{providerState:WZ(J.providerState,"add",_.id,_.providerState,D)}:{}});await Y.completeTorn(),Y.assertNotStaged(_.id);let f=await wZ(Y,_.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(d("add",M),M.type!==z.type)throw K("add",G,"type-mismatch",`row ${G} is a ${M.type} row`);if(Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw uZ("add",G);if(!M.hasEntry)Y.setEntry(G,{credentialEpoch:1,needsFirstReading:z.type==="oauth"});let b=mZ(Z,Y,G,z,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await Y.completeTorn();let f=await wZ(Y,G,b);if(!M.hasEntry)await Y.commitConfig();return{id:G,outcome:"completed",credential:f,credentialEpoch:M.credentialEpoch??1}}let C=vZ(Y.config,G);if(!x(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??Q;Y.roster().push(u1({id:G,credential:z,...A!==void 0?{identity:A}:{},...W!==void 0?{label:W}:{},addedAt:J.now()})),Y.setEntry(G,{credentialEpoch:C,needsFirstReading:z.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let T="added";if($.disabled)P1(Y,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))P1(Y,G,C0),T="added-disabled"}if(N?.credential)return await Y.commitConfig(),{id:G,outcome:T,credential:N.credential,credentialEpoch:N.credentialEpoch??C};Y.dropStateAccount(G);let R=mZ(Z,Y,G,z,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...W!==void 0?{label:W}:{},...D!==void 0?{providerState:E1(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await Y.completeTorn();let h=await wZ(Y,G,R);return await Y.commitConfig(),{id:G,outcome:T,credential:h,credentialEpoch:C}},{completeTorn:!1})});if(!B&&z.type==="oauth"&&(U.outcome==="added"||U.outcome==="completed"))Z.firePull(U.id,"add");return U}async function r3(Z,$,X,J={},G={}){w("replace");let{ctx:z}=Z,Q=await u(z,"replace",$,G.onFailure,async(W,B)=>{v0("replace",$,X),d1("replace",$,G.attribution);let U=J.providerState===void 0?void 0:F1(z.providerState,"replace",$,J.providerState),{row:H}=await D1(Z,"replace",$);if(await W.acquire(s(Z,H)),X.type==="oauth")await W.acquire(G.providerLock??Z.providerLock);for(let V of G.extraLocks??[])await W.acquire(V);return v(z,W,B,{operation:"replace",rowId:$},async(V)=>{if(G.attribution!==void 0)cZ("replace",$,V.row($),G.attribution),await V.completeTorn();let j=dZ("replace",$,V.row($),X);if(k(j)!==k(H))throw UZ("replace",$);let D=V.entry($)?.credentialEpoch,Y=(typeof D==="number"?D:1)+1;if(!x(Y))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=l3(z.providerState,j,Y,J.identity,U),F={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(E0(V,$,Y,F),J.identity!==void 0)g1(V,J.identity);let N=await lZ(Z,V,$,X,{clearErrors:!0,binding:F,providerState:q});return await V.commitConfig(),{id:$,credential:N,credentialEpoch:Y}},{completeTorn:G.attribution===void 0})});if(X.type==="oauth")Z.firePull($,"replace");return Q}async function o3(Z,$,X,J={},G={}){w("rotate");let{ctx:z}=Z;return u(z,"rotate",$,G.onFailure,async(Q,W)=>{v0("rotate",$,X),d1("rotate",$,G.attribution);let B=J.providerState===void 0?void 0:F1(z.providerState,"rotate",$,J.providerState),{row:U}=await D1(Z,"rotate",$);if(await Q.acquire(s(Z,U)),J.identity!==void 0&&X.type==="oauth")await Q.acquire(G.providerLock??Z.providerLock);for(let H of G.extraLocks??[])await Q.acquire(H);return v(z,Q,W,{operation:"rotate",rowId:$},async(H)=>{if(G.attribution!==void 0)cZ("rotate",$,H.row($),G.attribution),await H.completeTorn();let V=dZ("rotate",$,H.row($),X);if(k(V)!==k(U))throw UZ("rotate",$);if(d("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw uZ("rotate",$);let j=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,D=await lZ(Z,H,$,X,{identity:j,...B!==void 0?{providerState:WZ(z.providerState,"rotate",$,V.providerState,B)}:{}}),Y=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),Y=!0;if(J.identity!==void 0&&V.identity!==J.identity)A1(H,$,J.identity),Y=!0;if(Y)await H.commitConfig();return{id:$,credential:D}},{completeTorn:G.attribution===void 0})})}async function t3(Z,$,X,J,G){w($);let{ctx:z}=Z,Q=z.providerState,W=G.attribution,B=G.providerState;return u(z,$,X,G.onFailure,async(U,H)=>{if(d1($,X,W),B!==void 0){if(typeof B!=="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(!Q)throw K($,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await D1(Z,$,X);await U.acquire(s(Z,V));for(let j of G.extraLocks??[])await U.acquire(j);return v(z,U,H,{operation:$,rowId:X},async(j)=>{await pZ(j,X,G.protect),j.assertNotStaged(X);let D=j.row(X),Y=J.enabled?dZ("enable",X,D):D;if(!Y||!j.rosterRow(X))throw X1($,X);if(k(Y)!==k(V))throw UZ($,X);if(W!==void 0)cZ($,X,Y,W);if(J.enabled&&Y.disabledReason?.startsWith(v1))throw K("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let q=!J.enabled||!Y.enabled||Y.disabledReason!==void 0;if(J.enabled&&q&&Y.type==="oauth"){let _=Y.identity===void 0?void 0:j.rows().find((M)=>M.id!==X&&M.invalid===void 0&&M.type==="oauth"&&M.enabled&&M.identity===Y.identity);if(_)throw K("enable",X,"duplicate-identity",`row ${_.id} is enabled with the same identity as row ${X}`)}if(B===void 0||Q===void 0){if(await j.completeTorn(),!q)return{id:X};if(J.enabled)XZ(j,X);else P1(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!Y.credential)throw K($,X,"no-credential",`row ${X} holds no credential`);d($,Y);let F=await f0(j,Q,$,Y,B,!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)XZ(j,X);else P1(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:a3(),enabled:!0}:{mark:a3(),enabled:!1,reason:J.reason},O=F.account[I];return j.setStateAccount(X,{...F.account,[I]:{...O,[gZ]:L}}),await j.commitState(),BZ(j,X,L),await j.commitConfig(),N},{completeTorn:!1})})}function e3(Z,$,X,J={}){return t3(Z,"disable",$,{enabled:!1,reason:X},J)}function Z4(Z,$,X={}){return t3(Z,"enable",$,{enabled:!0},X)}async function $4(Z,$,X={}){w("remove");let{ctx:J}=Z;return u(J,"remove",$,X.onFailure,async(G,z)=>{if(typeof $!=="string"||$.length===0)throw K("remove",$,"invalid-input","id must be non-empty");let Q=X.attribution;if(d1("remove",$,Q),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 l(J);if(W.status!=="ready")throw $1(W,"remove",$);let B=W.rows.find((H)=>H.id===$);if(!B&&!l1(W.state,$))throw X1("remove",$);let U=k(B??{id:$});await G.acquire(s(Z,B??{id:$}));for(let H of X.extraLocks??[])await G.acquire(H);return v(J,G,z,{operation:"remove",rowId:$},async(H)=>{let V=H.reservation($);if(V!==void 0){if(!P(V)||!X.staged||V.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=l1(H.state,$);if(!j&&!D)throw X1("remove",$);if(k(j??{id:$})!==U)throw UZ("remove",$);if(Q!==void 0)if(j)sZ($,j,Q);else L7(Z,H,$,Q);let Y=X.protect;if(Y){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await z1("remove",()=>Y($,q));if(F!==void 0)throw K("remove",$,"row-protected",F)}if(j){if(Q===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 sZ(Z,$,X,J="remove"){if(cZ(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 L7(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),Q=c(z?.[I]);if(!z||!Q?.binding||Q.dispatch===void 0||Q.replace)throw G();let W;if(typeof z.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw G();W={type:"api",apiKey:z.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof z.refresh==="string")W={type:"oauth",refresh:z.refresh};else throw G();let[B]=T1({accounts:[u1({id:X,credential:W,identity:Q.binding.identity,addedAt:0})],[y]:{rows:{[X]:{credentialEpoch:Q.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!B?.credential||B.invalid||B.stamp!=="bound")throw G();if(Q.credentialEpoch!==J.credentialEpoch||Q.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 l1(Z,$){let X=Z.accounts;return P(X)&&Object.hasOwn(X,$)}function h0(Z){return P(Z)&&typeof Z.id==="string"?Z.id:void 0}function C7(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let X=new Set;for(let z of Z){let Q=h0(z);if(Q!==void 0)X.add(Q)}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 _7(Z,$){let X=new Map;for(let z of Z){let Q=h0(z);if(Q===void 0)continue;let W=X.get(Q);if(W)W.push(z);else X.set(Q,[z])}let J=$.flatMap((z)=>X.get(z)??[]),G=0;return Z.map((z)=>h0(z)===void 0?z:J[G++])}async function X4(Z,$,X={}){w("reorder");let{ctx:J}=Z,G=X.onFailure;return u(J,"reorder",void 0,G&&((z,Q)=>G(Q)),async(z,Q)=>{for(let W of X.extraLocks??[])await z.acquire(W);return v(J,z,Q,{operation:"reorder",rowId:void 0},async(W)=>{let B=W.roster(),U=C7(B,$);if(U)throw new E({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:U});let H=[...$],V=_7(B,H);if(V.every((j,D)=>j===B[D]))return{ids:H,outcome:"unchanged"};return W.config.accounts=V,await W.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function J4(Z,$,X,J,G={}){return w("recordIdentity"),u(Z.ctx,"recordIdentity",$,G.onFailure,async(z,Q)=>{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(!x(W))throw K("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:B}=await D1(Z,"recordIdentity",$);await z.acquire(s(Z,B)),await z.acquire(G.providerLock??Z.providerLock);for(let U of G.extraLocks??[])await z.acquire(U);return v(Z.ctx,z,Q,{operation:"recordIdentity",rowId:$},async(U)=>{let H=dZ("recordIdentity",$,U.row($));if(k(H)!==k(B))throw UZ("recordIdentity",$);if(d("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 uZ("recordIdentity",$);if(H.identity===void 0)await N7(U,H,X);let V=A1(U,$,X);return await U.commitConfig(),{id:$,disabled:V}})})}function z4(Z){let $=Z[y];return P($)&&P($.publications)?$.publications:{}}function Q4(Z,$){let X=z4(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"||!x(G.credentialEpoch))||J.finalized.some((G)=>!P(G)||typeof G.id!=="string"||!x(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 B4(Z,$){let X=await l(Z.ctx);if(X.status!=="ready")throw $1(X,"publishRoster",$);return Q4(X.config,$)}function T7(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"||x1(G.id)||J.has(G.id)||!G.attribution)X();if(J.add(G.id),d1("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"||x1(G))||new Set($.order).size!==$.order.length)X()}function W4(Z,$){Z.entries();let X=Z.config[y],J={...z4(Z.config)};Object.defineProperty(J,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function O7(Z,$,X){let J=new Set;for(let Q of w1(Z.config)){if(!P(Q)||typeof Q.id!=="string")continue;if(J.has(Q.id))throw K("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(Q.id)}let G=new Set($.remove.map((Q)=>Q.id)),z=X.filter((Q)=>Q.invalid!=="roster"&&!G.has(Q.id));if(z.length!==$.order.length||$.order.some((Q)=>!z.some((W)=>W.id===Q))||z.some((Q)=>!$.order.includes(Q.id)))throw K("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return z}async function G4(Z,$){await Z.assertAll();for(let J of $.removed)if(c(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=c(G?.[I]);if(G&&z?.credentialEpoch===J.credentialEpoch&&z.staged?.reservation===J.reservation){let Q={...G[I]};delete Q.staged,Z.setStateAccount(J.id,{...G,[I]:Q})}}await Z.commitState(void 0,{durable:!0});let X={...$,phase:"cleaned"};return W4(Z,X),await Z.commitConfig({durable:!0}),X}async function U4(Z,$,X={}){return w("publishRoster"),u(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=E1($),Q=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((W)=>P(W)&&typeof W.id==="string");for(let W=0;;W++){let B=await l(Z.ctx);if(B.status!=="ready")throw $1(B,"publishRoster",$.operationId);let U=new Map(Q.map(({id:V})=>[V,k(B.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(U.values())].sort())await J.acquire(s(Z,{id:V}));await J.acquire(X.providerLock??Z.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let H=await v(Z.ctx,J,G,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(Q.some(({id:M})=>k(j.find((C)=>C.id===M)??{id:M})!==U.get(M)))return;let D=Q4(V.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 V.markPublicationDecision(),await V.syncConfig(),{outcome:"cleaned",receipt:await G4(V,D)}}T7(Z,$);let Y=O7(V,$,j),q=[];for(let M of $.remove){V.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(sZ(M.id,C,M.attribution,"publishRoster"),!C.credential||M.fingerprint!==void 0&&Z1(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=c(V.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=V.stateAccount(M.id),R=V.rosterRow(M.id),h=T?.[p],b=h===void 0?void 0:E1(h);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");sZ(M.id,C,M.attribution,"publishRoster"),F.push(C)}let N=Y.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 Y){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 Y)if(M.identity!==void 0&&M.fingerprint!==void 0&&Y.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 pZ(V,$.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)V.dropRosterRows(M.id);for(let M of $.finalize){let C=V.rosterRow(M.id);C.enabled=M.enabled;let A={...V.entry(M.id)};if(delete A.staged,M.enabled)delete A.disabledReason;else A.disabledReason=M.disabledReason;V.setEntry(M.id,A)}let _=V.roster().filter((M)=>!P(M)||typeof M.id!=="string"||j.find((C)=>C.id===M.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((M)=>V.rosterRow(M)),..._],W4(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await G4(V,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 g0{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 L1(J.lockDefaults,J.lockEnv),z={writes:0};try{let Q=await v(J,G,z,{operation:"pull",rowId:Z},async(B)=>{if(B.reservation(Z)!==void 0)return;await B.completeTorn();let U=B.row(Z);if(U?.unbound&&U.enabled&&U.type==="oauth"&&U.credential&&!U.invalid)d("pull",U);if(!U?.candidate||U.type!=="oauth")return;if(!U.hasEntry)B.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await B.commitConfig();let H=B.row(Z);if(!H?.credential||H.credentialEpoch===void 0)return;return{id:Z,credential:H.credential,credentialEpoch:H.credentialEpoch,...H.identity!==void 0?{identity:H.identity}:{},reason:$}},{completeTorn:!1});if(await G.releaseAll(),!Q){this.firedAtLoad.delete(Z);return}await J.hold?.("pull-before-request",Z);let W;try{W=await this.hook?.(Q)}catch(B){throw new E({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:B})}await xZ(X,Z,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},W)}catch(Q){this.firedAtLoad.delete(Z);let W=p1(Q,"pull",Z,z);if(this.onFailure)try{await this.onFailure(Z,W)}catch(B){this.logger?.warn("pull failure hook threw",{rowId:Z,error:B instanceof Error?B.message:String(B)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:W.kind})}finally{await G.releaseAll()}}}import{randomUUID as A7}from"node:crypto";function x0(Z,$){if(R1("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 V4(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 Y4(Z,$,X,J={}){w("refresh");let{ctx:G}=Z;return u(G,"refresh",$,J.onFailure,async(z,Q)=>{let{row:W}=await D1(Z,"refresh",$);x0($,W);let B=await J.refuse?.(W);if(B!==void 0)return{status:"refused",rowId:$,reason:B};let U=k(W),H;for(let Y=0;;Y++){await z.acquire(s(Z,{id:$,identity:U===$?void 0:U})),await z.acquire(J.providerLock??Z.providerLock);for(let N of J.extraLocks??[])await z.acquire(N);let F=await v(G,z,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let L=x0($,N.row($));if(d("refresh",L),!L.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),L=x0($,N.row($));if(k(L)!==U)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(),Y>=1)throw K("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);U=F.keyNow;continue}H=F;break}if(R0(H.credential.lastRefreshedAt,G.now()))throw V4($);await G.hold?.("refresh-before-provider",$),await z.assertAll();let V;try{V=await X(H.credential,H.row)}catch(Y){throw new E({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:Y})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw K("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:F1(G.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),D=await v(G,z,Q,{operation:"refresh",rowId:$},async(Y)=>{let q=Y.row($),F=Y.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`});d("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(R0(O,L))throw V4($);let _={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},M=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,C=M?{mark:A7(),enabled:!1,reason:`${v1}${JSON.stringify(M)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,T=await lZ(Z,Y,$,_,{stamp:QZ(O,L),transition:C,identity:A,...j!==void 0?{providerState:WZ(G.providerState,"refresh",$,q.providerState,j)}:{}});if(C!==void 0)BZ(Y,$,C),await Y.commitConfig();let R=q.identity;if(A!==void 0)A1(Y,$,A),R=A,await Y.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 Y=J.onPersisted;await z1("refresh",()=>Y($,D.stored))}catch(Y){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:Y})}return{status:"rotated",rowId:$,credential:D.stored,...D.identity!==void 0?{identity:D.identity}:{}}})}import{isDeepStrictEqual as S7}from"node:util";var nZ=Object.freeze(["version","accounts",y]);function m0(Z){let $={};for(let[X,J]of Object.entries(Z))if(!nZ.includes(X))aZ($,X,J);return $}function aZ(Z,$,X){Object.defineProperty(Z,$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function R7(Z,$){let X={};for(let[J,G]of Object.entries(Z))if(nZ.includes(J))aZ(X,J,G);else if(Object.hasOwn($,J))aZ(X,J,$[J]);for(let[J,G]of Object.entries($))if(!Object.hasOwn(Z,J))aZ(X,J,G);return X}function H4(Z){return new E({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}async function j4(Z){let $=await l(Z.ctx);if($.status==="error")return $;return{status:$.status,settings:m0($.config)}}async function q4(Z,$,X={}){w("updateSettings");let{ctx:J}=Z,G=X.onFailure;return u(J,"updateSettings",void 0,G&&((z,Q)=>G(Q)),async(z,Q)=>{for(let B of X.extraLocks??[])await z.acquire(B);let W=z.held.length;try{for(let F of J.storeLocks)await z.acquire(F);let B=await l(J);if(B.status!=="ready")throw $1(B,"updateSettings",void 0);let U=m0(B.config),H=structuredClone(U),V=await z1("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!P(j))throw H4("the settings mutator must produce an object");let D=nZ.filter((F)=>Object.hasOwn(j,F));if(D.length>0)throw H4(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(S7(j,U))return{settings:U,outcome:"unchanged"};let Y=R7(B.config,j),q={operation:"updateSettings",rowId:void 0};return await I1(J.configPath,Y,{beforeRename:async()=>{await J.onStep?.("before-config-write",q),await z.assertAll()}}),Q.writes++,await J.onStep?.("after-config-write",q),{settings:m0(Y),outcome:"updated"}}finally{await z.releaseTo(W)}})}var D4=new Map;function E7(Z){let $=D4.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},D4.set(Z,$);return $}function F4(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:C1,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function VZ(Z){let $=E7(Z.configPath),X={..._0,...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 g0(()=>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,W)=>G.fire(Q,W)};return{async load(){let Q=await l(J);if(Q.status==="ready"){for(let W of Q.rows)if((W.candidate||W.torn&&W.enabled)&&W.type==="oauth"&&W.needsFirstReading)G.fire(W.id,"load")}return F4(Q)},async read(){return F4(await l(J))},async initialize(Q={}){return{status:await p3(J,Q.dropKeys??[])}},add:(Q,W)=>i3(z,Q,W),publishRoster:(Q,W)=>U4(z,Q,W),publication:(Q)=>B4(z,Q),replace:(Q,W,B,U)=>r3(z,Q,W,B,U),rotate:(Q,W,B,U)=>o3(z,Q,W,B,U),updateProviderState:(Q,W,B,U)=>c3(z,Q,W,B,U),disable:(Q,W,B)=>e3(z,Q,W,B),enable:(Q,W)=>Z4(z,Q,W),remove:(Q,W)=>$4(z,Q,W),reorder:(Q,W)=>X4(z,Q,W),readSettings:()=>j4(z),updateSettings:(Q,W)=>q4(z,Q,W),recordIdentity:(Q,W,B,U)=>J4(z,Q,W,B,U),refresh:(Q,W,B)=>Y4(z,Q,W,B),recordQuota:(Q,W,B)=>xZ(z,Q,W,B),requestReading:(Q)=>G.fire(Q,"admission"),pullsSettled:()=>G.settled()}}var I7=[/\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 p0(Z={}){let{redactStrings:$}=M4({...Z,extraValuePatterns:[...I7,...Z.extraValuePatterns??[]]});return(X)=>$(X)}class a extends Error{code;constructor(Z,$,X){super($,X);this.name="CommandError",this.code=Z}}var N4=/^[a-z][a-z0-9-]{0,63}$/,w0={code:"action-failed",text:"That action failed."},b7=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 YZ(Z){if(Z instanceof a)return{code:N4.test(Z.code)?Z.code:w0.code,text:Z.message};if(Z instanceof E)return{code:`pool-${Z.kind}`,text:b7.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return w0}var K4="This cannot be undone. Continue?",y7=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function k7(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return y7.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function f7(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function u0(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)=>u0(G,`${$}[${z}]`,X));if(!f7(Z))return Z;let J={};for(let[G,z]of Object.entries(Z)){if(k7(G)){X.dropped.push(`${$}.${G}`);continue}Object.defineProperty(J,G,{value:u0(z,`${$}.${G}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function P4(Z,$,X){let J={redact:X.redact,dropped:[],redacted:[]},G=u0(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 h7(Z){return{value:String(Z.value),label:String(Z.label)}}function v7(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(h7),...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 l0(Z){if(Z.irreversible===!0)return{message:Z.confirm||K4,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function L4(Z){let $=l0(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(v7),...$?{confirm:$}:{}}}function g7(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 x7(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:g7(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(L4)}}function m7(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(x7),actions:($.actions??[]).map(L4),...$.facts!==void 0?{facts:$.facts}:{}}}function C4(Z,$,X){return{command:Z,title:$,sections:X.map(m7)}}function _4(Z,$,X,J){return P4({command:Z,menu:C4(Z,$,X)},Z,J)}function T4(Z,$,X,J,G){return P4({command:Z,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:N4.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:C4(Z,$,X)},Z,G)}var b4="disabled from the command menu";function w7(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function M1(Z){return w7(Z)?{...Z}:{}}function u7(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 p7(Z,$){return Z.label??$??Z.id}function iZ(Z,$){return c1(Z.quota)?W1(Z.quota,$):void 0}function y4(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var HZ="Actions";function l7(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 O4(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 A4(Z){return YZ(Z).text}async function d7(Z){let $=await Z.read(),X=await Z.readSettings();return{load:$,rows:u7($),settings:X.status==="error"?{}:X.settings}}function rZ(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:p7(Z,X)}}function c7(Z,$){let{store:X,extraLocks:J}=Z,G=J?{extraLocks:J}:{},z=$.rows.map((V)=>V.id),Q=l7($.load),W=$.rows.filter((V)=>V.enabled).length,B=$.rows.map((V,j)=>{let{account:D,name:Y}=rZ(V,Z),q=[V.type==="api"?"API key":"OAuth",...D.identity!==void 0?[D.identity]:[],...!V.invalid&&!V.enabled&&V.disabledReason?[`disabled: ${V.disabledReason}`]:[]].join(" · "),F=V.invalid?"invalid":V.enabled?"enabled":"disabled",N=[];if(!V.invalid&&V.enabled)N.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,b4,G),`Disabled ${Y}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,G),`Enabled ${Y}.`}});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!==V.id);return _.splice(O-1,0,V.id),(await X.reorder(_,G)).outcome==="unchanged"?`${Y} is already at position ${O}.`:`Moved ${Y} to position ${O}.`}});return N.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${Y}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...G,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${Y}.`}}),{id:V.id,label:Y,detail:q,group:"Accounts",status:F,account:D,actions:N}}),U=Z.accounts?.login,H=[];if(U&&!Q)H.push({id:"add",label:U.label??"Add account",group:HZ,knobs:U.knobs??[],run:async({values:V,invocation:j})=>{let D=await U.run(V,j);if(D.status==="cancelled")return{ok:!1,text:D.message??"Login cancelled."};if(D.status==="ready"){let Y=await X.add(D.account,G);return O4(D.account.label??Y.id,Y)}return D.completion.then(async(Y)=>{if(!Y){j.notify("Login cancelled.","warning");return}let q=await X.add(Y,G);j.notify(O4(Y.label??q.id,q))},(Y)=>{j.notify(`Adding the account failed: ${A4(Y)}`,"error")}).catch((Y)=>{j.notify(`Adding the account failed: ${A4(Y)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[$.rows.length===0?"No accounts yet":`${y4($.rows.length,"account")}, ${W} enabled`],items:Q?[]:B,actions:H}}}function s7(Z,$){let X=Z.quota?.scope??"all",J=Z.now(),G=X==="all"?"Accounts":`Accounts · ${X}`,z=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},Q=$.rows.filter((H)=>H.candidate),W=Q.map((H)=>{let{account:V,name:j}=rZ(H,Z),D=iZ(H,X);return{id:H.id,label:j,group:G,status:B1(D,{now:J,form:"compact"}),detail:B1(D,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:Y})=>{return await z([H.id],Y),`Checked quota for ${j}.`}}]}}),B=$.rows.filter((H)=>!H.candidate).map((H)=>{let{name:V}=rZ(H,Z),j=H.invalid?"invalid":!H.enabled?"disabled":H.credential===void 0?"no credential":"unavailable",D=B1(iZ(H,X),{now:J,form:"compact"});return`${V} (${j}): ${D}`}),U=[];if(Q.length>0)U.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:HZ,run:async({invocation:H})=>{let V=Q.map((j)=>j.id);return await z(V,H),`Checked quota for ${y4(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:B,items:W,actions:U}}}function a7(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"}],Q=M1($.settings.routing).mode,W=typeof Q==="string"&&z.some((Y)=>Y.value===Q)?Q:"ordered",B=E4(W),U=$.rows.map((Y)=>Y.id),H=I4(U,B.placement,Z.routing?.formerMainId??R4),j=[`Mode: ${z.find((Y)=>Y.value===W)?.label??W}`];if(U.length>0)j.push(`Roster order: ${U.join(", ")}`);if(B.mode==="ordered"&&H.join()!==U.join())j.push(`Tried in order: ${H.join(", ")}`);let D=[{id:"mode",label:"Change mode",group:HZ,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:z,value:W}],run:async({values:Y})=>{let q=String(Y.mode);return await X.updateSettings((F)=>{F.routing={...M1(F.routing),mode:q};return},G),`Routing mode set to ${z.find((F)=>F.value===q)?.label??q}.`}}];if(U.length>1)D.push({id:"order",label:"Set order",group:HZ,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:U.join(", "),required:!0}],run:async({values:Y})=>{let q=String(Y.order).split(/[\s,]+/).filter((N)=>N.length>0),F=await X.reorder(q,G);return F.outcome==="unchanged"?"The order is unchanged.":`Order set to ${F.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:D}}}function n7(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 iZ(G,X)?.limits??[])if(!J.includes(z.label))J.push(z.label);return J.length>0?J:["primary"]}function i7(Z,$){let X=Z.quota?.scope??"all",J=new Map;for(let G of $.rows)for(let z of iZ(G,X)?.limits??[])if(z.windowMinutes!==void 0&&!J.has(z.label))J.set(z.label,S4(z));return(G)=>J.get(G)??G}function r7(Z,$){let{store:X,extraLocks:J}=Z,G=J?{extraLocks:J}:{},z=M1($.settings.killswitch),Q=z.enabled===!0,W=M1(z.accounts),B=n7(Z,$),U=i7(Z,$),H=Q?"on":"off",V=$.rows.map((j)=>{let{account:D,name:Y}=rZ(j,Z),q=M1(W[j.id]),F=B.filter((N)=>typeof q[N]==="number");return{id:j.id,label:Y,group:`Floors · killswitch ${H}`,status:F.length===0?"no floors":F.map((N)=>`${U(N)} ≥${q[N]}%`).join(" · "),account:D,actions:[{id:"floors",label:"Set floors",knobs:B.map((N)=>({kind:"number",id:N,label:`Minimum % left for ${U(N)}`,min:0,max:100,...typeof q[N]==="number"?{value:q[N]}:{}})),run:async({values:N})=>{return await X.updateSettings((L)=>{let O=M1(L.killswitch),_=M1(O.accounts),M=M1(_[j.id]);for(let C of B){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 ${Y}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${H}`],items:V,actions:[{id:"killswitch",label:Q?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:HZ,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!Q}],run:async({values:j})=>{let D=j.enabled===!0;return await X.updateSettings((Y)=>{Y.killswitch={...M1(Y.killswitch),enabled:D};return},G),`Killswitch ${D?"on":"off"}.`}}]}}}async function k4(Z){let $=await d7(Z.store);return[c7(Z,$),s7(Z,$),a7(Z,$),r7(Z,$)]}var o7=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),d0=["accounts","quota","routing","limits"];function f4(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 t7(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 e7(Z,$){let X={};for(let J of Z){let G=$&&Object.hasOwn($,J.id)?$[J.id]:void 0,z=t7(J,G);if("problem"in z)return z;X[J.id]=z.value}return{values:X}}function Z8(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 b1(Z){let $=Z.logger??J1("commands"),X=p0(Z.redaction),J={logger:$,redact:X},G=Z.now??Date.now,z=Z.extras??[],Q=Z.replace??{},W=d0.filter((j)=>!Q[j]);for(let j of d0)if(Q[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let B=Z.store;if(W.length>0&&!B)throw Error(`a store is required for the built-in ${W.join(", ")} section${W.length>1?"s":""}`);let U=new Set;for(let j of z){if(o7.has(j.id)||U.has(j.id))throw Error(`extra section id ${j.id} is taken`);U.add(j.id)}async function H(j,D,Y,q){try{return{id:j,slot:D,title:Y.title,content:await Y.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:Y.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let D=B&&W.length>0?await k4({store:B,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}:{}}):[],Y=[];for(let q of d0){let F=Q[q];if(F)Y.push(await H(q,q,F,j));else{let N=D.find((L)=>L.slot===q);if(N)Y.push(N)}}if(Z.cache)Y.push(await H("cache","cache",Z.cache,j));if(Z.diagnostics)Y.push(await H("diagnostics","diagnostics",Z.diagnostics,j));for(let q of z)Y.push(await H(q.id,"extra",q,j));return Y}return{command:Z.command,async open(j){let D=f4(j,X);return _4(Z.command,Z.title,await V(D),J)},async apply(j,D){let Y=f4(D,X),q=async(_)=>T4(Z.command,Z.title,await V(Y),_,J),F=j.command===Z.command?Z8(await V(Y),j):void 0;if(!F)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=l0(F);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let L=e7(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:Y});O=typeof _==="string"?{ok:!0,text:_}:{ok:_.ok,text:_.text,..._.ok?{}:{code:_.code??"refused"}}}catch(_){let M=YZ(_);$.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 $8(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function X8(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(!$8(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 m(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}import{statSync as G8}from"node:fs";import{rm as x4}from"node:fs/promises";import{dirname as z8,join as r4}from"node:path";import{resolveClaustrumConnectionPath as Q8}from"@cortexkit/claustrum-client";function h4(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 v4(Z){if(!m(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 J8(Z){let $=v4(Z.total),X=v4(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},...m(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function g4(Z,$){let X=h4(Z.usage?.primary,$.fetchedAt);if(!X||!Number.isFinite($.fetchedAt))return;let J=h4(Z.usage?.secondary,$.fetchedAt),G=Array.isArray(Z.spend)?Z.spend.find((W)=>m(W)&&W.id==="individual_limit"):void 0,z=m(G)?J8(G):void 0,Q=m(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof Q==="number"&&Number.isFinite(Q)&&Q>=0&&{resetCreditsAvailable:Q},...z&&{spendControl:z},...!G&&{spendControlCleared:!0}}}var oZ="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.";var U1=J1("vault"),B8="openai-auth",o4={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},W8={opencode:"OpenCode",pi:"Pi"};function U8(Z){return w4(B8,Z)}function iX(Z){return r4(z8(Z),"openai-auth-vault")}function V8(Z,$){return{...p4({stateDir:Z,host:$}),rosterPath:r4(Z,`${$}-roster.json`)}}var t4=2000,rX={"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-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 oX(Z){return Z.snapshot()===void 0?"vault-unreachable":"vault-empty"}function Y8(Z){let $=eZ(Z);return $?Z0($):void 0}class H8{host;name;paths;#$;#Z;#W=new Map;#U=new Map;#q=new Map;#D;#J;#V;#G;#F=!1;#Q=!1;#Y=Promise.withResolvers();#z;#M="unknown";#N;constructor(Z){this.#$=Z,this.host=Z.host,this.name=U8(Z.host),this.paths=V8(Z.stateDir,Z.host),this.#Z=new n4({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:o4,connect:()=>this.#L(),isCustodyActive:()=>this.enrolled(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:Y8,insula:{provider:"codex",normalize:g4},...Z.now?{now:Z.now}:{},onRoster:()=>{this.#J=void 0},onError:($)=>this.#X("vault roster refresh failed",$),logger:U1})}#K(){return(this.#$.connectionFile??Q8)()}#P(){return{connectionFile:this.#K(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>U1.debug("vault transport error",{errorClass:Z})}}#L(){return(this.#$.connectScoped?.()??i4(this.#P())).then((Z)=>{return this.#D=Z.insula!==void 0,Z})}#B(Z,$,X){if(this.#q.get(Z)===$)return;this.#q.set(Z,$),U1.info("vault background quota source changed",{routeId:Z,source:$,reason:X})}#C(){return this.#$.connectEnrollment?.()??u4(this.#P())}#X(Z,$){this.#J=V1($),U1.warn(Z,{host:this.host,error:this.#J})}#H(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=G8(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#H(),$=await d4(this.paths,this.name);if(Z===this.#H())return this.#M=$,this.#N=Z,$;return"unreadable"}enrolled(){return this.#N!==this.#H()||this.#M!=="local"}start(){if(this.#F||this.#Q)return;this.#F=!0;let Z=async()=>{try{await this.authority(),await this.#j(),await this.#Z.refreshInsulaQuota()}catch(X){if(!this.#Q)this.#X("vault roster refresh failed",X)}if(this.#Q)return;let $=this.#$.pollIntervalMs??5000;if($<=0)return;this.#z=setTimeout(()=>{this.#z=void 0,Z()},$),this.#z.unref?.()};Z()}#j(){return this.#G??=this.#Z.refresh().finally(()=>{this.#G=void 0,this.#Y.resolve()}),this.#G}firstRoster(){return this.#Y.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.#j()).catch((X)=>{this.#X("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let Z=this.#G;if(Z)await Z.catch(()=>{return});let $=await this.#j();return this.#J=void 0,$}catch(Z){return this.#X("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}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.#X("vault refused to serve an account",G);return}}async authorize(Z,$={}){try{return await this.#Z.authorize(Z,$.signal)}catch(X){this.#X("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.#X("vault failure report failed",X)}await this.refresh()}recordSnapshot(Z,$,X,J){let G=tZ($,(this.#$.now??Date.now)(),X);if(!G)return Promise.resolve();return this.#Z.recordQuota(Z,G,J).then(()=>{},(z)=>this.#X("vault quota write failed",z))}pollQuota(Z,$=!0){let X=this.#U.get(Z);if(X)return X;let J=this.#_(Z,$).finally(()=>{this.#U.delete(Z)});return this.#U.set(Z,J),J}async#_(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let z=(await a4(this.paths.rosterPath))?.rows.find((W)=>W.routeId===Z),Q=await this.#Z.cachedInsulaQuotaForRoute(Z);if(Q!==void 0&&z?.accountIdentity){let W=tZ(Q,Q.primary.checkedAt,!0);if(!W)return this.#B(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,z.accountIdentity,W))return this.#B(Z,"insula",null),{ok:!0};return this.#B(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}this.#B(Z,"fallback",this.#D===!1?"insula-not-configured":"no-insula-reading")}let X,J=this.#$.fetchImpl?.()??globalThis.fetch,G=await this.send(Z,async(z,Q)=>{try{let W=$?void 0:await this.#Z.cachedInsulaQuota(Q);if(W!==void 0){let U=tZ(W,W.primary.checkedAt,!0);if(!U)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,U,Q),new Response(null,{status:200})}let B=await jZ({accessToken:z,fetchImpl:J,now:this.#$.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:Z,logger:U1});return await this.recordSnapshot(Z,B,!0,Q),X=void 0,new Response(null,{status:200})}catch(W){X=V1(W);let B=W?.status;if(typeof B==="number")return new Response(null,{status:B});throw W}},{site:"quota"}).catch((z)=>{X=V1(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.#W.get(Z);if($)return $;let X=this.pollQuota(Z,!1).catch((J)=>{U1.warn("vault quota poll failed",{routeId:Z,error:V1(J)})}).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,X),X}async pollStale(Z){let $=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let G=j8(J.quota);if(G!==void 0&&$-G<Z)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async decline(Z){await this.#Z.decline(Z),U1.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),U1.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await l4(this.paths,this.name)}catch($){this.#X("vault enrollment state unreadable",$),Z={state:"blocked",proposedName:this.name,code:$ instanceof m4?$.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:Z,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#J?{lastError:this.#J}:{}}}async connectStep(){let Z=await this.#C().catch(($)=>{throw new a("vault-unreachable",`Could not reach the Claustrum vault (${this.#K()}): ${V1($)}. Is the vault running?`)});try{let $=new c4({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(U1.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#J=void 0,await this.refresh();return J}finally{Z.close()}}waitForApproval(Z={}){return this.#V??=(async()=>{let $=Z.sleep??((z)=>new Promise((Q)=>setTimeout(Q,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.#V=void 0}),this.#V}async disconnect(){await x4(this.paths.tokenPath,{force:!0}),await x4(this.paths.statePath,{force:!0}),await this.authority(),this.#J=void 0,U1.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())s4({mode:"custody",auth:Z,provider:"openai"})}close(){if(this.#Q=!0,this.#Y.resolve(),this.#z)clearTimeout(this.#z);this.#z=void 0,this.#Z.close()}}function j8(Z){if(!Z)return;let $=W1(Z).limits.map((X)=>X.checkedAt);return $.length>0?Math.max(...$):void 0}function $0(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 ${o4.category} --operation read`]}function e4(Z,$,X){let J=`${W8[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 c0(Z,$){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?`. ${oZ}`:"."}`}}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}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...$0(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 s0="/backend-api/wham/rate-limit-reset-credits",q8=`https://chatgpt.com${s0}`,z5=`${s0}/consume`,D8=`https://chatgpt.com${z5}`,F8=300000,M8=60000,N8=15000,K8=60000;function s1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class n extends Error{kind;cooldownUntil;constructor(Z,$,X){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=X}}class y1 extends Error{kind;status;constructor(Z,$,X){super($);this.name="ResetCreditError",this.kind=Z,this.status=X}}function Q5(Z,$,X){return{authorization:`Bearer ${Z}`,...X?{"chatgpt-account-id":X}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function J0(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function B5(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function G0(Z){if(!J0(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}:{},...W5(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function W5(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function X0(Z){return Z.kind==="http_error"&&W5(Z.status)}function U5(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function P8(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new n("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function V5(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function Y5(Z,$){return $-Z.startedAt<F8}function a1(Z,$){if(!N1($))return;return Z.reset?.[$]}function H5(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function j5(Z,$,X){if(!N1($))return;let J=H5(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 q5(Z,$){let X=B5(Z),J=G0(Z?.inFlight);if(V5(Z)&&!J)return{kind:"corrupt",beforeState:X};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:X,cooldownUntil:Z.cooldownUntil};if(J&&Y5(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 L8(Z,$){if(!N1($))return{kind:"fresh",beforeState:void 0};let X=await Z.loadAccountsFn(s1(Z));return q5(X?a1(X,$):void 0,Z.now())}async function C8(Z,$){let X;if(await Z.mutateAccountsFn((J)=>{let G=Z.now(),z=a1(J,$);if(X=q5(z,G),X.kind==="corrupt")j5(J,$,G);return J},s1(Z)),!X)throw Error("corrupt reset state mutation did not run");return X}async function _8(Z,$,X,J){if(!N1($))return{kind:"fresh",beforeState:void 0};let G;if(await Z.mutateAccountsFn((z)=>{let Q=Z.now(),W=a1(z,$),B=B5(W),U=G0(W?.inFlight);if(V5(W)&&!U)return j5(z,$,Q),G={kind:"corrupt",beforeState:B},z;if(W?.cooldownUntil!==void 0&&W.cooldownUntil>Q)return G={kind:"cooldown",beforeState:B,cooldownUntil:W.cooldownUntil},z;if(U&&Y5(U,Q))return G={kind:"claim",beforeState:B,claim:{inFlight:U,selectedCredit:{id:U.creditId}}},z;if(U&&!U5(U,J))return G={kind:"expired_unreconciled",beforeState:B,claim:{inFlight:U,selectedCredit:{id:U.creditId}}},z;let H=z0(X);if(!H)return G={kind:"fresh",beforeState:B},z;let V={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:Q,...J===void 0?{}:{chatgptAccountId:J}},j=H5(z);return j[$]={...W,inFlight:V},G={kind:"claim",beforeState:B,claim:{inFlight:V,selectedCredit:H}},z},s1(Z)),!G)throw Error("reset claim mutation did not run");return G}async function T8(Z,$,X,J,G){if(!N1($))return;if(!i0(J.kind))return O8(Z,$,X,J,G);await Z.mutateAccountsFn((z)=>{let Q=a1(z,$),W=G0(Q?.inFlight);if(!Q||!W||W.redeemRequestId!==X.redeemRequestId||W.creditId!==X.creditId)return z;let B=Z.now();if(delete Q.inFlight,Q.lastOutcome={code:J.kind,at:B},J.kind==="reset"||J.kind==="already_redeemed")Q.cooldownUntil=B+K8;else delete Q.cooldownUntil;return z},s1(Z));return}function Z5(Z,$){let X=G0(Z?.inFlight);return X&&X.redeemRequestId===$.redeemRequestId&&X.creditId===$.creditId?X:void 0}async function O8(Z,$,X,J,G){let z=X0(J)?J.status:void 0;if(!(X.chatgptAccountId===void 0&&G!==void 0)&&z!==void 0&&z===X.rejectedStatus){let B=await Z.loadAccountsFn(s1(Z));return Z5(B?a1(B,$):void 0,X)}let W;return await Z.mutateAccountsFn((B)=>{W=void 0;let U=a1(B,$),H=Z5(U,X);if(!U||!H)return B;let V={...H};if(V.chatgptAccountId===void 0&&G!==void 0)V.chatgptAccountId=G;if(z===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(X.unknownAnswers??0))V.rejectedStatus=z;return U.inFlight=V,W=V,B},s1(Z)),W}function qZ(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 a0(Z,$,X){if(!($||qZ(Z.primary,X)||qZ(Z.secondary,X)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function $5(Z,$){let X=Z[$];if(X===void 0||X===null)return;return typeof X==="string"?X:null}function A8(Z){if(!J0(Z))return;let $=$5(Z,"granted_at"),X=$5(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 n0(Z,$,X){let J;try{J=await Z(q8,{method:"GET",headers:Q5($,s0,X),signal:AbortSignal.timeout(N8)})}catch{throw new y1("http_error","reset credit list request failed")}if(!J.ok)throw new y1("http_error",`reset credit list request failed: ${J.status}`,J.status);let G;try{G=await J.json()}catch{throw new y1("invalid_response","reset credit list response was not valid JSON",J.status)}if(!J0(G))throw new y1("invalid_response","reset credit list response was not an object",J.status);return{credits:(Array.isArray(G.credits)?G.credits:[]).flatMap((Q)=>{let W=A8(Q);return W===void 0?[]:[W]}),availableCount:typeof G.available_count==="number"&&Number.isFinite(G.available_count)?G.available_count:void 0}}function z0(Z){return[...Z].filter(D5).sort(($,X)=>Date.parse($.expiresAt)-Date.parse(X.expiresAt))[0]}function D5(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function F5(Z){return Z.filter(D5).length}function i0(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function S8(Z,$,X,J,G){let z;try{z=await Z(D8,{method:"POST",headers:{...Q5($,z5,X),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:G,credit_id:J}),signal:AbortSignal.timeout(M8)})}catch(U){return{kind:"ambiguous",raw:U}}let Q;try{Q=await z.text()}catch(U){return z.ok?{kind:"ambiguous",raw:U}:{kind:"http_error",raw:U,status:z.status}}let W=Q,B=!1;try{W=JSON.parse(Q),B=!0}catch{}if(!z.ok)return{kind:"http_error",raw:W,status:z.status};if(!B||!J0(W)||!i0(W.code))return{kind:"ambiguous",raw:W};return{kind:W.code,raw:W}}function X5(Z){if(Z.kind==="cooldown")throw new n("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function J5(){throw new n("expired_unreconciled","the previous reset attempt outcome is unknown")}function G5(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 R8(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(X0(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 E8(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 M5(Z,$){if(!N1($.accountKey))throw new n("invalid_account_key","the reset account key is reserved");let X=await Z.resolveTarget($.accountKey);if(X.chatgptAccountId!==$.expectedChatgptAccountId)throw new n("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let J=X.chatgptAccountId,G=X.accountKey==="main"?void 0:J,z=await L8(Z,$.accountKey);if(z.kind==="corrupt"){if(z=await C8(Z,$.accountKey),z.kind==="corrupt")return G5(X,z.beforeState)}if(z.kind==="cooldown")X5(z);let Q;if(z.kind==="claim")Q=z.claim;else if(z.kind==="expired_unreconciled"&&($.retry||!U5(z.claim.inFlight,J))){if(!$.retry)J5();Q=z.claim}else{if($.retry)throw new n("retry_without_inflight","there is no active reset credit redemption to retry");let[j,D]=await Promise.all([Z.fetchUsage(X),n0(Z.fetchImpl,X.accessToken,G)]),Y=a0(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!Y.ok)throw new n("not_exhausted",Y.reason);if(!z0(D.credits))throw new n("no_eligible_credit","no eligible reset credit was returned");let q=await _8(Z,$.accountKey,D.credits,J);if(q.kind==="corrupt")return G5(X,q.beforeState);if(q.kind==="cooldown")X5(q);if(q.kind==="expired_unreconciled")J5();if(q.kind!=="claim")throw new n("no_eligible_credit","no eligible reset credit was available while claiming");Q=q.claim}P8(Q.inFlight,J);let W=await S8(Z.fetchImpl,X.accessToken,G,Q.inFlight.creditId,Q.inFlight.redeemRequestId),B,U=!1;try{B=await T8(Z,$.accountKey,Q.inFlight,W,J)}catch{U=!0}let H=U&&i0(W.kind),V=X0(W)&&!U&&B?.rejectedStatus!==void 0;return{target:X,selectedCredit:Q.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.":X0(W)&&!V?E8(U,B):R8(W),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function N5(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 K5(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 P5(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 r0(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 N5(Z.checks);for(let Q of K5($,J))X.print(Q);let G=J.findings.filter((Q)=>Q.repair);if(G.length===0){if(J.findings.length>0)X.print("No repairs are available.");return}let z=await P5(X,J);X.print(`Applied ${z.applied.length} of ${G.length} repair(s).`)}}}import{execFileSync as I8,spawn as b8}from"node:child_process";function C5(Z,$=process.platform,X=I8,J=b8){try{if($==="win32"){let G=`Start-Process '${Z.replaceAll("'","''")}'`,z=J("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}else X($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore",timeout:3000});return!0}catch{return!1}}function L5(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 Q0(Z,$){let X=new AbortController,J=await Z.begin({headless:!1,signal:X.signal});J.completion.catch(()=>{}),L5($,J);let G=!1;try{G=await(Z.openBrowser??C5)(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}),L5($,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 o0(Z){let $=Z.toString(),X=[];for(let J=0;J<$.length;){let G=$[J];if(G==="\x1B"){let z=$.slice(J,J+3),Q=z[1]==="["||z[1]==="O"?z[2]:void 0;if(Q&&"ABCD".includes(Q)){let B={A:"up",B:"down",C:"right",D:"left"}[Q];if(B)X.push(B);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 _5=`${String.fromCharCode(27)}\\[[0-9;]*m`,y8=new RegExp(_5,"g"),k8=new RegExp(`^${_5}`);function T5(Z){return Z.replace(y8,"")}function k1(Z,$){if($<=0)return"";if(T5(Z).length<=$)return Z;let X=$>=3?"...":".".repeat($),J=Math.max(0,$-X.length),G="",z=0,Q=0;while(z<Z.length&&Q<J){if(Z[z]==="\x1B"){let W=Z.slice(z).match(k8);if(W){G+=W[0],z+=W[0].length;continue}}G+=Z[z],z+=1,Q+=1}return G.includes("\x1B[")?`${G}${S.reset}${X}`:G+X}function t0(){return{input:process.stdin,output:process.stdout,signals:process}}function f1(Z){return Z.input.isTTY===!0}function e0(Z,$=""){Z.output.write(`${$}
4
+ `)}var f8=50;function h8(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function n1(Z,$,X){if(!f1(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,Q=0,W=null,B=!1,U=0,H=()=>{let V=G.columns??80,j=G.rows??24,D=U;if(X.clearScreen)G.write(S.clearScreen+S.moveTo(1,1));else if(D>0)G.write(S.up(D));let Y=0,q=(C)=>{G.write(`${S.clearLine}${C}
5
+ `),Y+=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(Q-Math.floor(L/2),Math.max(0,$.length-L))),_=$.slice(O,O+L);if(q(`${S.dim}┌ ${S.reset}${k1(X.message,Math.max(1,V-4))}`),X.subtitle)q(`${S.dim}│${S.reset}`),q(`${S.cyan}◆${S.reset} ${k1(X.subtitle,Math.max(1,V-4))}`),q("");for(let C of F)q(`${S.cyan}│${S.reset} ${k1(C,Math.max(1,V-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===Q,R=h8(A.color),h=R?`${T?"":S.dim}${R}${A.label}${S.reset}`:T?A.label:`${S.dim}${A.label}${S.reset}`;if(A.hint)h+=` ${S.dim}${A.hint}${S.reset}`;h=k1(h,Math.max(1,V-8)),q(T?`${S.cyan}│${S.reset} ${S.green}●${S.reset} ${h}`:`${S.cyan}│${S.reset} ${S.dim}○${S.reset} ${h}`)}let M=_.length<$.length?` (${O+1}-${O+_.length}/${$.length})`:"";q(`${S.cyan}│${S.reset} ${S.dim}${k1(`Up/Down to select | Enter: confirm | Esc: back${M}`,Math.max(1,V-6))}${S.reset}`),q(`${S.cyan}└${S.reset}`);for(let C=Y;C<D;C++)q("");U=Y};return new Promise((V)=>{let j=J.isRaw??!1,D=()=>{if(B)return;if(B=!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)},Y=(N)=>{D(),V(N)},q=()=>Y(null),F=(N)=>{for(let L of o0(N)){if(B)break;if(W)clearTimeout(W),W=null;switch(L){case"up":Q=(Q-1+$.length)%$.length,H();break;case"down":Q=(Q+1)%$.length,H();break;case"enter":Y($[Q]?.value??null);break;case"escape":Y(null);break;case"escape-start":W=setTimeout(()=>Y(null),f8);break;default:break}}};z?.once("SIGINT",q),z?.once("SIGTERM",q);try{J.setRawMode(!0)}catch{D(),V(null);return}J.resume(),G.write(S.hide),H(),J.on("data",F)})}async function Z3(Z,$,X=!1){if(!f1(Z))return!1;return await n1(Z,X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function O5(Z){let $=f1(Z);return{terminal:Z,interactive:$,print:(X)=>e0(Z,X),confirm:(X,J)=>Z3(Z,X,J),select:async(X,J)=>$&&X.length>0?n1(Z,X,J):null}}function v8(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 DZ(Z){let $=Z.terminal??t0(),X=O5($);if(!X.interactive)return v8(X,Z);if(Z.actions.length===0)return X.print("No actions are available."),{status:"cancelled"};let J=await n1($,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 S5="disabled from the auth menu",A5=8;async function Y1(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 g8(Z){let{rows:$}=await Y1(Z);return $.some((X)=>X.credential!==void 0)}function J3(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 x8(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,A5).map((J)=>`${J.id}: ${J3(J)}`),X=Z.rows.length-A5;if(X>0)$.push(`... and ${X} more`);return $}function m8(Z){return Z instanceof Error?Z.message:String(Z)}async function G3(Z,$,X){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((J)=>({label:J.id,value:J,hint:J3(J)})),{message:X})}function w8(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 R5(Z,$=Date.now()){let X=c1(Z.quota)?W1(Z.quota):void 0,J=B0(X,{now:$,form:"full"});return(J.length>0?J:[B1(X,{now:$})]).map((G)=>` ${G}`)}function E5(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 Q0(X,$),{rows:G}=await Y1(Z.store),z=(Z.newAccountId??w8)(J,G),Q=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(Q.outcome==="rotated")$.print(`That sign-in is already account ${Q.id}; its credential was updated.`);else if(Q.outcome==="added-disabled")$.print(`Added account ${Q.id}, disabled: another enabled account is the same provider account.`);else if(Q.outcome==="completed")$.print(`Finished adding account ${Q.id}.`);else $.print(`Added account ${Q.id}.`)}}}function I5(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 Y1(Z.store),G=await G3($,J,"Re-authenticate which account?");if(!G)return;let z=await Q0(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 Q=z.identity??G.identity;await Z.store.replace(G.id,z.credential,Q!==void 0?{identity:Q}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${G.id}.`)}}}function b5(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function y5(Z){return Z instanceof E&&Z.kind==="row-protected"?Z.message:void 0}function k5(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:X}=await Y1(Z.store),J=await G3($,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,b5(Z))}catch(G){let z=y5(G);if(z===void 0)throw G;$.print(`Account ${J.id} was kept: ${z}`);return}$.print(`Removed account ${J.id}.`)}}}function $3(Z){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run($){let{rows:X}=await Y1(Z.store),J=await G3($,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??S5,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 f5(Z){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run($){let X=await Y1(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}: ${J3(J)}`)}}}function X3(Z){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run($){let X=await Y1(Z.store);if(X.problem){$.print(X.problem);return}let J=new Map,G=Z.pollQuota;if(G)for(let Q of X.rows){if(Q.invalid||!Q.credential||Q.credentialEpoch===void 0){J.set(Q.id,"no usable credential");continue}try{let W=await G(Q);await Z.store.recordQuota(Q.id,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},W)}catch(W){J.set(Q.id,m8(W))}}let z=await Y1(Z.store);if(z.rows.length===0)$.print("No accounts yet.");for(let Q of z.rows){$.print(`${Q.id}:`);let W=J.get(Q.id);if(W)$.print(` quota check failed: ${W}`);for(let B of R5(Q,(Z.now??Date.now)()))$.print(B)}}}}function h5(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 Y1(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,b5(Z)),J.push(z.id)}catch(Q){let W=y5(Q);if(W===void 0)throw Q;G.push(`${z.id} (${W})`)}if($.print(`Deleted ${J.length} account(s).`),G.length>0)$.print(`Kept: ${G.join(", ")}.`)}}}async function z3(Z){return v5(Z,await Z.custody?.()===!0)}function v5(Z,$){let X=Z.doctor?.length?[r0({checks:Z.doctor})]:[],J=[...Z.extraActions??[]];if($)return[f5(Z),$3(Z),X3(Z),...X,...J];return[...Z.login?[E5(Z),I5(Z)]:[],k5(Z),$3(Z),X3(Z),...X,...J,h5(Z)]}async function u8(Z){let $=await Z.custody?.()===!0,X=v5(Z,$),[J,G]=await Promise.all([Y1(Z.store),Z.status?.()??[]]);return DZ({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...G,...x8(J)],actions:X,...Z.terminal?{terminal:Z.terminal}:{}})}function g5(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function x5(Z){return Z!==void 0}function p8(Z){return async($)=>{if(!x5($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),g5()}}function H1(Z){return Z.authority!=="local"}async function i(Z){return{authority:await Z.authority(),status:await Z.status(),identities:Z.identities(),routes:new Set(Z.routes().map(($)=>$.id))}}async function W0(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."),t4)})])}finally{clearTimeout($)}}function j1(Z){return Z.email||Z.label||Z.routeId}function m5(Z,$){let X=W1(c1(Z.quota)?Z.quota:void 0),J=B0(X,{now:$});return(J.length>0?J:[B1(X,{now:$})]).map((G)=>` ${G}`)}var FZ="Accounts are managed in the vault with ck. Disconnect to use local accounts.",i1="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function w5(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 l8(Z,$){let X=await W0($),J=await i($),{status:G}=J,z=H1(J)?void 0:await Z.store.read(),Q=await z3(Z),W=new Set(["check-quotas",...(Z.extraActions??[]).map((H)=>H.id)]),B=Q.filter((H)=>!H1(J)||W.has(H.id)).map((H)=>({...H,run:async(V)=>{if(!W.has(H.id)&&H1(await i($))){V.print(i1);return}await $.authority(),await H.run(V)}})),U=B.find((H)=>H.id==="check-quotas");if(U)U.run=async(H)=>{await W0($);let V=await i($),j=H1(V)?void 0:await Z.store.read();if(!j)H.print(FZ);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(w5(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 m5(N??q,(Z.now??Date.now)()))H.print(L)}let D=V.routes;for(let q of $.snapshot()?.rows??[]){if(H.print(`Vault ${j1(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 m5({quota:N?.quota},(Z.now??Date.now)()))H.print(L)}let Y=await $.status();if(Y.lastError)H.print(`Claustrum vault unreachable: ${Y.lastError}`)};return DZ({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 ${j1(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!z?[FZ]:z.status==="ready"?z.rows.map((H)=>w5(H)):["The local account store could not be read."]],actions:B,...Z.terminal?{terminal:Z.terminal}:{}})}function u5(Z){return m(Z)?{...Z}:{}}function U0(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:Q})=>{let W=await Z.apply({command:Z.command,sectionId:$,...J?{itemId:J}:{},actionId:X.id,values:z,confirmed:!0},Q);return{ok:W.ok,text:W.text,...W.code?{code:W.code}:{}}}}}function Q3(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 Q={...z,rows:z.rows.map((U)=>({...U,label:U.label??U.id}))};if(!$)return Q;let W=await i($);if(!H1(W))return Q;let B=[...W.status.accounts.map((U)=>({id:U.routeId,label:j1(U),type:"oauth",enabled:U.enabled,identity:U.accountIdentity,quota:U.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...z,rows:B}};if(J==="readSettings")return async()=>{let z=await X.readSettings();if(z.status==="error"||!$)return z;let Q=await i($),W=u5(z.settings.killswitch);if(!H1(Q)||!z.settings.killswitch)return z;let B=u5(W.accounts);for(let U of Q.status.accounts)B[U.routeId]=MZ({version:1,accounts:[],...z.settings},U.routeId);return{...z,settings:{...z.settings,killswitch:{...W,accounts:B}}}};let G=Reflect.get(X,J);return typeof G==="function"?G.bind(X):G}})}function B3(Z,$,X={}){let J=b1(Z),G=(U)=>b1({command:Z.command,title:Z.title,store:Q3(Z.store,$),accounts:Z.accounts,quota:Z.quota,limits:Z.limits,routing:{...Z.routing,formerMainId:U??""},...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.now?{now:Z.now}:{}}),z=async(U,H)=>{let V=await i($),j=H1(V),D=p5(V.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),Y=j?G(D):J,F=(await Y.open(H)).menu.sections.find((T)=>T.id===U);if(!F)throw new a("unavailable","The account menu is unavailable.");if(!j)return{lines:F.lines,items:F.items.map((T)=>({...T,actions:T.actions.map((R)=>U0(Y,U,R,T.id))})),actions:F.actions.map((T)=>U0(Y,U,T))};let N=new Map(V.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 h=[...(await i($)).routes].filter((b)=>!T||b===T);if(T&&h.length===0)throw new a("unavailable","This vault account cannot be checked right now.");for(let b of h){let f=await $.pollQuota(b);if(!f.ok)throw new a("quota-check-failed",`${b}: ${f.error??"vault unavailable"}`)}return`Checked quota for ${h.length} account${h.length===1?"":"s"}.`}});if(U==="quota"){let T=(R,h)=>B1(W1(R.quota,Z.quota?.scope),{now:L,form:h});return{lines:V.status.accounts.filter((R)=>!V.routes.has(R.routeId)).map((R)=>`${j1(R)} (${R.enabled?R.state:"disabled"}): ${T(R,"compact")}`),items:V.status.accounts.filter((R)=>V.routes.has(R.routeId)).map((R)=>({id:R.routeId,label:j1(R),group:"Accounts",status:T(R,"compact"),detail:T(R,"full"),actions:[O(R.routeId)]})),actions:V.routes.size>0?[O()]:[]}}let _=F.items.map((T)=>{let R=N.get(T.id),h=R&&U==="accounts"?`Vault · ${R.credentialType==="oauth"?"login":"API key"} · ${R.state} · ${R.enabled?"enabled":"declined"}`:T.detail;return{id:T.id,label:T.label,detail:h,group:T.group,status:R&&U==="accounts"?R.enabled?R.state:"disabled":T.status,...T.facts?{facts:T.facts}:{},actions:R&&U!=="limits"?[]:T.actions.map((b)=>U0(Y,U,b,T.id))}}),M=F.actions.filter((T)=>U==="limits"||U==="routing"&&T.id==="mode").map((T)=>U0(Y,U,T)),C=F.actions.find((T)=>T.id==="mode")?.knobs.find((T)=>T.id==="mode"),A=U==="routing"&&D===null&&C?.kind==="choice"&&(C.value==="main-first"||C.value==="fallback-first");return{lines:U==="accounts"?[`${V.status.accounts.length} vault account${V.status.accounts.length===1?"":"s"}`,`${V.routes.size} can route`,FZ]:[...F.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:_,actions:M}},Q=b1({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(U)=>z("accounts",U)},quota:{title:"Quota",build:(U)=>z("quota",U)},routing:{title:"Routing",build:(U)=>z("routing",U)},limits:{title:"Limits",build:(U)=>z("limits",U)}},extras:Z.extras?.map((U)=>U.id!=="reset"?U:{...U,build:async(H)=>{let V=await i($);if(H1(V))return{lines:[FZ]};return U.build(H)}})}),W=async()=>{if(!H1(await i($)))return{menu:J,error:void 0};let U=X.refresh===!1?void 0:await W0($);return{menu:Q,error:U}},B=async(U,H)=>{let V=await U.menu.open(H);if(U.error)V.menu.sections.find((D)=>D.id==="vault")?.lines.push(`Last error: ${U.error}`);return V};return{command:Z.command,open:async(U)=>B(await W(),U),apply:async(U,H)=>{let V=await W(),{menu:j}=V;if(j===Q&&(U.sectionId==="accounts"||U.sectionId==="routing"&&U.actionId==="order"||U.sectionId==="reset"||U.sectionId==="quota"&&(await i($)).routes.size===0||U.sectionId==="limits"&&U.itemId!==void 0&&!(await i($)).status.accounts.some((D)=>D.routeId===U.itemId)))return{...await B(V,H),ok:!1,code:"vault-local-action",text:i1};if(X.refuseApply)return{...await B(V,H),ok:!1,...X.refuseApply};return j.apply(U,H)}}}var KZ="openai",a5="OpenAI accounts",O1="main",n5="that account is already your main account, so it was not added again",o=J1("commands"),i5=new Set(["__proto__","constructor","prototype"]);function d8(Z,$){let X={version:1,accounts:[],killswitch:Z},J=m(Z.accounts)?Object.keys(Z.accounts):[],G={};for(let W of new Set([O1,...$,...J])){if(i5.has(W))continue;let B=MZ(X,W===O1?void 0:W);G[W]={primary:B.primary,secondary:B.secondary}}let z=MZ(X,void 0),Q={...Z};return delete Q.main,Q.accounts=G,Q.defaults={primary:z.primary,secondary:z.secondary},Q.schema=PZ,Q}function c8(Z,$){let X=m(Z.accounts)?{...Z.accounts}:{};for(let G of new Set([O1,...$])){if(i5.has(G)||Object.hasOwn(X,G))continue;X[G]={primary:NZ.primary,secondary:NZ.secondary}}let J=m(Z.defaults)?Z.defaults:{primary:NZ.primary,secondary:NZ.secondary};return{...Z,accounts:X,defaults:J,schema:PZ}}function l5(Z,$){let X=!1;if(m(Z.cachekeep))Z.cacheKeep={...Z.cachekeep,...m(Z.cacheKeep)?Z.cacheKeep:{}},delete Z.cachekeep,X=!0;let J=Z.killswitch;if(m(J)&&J.schema!==PZ)Z.killswitch=d8(J,$),X=!0;return X}async function d5(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((X)=>X.id):[]}function V3(Z){let $=async()=>{let J=await Z.readSettings();if(J.status==="error")return J;let G=structuredClone(J.settings);return l5(G,await d5(Z)),{...J,settings:G}},X=async(J,G)=>{let z=await d5(Z);return Z.updateSettings(async(Q)=>{l5(Q,z);let W=await J(Q)??Q;if(m(W.killswitch)&&W.killswitch.schema!==PZ)W.killswitch=c8(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 s8(Z,$){let X=(B,U)=>$.rowLocks?$.rowLocks(B):U,J=(B,U)=>{let H=X(B,U?.extraLocks);return{...U??{},...H?{extraLocks:H}:{}}},G=(B,U,H,V)=>Z.replace(B,U,H,J(B,V)),W={add:async(B,U)=>{let H=await Z.read(),j=(H.status==="ready"?H.rows:[]).filter((F)=>F.type==="oauth"&&!F.invalid),D=B.identity?j.find((F)=>F.identity===B.identity):void 0;if(D?.id===O1)throw new a("main-account",n5);let Y=D??j.find((F)=>F.id===B.id&&F.id!==O1);if(!Y||B.credential.type!=="oauth")return Z.add(B,U);let q=await G(Y.id,B.credential,B.identity!==void 0?{identity:B.identity}:{},U?.extraLocks?{extraLocks:U.extraLocks}:void 0);return o.info("account signed in again",{id:Y.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:G,enable:(B,U)=>Z.enable(B,J(B,U)),disable:(B,U,H)=>Z.disable(B,U,J(B,H)),remove:(B,U)=>Z.remove(B,J(B,U))};return new Proxy(Z,{get(B,U){if(Object.hasOwn(W,U))return W[U];let H=Reflect.get(B,U,B);return typeof H==="function"?H.bind(B):H}})}async function XG(Z,$,X){await V3(Z).updateSettings((J)=>{X(J);return},$?{extraLocks:$}:{})}var a8=["version","accounts","commonAuthPool"];function JG(Z,$){return async(X)=>{let J;if(await V3(Z).updateSettings((G)=>{let z={...G,version:1,accounts:[]},Q=X(z)??z;J=Q;let W={...Q};for(let B of a8)delete W[B];return W},$?{extraLocks:$}:{}),!J)throw Error("the settings write did not run");return J}}var n8="migration";function c5(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:KZ,title:a5,sections:[{id:n8,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 U3(X)}var i8=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function r8(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(i8.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function W3(Z,$,X){if(Array.isArray(Z))return Z.map((G,z)=>W3(G,`${$}[${z}]`,X));if(!m(Z))return Z;let J={};for(let[G,z]of Object.entries(Z)){if(r8(G)){X.push(`${$}.${G}`);continue}J[G]=W3(z,`${$}.${G}`,X)}return J}function U3(Z){let $=[],X=W3(Z,"menu",$);if($.length>0)o.warn("credential-shaped field stripped before RPC",{fields:$});return X}function o8(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 t8(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}),Q=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(B)=>{if($&&await $.authority()!=="local")throw new a("vault-local-action",i1);let U=await Z.mainIdentity?.();if(B.id===O1||B.accountId&&U&&B.accountId===U)throw o.warn("account add rejected (main identity)",{id:B.id}),new a("main-account",n5);return o.info("account added",{id:B.id}),o8(B)});return{status:"pending",message:Q,completion:W}}}}function GG(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),o.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 zG(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}`,e4(X.host,X.name,X.enrollment),...$0(X.name,X.enrollment),...J?[X.accounts.length===0?oZ:`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:j1(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?.(),`${j1(z)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(z.routeId),await Z.changed?.(),`${j1(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 Q=await $.connectStep();if(Q.state!=="pending"&&Q.state!=="busy")return await Z.changed?.(),c0($,Q);return $.waitForApproval(Z.wait).then(async(W)=>{await Z.changed?.();let B=c0($,W);z.notify(B.text,B.ok?"info":"warning")}).catch((W)=>{z.notify(`Connecting to the vault failed: ${W instanceof Error?W.message:String(W)}`,"error")}),{ok:!0,text:[...$0($.name,Q),"Waiting for the approval; you are told here when it lands."].join(`
18
+ `)}}}]}}}}async function s5(Z,$,X){if(!N1($))return r($,"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 Q=await o5($,Z);if(!Q.eligible)return r($,"not_eligible",t5(Q));J=Q.chatgptAccountId}if(!J)return r($,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");o.info("reset redemption decision",{accountKey:$,retry:X});let z=await M5({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:(Q)=>jZ({accessToken:Q.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:Q.chatgptAccountId}),hasActiveRateLimitMark:(Q)=>Z.quotaManager.isRateLimited(Q)},{accountKey:$,expectedChatgptAccountId:J,retry:X});return o.info("reset redemption outcome",{accountKey:$,code:z.outcome.kind}),e5(z,Z,J)}catch(G){let z=G9($,G,J);return o.info("reset redemption outcome",{accountKey:$,code:z.code}),z}}function QG(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===O1?"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 o5($,Z);return{ok:X.eligible,text:`${J9(X)}
19
+
20
+ ${t5(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 s5(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 s5(Z,$,!0);return{ok:X,text:J}}}]}))})}}var e8=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],Z9=["primary","secondary"];function BG(Z){let $=new Set(Z.unavailableSections),X=(B)=>({title:B,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...Z.extras??[]];if($.has("reset")){let B={id:"reset",...X("Reset credits")},U=J.findIndex((H)=>H.id==="reset");if(U<0)J.unshift(B);else J[U]=B}let G={command:KZ,title:a5,store:Q3(V3(s8(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:t8(Z.login,Z.vault)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:e8,formerMainId:O1},limits:{labels:Z9},...$.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?B3(G,Z.vault,{refresh:!Z.readOnly,...Z.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):b1(G),Q=Z.vault?B3(G,Z.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,W=(B)=>{let{sessionId:U}=B,H=B.notify.bind(B);return{...U!==void 0?{sessionId:U}:{},notify:H}};return{command:KZ,async open(B){let U=W(B),H=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(H&&!H.migrated)return{command:KZ,menu:c5(H.blockers)};let V=await z.open(U);return{...V,menu:U3(V.menu)}},async apply(B,U){let H=W(U),V=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(V&&!V.migrated)return{command:KZ,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:c5(V.blockers)};if(Z.readOnly&&Z.vault)return z.apply(B,H);if(Z.readOnly||Z.allowAction&&!Z.allowAction(B)||$.has(B.sectionId)){if(Q)return Q.apply(B,H);return{...await z.open(H),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let j=await z.apply(B,H);if(j.ok)await Z.afterApply?.();return{...j,menu:U3(j.menu)}}}}function r5(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((X)=>X!==void 0);return $.length>0?Math.max(...$):void 0}function $9(Z,$){let X=[Z.primary,Z.secondary].filter((G)=>G!==void 0),J=X.filter((G)=>qZ(G,$));return(J.length>0?J:X).sort((G,z)=>z.usedPercent-G.usedPercent)[0]?.resetsAt}function X9(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)=>!qZ(J,$))}async function o5(Z,$){let X;try{X=await $.resolveResetTarget(Z);let J=X.accountKey==="main"?void 0:X.chatgptAccountId,[G,z]=await Promise.all([jZ({accessToken:X.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:X.chatgptAccountId}),n0($.fetchImpl,X.accessToken,J)]),Q=z0(z.credits),W=F5(z.credits),B=z.availableCount??G.resetCreditsAvailable??(W>0?W:void 0),U=G.resetCreditsApplicable,H=a0(G,$.quotaManager.isRateLimited(Z),$.now()),V;if(!X.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!H.ok)V=H.reason;else if(!Q)V="no eligible credit";return{accountKey:X.accountKey,label:X.label,chatgptAccountId:X.chatgptAccountId,usedPercent:r5(G),resetTime:$9(G,$.now()),availableCount:B,applicableAvailableCount:U,eligible:V===void 0,reason:V,selectedCreditId:Q?.id,selectedCreditExpiresAt:Q?.expiresAt}}catch(J){if(J?.status===401)await X?.onAuthFailure?.(401);return o.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 J9(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 t5(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 r(Z,$,X,J={}){if(Object.keys(J).length>0)o.debug("reset step details",{accountKey:Z,code:$,...J});return{ok:$==="reset"||$==="already_redeemed",code:$,text:X}}function G9(Z,$,X){if($ instanceof n){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 r(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 r(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 y1)return r(Z,$.kind,`## Reset credit
30
+
31
+ No redemption was attempted: reset credit availability could not be loaded.
32
+
33
+ Code: \`${$.kind}\``);return o.warn("reset command failed before a known result",{accountKey:Z,error:$?.message??String($)}),r(Z,"error",`## Reset credit
34
+
35
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function e5(Z,$,X){let{accountKey:J}=Z.target,G=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return r(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 Q={account:J,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await $.refreshResetTargetQuota(J)}catch(D){Q.error=D?.message??String(D)}let W=!Q.ok&&Q.error!==void 0;if(W)o.warn("reset quota re-check failed",{accountKey:J,error:Q.error});let B=J==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(J),U=Q.ok&&X9(B?.quota,$.now()),H=B?.quota.resetCreditsApplicable,V=U?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${G}\`).`,j=W?`
40
+
41
+ quota re-check failed — see log.`:"";return r(J,G,`## Reset credit result
42
+
43
+ Account: **${Z.target.label}** (\`${J}\`)
44
+
45
+ Code: \`${G}\`
46
+
47
+ ${V}${j}${H===void 0?"":`
48
+
49
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:U,afterUsedPercent:r5(B?.quota??{}),remainingCredits:H})}if(G==="ambiguous_local")return r(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 Q=Z.refused?' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.':"";return r(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.${Q}`,{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 r(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 Y3=J1("quota"),Z6="the account holds a tombstone from the removed vault custody, not a credential";function z9(Z){return Z?.status===401}async function qG(Z,$={}){let X=Z.whamFn;if(!X)throw Error("whamFn is required for refreshAllQuota");let J=[],G=Z.logger??Y3,z=(Y)=>{J.push(Y);let q={pid:process.pid,accountId:Y.account,status:Y.ok?"ok":"error",...Y.error?{error:Y.error}:{}};if(Y.ok)G.debug("quota refresh succeeded",q);else G.warn("quota refresh failed",q)},Q=Z.skipFresherThanMs,W=!1,B;if(Q!==void 0)try{B=await Z.readSidebarState()}catch{}let U=new Map(B?.fallbacks.map((Y)=>[Y.id,Y])??[]),H=(...Y)=>Q!==void 0&&Y.some((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=Z.now()&&Z.now()-q<Q),V=await Z.loadAccounts(Z.paths).catch(()=>{return}),j=V?.mainAccountId??Z.storageMainAccountId,D;if(!$.accountKey||$.accountKey==="main")try{let Y=await Z.getAuth();if(G6(Y)){if(D=z6(V),!D)z({account:"main",ok:!1,error:LZ(Y)?Z6:"main account row is missing from the account pool"})}else if(Y.type==="oauth"){let q=B&&j!==void 0&&B.main.mainAccountId===j?B.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(!Y.access||(Y.expires??0)<Z.now()){let N=await Z.refreshMainWithLease();Y={...Y,access:N.access,expires:N.expires}}if(Y.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())z({account:"main",ok:!0});else{let N=await X({accessToken:Y.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:j,accountKey:"main"});Z.quotaManager.setMain(Y.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(Y){z({account:"main",ok:!1,error:V1(Y)})}if(V)for(let Y of V.accounts){let q=D!==void 0&&Y===D;if(!q&&$.accountKey&&($.accountKey==="main"||Y.id!==$.accountKey))continue;if(!q&&Z.isOAuthAccountFn(Y)&&J6(V,Y)){if($.accountKey)z({account:Y.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let F=q?Y.accountId??j:void 0,N=(L,O,_)=>{if(q)Z.quotaManager.setMain(O,L,F,!0);else Z.quotaManager.setFallback(Y.id,L,O,!0,_)};if(Y.enabled===!1||!Z.isOAuthAccountFn(Y)){if($.accountKey)z({account:Y.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let L=U.get(Y.id),O=Y.accountId,_=q?B&&F!==void 0&&B.main.mainAccountId===F?B.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(Y.id,O)?.checkedAt,_?.primary?.checkedAt,_?.secondary?.checkedAt,_?.checkedAt)){z({account:Y.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(Y.id,Y.access))){z({account:Y.id,ok:!0});continue}let M=Y.lastRefreshError;if($6(M,Y.refresh,Z.now())){z({account:Y.id,ok:!1,error:X6(M,Z.now()),permanent:!0});continue}if(LZ(Y)){z({account:Y.id,ok:!1,error:Z6});continue}let C;try{C=q?await Z.fallbackManager.refreshAccount(Y,V,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(Y,V)}catch(T){Y3.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:Y.id,error:V1(T)}),C=Y}if(!C.access||(C.expires??0)<Z.now()){z({account:Y.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:Y.id})}catch(T){if(!z9(T))throw T;if(Y3.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:Y.id}),C=await Z.fallbackManager.refreshAccount(Y,V,q?{force:!0,asPoolMain:!0}:{force:!0}),!C.access){z({account:Y.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:Y.id})}N({quota:A,refreshAfter:Z.now()+300000,checkedAt:Z.now()},C.access,C.accountId),W=!0,z({account:Y.id,ok:!0})}catch(L){z({account:Y.id,ok:!1,error:V1(L)})}}if($.accountKey&&$.accountKey!=="main"&&!J.some((Y)=>Y.account===$.accountKey))J.push({account:$.accountKey,ok:!1,error:"account not found"});if(Q===void 0||W){let Y=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,Y)}return J}import{types as Q9}from"node:util";var B9=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,W9=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function V6(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 U9(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 B=0;B<X.length;B++){let U=X[B]??"";if(!/\s/.test(U))z.push(B)}let Q=[],W=0;for(let B=G.indexOf(J);B>=0;B=G.indexOf(J,B+J.length)){let U=z[B]??W,H=(z[B+J.length-1]??U)+1;Q.push(X.slice(W,U),"[credential]"),W=H}return Q.length?Q.join("")+X.slice(W):X}function Q6(Z,$){let X=U9(Z,$);return U6(X).replaceAll("***REDACTED***","[credential]")}function r1(Z,$){let X=Q6(Z,$),J=V6(X),G=Q6(J,$);return G===J?X:G}function B6(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 Q=$[4]??"0",W=Q.startsWith("-")||Q.startsWith("+")?1:0;while(Q[W]==="0")W++;let B=Q.slice(W)||"0";if(B.length>16)return;let U=BigInt((Q.startsWith("-")?"-":"")+B)-BigInt(X.length)+BigInt(J.length-z);return`${$[1]}${J.slice(G,z)}e${U}`}function Y6(Z,$){let X=$?B6($):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&&B6(J)===X||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===$)?'"[credential]"':J;let G=V6(J.slice(1,-1)),z=r1(G,$);return z===G?J:JSON.stringify(z)})}function j3(Z,$){let X=Y6(Z,$);try{return JSON.parse(Z),X}catch{return r1(X,$)}}var V9=16384,Y9=65536,H9=[/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 j9(Z){try{let $=g(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let X=0,J,G=!0,z=!1,Q;for(let W of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let B=W[0];if(B==="{"||B==="["){X++;continue}if(B==="}"||B==="]"){X--;continue}if(X!==1)continue;if(B===","){G=!0,z=!1,J=void 0;continue}if(B===":"){z=!0;continue}if(G&&B.startsWith('"')){J=JSON.parse(B),G=!1;continue}if(z&&J==="request_id"&&!B.startsWith('"'))Q=B;z=!1}return Q}catch{return}}function q9(Z,$){let X=j3(Z,$);if(Buffer.byteLength(X,"utf8")<=Y9)return X;let J=H9.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(g(z,"type")==="error")G.type="error";let Q=g(z,"error"),W={};for(let U of["code","type"]){let H=g(Q,U);if(typeof H==="string")W[U]=H.slice(0,256)}if(Object.keys(W).length)G.error=W;let B={};for(let U of["workspace","limitName"]){let H=g(g(z,"metadata"),U);if(typeof H==="string")B[U]=H.slice(0,256)}if(Object.keys(B).length)G.metadata=B}catch{}return JSON.stringify(G)}function V0(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let X=0;$&&X<16;X++){if(Q9.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function g(Z,$){if(!V0(Z))return;let X=Object.getOwnPropertyDescriptor(Z,$);return X&&"value"in X?X.value:void 0}function CZ(Z,$){return r1(Z,$).slice(0,V9)}function o1(Z,$){let X=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!X)throw Error(`Missing native ${$} accessor`);return X}var D9=o1(DOMException.prototype,"message"),F9=o1(DOMException.prototype,"name");function H3(Z,$){let X=g(Z,"message"),J=g(Z,"name");if(V0(Z)&&Z instanceof DOMException)try{X=D9.call(Z),J=F9.call(Z)}catch{}let G=Error(CZ(typeof X==="string"?X:typeof Z==="string"?Z:"Provider request failed",$));for(let V of Object.getOwnPropertyNames(G))if(V!=="message")Reflect.deleteProperty(G,V);Object.defineProperty(G,"name",{value:typeof J==="string"?CZ(J,$):"Error",configurable:!0,writable:!0});let z=(V,j,D)=>{let Y=g(V,D);if(typeof Y==="string"||typeof Y==="number"&&Number.isFinite(Y)||typeof Y==="boolean")Object.defineProperty(j,D,{value:typeof Y==="string"?CZ(Y,$):Y,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=g(Z,V);if(typeof j==="number"&&Number.isFinite(j))z(Z,G,V)}for(let V of["code","type","isRetryable"])z(Z,G,V);for(let V of["error","data"]){let j=g(Z,V),D=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])z(j,D,q);let Y=g(j,"error");if(V0(Y)){let q=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])z(Y,q,F);D.error=q}if(Object.keys(D).length)Object.defineProperty(G,V,{value:D,enumerable:!0})}let Q=g(Z,"responseHeaders");if(Q&&typeof Q==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let D=g(Q,j);if(typeof D==="string")V[j]=CZ(D,$)}Object.defineProperty(G,"responseHeaders",{value:V,enumerable:!0})}let W=g(Z,"responseBody");if(typeof W==="string")Object.defineProperty(G,"responseBody",{value:q9(W,$),enumerable:!0});let B=g(Z,"request_id"),U=g(Q,"x-request-id"),H=typeof B==="string"?B:typeof U==="string"?U:typeof W==="string"?j9(j3(W,$)):void 0;if(typeof H==="string")Object.defineProperty(G,"request_id",{value:CZ(H,$),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(g(Z,j)===!0)Object.defineProperty(G,j,{value:!0})}return G}function M9(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!B9.test(Z)&&!W9.test(Z)))return Z;let X;try{X=JSON.parse(Z)}catch{return Z}if(X?.type==="error"||X?.error||X?.response?.error)return Y6(Z,$);return Z}var N9=o1(Response.prototype,"status"),K9=o1(Response.prototype,"statusText"),P9=o1(Response.prototype,"headers"),L9=o1(Response.prototype,"body"),C9=Response.prototype.text,W6=Headers.prototype.entries;async function NG(Z,$,X="http"){try{let D=function(Y){let q=j&&Y.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+Y.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(F,N)=>F.slice(0,F.length-N.length)+M9(N,$))};if(!V0(Z))throw Error("Invalid provider response");let J=N9.call(Z),G=P9.call(Z),z=L9.call(Z),Q=new Headers;for(let[Y,q]of W6.call(G))Q.append(Y,q);let W={status:J,statusText:r1(K9.call(Z),$),headers:Q};if(J<200||J>299){for(let[q,F]of W6.call(G)){if(r1(q,$?.toLowerCase())!==q){W.headers.delete(q);continue}try{W.headers.set(q,r1(F,$))}catch{W.headers.delete(q)}}W.headers.delete("content-length");let Y=await C9.call(Z);return new Response(j3(Y,$),W)}if(!z||X==="http")return Z;W.headers.delete("content-length");let B=ReadableStream.prototype.getReader.call(z),U=new TextDecoder("utf-8",{ignoreBOM:!0}),H=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(Y){try{for(;;){let q=await B.read();V+=U.decode(q.value,{stream:!q.done});let F=!1;for(;;){let N=/\r?\n\r?\n/.exec(V);if(!N)break;let L=N.index+N[0].length;Y.enqueue(H.encode(D(V.slice(0,L)))),V=V.slice(L),F=!0}if(q.done){if(V)Y.enqueue(H.encode(D(V)));Y.close();return}if(F)return}}catch(q){Y.error(H3(q,$))}},async cancel(Y){try{await B.cancel(Y)}catch(q){throw H3(q,$)}finally{B.releaseLock()}}}),W)}catch(J){throw H3(J,$)}}function LG(Z,$,X){let J=Z.get($.sessionId),G=new Set($.validPinnedAccountIds);if(J&&!$.excludeAccountIds.includes(J.accountId)&&H6(J,G,$.wireAccountIdByAccount[J.accountId])){if($.persist){let B=$.quotaCheckedAtByAccount[J.accountId];X($.sessionId,{accountId:J.accountId,inputBytes:$.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...B!==void 0?{quotaCheckedAt:B}:{}})}return{accountId:J.accountId}}let z=new Map(Object.entries($.quotaCheckedAtByAccount)),Q=j6(Z,z,$.sessionId),W=$.select(Q);if(!W)return;if($.persist){let B=$.wireAccountIdByAccount[W.accountId];X($.sessionId,{accountId:W.accountId,inputBytes:$.requestBytes,...B!==void 0?{wireIdentity:B}:{},...W.quotaCheckedAt!==void 0?{quotaCheckedAt:W.quotaCheckedAt}:{}})}return{accountId:W.accountId}}import{statSync as _9}from"node:fs";var M6=30000,T9=8,O9=1800000;function N6(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function AG(Z){try{let $=_9(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function SG(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function A9(Z,$){try{return q6(Z,$)}catch{return Z}}function RG(Z,$,X){let J=N6($);Z.set(J,[...Z.get(J)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:X}].slice(-T9))}function EG(Z,$,X){let J=Z;for(let G of $.get(N6(Z))??[]){if(!(X-G.observation.checkedAt<=O9)||G.credentialEpoch!==Z.credentialEpoch||G.identity!==Z.identity)continue;J={...J,quota:A9(J.quota,G.observation)}}return J}function IG(Z,$,X,J){let G=_Z(Z);if(typeof $?.status==="number"||D6($)){let Q=F6({error:$,now:X,refreshToken:Z,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:Q.nextRetryAt,tokenHash:G,retryCount:Q.retryCount}}return{nextRetryAt:X+M6,tokenHash:G,retryCount:J?.tokenHash===G?J.retryCount:0}}function bG(Z,$,X,J){let G=new Map;for(let z of Z){if(J(z,X))continue;let Q=$.get(z.id);G.set(z.id,Q&&Q.nextRetryAt>X?Q.nextRetryAt:X+M6)}return G}import{realpathSync as K6}from"node:fs";import{homedir as S9}from"node:os";import{basename as R9,dirname as E9,join as H0,resolve as _6}from"node:path";function I9(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return H0(process.env.XDG_CONFIG_HOME||H0(S9(),".config"),"opencode")}function T6(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||H0(I9(),L6)}function Y0(Z,$){let X=_6(Z);return $==="win32"||$==="darwin"?X.toLowerCase():X}function P6(Z){try{return K6.native(Z)}catch{try{return H0(K6.native(E9(Z)),R9(Z))}catch{return}}}function b9(Z,$,X=process.platform){if(Y0(Z,X)===Y0($,X))return!0;let J=P6(Z),G=P6($);return J!==void 0&&G!==void 0&&Y0(J,X)===Y0(G,X)}function y9(Z=T6()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(b9(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${_6(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}return C6(Z)}function Wz(Z=T6()){return{configPath:Z,statePath:y9(Z)}}import{createHash as w9}from"node:crypto";import{readFileSync as u9}from"node:fs";import{readFile as p9}from"node:fs/promises";import{resolve as l9}from"node:path";import{createHash as k9}from"node:crypto";import{readFile as f9}from"node:fs/promises";import{homedir as h9}from"node:os";import{join as O6,resolve as v9}from"node:path";var g9="openai",A6=250,OZ="main-refresh";function D3(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 k9("sha256").update(J($)).update($).update(J(X)).update(X).digest("hex")}function y6(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 k6(Z){let $=y6(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function S6(Z){if(h1(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=y6(Z);if(!$)return{kind:"indeterminate"};return LZ($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function R6(Z){return Z.auth.get({path:{id:g9}})}async function E6(Z){return Object.keys(await Z.auth.all()).length>0}async function f6(Z){let $=await R6(Z.client);if($!==void 0)return S6($);let X=await E6(Z.client),J=Z.now();if(await Z.sleep(A6),Z.now()-J<A6)return{kind:"indeterminate"};let G=await R6(Z.client);if(G!==void 0)return S6(G);let z=await E6(Z.client);return X&&z?{kind:"slot-absent"}:{kind:"indeterminate"}}function j0(Z=process.env,$=h9()){let X=Z.XDG_DATA_HOME||O6($,".local","share");return O6(X,"opencode","auth.json")}function h1(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var I6=(Z)=>Z===void 0||typeof Z==="string";function x9(Z){if(!h1(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&&I6(Z.accountId)&&I6(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||h1(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 q3(Z,$=process.env){let X=$.OPENCODE_AUTH_CONTENT;if(X)try{let G=JSON.parse(X);return h1(G)?G:{}}catch{}let J;try{J=JSON.parse(await f9(Z,"utf8"))}catch{return{}}if(!h1(J))return{};return Object.fromEntries(Object.entries(J).filter(([,G])=>x9(G)))}function b6(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class q0 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function m9(Z){let $=Z.env??process.env,X=Z.path??j0($),J=new Map;return{path:v9(X),migrationDisabledReason:()=>b6($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(G){let z=(await q3(X,$))[G.path.id];return J.set(G.path.id,JSON.stringify(z)),z},async all(){return q3(X,$)},async set(G){if(b6($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let z=(await q3(X,$))[G.path.id];if(TZ(G.body)&&(!J.has(G.path.id)||J.get(G.path.id)!==JSON.stringify(z)))throw new q0;let Q=await Z.set(G);if(h1(Q)&&"error"in Q&&Q.error!==void 0)throw Error(`OpenCode refused the write of its ${G.path.id} login: ${JSON.stringify(Q.error)}`);return Q}}}function Fz(Z,$={}){let X=h1(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:m9({...$,set:(G)=>J.call(X,G)})}}var t1="openai",d9="common-auth-placeholder:v1:openai",AZ=Object.freeze({type:"oauth",access:"",refresh:d9,expires:0});function TZ(Z){if(!t(Z))return!1;return Z.type===AZ.type&&Z.access===AZ.access&&Z.refresh===AZ.refresh&&Z.expires===AZ.expires}var D0="openaiAuthPool",c9=120000,l6="pool-migration",s9="slot-transfer-origin-unknown",a9="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.",P0=Object.freeze({mainRefreshTtlMs:c9,fallbackTtlMs:u6,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function F0(Z,$,X){return Z.kind==="placeholder"&&!$&&!X.pending}class SZ extends Error{constructor(Z){super(`timed out waiting for the legacy ${Z} lock`);this.name="LegacyLockContention"}}function t(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function n9(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??J1("pool-migration"),...Z.vaultServes?{vaultServes:Z.vaultServes}:{},locks:{...P0,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:VZ({provider:t1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:N0,now:$,...Z.store}),onStep:async(X)=>{await Z.onStep?.(X)}}}async function ZZ(Z){let $;try{$=await p9(Z,"utf8")}catch(J){if(J.code==="ENOENT")return{};throw J}let X=JSON.parse($);if(!t(X))throw Error("config root is not an object");return X}async function RZ(Z,$,X,J){let G=performance.now();for(;;){let z=await S1({name:$,path:X,ttlMs:J,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(z)return z;if(performance.now()-G>=Z.locks.timeoutMs)throw new SZ($);await Z.sleep(Z.locks.retryMs)}}async function Rz(Z,$,X={}){let J={...P0,...X},G=performance.now();for(;;){let z=await S1({name:OZ,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 SZ(OZ);await new Promise((Q)=>setTimeout(Q,J.retryMs))}}async function EZ(Z,$){let X=Z.locks.saveTtlMs,J=await RZ(Z,"save",Z.paths.configPath,X);try{let G=await RZ(Z,"save",Z.paths.statePath,X);try{let z=await ZZ(Z.paths.configPath);if(!await $(z))return;await I1(Z.paths.configPath,z,{beforeRename:async()=>{await J.assertOwned(),await G.assertOwned()}})}finally{await G.release().catch(()=>{})}}finally{await J.release().catch(()=>{})}}function i9(Z){if(!t(Z))return;let{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:G}=Z,{credentialFingerprint:z,carryLegacyMain:Q,recordedAt:W,identity:B}=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 B==="string"&&B?{identity:B}:{},carryLegacyMain:Q===!0,recordedAt:typeof W==="number"?W:0}}function d6(Z,$){if(!t(Z)||!$)return!1;return G1(Z).pending?.credentialFingerprint===Z1({type:"oauth",refresh:$})}function Ez(Z,$){let X;try{X=JSON.parse(u9(Z,"utf8"))}catch{return!1}return d6(X,$)}class r9 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var o9=600000;async function Iz(Z,$,X={}){let J=X.now??Date.now,G=(B)=>{let U=G1(B).pending;return U&&d6(B,$)&&J()-U.recordedAt>=o9?U:void 0},z=G(await ZZ(Z.configPath));if(!z)return!1;let Q={...P0,...X.legacyLocks},W=await S1({name:l6,path:Z.configPath,ttlMs:Q.mainRefreshTtlMs});if(!W)return!1;try{let B=await ZZ(Z.configPath),U=G1(B).migratedAt!==void 0,H=await VZ({provider:t1,configPath:Z.configPath,statePath:Z.statePath,quota:N0,now:J}).read();if(U&&H.status!=="ready")return!1;let V;if(H.status==="ready"){let D=H.rows.find((q)=>q.id===z.rowId&&!q.invalid),Y=D?.fingerprint??null;if(U&&D&&Y===z.credentialFingerprint)return!1;if(D&&Y!==z.credentialFingerprint&&Y!==z.rowFingerprint)V=X.slotAccess!==void 0?D3({type:"oauth",access:X.slotAccess,refresh:$}):z.slotFingerprint}let j=!1;if(await EZ({paths:Z,locks:Q,sleep:(D)=>new Promise((Y)=>setTimeout(Y,D))},(D)=>{let Y=G1(D),q=G(D);if(!q||q.recordedAt!==z.recordedAt)return!1;let{pending:F,...N}=Y;return L0(D,V!==void 0?{...N,declinedSlotFingerprint:V}:N),j=!0,!0}),j)(X.log??J1("pool-migration")).warn(V!==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 G1(Z){let $=Z[D0];if(!t($))return{};let X=i9($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...X?{pending:X}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function L0(Z,$){let J={...t(Z[D0])?Z[D0]:{}};for(let G of["migratedAt","pending","declinedSlotFingerprint"])delete J[G];Object.assign(J,$),Z[D0]=J}function t9(Z){let $=Z?eZ(Z):void 0;return $?Z0($):void 0}function e9(Z){let $=D3({type:"oauth",...Z}),X=t9(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:Z1({type:"oauth",refresh:Z.refresh}),...X?{identity:X}:{}}}function c6(Z){if(TZ(Z))return{kind:"placeholder",...t(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=k6(Z);if(!$?.refresh.trim())return{kind:"empty"};return e9($)}async function IZ(Z){let $=await f6({client:{auth:{get:(X)=>Z.slot.get(X),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return c6($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function bz(Z,$){if(!TZ($))return!1;let X=await ZZ(Z.configPath),J=await VZ({provider:t1,configPath:Z.configPath,statePath:Z.statePath,quota:N0}).read();if(J.status==="error")return!1;let G=J.status==="ready"?J.rows.some((z)=>z.id==="main"):J.roster.some((z)=>t(z)&&z.id==="main");return F0({kind:"placeholder"},G,G1(X))}async function Z$(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let X=await IZ(Z);if(X.kind!=="real")return X;if(!await s6(Z,X.credential.refresh))return X;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function s6(Z,$){let X=await K0(Z.paths),J=X?.refresh?.mainRefreshLeaseUntil;return Boolean(J&&J>Z.now()&&X?.refresh?.mainRefreshLeaseTokenHash===_Z($))}function $$(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function X$(Z,$,X,J,G){let z=X.identity?{identity:X.identity}:{},Q=$.find((H)=>!H.invalid&&H.fingerprint===X.credentialFingerprint);if(Q)return{rowId:Q.id,operation:"rotate",rowFingerprint:Q.fingerprint??null,...z,carryLegacyMain:Z==="migrate"&&Q.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((V)=>!V.invalid&&V.type==="oauth"&&V.enabled&&V.identity===X.identity);if(H)return{rowId:H.id,operation:"replace",rowFingerprint:H.fingerprint??null,...z,carryLegacyMain:Z==="migrate"&&H.id==="main"}}let B=new Set($.map((H)=>H.id));return{rowId:J??(X.identity&&$$(X.identity)&&!B.has(X.identity)?X.identity:G()),operation:"add",rowFingerprint:null,...z,carryLegacyMain:!1}}function J$(Z,$,X,J,G,z,Q){let W=$.pending;if(W){let B=X.find((V)=>V.id===W.rowId&&!V.invalid),U=B?.fingerprint??null,H=J.kind==="real"&&J.fingerprint===W.slotFingerprint;if(B&&U===W.credentialFingerprint)return{kind:"finish",record:W};if((B||W.rowFingerprint===null)&&U===W.rowFingerprint)return H&&J.kind==="real"?{kind:"transfer",record:W,credential:J.credential,fresh:!1}:{kind:"drop-record"};if(!B)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:{...X$(Z,X,J,G,Q),slotFingerprint:J.fingerprint,credentialFingerprint:J.credentialFingerprint,recordedAt:z},credential:J.credential,fresh:!0}}async function G$(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:M0(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 Q=await Z.store.read(),W=Q.status==="ready"?Q.rows.find((B)=>B.id===$.rowId):void 0;await Z.store.rotate($.rowId,J,W?.identity===void 0?G:{},z)}}async function z$(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 Q$(Z,$){let X=[],J=[["primary",Z.primary],["secondary",Z.secondary]],G=0;for(let[W,B]of J){if(!B||!Number.isFinite(B.checkedAt)||!Number.isFinite(B.usedPercent))continue;G=Math.max(G,B.checkedAt),X.push({checkedAt:B.checkedAt,readings:[{label:W,usedPercent:B.usedPercent,...typeof B.resetsAt==="string"?{resetsAt:B.resetsAt}:{},...Number.isFinite(B.windowMinutes)?{windowMinutes:B.windowMinutes}:{}}]})}let z=$??(G||void 0),Q=Z.spendControl;if(z!==void 0&&Q)X.push({checkedAt:z,budget:{kind:"reading",reached:Q.reached,remainingPercent:Q.remainingPercent,usedPercent:Q.usedPercent,limit:Q.limit,used:Q.used,remaining:Q.remaining,...Q.resetsAt!==void 0?{resetsAt:Q.resetsAt}:{},...Q.unit!==void 0?{unit:Q.unit}:{}}});else if(z!==void 0&&Z.spendControlCleared)X.push({checkedAt:z,budget:{kind:"cleared"}});return X.sort((W,B)=>W.checkedAt-B.checkedAt)}async function B$(Z,$){let X=await K0(Z.paths);if(!X)return;let J=X.quota?.mainQuotaToken,G=$.credential?.type==="oauth"?$.credential.access:void 0,Q=!J||G!==void 0&&J===x6(G)?X.quota?.mainQuota:void 0;if(Q&&$.credentialEpoch!==void 0){let H={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let V of Q$(Q,X.quota?.mainQuotaCheckedAt))try{await Z.store.recordQuota($.id,H,V)}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,B=X.accounts.find((H)=>H.id===$.id);if(!B||!m6(B)||B.corrupt)return;if(!W&&!Q)return;let U={...X,accounts:[{...B,...B.lastRefreshError||!W?{}:{lastRefreshError:W},...B.quota||!Q?{}:{quota:Q}}]};try{await w6(U,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 e1(Z,$,X={}){await EZ(Z,(J)=>{let G=G1(J);if(delete J.mainAccountId,$==="migrate"&&G.migratedAt===void 0)W$(J);return L0(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 W$(Z){let $=Z.routing;if($===void 0)Z.routing={mode:"main-first"};else if(t($)&&$.mode===void 0)Z.routing={...$,mode:"main-first"}}async function M3(Z){await EZ(Z,($)=>{let X=G1($);if(!X.pending)return!1;let{pending:J,...G}=X;return L0($,G),!0})}async function U$(Z,$){await EZ(Z,(X)=>{let J=G1(X);if($.identity)X.mainAccountId=$.identity;return L0(X,{...J,pending:$}),!0})}async function V$(Z,$,X,J){let G=await RZ(Z,OZ,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await Y$(Z,$,X,J)}finally{await G.release().catch(()=>{})}}async function Y$(Z,$,X,J){let G=(U)=>({status:"completed",rowId:X.rowId,operation:J,placeholder:U}),z=await IZ(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!==F3(Z))return{status:"foreign-placeholder"};return await e1(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 M3(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(z.kind!=="real"||z.fingerprint!==X.slotFingerprint)return await e1(Z,$),await Z.onStep("after-record-clear"),G("slot-moved-on");await Z.onStep("before-placeholder-write");let Q=await Z.slot.get({path:{id:t1}}),W=Q===void 0||Q===null?void 0:c6(Q);if(W?.kind!=="real"||W.fingerprint!==X.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:t1},body:{...AZ,accountId:F3(Z)}})}catch(U){if(U instanceof q0)return{status:"retry",reason:"slot-changed"};throw U}await Z.onStep("after-placeholder-write");let B=await Z.slot.get({path:{id:t1}});if(!TZ(B))return{status:"retry",reason:"placeholder-overwritten"};if(t(B)&&B.accountId===void 0)return{status:"untagged-placeholder"};if(t(B)&&B.accountId!==F3(Z))return{status:"foreign-placeholder"};return await e1(Z,$),await Z.onStep("after-record-clear"),G("written")}async function H$(Z,$,X){let{record:J}=X;if(X.fresh)await U$(Z,J),await Z.onStep("after-record-write");if(await s6(Z,X.credential.refresh))return{status:"restart"};let G=await IZ(Z);if(G.kind!=="real"||G.fingerprint!==J.slotFingerprint)return{status:"restart"};return await G$(Z,J,X.credential),await Z.onStep("after-row-write"),a6(Z,$,J,X.fresh?J.operation:"resumed")}async function a6(Z,$,X,J){let G=await z$(Z,X);if(!G)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),X.carryLegacyMain)await B$(Z,G),await Z.onStep("after-carry-over");let z=await V$(Z,$,X,J);if(z.status==="untagged-placeholder"){await Z.store.disable(X.rowId,s9,{extraLocks:M0(Z.paths,X.rowId,Z.locks),attribution:{credentialEpoch:G.credentialEpoch,...G.identity!==void 0?{identity:G.identity}:{}}}),await e1(Z,$);let Q=`${Z.paths.configPath}\x00${X.rowId}`;if(!g6.has(Q))g6.add(Q),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${a9}`,{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:M0(Z.paths,X.rowId,Z.locks),protect:(Q,W)=>W.row?.fingerprint!==X.credentialFingerprint?"the transfer row changed before rollback":void 0}),await M3(Z),await N3(Z),{status:"refused",reason:"placeholder-without-main"}}var h6=new Set,v6=new Set,g6=new Set;function F3(Z){return`openai-auth-pool:${w9("sha256").update(l9(Z.paths.configPath)).digest("hex")}`}async function j$(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function n6(Z,$,X){let J=n9(Z),G=J.slot.migrationDisabledReason?.();if(G){let U=J.slot.path??j0();if(!v6.has(U))v6.add(U),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 ZZ(J.paths.configPath)}catch(U){return{status:"error",reason:U instanceof Error?U.message:String(U)}}let Q=await i6(J,$,z);if(Q){if(Q.status==="already-migrated"&&"mainAccountId"in z)await N3(J);return Q}if(X){let U=await j$(X);if(U.length>0){let H=`${J.paths.configPath}\x00${U.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!h6.has(H))h6.add(H),J.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:U});return{status:"deferred",reason:"older-version-running",blockers:U}}}let W,B;try{B=await RZ(J,"pool-slot-transfer",J.slot.path??j0(),J.locks.mainRefreshTtlMs),W=await RZ(J,l6,J.paths.configPath,J.locks.mainRefreshTtlMs)}catch(U){if(await B?.release().catch(()=>{}),U instanceof SZ)return{status:"retry",reason:"lock-contention"};throw U}try{return await q$(J,$)}catch(U){if(U instanceof SZ)return{status:"retry",reason:"lock-contention"};if(U instanceof E)return{status:"retry",reason:U.kind==="lock-contention"?"lock-contention":`store-${U.kind}`};throw U}finally{await W?.release().catch(()=>{}),await B?.release().catch(()=>{})}}async function i6(Z,$,X){let J=G1(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&&F0(await IZ(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 q$(Z,$){let X;for(let J=0;J<4;J++){let G=await ZZ(Z.paths.configPath),z=await i6(Z,$,G);if(z){if(z.status==="already-migrated")await N3(Z);return z}let Q=await Z.store.read(),W=G1(G);if(Q.status==="pending-migration"){if(F0(await IZ(Z),Q.roster.some((V)=>t(V)&&V.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};await Z.store.initialize(),await Z.onStep("after-pool-key-write"),Q=await Z.store.read()}if(Q.status!=="ready")return{status:"error",reason:Q.status==="error"?`${Q.file}: ${Q.reason}`:"pool still pending migration"};let B=await Z$(Z);if(B.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(B.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(F0(B,Q.rows.some((V)=>V.id==="main"),W))return{status:"refused",reason:"placeholder-without-main"};let U=J$($,W,Q.rows,B,X,Z.now(),Z.newId);if(U.kind==="nothing"){if($==="migrate")await e1(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:U.slot}}if(U.kind==="drop-record"){await M3(Z),await Z.onStep("after-record-clear");continue}if(U.kind==="ambiguous")return await e1(Z,$,{declinedSlotFingerprint:U.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:U.record.rowId}),{status:"ambiguous",rowId:U.record.rowId};if(U.kind==="transfer"&&U.fresh)X=U.record.rowId;let H=U.kind==="finish"?await a6(Z,$,U.record,"resumed"):await H$(Z,$,U);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function N3(Z){await EZ(Z,($)=>{if(!("mainAccountId"in $))return!1;if(G1($).pending)return!1;return delete $.mainAccountId,!0})}function yz(Z){return n6(Z,"migrate",Z.fence)}function kz(Z){return n6(Z,"adopt")}class r6 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function M0(Z,$,X={}){let J={...P0,...X},G={renew:J.renew,timeoutMs:J.timeoutMs,retryMs:J.retryMs,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}};return[{name:OZ,path:Z.configPath,ttlMs:J.mainRefreshTtlMs,...G},{name:p6($),path:Z.configPath,ttlMs:J.fallbackTtlMs,...G}]}async function fz(Z,$,X,J={}){let G=Z.now??Date.now,z=Z.sleep??((B)=>new Promise((U)=>setTimeout(U,B))),Q=Z.leaseWait??{timeoutMs:4000,pollMs:50},W=async(B,U)=>{let H=_Z(B.refresh),V=async()=>{let j=await K0(Z.paths),D=j?.refresh?.mainRefreshLeaseUntil;return Boolean(D&&D>G()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await V()){let j=G()+Q.timeoutMs;while(G()<j&&await V())await z(Q.pollMs);throw new r6}return X(B,U)};return Z.store.refresh($,W,{...J,extraLocks:M0(Z.paths,$,Z.legacyLocks)})}
69
+ export{VZ as la,a as ma,X8 as na,m as oa,o4 as pa,U8 as qa,iX as ra,rX as sa,oX as ta,H8 as ua,$0 as va,e4 as wa,c0 as xa,r0 as ya,t0 as za,f1 as Aa,e0 as Ba,n1 as Ca,DZ as Da,g8 as Ea,u8 as Fa,p8 as Ga,i1 as Ha,l8 as Ia,KZ as Ja,s8 as Ka,XG as La,JG as Ma,GG as Na,zG as Oa,QG as Pa,BG as Qa,LG as Ra,N6 as Sa,AG as Ta,SG as Ua,A9 as Va,RG as Wa,EG as Xa,IG as Ya,bG as Za,qG as _a,r1 as $a,H3 as ab,M9 as bb,NG as cb,y9 as db,Wz as eb,d9 as fb,AZ as gb,s9 as hb,a9 as ib,Rz as jb,Ez as kb,r9 as lb,Iz as mb,G1 as nb,bz as ob,yz as pb,kz as qb,M0 as rb,fz as sb,OZ as tb,S6 as ub,j0 as vb,b6 as wb,q0 as xb,Fz as yb};