@cortexkit/opencode-openai-auth 1.2.0 → 1.4.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 (90) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-CjXETpTA.d.ts → codex-request-hw0XcldE.d.ts} +146 -29
  3. package/dist/index-1eq2s1cp.js +2 -0
  4. package/dist/{index-qp5hdpw8.js → index-1tdnrt68.js} +1 -1
  5. package/dist/index-5230x6s8.js +2 -0
  6. package/dist/{index-qxbchh2d.js → index-ag04nyv7.js} +7 -7
  7. package/dist/index-brbqqer5.js +90 -0
  8. package/dist/{index-xwvze96g.js → index-d98f1xdp.js} +1 -1
  9. package/dist/index-jcyrm58f.js +65 -0
  10. package/dist/{index-htvcmtcx.js → index-rsvnabbe.js} +2 -2
  11. package/dist/{index-ftkhhr6d.js → index-s88n2bjn.js} +1 -1
  12. package/dist/{index-bc89akak.js → index-t5m0dhmq.js} +1 -1
  13. package/dist/index-vy729a0b.js +69 -0
  14. package/dist/index-wgwze391.js +2 -0
  15. package/dist/{index-ffg0sgg5.js → index-yhw3hnsh.js} +2 -2
  16. package/dist/index.d.ts +11 -3
  17. package/dist/index.js +1 -1
  18. package/dist/{model-CQcw10oW.d.ts → model-DphbMQce.d.ts} +1 -1
  19. package/dist/{port-file-BDJnzgHH.d.ts → port-file-Cx-wwe5Q.d.ts} +1 -1
  20. package/dist/{protocol-C-kagE6O.d.ts → protocol-CDqdjh74.d.ts} +1 -1
  21. package/dist/rpc/port-file.d.ts +1 -1
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/protocol.d.ts +1 -1
  24. package/dist/rpc/protocol.js +1 -1
  25. package/dist/rpc/rpc-client.d.ts +3 -3
  26. package/dist/rpc/rpc-client.js +1 -1
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{sidebar-state-BfQ4mpZO.d.ts → sidebar-state-pTd9gg9W.d.ts} +71 -7
  29. package/dist/sidebar-state.d.ts +2 -2
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-z6qq7a1d.js → token-0z5g59p8.js} +1 -1
  32. package/dist/token-util-jf9g6stk.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +30 -3
  35. package/dist/v2/server.d.ts +2 -2
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +6 -6
  38. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +119 -6
  39. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +294 -16
  40. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +178 -26
  41. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
  42. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +100 -43
  43. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +10 -2
  44. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
  45. package/src/tui-compiled/raw/shared/42ae93ab554fcec2-open-url.js +7 -9
  46. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -0
  47. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +17 -3
  48. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +253 -0
  49. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +31 -6
  50. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +106 -0
  51. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +116 -12
  52. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
  53. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +348 -21
  54. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +2 -2
  55. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +5 -4
  56. package/src/tui-compiled/raw/shared/dc9290c2a7552ba6-watch.js +254 -0
  57. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +5 -1
  58. package/src/tui-compiled/raw/sidebar-state.js +32 -3
  59. package/src/tui-compiled/raw/tui/v2-dialog.js +2 -1
  60. package/src/tui-compiled/raw/tui.tsx +170 -26
  61. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +119 -6
  62. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +294 -16
  63. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +178 -26
  64. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
  65. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +100 -43
  66. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +10 -2
  67. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
  68. package/src/tui-compiled/runtime/shared/42ae93ab554fcec2-open-url.js +7 -9
  69. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -0
  70. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +17 -3
  71. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +253 -0
  72. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +31 -6
  73. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +106 -0
  74. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +116 -12
  75. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
  76. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +348 -21
  77. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +2 -2
  78. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +5 -4
  79. package/src/tui-compiled/runtime/shared/dc9290c2a7552ba6-watch.js +254 -0
  80. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +5 -1
  81. package/src/tui-compiled/runtime/sidebar-state.js +32 -3
  82. package/src/tui-compiled/runtime/tui/v2-dialog.js +2 -1
  83. package/src/tui-compiled/runtime/tui.js +350 -219
  84. package/dist/index-03em8hv1.js +0 -69
  85. package/dist/index-6n4pnfkg.js +0 -2
  86. package/dist/index-ehjj89rx.js +0 -2
  87. package/dist/index-f21addzm.js +0 -90
  88. package/dist/index-r2s51ac1.js +0 -2
  89. package/dist/index-rwbrhkse.js +0 -65
  90. package/dist/token-util-cf0nyh7n.js +0 -1
@@ -0,0 +1,69 @@
1
+ import{Ac as I5,Ad as LZ,Cc as B3,Cd as KZ,Dc as W1,Dd as N1,Ec as s6,Fc as U1,Fd as K3,Gc as b5,Hc as y5,Hd as s7,Ic as k5,Kc as N7,Lc as K7,Nc as L7,Nd as NZ,Oc as TZ,Pc as C7,Qc as B7,Rc as W7,Sd as U7,Ud as V7,Vc as eZ,Vd as Y7,Wc as Z3,Xd as a7,Yd as n7,_d as tZ,be as a6,gd as p5,id as l5,jd as d5,kd as c5,ld as s5,md as a5,nd as n5,od as i5,pd as r5,qd as o5,rd as t5,sd as CZ,vd as qZ,xc as O1,xd as d7,yc as P7,zc as N3,zd as c7}from"./index-brbqqer5.js";import{ne as u4,oe as b1,pe as p4,qe as k3,re as R1,se as yZ,te as l4}from"./index-ag04nyv7.js";import{Ie as P5,Me as J1,Ne as D7,Pe as S7,Qe as R7,Re as V1}from"./index-wgwze391.js";import{Ue as m4,_e as w4}from"./index-5230x6s8.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 x1="identity-contradicted: ",C3="duplicate-identity";function P1(Z,$,X){let J=Z.rosterRow($);if(!J)return;J.enabled=!1;let z=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0},G=typeof z.disabledReason==="string"&&z.disabledReason.startsWith("identity-contradicted: ");Z.setEntry($,{...z,disabledReason:G?z.disabledReason:X})}function JZ(Z,$){let X=Z.rosterRow($);if(!X)return;X.enabled=!0;let J=Z.entry($);if(J&&"disabledReason"in J){let z={...J};delete z.disabledReason,Z.setEntry($,z)}}function m1(Z,$){let X=Z.rows().filter((z)=>z.invalid===void 0&&!z.staged&&z.type==="oauth"&&z.enabled&&z.identity===$),J=[];for(let z of X.slice(1))P1(Z,z.id,"duplicate-identity"),J.push(z.id);return J}function S1(Z,$,X){let J=Z.rosterRow($);if(!J)return[];return J.accountId=X,m1(Z,X)}import{setTimeout as P8}from"node:timers/promises";import{AsyncLocalStorage as J8}from"node:async_hooks";var _4=new J8;function w(Z){if(_4.getStore()!==void 0)throw new bZ(Z)}function Q1(Z,$){return _4.run(Z,async()=>await $())}async function T4(Z,$,X,J,z){if(!$)return;try{await Q1(Z,()=>$(X,J))}catch(G){z?.warn("store failure hook threw; the original failure stands",{operation:Z,rowId:X,error:G instanceof Error?G.message:String(G)})}}var _3=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function z8(Z,$,X){let J=(Q)=>{try{let B=X.onLockEvent?.({type:Q,name:Z.name,path:Z.path});if(B&&(typeof B==="object"||typeof B==="function")&&"then"in B&&typeof B.then==="function")Promise.resolve(B).catch(()=>{})}catch{}},z={...$,...G8(Z)},G=performance.now();for(;;){let Q=await R1({name:Z.name,path:Z.path,ttlMs:z.ttlMs,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(U)=>X.onRenewalTimer?.({name:Z.name,path:Z.path},U)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.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 B=z.timeoutMs-(performance.now()-G);if(B<=0)throw new yZ({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let W=Math.floor(Math.random()*(z.retryMs+1));await new Promise((U)=>setTimeout(U,Math.min(z.retryMs+W,B)))}}function G8(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 z8(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 E1(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 zZ}from"node:crypto";var y="commonAuthPool",C1=1,e="rows",kZ="retiredEpochs",GZ=1,T3=300000,I=y;function Q8(Z){let $=JSON.parse(JSON.stringify(Z)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(P(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X($)}function I1(Z){return zZ("sha256").update(Q8(Z)).digest("hex")}function O4(Z){if(!P(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function B8(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 W8=new Set(["__proto__","constructor","prototype"]);function w1(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(W8.has(Z))return"id is a reserved object key";return}function O3(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 A4(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function Z1(Z){return zZ("sha256").update(A4(Z)).digest("hex")}function B1(Z){return zZ("sha256").update(`credential-stamp\x00${A4(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 zZ("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function A3(Z,$,X,J={}){return{credentialEpoch:$,digest:B1(Z),dispatch:q1(Z),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function u1(Z,$){let X=Z?.credentialBound?Z.credentialBound($):$;return zZ("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function QZ(Z,$,X,J){if(!$||X===void 0)return;if(!P(Z)||!Object.hasOwn(Z,p))return;let z=c(Z[I]);if(!z||z.providerState===void 0||z.digest!==B1($)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.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?B8(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 z=Z.binding;if(!P(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!O3(z.baseURL))return;if("authHeader"in z&&z.authHeader!=="authorization-bearer"&&z.authHeader!=="x-api-key")return;return{credentialEpoch:$,digest:Z.digest,...J,binding:{...typeof z.identity==="string"?{identity:z.identity}:{},...typeof z.baseURL==="string"?{baseURL:z.baseURL.trim()}:{},...z.authHeader==="authorization-bearer"||z.authHeader==="x-api-key"?{authHeader:z.authHeader}:{}}}}function U8(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 V8(Z,$,X,J){if(!Z)return"none";if(!P(J)||!Object.hasOwn(J,I))return"missing";let z=c(J[I]);if(!z)return"malformed";if(z.digest!==B1(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!U8(z.binding,Z,X))return"mismatched";if(z.dispatch!==q1(Z))return"mismatched";return"bound"}function S4(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 R4(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 p1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function E4(Z){let $=Z[y];if(!P($))return{};let X=$[e];return P(X)?X:{}}function Y8(Z){return P(Z.accounts)?Z.accounts:{}}function H8(Z){if(!P(Z))return"not an object";let $=w1(Z.id);if($)return $;if(Z.type==="api")return O3(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function j8(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&&!O4(Z.staged))return;return{credentialEpoch:X,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:J}:{}}}function q8(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 p1(Z).find((X)=>P(X)&&X.id===$)}function I4(Z){if(!P(Z[y]))Z[y]={};return Z[y]}function S3(Z){let $=I4(Z);if(!P($[e]))$[e]={};return $[e]}function _1(Z,$){let X=E4(Z),J=Object.hasOwn(X,$)?X[$]:void 0;return P(J)?J:void 0}function hZ(Z,$,X){Object.defineProperty(S3(Z),$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function b4(Z,$){let X=Z[y];if(!P(X))return;let J=X[kZ];if(!P(J)||!Object.hasOwn(J,$))return;let z=J[$];return x(z)?z:void 0}function y4(Z,$){let X=_1(Z,$)?.credentialEpoch;return x(X)?X:void 0}function vZ(Z,$){return Math.max(b4(Z,$)??0,y4(Z,$)??0)+1}function k4(Z,$){let X=[...$];if(X.length===0)return;let J=I4(Z),z=P(J[kZ])?J[kZ]:{},G={},Q=(B,W)=>Object.defineProperty(G,B,{value:W,enumerable:!0,writable:!0,configurable:!0});for(let[B,W]of Object.entries(z))if(x(W))Q(B,W);for(let B of X)Q(B,Math.max(b4(Z,B)??0,y4(Z,B)??1));J[kZ]=G}function T1(Z,$,X,J){let z=E4(Z),G=Y8($),Q=new Set,B=[];for(let W of p1(Z)){let U=H8(W),H=P(W)&&typeof W.id==="string"?W.id:void 0,V=H===void 0?void 0:z[H],j=P(V)&&Object.hasOwn(V,"staged"),D=j?O4(V.staged):void 0;if(U||!P(W)||H===void 0||Q.has(H)){if(H!==void 0&&!Q.has(H))Q.add(H);if(H!==void 0)B.push({id:H,type:P(W)&&W.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,H),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}Q.add(H);let Y=W.type==="api"?"api":"oauth",q=Object.hasOwn(z,H),F=q?j8(z[H],X):void 0,N=q8(W,G[H]),L=W.enabled!==!1,O=F?F.credentialEpoch:q?void 0:1,_=typeof W.accountId==="string"&&W.accountId?W.accountId:void 0,M={id:H,type:Y,enabled:L,needsFirstReading:F?F.needsFirstReading:Y==="oauth",hasEntry:q,candidate:!1,...typeof W.label==="string"?{label:W.label}:{},...typeof W.addedAt==="number"?{addedAt:W.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}:{},...D8(G[H],N,O,_,J),stamp:V8(N,O,_,G[H])};if(q&&!F)M.invalid="entry";else M.candidate=L&&N!==void 0&&!j;B.push(M)}return B}function D8(Z,$,X,J,z){if(!P(Z)||!Object.hasOwn(Z,p))return{};let G=QZ(Z,$,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let Q=Z[p];if(!z?.validate(Q))return{providerStateDropped:"invalid"};if(u1(z,Q)!==G)return{providerStateDropped:"uncovered"};return{providerState:Q}}function k(Z){return Z.identity??Z.id}function BZ(Z,$){if(Z===void 0||Z>$+T3)return $;return Math.max($,Z+1)}function R3(Z,$){return BZ(Z,$)>$+T3}function l1(Z){let{id:$,credential:X,identity:J,label:z,addedAt:G}=Z;return{id:$,...z!==void 0?{label:z}:{},type:X.type,addedAt:G,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function f4(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 h4(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function v4(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)&&!O3(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var gZ="transition",g4="transitionMark";function F8(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 WZ(Z,$,X){if(X.enabled)JZ(Z,$);else P1(Z,$,X.reason??"");if(!Z.rosterRow($))return;let J=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...J,[g4]:X.mark}),!X.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)m1(Z,z.identity)}function M8(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function N8(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function K8(Z,$,X,J={}){let z=P($.accounts)?$.accounts:{},G=new Map;for(let Q of T1(Z,$,X)){if(Q.invalid||Q.staged||!Q.credential)continue;let B=Object.hasOwn(z,Q.id)?z[Q.id]:void 0;if(!P(B))continue;let W=c(B[I]);if(!W?.binding)continue;if(W.digest!==B1(Q.credential))continue;let U=Q.credentialEpoch??1;if(W.credentialEpoch>U){if(!N8(W))continue;if(J.requireCredentialStamps){if(W.dispatch===void 0)continue;if(W.dispatch!==q1(M8(Q.credential,W.binding)))continue}G.set(Q.id,{kind:"replace",stamp:{...W,binding:W.binding}})}else if(W.credentialEpoch===U&&W.dispatch!==void 0&&W.dispatch===q1(Q.credential)&&W.binding.identity!==void 0&&Q.identity===void 0)G.set(Q.id,{kind:"identity",identity:W.binding.identity});else if(W.credentialEpoch===U&&W.binding.identity===Q.identity){if(J.requireCredentialStamps&&W.dispatch!==q1(Q.credential))continue;let H=F8(B[I]);if(H&&_1(Z,Q.id)?.[g4]!==H.mark)G.set(Q.id,{kind:"transition",transition:H})}}return G}function E3(Z,$,X,J){let G={...Z.entry($)??{},credentialEpoch:X,needsFirstReading:!0};if(delete G.quota,J.identity!==void 0&&typeof G.disabledReason==="string"&&G.disabledReason.startsWith(x1))delete G.disabledReason;Z.setEntry($,G);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 I3(Z,$,X,J={}){let z=K8(Z,$,X,J);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),Q={rows:()=>T1(G,$,X),rosterRow:(B)=>fZ(G,B),entry:(B)=>_1(G,B),setEntry:(B,W)=>hZ(G,B,W)};for(let[B,W]of z)if(W.kind==="replace")E3(Q,B,W.stamp.credentialEpoch,W.stamp.binding);for(let[B,W]of z)if(W.kind==="identity")S1(Q,B,W.identity);else if(W.kind==="transition")WZ(Q,B,W.transition);else if(W.stamp.binding.identity!==void 0)m1(Q,W.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function b3(Z,$,X,J={}){let{config:z,torn:G}=I3(Z,$,X,J),Q=T1(z,$,X,J.providerState);for(let B of Q){if(G.includes(B.id))B.torn=!0,B.candidate=!1;if(J.requireCredentialStamps&&B.stamp!=="bound")B.unbound=!0,B.candidate=!1}return Q}async function y3(Z){try{return await w4(Z,m4)}catch($){if($.code==="ENOENT")return;throw $}}function x4(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 y3(Z.configPath),J=await y3(Z.statePath),z=await y3(Z.configPath);if(X!==z){if($<2)await P8(2+Math.floor(Math.random()*4));continue}let G=S4(x4(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let Q=R4(x4(J));if(Q.status==="error")return{status:"error",file:"state",reason:Q.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:Q.exists,config:G.config,state:Q.state,rows:b3(G.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 d4{ctx;snapshot;locks;progress;info;config;state;constructor(Z,$,X,J,z){this.ctx=Z,this.snapshot=$,this.locks=X,this.progress=J,this.info=z,this.config=structuredClone($.config),this.state=structuredClone($.state)}rows(){return b3(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){E1(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 S3(this.config)}entry(Z){return this.entries(),_1(this.config,Z)}setEntry(Z,$){hZ(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=I3(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 W of $)if(P(W)&&typeof W.id==="string")X.add(W.id);let J=new Set;for(let W of p1(this.snapshot.config))if(P(W)&&typeof W.id==="string"&&!X.has(W.id))J.add(W.id);for(let W of Object.keys(this.entries()))if(!X.has(W))J.add(W);k4(this.config,J);let z=this.entries(),G={};for(let[W,U]of Object.entries(z))if(X.has(W))Object.defineProperty(G,W,{value:U,enumerable:!0,writable:!0,configurable:!0});let Q=this.config[y],B={...this.config,version:GZ,accounts:$,[y]:{...Q,schemaVersion:C1,[e]:G}};await this.write(this.ctx.configPath,B,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let W of J)this.ctx.removedIds.add(W);this.config=B}),this.config=B}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 k3(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 k3(this.ctx.configPath)}async write(Z,$,X,J=!0,z=!1,G){await p4(Z,$,{durable:z,beforeRename:async()=>{await this.ctx.onStep?.(`before-${X}-write`,this.info),await this.locks.assertAll()}},()=>{if(J)this.progress.writes++;G?.()}),await this.ctx.onStep?.(`after-${X}-write`,this.info)}}async function c4(Z,$){let X=new L1(Z.lockDefaults,Z.lockEnv),J={writes:0};try{for(let B of Z.storeLocks)await X.acquire(B);let z=await l(Z);if(z.status==="error")throw $1(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[B,W]of Object.entries(z.config))if(!$.includes(B))G[B]=W;G.version=GZ,G[y]={schemaVersion:C1,[e]:{}};let Q={operation:"initialize",rowId:void 0};return await b1(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",Q),await X.assertAll()}}),J.writes++,await Z.onStep?.("after-config-write",Q),"initialized"}catch(z){throw d1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function v(Z,$,X,J,z,G={}){let Q=$.held.length;try{for(let U of Z.storeLocks)await $.acquire(U);let B=await l(Z);if(B.status!=="ready")throw $1(B,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let W=new d4(Z,B,$,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))W.assertNotStaged(J.rowId);if(G.completeTorn??!0)await W.completeTorn();return await z(W)}finally{await $.releaseTo(Q)}}function d1(Z,$,X,J){let z=$==="pull"?"pull":J.writes>0?"after-first-write":"before-first-write",G=z==="after-first-write"?J.committed:void 0;if($==="publishRoster"&&J.publicationDecided)return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-incomplete",retryable:!0,message:"The publication may already be decided. Replay the same plan or check publication(operationId).",cause:Z});if($==="publishRoster"&&Z instanceof u4)return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:z,kind:"publication-sync",retryable:!0,message:"Publication sync failed before the decision; nothing was written. Retry the same plan.",cause:Z});if(Z instanceof E){if(Z.phase===z&&Z.rowId===X&&Z.operation===$&&Z.committed===G)return Z;return new E({operation:$,...X!==void 0?{rowId:X}:{},phase:Z.kind==="after-persist-hook"?Z.phase:z,retryable:Z.retryable,kind:Z.kind,...Z.committed??G?{committed:Z.committed??G}:{},message:Z.message,...Z.cause!==void 0?{cause:Z.cause}:{}})}let Q={operation:$,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof l4)return new E({...Q,retryable:!0,kind:"lock-ownership",message:z==="after-first-write"?`${$} lost a lease after its first write; the intermediate stays on disk`:`${$} lost a lease before writing; nothing was written`});if(Z instanceof 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,z){let G=new L1(Z.lockDefaults,Z.lockEnv),Q={writes:0};try{return await z(G,Q)}catch(B){let W=d1(B,$,X,Q);if(W.kind!=="after-persist-hook")await T4($,J,X,W,Z.logger);throw W}finally{await G.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 z=J.rows.find((U)=>U.id===X),G=_1(J.config,X),Q=J.state.accounts,B=P(Q)&&Object.hasOwn(Q,X)?Q[X]:void 0,W=P(B)?B[I]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))E1($,X,G.staged);if(!z&&P(W)&&Object.hasOwn(W,"staged"))E1($,X,W.staged);if(!z)throw X1($,X);return{result:J,row:z}}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,z=!1){return new E({operation:Z,rowId:$,phase:Z==="pull"?"pull":"before-first-write",retryable:z,kind:X,message:J})}async function xZ(Z,$,X,J){let{ctx:z}=Z,G=new L1(z.lockDefaults,z.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(z,G,Q,{operation:"pull",rowId:$},async(B)=>{B.assertNotStaged($);let W=B.row($);if(!W)throw X1("pull",$);if(W.invalid)throw K("pull",$,"invalid-row",`row ${$} is invalid`);if(!W.credential)throw K("pull",$,"no-credential",`row ${$} holds no credential`);d("pull",W);let U=B.entry($);if(W.torn||!U||U.credentialEpoch!==X.credentialEpoch||W.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=z.codec.merge(U.quota,J);if(!z.codec.validate(H))throw K("pull",$,"invalid-quota","the quota codec rejected the merged map");B.setEntry($,{...U,quota:H,needsFirstReading:!1}),await B.commitConfig()},{completeTorn:!1})}catch(B){throw d1(B,"pull",$,Q)}finally{await G.releaseAll()}}function F1(Z,$,X,J,z="the provider state"){if(!Z)throw K($,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let Q=JSON.stringify(J);G=Q===void 0?void 0:JSON.parse(Q)}catch{G=void 0}if(G===void 0)throw K($,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw K($,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function UZ(Z,$,X,J,z){if(J===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:F1(Z,$,X,Z.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function s4(Z,$,X,J,z){let G=Z?.onReplace,Q=G?G($.providerState===void 0?void 0:structuredClone($.providerState),{id:$.id,credentialEpoch:X,...$.identity!==void 0?{previousIdentity:$.identity}:{},...J!==void 0?{identity:J}:{},...z!==void 0?{incoming:structuredClone(z)}:{}}):z;if(Q===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:Q};return{kind:"set",value:F1(Z,"replace",$.id,Q,"the provider state onReplace returned")}}function a4(Z,$,X,J,z){if($.kind==="set")return u1(Z,$.value);if($.kind==="clear")return;return QZ(X,J?.credential,z,J?.identity)}async function n4(Z,$,X,J,z={}){w("updateProviderState");let{ctx:G}=Z,Q="updateProviderState";return u(G,Q,$,z.onFailure,async(B,W)=>{let U=G.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 B.acquire(s(Z,V));for(let j of z.extraLocks??[])await B.acquire(j);return v(G,B,W,{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 f3(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 i4=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function f3(Z,$,X,J,z,G=!1){let{id:Q,credential:B}=J;if(!B)throw K(X,Q,"no-credential",`row ${Q} holds no credential`);let W=J.credentialEpoch??1,U=Z.stateAccount(Q),H=U?.[I],V=c(H);if(!P(H)||!V?.binding||V.digest!==B1(B)||V.credentialEpoch!==W||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 Q1(X,()=>z(j,J));if(G&&D===i4)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=u1($,Y);if(V.providerState!==N)F[I]={...H,providerState:N}}return{kind:"changed",...Y!==void 0?{value:Y}:{},account:F}}import{randomUUID as r4}from"node:crypto";async function pZ(Z,$,X){if(!X)return;let J=Z.rows().map((G)=>{let{id:Q,type:B,label:W,enabled:U,disabledReason:H,identity:V,credentialEpoch:j,stamp:D,staged:Y,torn:q,invalid:F}=G;return{id:Q,type:B,label:W,enabled:U,disabledReason:H,identity:V,credentialEpoch:j,stamp:D,staged:Y,torn:q,invalid:F}}),z=await Q1(Z.info.operation,()=>X({id:$,row:J.find((G)=>G.id===$),rows:J,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw K(Z.info.operation,$,"row-protected",z)}var L8=["access","refresh","expires","lastRefreshedAt","apiKey"];function C8(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function _8(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 z=Z.row($)?.credential,G=z?.type==="api"?{baseURL:z.baseURL.trim(),authHeader:z.authHeader??"authorization-bearer"}:C8(J),Q=X.baseURL?.trim()??G.baseURL,B=X.authHeader??G.authHeader;if(Q!==G.baseURL||B!==G.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:B}}function o4(Z,$,X,J){let z=Z.rosterRow($),G=Z.row($),Q=J??(G?G.identity:P(z)&&typeof z.accountId==="string"&&z.accountId?z.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,z={}){let G=_8($,X,J),Q=$.stateAccount(X),B=z.providerState??{kind:"keep"},W=$.row(X)?.credentialEpoch??$.entry(X)?.credentialEpoch,U=typeof W==="number"?W:1,H=a4(Z.ctx.providerState,B,Q,Q&&Object.hasOwn(Q,p)?$.row(X):void 0,U),V=typeof Q?.lastRefreshedAt==="number"?Q.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??BZ(V,Z.ctx.now()):void 0,D={...Q??{}};for(let F of L8)delete D[F];if(z.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(B.kind==="clear")delete D[p];else if(B.kind==="set")D[p]=B.value;let Y=h4(G,j),q={...D,...f4(G,j),[I]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[gZ]:z.transition}:{},...A3(Y,U,z.binding??o4($,X,Y,z.identity),{replace:z.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,z={}){return wZ($,X,mZ(Z,$,X,J,z))}async function T8(Z,$,X){if(!$.credential||$.stamp!=="bound")return;let J=Z.stateAccount($.id),z=QZ(J,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...J??{},[I]:A3($.credential,$.credentialEpoch??1,o4(Z,$.id,$.credential,X),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function v3(Z,$,X){let J=Z==="add"?w1($):void 0;if(J)throw K(Z,$,"invalid-input",J);let z=v4(X,{baseURLOptional:Z==="rotate"});if(z)throw K(Z,$,"invalid-input",z)}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 s1(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 VZ(Z,$){return K(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function O8(Z,$,X,J){let{id:z,credential:G,identity:Q}=X;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!c1($.state,z))return;let B=()=>{throw K("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},W=$.stateAccount(z),U=c(W?.[I]);if(!U?.binding||U.dispatch===void 0||U.replace)return B();if(G.type==="api"&&(U.binding.baseURL===void 0||U.binding.authHeader===void 0))return B();let H=G.type==="api"?{...G,baseURL:U.binding.baseURL,authHeader:U.binding.authHeader}:G,[V]=T1({accounts:[l1({id:z,credential:H,identity:U.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:vZ($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return B();if(Q!==void 0&&Q!==V.identity)return B();if(B1(G)!==U.digest)return B();if(G.type==="api"){if(G.baseURL.trim()!==U.binding.baseURL)return B();if((G.authHeader??"authorization-bearer")!==U.binding.authHeader)return B()}else if(q1(G)!==U.dispatch)return B();if(U.providerState!==void 0&&V.providerState===void 0)return B();if(J!==void 0&&u1(Z.ctx.providerState,J)!==U.providerState)return B();return V}function A8(Z,$,X,J){let{id:z,credential:G,identity:Q,label:B}=X,W=$.rosterRow(z),U=()=>{throw K("add",z,W?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},H=$.stateAccount(z),V=c(H?.[I]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return U();if(W&&(W.type!==G.type||W.label!==B||W.accountId!==Q))return U();if(j.reservation!==X.stage?.reservation||j.label!==B||j.disabledReason!==X.disabled?.reason||V.binding.identity!==Q)return U();let D=J===void 0?void 0:I1(J),Y=H?.[p],q=Y===void 0?void 0:I1(Y);if(j.providerState!==D||j.providerState!==q)return U();if(B1(G)!==V.digest||q1(G)!==V.dispatch)return U();let F=W?$.config:{accounts:[{...l1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},N=T1(F,$.state,Z.ctx.codec,Z.ctx.providerState).find((L)=>L.id===z);if(!N?.credential||N.invalid||N.stamp!=="bound"||N.type!==G.type||N.enabled||N.label!==j.label||N.identity!==V.binding.identity||N.disabledReason!==j.disabledReason||N.staged?.reservation!==j.reservation)return U();if(W)return{id:z,outcome:"exists",credential:N.credential,credentialEpoch:V.credentialEpoch};if(vZ($.config,z)!==V.credentialEpoch)return U();return $.roster().push({...l1({id:z,credential:G,identity:Q,label:B,addedAt:Z.ctx.now()}),enabled:!1}),$.setEntry(z,{credentialEpoch:V.credentialEpoch,needsFirstReading:G.type==="oauth",disabledReason:j.disabledReason,staged:{reservation:j.reservation}}),$.commitConfig().then(()=>({id:z,outcome:"completed",credential:N.credential,credentialEpoch:V.credentialEpoch}))}async function t4(Z,$,X={}){w("add");let{ctx:J}=Z,{id:z,credential:G,identity:Q,label:B}=$,W=$.stage!==void 0||$.disabled!==void 0,U=await u(J,"add",z,X.onFailure,async(H,V)=>{v3("add",z,G);let j=X.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw K("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(B!==void 0&&typeof B!=="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",z,"invalid-input","staging requires a reservation and a disabled reason");let D=$.providerState===void 0?void 0:F1(J.providerState,"add",z,$.providerState);if(await H.acquire(s(Z,{id:z,identity:Q})),G.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:z},async(Y)=>{await pZ(Y,z,X.protect);let q=P(Y.state.accounts)?Y.state.accounts:{},F=Object.entries(q).find(([b,f])=>{if(b===z||Y.rosterRow(b)||!P(f))return!1;let XZ=f[I];if(!P(XZ)||!Object.hasOwn(XZ,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.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(z))throw K("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(Y.rosterRow(z)||c1(Y.state,z)))return A8(Z,Y,$,D);if(j==="rotate"){Y.assertNotStaged(z);let b=Y.rows().find((f)=>f.fingerprint===Z1(G));if(b)Y.assertNotStaged(b.id)}if(j==="refuse"){let b=Y.rows().find((K1)=>K1.fingerprint===Z1(G)||K1.id===z&&K1.credential),f=P(Y.state.accounts)?Y.state.accounts:{},XZ=Object.entries(f).find(([,K1])=>{if(!P(K1))return!1;if(G.type==="oauth")return K1.refresh===G.refresh;return typeof K1.apiKey==="string"&&K1.apiKey.trim()===G.apiKey.trim()})?.[0],C4=b?.id??XZ??z;if(b||XZ!==void 0||c1(Y.state,z))throw K("add",C4,"credential-exists",`row ${C4} already holds this secret or id`)}if(j==="stage-duplicate"&&(Y.rosterRow(z)||c1(Y.state,z)))throw K("add",z,"id-exists",`row ${z} already exists`);let N=O8(Z,Y,$,D),L=Y.rows(),O=Z1(G),_=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,G,{...D!==void 0?{providerState:UZ(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===z);if(M){if(M.invalid)throw K("add",z,"invalid-row",`row ${z} is invalid`);if(M.credential)throw K("add",z,"id-exists",`row ${z} already holds a credential`);if(d("add",M),M.type!==G.type)throw K("add",z,"type-mismatch",`row ${z} is a ${M.type} row`);if(Q!==void 0&&M.identity!==void 0&&Q!==M.identity)throw uZ("add",z);if(!M.hasEntry)Y.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let b=mZ(Z,Y,z,G,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await Y.completeTorn();let f=await wZ(Y,z,b);if(!M.hasEntry)await Y.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:M.credentialEpoch??1}}let C=vZ(Y.config,z);if(!x(C))throw K("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let A=N?.identity??Q;Y.roster().push(l1({id:z,credential:G,...A!==void 0?{identity:A}:{},...B!==void 0?{label:B}:{},addedAt:J.now()})),Y.setEntry(z,{credentialEpoch:C,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let T="added";if($.disabled)P1(Y,z,$.disabled.reason),T="added-disabled";if(!$.disabled&&A!==void 0&&G.type==="oauth"){if(L.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===A))P1(Y,z,C3),T="added-disabled"}if(N?.credential)return await Y.commitConfig(),{id:z,outcome:T,credential:N.credential,credentialEpoch:N.credentialEpoch??C};Y.dropStateAccount(z);let R=mZ(Z,Y,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...B!==void 0?{label:B}:{},...D!==void 0?{providerState:I1(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await Y.completeTorn();let h=await wZ(Y,z,R);return await Y.commitConfig(),{id:z,outcome:T,credential:h,credentialEpoch:C}},{completeTorn:!1})});if(!W&&G.type==="oauth"&&(U.outcome==="added"||U.outcome==="completed"))Z.firePull(U.id,"add");return U}async function e4(Z,$,X,J={},z={}){w("replace");let{ctx:G}=Z,Q=await u(G,"replace",$,z.onFailure,async(B,W)=>{v3("replace",$,X),s1("replace",$,z.attribution);let U=J.providerState===void 0?void 0:F1(G.providerState,"replace",$,J.providerState),{row:H}=await D1(Z,"replace",$);if(await B.acquire(s(Z,H)),X.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await B.acquire(V);return v(G,B,W,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)cZ("replace",$,V.row($),z.attribution),await V.completeTorn();let j=dZ("replace",$,V.row($),X);if(k(j)!==k(H))throw VZ("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=s4(G.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(E3(V,$,Y,F),J.identity!==void 0)m1(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:z.attribution===void 0})});if(X.type==="oauth")Z.firePull($,"replace");return Q}async function Z5(Z,$,X,J={},z={}){w("rotate");let{ctx:G}=Z;return u(G,"rotate",$,z.onFailure,async(Q,B)=>{v3("rotate",$,X),s1("rotate",$,z.attribution);let W=J.providerState===void 0?void 0:F1(G.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(z.providerLock??Z.providerLock);for(let H of z.extraLocks??[])await Q.acquire(H);return v(G,Q,B,{operation:"rotate",rowId:$},async(H)=>{if(z.attribution!==void 0)cZ("rotate",$,H.row($),z.attribution),await H.completeTorn();let V=dZ("rotate",$,H.row($),X);if(k(V)!==k(U))throw VZ("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,...W!==void 0?{providerState:UZ(G.providerState,"rotate",$,V.providerState,W)}:{}}),Y=!1;if(!V.hasEntry)H.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),Y=!0;if(J.identity!==void 0&&V.identity!==J.identity)S1(H,$,J.identity),Y=!0;if(Y)await H.commitConfig();return{id:$,credential:D}},{completeTorn:z.attribution===void 0})})}async function $5(Z,$,X,J,z){w($);let{ctx:G}=Z,Q=G.providerState,B=z.attribution,W=z.providerState;return u(G,$,X,z.onFailure,async(U,H)=>{if(s1($,X,B),W!==void 0){if(typeof W!=="function")throw K($,X,"invalid-input","the provider-state mutator must be a function");if(B===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 z.extraLocks??[])await U.acquire(j);return v(G,U,H,{operation:$,rowId:X},async(j)=>{await pZ(j,X,z.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 VZ($,X);if(B!==void 0)cZ($,X,Y,B);if(J.enabled&&Y.disabledReason?.startsWith(x1))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(W===void 0||Q===void 0){if(await j.completeTorn(),!q)return{id:X};if(J.enabled)JZ(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 f3(j,Q,$,Y,W,!0);if(F.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let N={id:X,providerStateOutcome:F.kind==="unchanged"?"unchanged":F.value===void 0?"cleared":"updated",...F.value!==void 0?{providerState:F.value}:{}};if(F.kind==="unchanged"){if(q){if(J.enabled)JZ(j,X);else 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:r4(),enabled:!0}:{mark:r4(),enabled:!1,reason:J.reason},O=F.account[I];return j.setStateAccount(X,{...F.account,[I]:{...O,[gZ]:L}}),await j.commitState(),WZ(j,X,L),await j.commitConfig(),N},{completeTorn:!1})})}function X5(Z,$,X,J={}){return $5(Z,"disable",$,{enabled:!1,reason:X},J)}function J5(Z,$,X={}){return $5(Z,"enable",$,{enabled:!0},X)}async function z5(Z,$,X={}){w("remove");let{ctx:J}=Z;return u(J,"remove",$,X.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw K("remove",$,"invalid-input","id must be non-empty");let Q=X.attribution;if(s1("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 B=await l(J);if(B.status!=="ready")throw $1(B,"remove",$);let W=B.rows.find((H)=>H.id===$);if(!W&&!c1(B.state,$))throw X1("remove",$);let U=k(W??{id:$});await z.acquire(s(Z,W??{id:$}));for(let H of X.extraLocks??[])await z.acquire(H);return v(J,z,G,{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=c1(H.state,$);if(!j&&!D)throw X1("remove",$);if(k(j??{id:$})!==U)throw VZ("remove",$);if(Q!==void 0)if(j)sZ($,j,Q);else S8(Z,H,$,Q);let Y=X.protect;if(Y){let q={row:j,config:H.snapshot.config,state:H.snapshot.state},F=await Q1("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 S8(Z,$,X,J){let z=()=>K("remove",X,"unbound-credential",`orphan ${X} has no credential stamp this store can bind, so the removal cannot be attributed to it`),G=$.stateAccount(X),Q=c(G?.[I]);if(!G||!Q?.binding||Q.dispatch===void 0||Q.replace)throw z();let B;if(typeof G.apiKey==="string"){if(Q.binding.baseURL===void 0||Q.binding.authHeader===void 0)throw z();B={type:"api",apiKey:G.apiKey,baseURL:Q.binding.baseURL,authHeader:Q.binding.authHeader}}else if(typeof G.refresh==="string")B={type:"oauth",refresh:G.refresh};else throw z();let[W]=T1({accounts:[l1({id:X,credential:B,identity:Q.binding.identity,addedAt:0})],[y]:{rows:{[X]:{credentialEpoch:Q.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!W?.credential||W.invalid||W.stamp!=="bound")throw z();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 c1(Z,$){let X=Z.accounts;return P(X)&&Object.hasOwn(X,$)}function h3(Z){return P(Z)&&typeof Z.id==="string"?Z.id:void 0}function R8(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let X=new Set;for(let G of Z){let Q=h3(G);if(Q!==void 0)X.add(Q)}let J=new Set;for(let G of $){if(typeof G!=="string")return"ids must be an array of roster ids";if(J.has(G))return`id ${G} appears more than once`;if(!X.has(G))return`id ${G} is not in the roster`;J.add(G)}let z=[...X].filter((G)=>!J.has(G));if(z.length>0)return`the order leaves out roster id(s) ${z.join(", ")}`;return}function E8(Z,$){let X=new Map;for(let G of Z){let Q=h3(G);if(Q===void 0)continue;let B=X.get(Q);if(B)B.push(G);else X.set(Q,[G])}let J=$.flatMap((G)=>X.get(G)??[]),z=0;return Z.map((G)=>h3(G)===void 0?G:J[z++])}async function G5(Z,$,X={}){w("reorder");let{ctx:J}=Z,z=X.onFailure;return u(J,"reorder",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let B of X.extraLocks??[])await G.acquire(B);return v(J,G,Q,{operation:"reorder",rowId:void 0},async(B)=>{let W=B.roster(),U=R8(W,$);if(U)throw new E({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:U});let H=[...$],V=E8(W,H);if(V.every((j,D)=>j===W[D]))return{ids:H,outcome:"unchanged"};return B.config.accounts=V,await B.commitConfig(),{ids:H,outcome:"reordered"}},{completeTorn:!1})})}async function Q5(Z,$,X,J,z={}){return w("recordIdentity"),u(Z.ctx,"recordIdentity",$,z.onFailure,async(G,Q)=>{if(typeof X!=="string"||X.length===0)throw K("recordIdentity",$,"invalid-input","identity must be non-empty");let B=P(J)?J.credentialEpoch:void 0;if(!x(B))throw K("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:W}=await D1(Z,"recordIdentity",$);await G.acquire(s(Z,W)),await G.acquire(z.providerLock??Z.providerLock);for(let U of z.extraLocks??[])await G.acquire(U);return v(Z.ctx,G,Q,{operation:"recordIdentity",rowId:$},async(U)=>{let H=dZ("recordIdentity",$,U.row($));if(k(H)!==k(W))throw VZ("recordIdentity",$);if(d("recordIdentity",H),(H.credentialEpoch??1)!==B)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 T8(U,H,X);let V=S1(U,$,X);return await U.commitConfig(),{id:$,disabled:V}})})}function W5(Z){let $=Z[y];return P($)&&P($.publications)?$.publications:{}}function U5(Z,$){let X=W5(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((z)=>!P(z)||typeof z.id!=="string"||!x(z.credentialEpoch))||J.finalized.some((z)=>!P(z)||typeof z.id!=="string"||!x(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw K("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function V5(Z,$){let X=await l(Z.ctx);if(X.status!=="ready")throw $1(X,"publishRoster",$);return U5(X.config,$)}function I8(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 z of[...$.remove,...$.finalize]){if(!P(z)||typeof z.id!=="string"||w1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),s1("publishRoster",z.id,z.attribution),z.attribution.identity!==void 0&&(typeof z.attribution.identity!=="string"||!z.attribution.identity))X()}for(let z of $.remove)if(Z.ctx.requireRemovedFingerprint&&!z.fingerprint||z.fingerprint!==void 0&&typeof z.fingerprint!=="string")X();for(let z of $.finalize)if(typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"||(z.enabled?z.disabledReason!==void 0:typeof z.disabledReason!=="string"))X();if($.order.some((z)=>typeof z!=="string"||w1(z))||new Set($.order).size!==$.order.length)X()}function Y5(Z,$){Z.entries();let X=Z.config[y],J={...W5(Z.config)};Object.defineProperty(J,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function b8(Z,$,X){let J=new Set;for(let Q of p1(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 z=new Set($.remove.map((Q)=>Q.id)),G=X.filter((Q)=>Q.invalid!=="roster"&&!z.has(Q.id));if(G.length!==$.order.length||$.order.some((Q)=>!G.some((B)=>B.id===Q))||G.some((Q)=>!$.order.includes(Q.id)))throw K("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function B5(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 z=Z.stateAccount(J.id),G=c(z?.[I]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let Q={...z[I]};delete Q.staged,Z.setStateAccount(J.id,{...z,[I]:Q})}}await Z.commitState(void 0,{durable:!0});let X={...$,phase:"cleaned"};return Y5(Z,X),await Z.commitConfig({durable:!0}),X}async function H5(Z,$,X={}){return w("publishRoster"),u(Z.ctx,"publishRoster",$?.operationId??"",X.onFailure,async(J,z)=>{if(!P($)||typeof $.operationId!=="string"||!$.operationId)throw K("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=I1($),Q=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((B)=>P(B)&&typeof B.id==="string");for(let B=0;;B++){let W=await l(Z.ctx);if(W.status!=="ready")throw $1(W,"publishRoster",$.operationId);let U=new Map(Q.map(({id:V})=>[V,k(W.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,z,{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=U5(V.config,$.operationId);if(D){if(D.planDigest!==G)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 B5(V,D)}}I8(Z,$);let Y=b8(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:I1(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:G,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)),..._],Y5(V,O),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await B5(V,O)}},{completeTorn:!1});if(H)return H;if(await J.releaseAll(),B>=1)throw K("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class g3{rt;hook;onFailure;firedAtLoad;logger;inflight=new Set;constructor(Z,$,X,J,z){this.rt=Z,this.hook=$,this.onFailure=X,this.firedAtLoad=J,this.logger=z}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,z=new L1(J.lockDefaults,J.lockEnv),G={writes:0};try{let Q=await v(J,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let U=W.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)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let H=W.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 z.releaseAll(),!Q){this.firedAtLoad.delete(Z);return}await J.hold?.("pull-before-request",Z);let B;try{B=await this.hook?.(Q)}catch(W){throw new E({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await xZ(X,Z,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(Q){this.firedAtLoad.delete(Z);let B=d1(Q,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,B)}catch(W){this.logger?.warn("pull failure hook threw",{rowId:Z,error:W instanceof Error?W.message:String(W)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:B.kind})}finally{await z.releaseAll()}}}import{randomUUID as y8}from"node:crypto";function x3(Z,$){if(E1("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 j5(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 q5(Z,$,X,J={}){w("refresh");let{ctx:z}=Z;return u(z,"refresh",$,J.onFailure,async(G,Q)=>{let{row:B}=await D1(Z,"refresh",$);x3($,B);let W=await J.refuse?.(B);if(W!==void 0)return{status:"refused",rowId:$,reason:W};let U=k(B),H;for(let Y=0;;Y++){await G.acquire(s(Z,{id:$,identity:U===$?void 0:U})),await G.acquire(J.providerLock??Z.providerLock);for(let N of J.extraLocks??[])await G.acquire(N);let F=await v(z,G,{writes:0},{operation:"refresh",rowId:$},async(N)=>{let L=x3($,N.row($));if(d("refresh",L),!L.hasEntry)N.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await N.commitConfig(),L=x3($,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 G.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(R3(H.credential.lastRefreshedAt,z.now()))throw j5($);await z.hold?.("refresh-before-provider",$),await G.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(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),D=await v(z,G,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=z.now(),O=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(R3(O,L))throw j5($);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:y8(),enabled:!1,reason:`${x1}${JSON.stringify(M)}`}:void 0,A=q.identity===void 0&&V.identity?V.identity:void 0,T=await lZ(Z,Y,$,_,{stamp:BZ(O,L),transition:C,identity:A,...j!==void 0?{providerState:UZ(z.providerState,"refresh",$,q.providerState,j)}:{}});if(C!==void 0)WZ(Y,$,C),await Y.commitConfig();let R=q.identity;if(A!==void 0)S1(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 Q1("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 k8}from"node:util";var nZ=Object.freeze(["version","accounts",y]);function m3(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 f8(Z,$){let X={};for(let[J,z]of Object.entries(Z))if(nZ.includes(J))aZ(X,J,z);else if(Object.hasOwn($,J))aZ(X,J,$[J]);for(let[J,z]of Object.entries($))if(!Object.hasOwn(Z,J))aZ(X,J,z);return X}function D5(Z){return new E({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}async function F5(Z){let $=await l(Z.ctx);if($.status==="error")return $;return{status:$.status,settings:m3($.config)}}async function M5(Z,$,X={}){w("updateSettings");let{ctx:J}=Z,z=X.onFailure;return u(J,"updateSettings",void 0,z&&((G,Q)=>z(Q)),async(G,Q)=>{for(let W of X.extraLocks??[])await G.acquire(W);let B=G.held.length;try{for(let F of J.storeLocks)await G.acquire(F);let W=await l(J);if(W.status!=="ready")throw $1(W,"updateSettings",void 0);let U=m3(W.config),H=structuredClone(U),V=await Q1("updateSettings",()=>$(H)),j=V===void 0?H:V;if(!P(j))throw D5("the settings mutator must produce an object");let D=nZ.filter((F)=>Object.hasOwn(j,F));if(D.length>0)throw D5(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(k8(j,U))return{settings:U,outcome:"unchanged"};let Y=f8(W.config,j),q={operation:"updateSettings",rowId:void 0};return await b1(J.configPath,Y,{beforeRename:async()=>{await J.onStep?.("before-config-write",q),await G.assertAll()}}),Q.writes++,await J.onStep?.("after-config-write",q),{settings:m3(Y),outcome:"updated"}}finally{await G.releaseTo(B)}})}var N5=new Map;function h8(Z){let $=N5.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},N5.set(Z,$);return $}function K5(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 YZ(Z){let $=h8(Z.configPath),X={..._3,...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}:{}},z=new g3(()=>G,Z.pull,Z.onPullFailure,$.firedAtLoad,Z.logger),G={ctx:J,providerLock:Z.providerLock??{name:`provider-${encodeURIComponent(Z.provider)}`,path:Z.statePath},rowLockOptions:Z.rowLockOptions??{},firePull:(Q,B)=>z.fire(Q,B)};return{async load(){let Q=await l(J);if(Q.status==="ready"){for(let B of Q.rows)if((B.candidate||B.torn&&B.enabled)&&B.type==="oauth"&&B.needsFirstReading)z.fire(B.id,"load")}return K5(Q)},async read(){return K5(await l(J))},async initialize(Q={}){return{status:await c4(J,Q.dropKeys??[])}},add:(Q,B)=>t4(G,Q,B),publishRoster:(Q,B)=>H5(G,Q,B),publication:(Q)=>V5(G,Q),replace:(Q,B,W,U)=>e4(G,Q,B,W,U),rotate:(Q,B,W,U)=>Z5(G,Q,B,W,U),updateProviderState:(Q,B,W,U)=>n4(G,Q,B,W,U),disable:(Q,B,W)=>X5(G,Q,B,W),enable:(Q,B)=>J5(G,Q,B),remove:(Q,B)=>z5(G,Q,B),reorder:(Q,B)=>G5(G,Q,B),readSettings:()=>F5(G),updateSettings:(Q,B)=>M5(G,Q,B),recordIdentity:(Q,B,W,U)=>Q5(G,Q,B,W,U),refresh:(Q,B,W)=>q5(G,Q,B,W),recordQuota:(Q,B,W)=>xZ(G,Q,B,W),requestReading:(Q)=>z.fire(Q,"admission"),pullsSettled:()=>z.settled()}}var v8=[/\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 p3(Z={}){let{redactStrings:$}=P5({...Z,extraValuePatterns:[...v8,...Z.extraValuePatterns??[]]});return(X)=>$(X)}class a extends Error{code;constructor(Z,$,X){super($,X);this.name="CommandError",this.code=Z}}var L5=/^[a-z][a-z0-9-]{0,63}$/,w3={code:"action-failed",text:"That action failed."},g8=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 HZ(Z){if(Z instanceof a)return{code:L5.test(Z.code)?Z.code:w3.code,text:Z.message};if(Z instanceof E)return{code:`pool-${Z.kind}`,text:g8.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return w3}var C5="This cannot be undone. Continue?",x8=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function m8(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return x8.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function w8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function u3(Z,$,X){if(typeof Z==="string"){let z=X.redact(Z);if(z!==Z)X.redacted.push($);return z}if(Array.isArray(Z))return Z.map((z,G)=>u3(z,`${$}[${G}]`,X));if(!w8(Z))return Z;let J={};for(let[z,G]of Object.entries(Z)){if(m8(z)){X.dropped.push(`${$}.${z}`);continue}Object.defineProperty(J,z,{value:u3(G,`${$}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function _5(Z,$,X){let J={redact:X.redact,dropped:[],redacted:[]},z=u3(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 z}function u8(Z){return{value:String(Z.value),label:String(Z.label)}}function p8(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(u8),...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 l3(Z){if(Z.irreversible===!0)return{message:Z.confirm||C5,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function T5(Z){let $=l3(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(p8),...$?{confirm:$}:{}}}function l8(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 d8(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:l8(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(T5)}}function c8(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(d8),actions:($.actions??[]).map(T5),...$.facts!==void 0?{facts:$.facts}:{}}}function O5(Z,$,X){return{command:Z,title:$,sections:X.map(c8)}}function A5(Z,$,X,J){return _5({command:Z,menu:O5(Z,$,X)},Z,J)}function S5(Z,$,X,J,z){return _5({command:Z,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:L5.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:O5(Z,$,X)},Z,z)}var f5="disabled from the command menu";function s8(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function M1(Z){return s8(Z)?{...Z}:{}}function a8(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 n8(Z,$){return Z.label??$??Z.id}function iZ(Z,$){return O1(Z.quota)?U1(Z.quota,$):void 0}function h5(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var jZ="Actions";function i8(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 R5(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 E5(Z){return HZ(Z).text}async function r8(Z){let $=await Z.read(),X=await Z.readSettings();return{load:$,rows:a8($),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:n8(Z,X)}}function o8(Z,$){let{store:X,extraLocks:J}=Z,z=J?{extraLocks:J}:{},G=$.rows.map((V)=>V.id),Q=i8($.load),B=$.rows.filter((V)=>V.enabled).length,W=$.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,f5,z),`Disabled ${Y}.`}});if(!V.invalid&&!V.enabled)N.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${Y}.`}});if(G.length>1)N.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((L,O)=>({value:String(O+1),label:String(O+1)})),value:String(j+1)}],run:async({values:L})=>{let O=Number(L.position),_=G.filter((C)=>C!==V.id);return _.splice(O-1,0,V.id),(await X.reorder(_,z)).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,{...z,...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:jZ,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,z);return R5(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,z);j.notify(R5(Y.label??q.id,q))},(Y)=>{j.notify(`Adding the account failed: ${E5(Y)}`,"error")}).catch((Y)=>{j.notify(`Adding the account failed: ${E5(Y)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:Q?[Q]:[$.rows.length===0?"No accounts yet":`${h5($.rows.length,"account")}, ${B} enabled`],items:Q?[]:W,actions:H}}}function t8(Z,$){let X=Z.quota?.scope??"all",J=Z.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(H,V)=>{if(Z.quota?.check)await Z.quota.check(H,V);else{for(let j of H)Z.store.requestReading(j);await Z.store.pullsSettled()}},Q=$.rows.filter((H)=>H.candidate),B=Q.map((H)=>{let{account:V,name:j}=rZ(H,Z),D=iZ(H,X);return{id:H.id,label:j,group:z,status:W1(D,{now:J,form:"compact"}),detail:W1(D,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:Y})=>{return await G([H.id],Y),`Checked quota for ${j}.`}}]}}),W=$.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=W1(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:jZ,run:async({invocation:H})=>{let V=Q.map((j)=>j.id);return await G(V,H),`Checked quota for ${h5(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:W,items:B,actions:U}}}function e8(Z,$){let{store:X,extraLocks:J}=Z,z=J?{extraLocks:J}:{},G=[{value:"ordered",label:"Ordered (roster order)"},...Z.routing?.orderedVariants??[],{value:"sticky-balanced",label:"Sticky balanced"}],Q=M1($.settings.routing).mode,B=typeof Q==="string"&&G.some((Y)=>Y.value===Q)?Q:"ordered",W=y5(B),U=$.rows.map((Y)=>Y.id),H=k5(U,W.placement,Z.routing?.formerMainId??b5),j=[`Mode: ${G.find((Y)=>Y.value===B)?.label??B}`];if(U.length>0)j.push(`Roster order: ${U.join(", ")}`);if(W.mode==="ordered"&&H.join()!==U.join())j.push(`Tried in order: ${H.join(", ")}`);let D=[{id:"mode",label:"Change mode",group:jZ,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:B}],run:async({values:Y})=>{let q=String(Y.mode);return await X.updateSettings((F)=>{F.routing={...M1(F.routing),mode:q};return},z),`Routing mode set to ${G.find((F)=>F.value===q)?.label??q}.`}}];if(U.length>1)D.push({id:"order",label:"Set order",group:jZ,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,z);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 Z9(Z,$){if(Z.limits?.labels)return[...Z.limits.labels];let X=Z.quota?.scope??"all",J=[];for(let z of $.rows)for(let G of iZ(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function $9(Z,$){let X=Z.quota?.scope??"all",J=new Map;for(let z of $.rows)for(let G of iZ(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,I5(G));return(z)=>J.get(z)??z}function X9(Z,$){let{store:X,extraLocks:J}=Z,z=J?{extraLocks:J}:{},G=M1($.settings.killswitch),Q=G.enabled===!0,B=M1(G.accounts),W=Z9(Z,$),U=$9(Z,$),H=Q?"on":"off",V=$.rows.map((j)=>{let{account:D,name:Y}=rZ(j,Z),q=M1(B[j.id]),F=W.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:W.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 W){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},z),`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:jZ,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},z),`Killswitch ${D?"on":"off"}.`}}]}}}async function v5(Z){let $=await r8(Z.store);return[o8(Z,$),t8(Z,$),e8(Z,$),X9(Z,$)]}var J9=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),d3=["accounts","quota","routing","limits"];function g5(Z,$){let{sessionId:X}=Z,J=Z.notify.bind(Z);return Object.freeze({...X!==void 0?{sessionId:X}:{},notify:(z,G)=>G===void 0?J($(String(z))):J($(String(z)),G)})}function z9(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 G9(Z,$){let X={};for(let J of Z){let z=$&&Object.hasOwn($,J.id)?$[J.id]:void 0,G=z9(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function Q9(Z,$){let X=Z.find((z)=>z.id===$.sectionId);if(!X)return;return($.itemId===void 0?X.content.actions:X.content.items?.find((z)=>z.id===$.itemId)?.actions)?.find((z)=>z.id===$.actionId)}function y1(Z){let $=Z.logger??J1("commands"),X=p3(Z.redaction),J={logger:$,redact:X},z=Z.now??Date.now,G=Z.extras??[],Q=Z.replace??{},B=d3.filter((j)=>!Q[j]);for(let j of d3)if(Q[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let W=Z.store;if(B.length>0&&!W)throw Error(`a store is required for the built-in ${B.join(", ")} section${B.length>1?"s":""}`);let U=new Set;for(let j of G){if(J9.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=W&&B.length>0?await v5({store:W,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],Y=[];for(let q of d3){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 G)Y.push(await H(q.id,"extra",q,j));return Y}return{command:Z.command,async open(j){let D=g5(j,X);return A5(Z.command,Z.title,await V(D),J)},async apply(j,D){let Y=g5(D,X),q=async(_)=>S5(Z.command,Z.title,await V(Y),_,J),F=j.command===Z.command?Q9(await V(Y),j):void 0;if(!F)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let N=l3(F);if(N&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:N.message,needsConfirmation:!0});let L=G9(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=HZ(_);$.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 B9(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function W9(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,z]of Object.entries($.values)){if(!B9(z))return;Object.defineProperty(X,J,{value:z,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 V9}from"node:fs";import{rm as u5}from"node:fs/promises";import{dirname as Y9,join as e5}from"node:path";import{resolveClaustrumConnectionPath as H9}from"@cortexkit/claustrum-client";function x5(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 m5(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 U9(Z){let $=m5(Z.total),X=m5(Z.remaining);if($===void 0||X===void 0||$<0||X<0)return;let J=$-X,z=Z.spendable===!1,G=$>0?J/$*100:z?100:0;return{limit:$,used:J,remaining:X,usedPercent:G,remainingPercent:100-G,reached:z,...typeof Z.resetsAt==="string"&&{resetsAt:Z.resetsAt},...m(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function w5(Z,$){let X=x5(Z.usage?.primary,$.fetchedAt);if(!X||!Number.isFinite($.fetchedAt))return;let J=x5(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((B)=>m(B)&&B.id==="individual_limit"):void 0,G=m(z)?U9(z):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},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}function c3(Z){return`ck auth grant --principal enrolled:${Z} --selector-kind category --selector openai-native --operation read`}var s3="ck auth reclassify --from-registry";function oZ(Z,$){if($===void 0)return"No ChatGPT login in the vault has the `openai-native` category, or the grant is missing. Check `ck auth status` for categories and `ck auth grant` for the grant.";if($.grants===0)return`The vault has no grant letting ${Z} read OpenAI accounts. Grant it with \`${c3(Z)}\`.`;return`The vault's grant for ${Z} reaches no ChatGPT login: no login has the \`openai-native\` category. \`${s3}\` fills empty category sets from the vault's defaults; then check the CATEGORIES column with \`ck auth status\`.`}var z1=J1("vault"),j9="openai-auth",Z6={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},q9={opencode:"OpenCode",pi:"Pi"};function D9(Z){return l5(j9,Z)}function $J(Z){return e5(Y9(Z),"openai-auth-vault")}function F9(Z,$){return{...c5({stateDir:Z,host:$}),rosterPath:e5(Z,`${$}-roster.json`)}}var $6=2000,XJ=["vault-unreachable","vault-empty","vault-no-grant","vault-grant-unreached","vault-refused"],M9={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-grant-unreached":`Request refused locally: this host is connected to the credential vault, whose grant for it reaches no ChatGPT login, and local accounts are not used while it is connected. Logins without the openai-native category are not reached: run ${s3} to fill empty category sets, then check the CATEGORIES column with ck auth status. Or disconnect this host from the vault.`,"vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function JJ(Z,$){if(Z!=="vault-no-grant")return M9[Z];return`Request refused locally: this host is connected to the credential vault, which has no grant letting it read OpenAI accounts, and local accounts are not used while it is connected. Disconnect this host from the vault, or grant it access with: ${c3($)}`}function zJ(Z){let $=Z.snapshot();if($===void 0)return"vault-unreachable";if($.rows.length===0){let X=Z.grantReach();if(X!==void 0)return X.grants===0?"vault-no-grant":"vault-grant-unreached"}return"vault-empty"}function N9(Z){let $=eZ(Z);return $?Z3($):void 0}class X6 extends o5{#$;constructor(Z,$){super(Z);this.#$=$}refresh(){let Z=super.refresh();return this.#$(Z),Z}}class K9{host;name;paths;#$;#Z;#B=new Map;#W=new Map;#H=new Map;#j;#X;#U;#z;#q=!1;#D=!1;#V=Promise.withResolvers();#F="unknown";#Y;constructor(Z){this.#$=Z,this.host=Z.host,this.name=D9(Z.host),this.paths=F9(Z.stateDir,Z.host),this.#Z=new X6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:Z6,connect:()=>this.#L(),isCustodyActive:()=>this.#_(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:N9,insula:{provider:"codex",normalize:w5},...Z.now?{now:Z.now}:{},...Z.pollIntervalMs!==void 0?{pollIntervalMs:Z.pollIntervalMs}:{},...Z.setTimeoutImpl?{setTimeoutImpl:Z.setTimeoutImpl}:{},...Z.clearTimeoutImpl?{clearTimeoutImpl:Z.clearTimeoutImpl}:{},onRoster:()=>{this.#X=void 0},onError:($)=>this.#J("vault roster refresh failed",$),logger:{...z1,warn:($,X)=>{if($!=="skipped insula provider poll")z1.warn($,X)}}},($)=>this.#T($))}#M(){return(this.#$.connectionFile??H9)()}#N(){return{connectionFile:this.#M(),projectRoot:this.#$.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>z1.debug("vault transport error",{errorClass:Z})}}#L(){return(this.#$.connectScoped?.()??t5(this.#N())).then((Z)=>{return this.#j=Z.insula!==void 0,Z})}#G(Z,$,X){let J=this.#H.get(Z);if(J?.source===$&&J.reason===X)return;this.#H.set(Z,{source:$,reason:X}),z1.info("vault background quota source changed",{routeId:Z,source:$,reason:X})}#C(){return this.#$.connectEnrollment?.()??d5(this.#N())}#J(Z,$){this.#X=V1($),z1.warn(Z,{host:this.host,error:this.#X})}#Q(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=V9(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#Q(),$=await a5(this.paths,this.name);if(Z===this.#Q())return this.#F=$,this.#Y=Z,$;return"unreadable"}enrolled(){return this.#Y!==this.#Q()||this.#F!=="local"}async#_(){if(this.#Y!==this.#Q())await this.authority();return this.enrolled()}start(){if(this.#q||this.#D)return;this.#q=!0,this.#Z.start()}#T(Z){if(this.#z===Z)return;this.#z=Z,Z.finally(()=>{if(this.#z===Z)this.#z=void 0;this.#V.resolve()}).catch(()=>{})}#K(){return this.#Z.refresh()}firstRoster(){return this.#V.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#z;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#z??this.#K()).catch((X)=>{this.#J("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let Z=this.#z;if(Z)await Z.catch(()=>{return});let $=await this.#K();return this.#X=void 0,$}catch(Z){return this.#J("vault roster refresh failed",Z),this.#Z.snapshot()}}snapshot(){return this.#Z.snapshot()}watchState(){return this.#Z.watchState()}keptReceiptState(){return this.#Z.keptReceiptState()}grantReach(){return this.#Z.grantReach()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#Z.routingRows().map(($)=>{let X=Z.get($.id)?.accountIdentity;return{id:$.id,credentialId:Z.get($.id)?.credentialId,kind:$.kind==="api-key"?"api-key":"oauth",...X!==void 0?{identity:X}:{},...$.quota!==void 0?{quota:$.quota}:{}}})}owns(Z){return(this.snapshot()?.rows??[]).some(($)=>$.routeId===Z)}async send(Z,$,X){let J=!1;try{return await this.#Z.send(Z,(z)=>{return J=!0,$(z.accessToken,z)},{site:X.site,...X.signal?{signal:X.signal}:{}})}catch(z){if(J)throw z;this.#J("vault refused to serve an account",z);return}}async authorize(Z,$={}){try{return await this.#Z.authorize(Z,$.signal)}catch(X){this.#J("vault refused to serve an account",X);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#Z.reportFailure(Z,401,"direct")}catch(X){this.#J("vault failure report failed",X)}await this.refresh()}recordSnapshot(Z,$,X,J){let z=tZ($,(this.#$.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#Z.recordQuota(Z,z,J).then(()=>{},(G)=>this.#J("vault quota write failed",G))}pollQuota(Z,$=!0){let X=this.#W.get(Z);if(X)return X;let J=this.#O(Z,$).finally(()=>{this.#W.delete(Z)});return this.#W.set(Z,J),J}async#O(Z,$){if($){await this.authority(),await this.#Z.refreshInsulaQuota();let X=(await r5(this.paths.rosterPath))?.rows.find((B)=>B.routeId===Z),J,z=await this.#Z.pollInsulaQuotaForRoute(Z,async()=>{this.#G(Z,"fallback",this.#j===!1?"insula-not-configured":"no-insula-reading"),J=await this.#P(Z,$);return});if(J)return J;if(z!==void 0&&X?.accountIdentity){let B=tZ(z,z.primary.checkedAt,!0);if(!B)return this.#G(Z,"fallback","insula-unusable"),{ok:!1,error:"unusable insula reading"};if(await this.#Z.recordAccountQuota(Z,X.accountIdentity,B))return this.#G(Z,"insula",null),{ok:!0};return this.#G(Z,"fallback","account-changed"),{ok:!1,error:"vault account changed"}}let{miss:G}=await this.#Z.lookupInsulaQuotaForRoute(Z),Q=G==="cold"||G==="upstream-failed"?G:"no-insula-reading";return this.#G(Z,"insula",Q),{ok:!1,error:`insula ${Q}`}}return this.#P(Z,$)}async#P(Z,$){let X,J=this.#$.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,Q)=>{try{let B=$?void 0:await this.#Z.cachedInsulaQuota(Q);if(B!==void 0){let U=tZ(B,B.primary.checkedAt,!0);if(!U)throw Error("unusable insula reading");return await this.#Z.recordQuota(Z,U,Q),new Response(null,{status:200})}let W=await qZ({accessToken:G,fetchImpl:J,now:this.#$.now??Date.now,...Q.accountIdentity?{accountId:Q.accountIdentity}:{},accountKey:Z,logger:z1});return await this.recordSnapshot(Z,W,!0,Q),X=void 0,new Response(null,{status:200})}catch(B){X=V1(B);let W=B?.status;if(typeof W==="number")return new Response(null,{status:W});throw B}},{site:"quota"}).catch((G)=>{X=V1(G);return});if(!z)return{ok:!1,error:X??"vault refused"};return z.ok?{ok:!0}:{ok:!1,error:X??`status ${z.status}`}}requestReading(Z){let $=this.#B.get(Z);if($)return $;let X=this.pollQuota(Z,!1).catch((J)=>{z1.warn("vault quota poll failed",{routeId:Z,error:V1(J)})}).finally(()=>{this.#B.delete(Z)});return this.#B.set(Z,X),X}async pollStale(Z){let $=(this.#$.now??Date.now)(),X=[];for(let J of this.routes()){let z=P9(J.quota);if(z!==void 0&&$-z<Z)continue;X.push({id:J.id,...await this.pollQuota(J.id)})}return X}async decline(Z){await this.#Z.decline(Z),z1.info("vault account declined",{routeId:Z})}async accept(Z){await this.#Z.accept(Z),z1.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await s5(this.paths,this.name)}catch($){this.#J("vault enrollment state unreadable",$),Z={state:"blocked",proposedName:this.name,code:$ instanceof p5?$.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:Z,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#X?{lastError:this.#X}:{}}}async connectStep(){let Z=await this.#C().catch(($)=>{throw new a("vault-unreachable",`Could not reach the Claustrum vault (${this.#M()}): ${V1($)}. Is the vault running?`)});try{let $=new n5({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(z1.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#X=void 0,await this.refresh();return J}finally{Z.close()}}waitForApproval(Z={}){return this.#U??=(async()=>{let $=Z.sleep??((G)=>new Promise((Q)=>setTimeout(Q,G))),X=Z.pollIntervalMs??2000,J=Date.now()+(Z.timeoutMs??600000),z=await this.connectStep();while(z.state==="pending"||z.state==="busy"){if(Z.onPending?.(z),Date.now()>=J)return z;await $(X),z=await this.connectStep()}return z})().finally(()=>{this.#U=void 0}),this.#U}async disconnect(){await u5(this.paths.tokenPath,{force:!0}),await u5(this.paths.statePath,{force:!0}),await this.authority(),this.#X=void 0,z1.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())i5({mode:"custody",auth:Z,provider:"openai"})}close(){this.#D=!0,this.#V.resolve(),this.#Z.close()}}function P9(Z){if(!Z)return;let $=U1(Z).limits.map((X)=>X.checkedAt);return $.length>0?Math.max(...$):void 0}function $3(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 ${Z6.category} --operation read`]}function J6(Z,$,X){let J=`${q9[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 a3(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(Z.name,Z.grantReach())}`:"."}`}}case"denied":return{ok:!1,text:"The vault denied the enrollment request. Run Connect again to send a new one."};case"blocked":return{ok:!1,text:`Enrollment stopped (${$.code}). Run Connect again to send a new request.`};case"pending":case"busy":return{ok:!1,text:[...$3(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 n3="/backend-api/wham/rate-limit-reset-credits",L9=`https://chatgpt.com${n3}`,U6=`${n3}/consume`,C9=`https://chatgpt.com${U6}`,_9=300000,T9=60000,O9=15000,A9=60000;function a1(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 k1 extends Error{kind;status;constructor(Z,$,X){super($);this.name="ResetCreditError",this.kind=Z,this.status=X}}function V6(Z,$,X){return{authorization:`Bearer ${Z}`,...X?{"chatgpt-account-id":X}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function J3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function Y6(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function z3(Z){if(!J3(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}:{},...H6(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function H6(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function X3(Z){return Z.kind==="http_error"&&H6(Z.status)}function j6(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function S9(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 q6(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function D6(Z,$){return $-Z.startedAt<_9}function n1(Z,$){if(!N1($))return;return Z.reset?.[$]}function F6(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function M6(Z,$,X){if(!N1($))return;let J=F6(Z),z=J[$]??{},G=z.lastOutcome;delete z.inFlight,z.lastOutcome={code:"ambiguous_local",at:X,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},J[$]=z}function N6(Z,$){let X=Y6(Z),J=z3(Z?.inFlight);if(q6(Z)&&!J)return{kind:"corrupt",beforeState:X};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:X,cooldownUntil:Z.cooldownUntil};if(J&&D6(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 R9(Z,$){if(!N1($))return{kind:"fresh",beforeState:void 0};let X=await Z.loadAccountsFn(a1(Z));return N6(X?n1(X,$):void 0,Z.now())}async function E9(Z,$){let X;if(await Z.mutateAccountsFn((J)=>{let z=Z.now(),G=n1(J,$);if(X=N6(G,z),X.kind==="corrupt")M6(J,$,z);return J},a1(Z)),!X)throw Error("corrupt reset state mutation did not run");return X}async function I9(Z,$,X,J){if(!N1($))return{kind:"fresh",beforeState:void 0};let z;if(await Z.mutateAccountsFn((G)=>{let Q=Z.now(),B=n1(G,$),W=Y6(B),U=z3(B?.inFlight);if(q6(B)&&!U)return M6(G,$,Q),z={kind:"corrupt",beforeState:W},G;if(B?.cooldownUntil!==void 0&&B.cooldownUntil>Q)return z={kind:"cooldown",beforeState:W,cooldownUntil:B.cooldownUntil},G;if(U&&D6(U,Q))return z={kind:"claim",beforeState:W,claim:{inFlight:U,selectedCredit:{id:U.creditId}}},G;if(U&&!j6(U,J))return z={kind:"expired_unreconciled",beforeState:W,claim:{inFlight:U,selectedCredit:{id:U.creditId}}},G;let H=G3(X);if(!H)return z={kind:"fresh",beforeState:W},G;let V={redeemRequestId:Z.randomUUID(),creditId:H.id,startedAt:Q,...J===void 0?{}:{chatgptAccountId:J}},j=F6(G);return j[$]={...B,inFlight:V},z={kind:"claim",beforeState:W,claim:{inFlight:V,selectedCredit:H}},G},a1(Z)),!z)throw Error("reset claim mutation did not run");return z}async function b9(Z,$,X,J,z){if(!N1($))return;if(!o3(J.kind))return y9(Z,$,X,J,z);await Z.mutateAccountsFn((G)=>{let Q=n1(G,$),B=z3(Q?.inFlight);if(!Q||!B||B.redeemRequestId!==X.redeemRequestId||B.creditId!==X.creditId)return G;let W=Z.now();if(delete Q.inFlight,Q.lastOutcome={code:J.kind,at:W},J.kind==="reset"||J.kind==="already_redeemed")Q.cooldownUntil=W+A9;else delete Q.cooldownUntil;return G},a1(Z));return}function z6(Z,$){let X=z3(Z?.inFlight);return X&&X.redeemRequestId===$.redeemRequestId&&X.creditId===$.creditId?X:void 0}async function y9(Z,$,X,J,z){let G=X3(J)?J.status:void 0;if(!(X.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===X.rejectedStatus){let W=await Z.loadAccountsFn(a1(Z));return z6(W?n1(W,$):void 0,X)}let B;return await Z.mutateAccountsFn((W)=>{B=void 0;let U=n1(W,$),H=z6(U,X);if(!U||!H)return W;let V={...H};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(H.unknownAnswers??0)+1;else if((H.unknownAnswers??0)===(X.unknownAnswers??0))V.rejectedStatus=G;return U.inFlight=V,B=V,W},a1(Z)),B}function DZ(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 i3(Z,$,X){if(!($||DZ(Z.primary,X)||DZ(Z.secondary,X)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function G6(Z,$){let X=Z[$];if(X===void 0||X===null)return;return typeof X==="string"?X:null}function k9(Z){if(!J3(Z))return;let $=G6(Z,"granted_at"),X=G6(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 r3(Z,$,X){let J;try{J=await Z(L9,{method:"GET",headers:V6($,n3,X),signal:AbortSignal.timeout(O9)})}catch{throw new k1("http_error","reset credit list request failed")}if(!J.ok)throw new k1("http_error",`reset credit list request failed: ${J.status}`,J.status);let z;try{z=await J.json()}catch{throw new k1("invalid_response","reset credit list response was not valid JSON",J.status)}if(!J3(z))throw new k1("invalid_response","reset credit list response was not an object",J.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((Q)=>{let B=k9(Q);return B===void 0?[]:[B]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function G3(Z){return[...Z].filter(K6).sort(($,X)=>Date.parse($.expiresAt)-Date.parse(X.expiresAt))[0]}function K6(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function P6(Z){return Z.filter(K6).length}function o3(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function f9(Z,$,X,J,z){let G;try{G=await Z(C9,{method:"POST",headers:{...V6($,U6,X),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:J}),signal:AbortSignal.timeout(T9)})}catch(U){return{kind:"ambiguous",raw:U}}let Q;try{Q=await G.text()}catch(U){return G.ok?{kind:"ambiguous",raw:U}:{kind:"http_error",raw:U,status:G.status}}let B=Q,W=!1;try{B=JSON.parse(Q),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:B,status:G.status};if(!W||!J3(B)||!o3(B.code))return{kind:"ambiguous",raw:B};return{kind:B.code,raw:B}}function Q6(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 B6(){throw new n("expired_unreconciled","the previous reset attempt outcome is unknown")}function W6(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 h9(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(X3(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 v9(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 L6(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,z=X.accountKey==="main"?void 0:J,G=await R9(Z,$.accountKey);if(G.kind==="corrupt"){if(G=await E9(Z,$.accountKey),G.kind==="corrupt")return W6(X,G.beforeState)}if(G.kind==="cooldown")Q6(G);let Q;if(G.kind==="claim")Q=G.claim;else if(G.kind==="expired_unreconciled"&&($.retry||!j6(G.claim.inFlight,J))){if(!$.retry)B6();Q=G.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),r3(Z.fetchImpl,X.accessToken,z)]),Y=i3(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!Y.ok)throw new n("not_exhausted",Y.reason);if(!G3(D.credits))throw new n("no_eligible_credit","no eligible reset credit was returned");let q=await I9(Z,$.accountKey,D.credits,J);if(q.kind==="corrupt")return W6(X,q.beforeState);if(q.kind==="cooldown")Q6(q);if(q.kind==="expired_unreconciled")B6();if(q.kind!=="claim")throw new n("no_eligible_credit","no eligible reset credit was available while claiming");Q=q.claim}S9(Q.inFlight,J);let B=await f9(Z.fetchImpl,X.accessToken,z,Q.inFlight.creditId,Q.inFlight.redeemRequestId),W,U=!1;try{W=await b9(Z,$.accountKey,Q.inFlight,B,J)}catch{U=!0}let H=U&&o3(B.kind),V=X3(B)&&!U&&W?.rejectedStatus!==void 0;return{target:X,selectedCredit:Q.selectedCredit,beforeState:G.beforeState,outcome:B,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.":X3(B)&&!V?v9(U,W):h9(B),...V?{refused:!0}:{},...H?{finalizeStateWriteFailed:!0}:{}}}async function C6(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 _6(Z,$){let X=[Z];if($.findings.length===0)return X.push("No problems found."),X;for(let J of $.findings){let z=J.repair?" (repair available)":"";X.push(`- ${J.message}${z}`)}return X}async function T6(Z,$){let X={applied:[],declined:[],failed:[]};for(let J of $.findings){let z=J.repair;if(!z)continue;if(!await Z.confirm(`Apply repair: ${z.label}?`)){X.declined.push(J);continue}try{await z.apply(),X.applied.push(J)}catch(G){X.failed.push({finding:J,error:G}),Z.print(`Repair failed: ${z.label}: ${G instanceof Error?G.message:String(G)}`)}}return X}function t3(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 C6(Z.checks);for(let Q of _6($,J))X.print(Q);let z=J.findings.filter((Q)=>Q.repair);if(z.length===0){if(J.findings.length>0)X.print("No repairs are available.");return}let G=await T6(X,J);X.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{spawn as g9}from"node:child_process";function A6(Z,$=process.platform,X=g9){try{if($==="win32"){let z=`Start-Process '${Z.replaceAll("'","''")}'`,G=X("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",Buffer.from(z,"utf16le").toString("base64")],{stdio:"ignore",windowsHide:!0});return G.on("error",()=>{}),G.unref(),G.pid!==void 0}let J=X($==="darwin"?"open":"xdg-open",[Z],{stdio:"ignore"});return J.on("error",()=>{}),J.unref(),J.pid!==void 0}catch{return!1}}function O6(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 Q3(Z,$){let X=new AbortController,J=await Z.begin({headless:!1,signal:X.signal});J.completion.catch(()=>{}),O6($,J);let z=!1;try{z=await(Z.openBrowser??A6)(J.url)!==!1}catch{z=!1}if(!z)X.abort(),$.print("Could not open a browser. Switching to device authorization."),$.print(""),J=await Z.begin({headless:!0}),O6($,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 e3(Z){let $=Z.toString(),X=[];for(let J=0;J<$.length;){let z=$[J];if(z==="\x1B"){let G=$.slice(J,J+3),Q=G[1]==="["||G[1]==="O"?G[2]:void 0;if(Q&&"ABCD".includes(Q)){let W={A:"up",B:"down",C:"right",D:"left"}[Q];if(W)X.push(W);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(z==="\r"||z===`
3
+ `)X.push("enter");else if(z==="\x03")X.push("escape");else if(z&&z>=" ")X.push("char");J+=1}return X}var S6=`${String.fromCharCode(27)}\\[[0-9;]*m`,x9=new RegExp(S6,"g"),m9=new RegExp(`^${S6}`);function R6(Z){return Z.replace(x9,"")}function f1(Z,$){if($<=0)return"";if(R6(Z).length<=$)return Z;let X=$>=3?"...":".".repeat($),J=Math.max(0,$-X.length),z="",G=0,Q=0;while(G<Z.length&&Q<J){if(Z[G]==="\x1B"){let B=Z.slice(G).match(m9);if(B){z+=B[0],G+=B[0].length;continue}}z+=Z[G],G+=1,Q+=1}return z.includes("\x1B[")?`${z}${S.reset}${X}`:z+X}function Z4(){return{input:process.stdin,output:process.stdout,signals:process}}function h1(Z){return Z.input.isTTY===!0}function $4(Z,$=""){Z.output.write(`${$}
4
+ `)}var w9=50;function u9(Z){if(Z==="red")return S.red;if(Z==="cyan")return S.cyan;return""}async function i1(Z,$,X){if(!h1(Z))throw Error("Interactive select requires a TTY terminal");if($.length===0)throw Error("No menu items provided");let{input:J,output:z,signals:G}=Z,Q=0,B=null,W=!1,U=0,H=()=>{let V=z.columns??80,j=z.rows??24,D=U;if(X.clearScreen)z.write(S.clearScreen+S.moveTo(1,1));else if(D>0)z.write(S.up(D));let Y=0,q=(C)=>{z.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}${f1(X.message,Math.max(1,V-4))}`),X.subtitle)q(`${S.dim}│${S.reset}`),q(`${S.cyan}◆${S.reset} ${f1(X.subtitle,Math.max(1,V-4))}`),q("");for(let C of F)q(`${S.cyan}│${S.reset} ${f1(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=u9(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=f1(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}${f1(`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(W)return;if(W=!0,B)clearTimeout(B);J.removeListener("data",F);try{J.setRawMode(j),J.pause(),z.write(S.show)}catch{}G?.removeListener("SIGINT",q),G?.removeListener("SIGTERM",q)},Y=(N)=>{D(),V(N)},q=()=>Y(null),F=(N)=>{for(let L of e3(N)){if(W)break;if(B)clearTimeout(B),B=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":B=setTimeout(()=>Y(null),w9);break;default:break}}};G?.once("SIGINT",q),G?.once("SIGTERM",q);try{J.setRawMode(!0)}catch{D(),V(null);return}J.resume(),z.write(S.hide),H(),J.on("data",F)})}async function X4(Z,$,X=!1){if(!h1(Z))return!1;return await i1(Z,X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function E6(Z){let $=h1(Z);return{terminal:Z,interactive:$,print:(X)=>$4(Z,X),confirm:(X,J)=>X4(Z,X,J),select:async(X,J)=>$&&X.length>0?i1(Z,X,J):null}}function p9(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 FZ(Z){let $=Z.terminal??Z4(),X=E6($);if(!X.interactive)return p9(X,Z);if(Z.actions.length===0)return X.print("No actions are available."),{status:"cancelled"};let J=await i1($,Z.actions.map((z)=>({label:z.label,value:z,color:z.destructive?"red":"cyan",...z.hint?{hint:z.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(z){return X.print(`${J.label} failed: ${z instanceof Error?z.message:String(z)}`),{status:"failed",action:J.id,error:z}}}var b6="disabled from the auth menu",I6=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 l9(Z){let{rows:$}=await Y1(Z);return $.some((X)=>X.credential!==void 0)}function G4(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 d9(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,I6).map((J)=>`${J.id}: ${G4(J)}`),X=Z.rows.length-I6;if(X>0)$.push(`... and ${X} more`);return $}function c9(Z){return Z instanceof Error?Z.message:String(Z)}async function Q4(Z,$,X){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((J)=>({label:J.id,value:J,hint:G4(J)})),{message:X})}function s9(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 z=`account-${J}`;if(!X.has(z))return z}}function y6(Z,$=Date.now()){let X=O1(Z.quota)?U1(Z.quota):void 0,J=B3(X,{now:$,form:"full"});return(J.length>0?J:[W1(X,{now:$})]).map((z)=>` ${z}`)}function k6(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 Q3(X,$),{rows:z}=await Y1(Z.store),G=(Z.newAccountId??s9)(J,z),Q=await Z.store.add({id:G,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 f6(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),z=await Q4($,J,"Re-authenticate which account?");if(!z)return;let G=await Q3(X,$);if(G.identity!==void 0&&z.identity!==void 0&&G.identity!==z.identity){$.print(`That sign-in is a different account from ${z.id}; nothing was changed. Use Add account to add it.`);return}let Q=G.identity??z.identity;await Z.store.replace(z.id,G.credential,Q!==void 0?{identity:Q}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${z.id}.`)}}}function h6(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function v6(Z){return Z instanceof E&&Z.kind==="row-protected"?Z.message:void 0}function g6(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:X}=await Y1(Z.store),J=await Q4($,X,"Remove which account?");if(!J)return;if(!await $.confirm(`Remove account ${J.id}?`)){$.print("Cancelled; nothing was changed.");return}try{await Z.store.remove(J.id,h6(Z))}catch(z){let G=v6(z);if(G===void 0)throw z;$.print(`Account ${J.id} was kept: ${G}`);return}$.print(`Removed account ${J.id}.`)}}}function J4(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 Q4($,X,"Enable or disable which account?");if(!J)return;let z=Z.extraLocks?{extraLocks:Z.extraLocks}:{};if(J.enabled){await Z.store.disable(J.id,Z.disableReason??b6,z),$.print(`Disabled account ${J.id}.`);return}try{await Z.store.enable(J.id,z)}catch(G){if(G instanceof E&&G.kind==="duplicate-identity"){$.print(`Account ${J.id} stays disabled: another enabled account is the same provider account.`);return}throw G}$.print(`Enabled account ${J.id}.`)}}}function x6(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}: ${G4(J)}`)}}}function z4(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,z=Z.pollQuota;if(z)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 B=await z(Q);await Z.store.recordQuota(Q.id,{credentialEpoch:Q.credentialEpoch,...Q.identity!==void 0?{identity:Q.identity}:{}},B)}catch(B){J.set(Q.id,c9(B))}}let G=await Y1(Z.store);if(G.rows.length===0)$.print("No accounts yet.");for(let Q of G.rows){$.print(`${Q.id}:`);let B=J.get(Q.id);if(B)$.print(` quota check failed: ${B}`);for(let W of y6(Q,(Z.now??Date.now)()))$.print(W)}}}}function m6(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=[],z=[];for(let G of X.rows)try{await Z.store.remove(G.id,h6(Z)),J.push(G.id)}catch(Q){let B=v6(Q);if(B===void 0)throw Q;z.push(`${G.id} (${B})`)}if($.print(`Deleted ${J.length} account(s).`),z.length>0)$.print(`Kept: ${z.join(", ")}.`)}}}async function B4(Z){return w6(Z,await Z.custody?.()===!0)}function w6(Z,$){let X=Z.doctor?.length?[t3({checks:Z.doctor})]:[],J=[...Z.extraActions??[]];if($)return[x6(Z),J4(Z),z4(Z),...X,...J];return[...Z.login?[k6(Z),f6(Z)]:[],g6(Z),J4(Z),z4(Z),...X,...J,m6(Z)]}async function a9(Z){let $=await Z.custody?.()===!0,X=w6(Z,$),[J,z]=await Promise.all([Y1(Z.store),Z.status?.()??[]]);return FZ({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...z,...d9(J)],actions:X,...Z.terminal?{terminal:Z.terminal}:{}})}function u6(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function p6(Z){return Z!==void 0}function n9(Z){return async($)=>{if(!p6($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),u6()}}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 W3(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."),$6)})])}finally{clearTimeout($)}}function j1(Z){return Z.email||Z.label||Z.routeId}function l6(Z,$){let X=U1(O1(Z.quota)?Z.quota:void 0),J=B3(X,{now:$});return(J.length>0?J:[W1(X,{now:$})]).map((z)=>` ${z}`)}var MZ="Accounts are managed in the vault with ck. Disconnect to use local accounts.",r1="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function d6(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 i9(Z,$){let X=await W3($),J=await i($),{status:z}=J,G=H1(J)?void 0:await Z.store.read(),Q=await B4(Z),B=new Set(["check-quotas",...(Z.extraActions??[]).map((H)=>H.id)]),W=Q.filter((H)=>!H1(J)||B.has(H.id)).map((H)=>({...H,run:async(V)=>{if(!B.has(H.id)&&H1(await i($))){V.print(r1);return}await $.authority(),await H.run(V)}})),U=W.find((H)=>H.id==="check-quotas");if(U)U.run=async(H)=>{await W3($);let V=await i($),j=H1(V)?void 0:await Z.store.read();if(!j)H.print(MZ);else if(j.status!=="ready")H.print("The local account store could not be read.");else for(let q of j.rows){H.print(d6(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 l6(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 l6({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 FZ({title:Z.title,subtitle:"Select an account action",status:[...await Z.status?.()??[],...X?[`Last error: ${X}`]:[],...z.lastError?[`Claustrum vault unreachable: ${z.lastError}`]:[],...z.accounts.map((H)=>`Vault ${j1(H)}: ${H.enabled?`enabled (${H.state})`:"declined"}`),...!G?[MZ]:G.status==="ready"?G.rows.map((H)=>d6(H)):["The local account store could not be read."]],actions:W,...Z.terminal?{terminal:Z.terminal}:{}})}function c6(Z){return m(Z)?{...Z}:{}}function W4(Z,$){let X=O1($)?s6($.credits):void 0;return X?`${Z} · prepaid ${X}`:Z}function n6(Z,$){return{...Z,sections:Z.sections.map((X)=>X.id!=="quota"?X:{...X,items:X.items.map((J)=>J.detail===void 0?J:{...J,detail:W4(J.detail,$.get(J.id))})})}}function U3(Z,$,X,J){let z=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,...z,run:async({values:G,invocation:Q})=>{let B=await Z.apply({command:Z.command,sectionId:$,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},Q);return{ok:B.ok,text:B.text,...B.code?{code:B.code}:{}}}}}function U4(Z,$){return new Proxy(Z,{get(X,J){if(J==="read")return async()=>{let G=await X.read();if(G.status!=="ready")return G;let Q={...G,rows:G.rows.map((U)=>({...U,label:U.label??U.id}))};if(!$)return Q;let B=await i($);if(!H1(B))return Q;let W=[...B.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{...G,rows:W}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!$)return G;let Q=await i($),B=c6(G.settings.killswitch);if(!H1(Q)||!G.settings.killswitch)return G;let W=c6(B.accounts);for(let U of Q.status.accounts)W[U.routeId]=NZ({version:1,accounts:[],...G.settings},U.routeId);return{...G,settings:{...G.settings,killswitch:{...B,accounts:W}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function V4(Z,$,X={}){let J=y1(Z),z=(U)=>y1({command:Z.command,title:Z.title,store:U4(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}:{}}),G=async(U,H)=>{let V=await i($),j=H1(V),D=a6(V.status.accounts.map((T)=>({id:T.routeId,credentialId:T.credentialId}))),Y=j?z(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)=>U3(Y,U,R,T.id))})),actions:F.actions.map((T)=>U3(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)=>W1(U1(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"}): ${W4(T(R,"compact"),R.quota)}`),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:W4(T(R,"full"),R.quota),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)=>U3(Y,U,b,T.id))}}),M=F.actions.filter((T)=>U==="limits"||U==="routing"&&T.id==="mode").map((T)=>U3(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`,MZ]:[...F.lines,...A?["No default vault account, so this mode orders like Ordered"]:[]],items:_,actions:M}},Q=y1({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(U)=>G("accounts",U)},quota:{title:"Quota",build:(U)=>G("quota",U)},routing:{title:"Routing",build:(U)=>G("routing",U)},limits:{title:"Limits",build:(U)=>G("limits",U)}},extras:Z.extras?.map((U)=>U.id!=="reset"?U:{...U,build:async(H)=>{let V=await i($);if(H1(V))return{lines:[MZ]};return U.build(H)}})}),B=async()=>{if(!H1(await i($)))return{menu:J,error:void 0};let U=X.refresh===!1?void 0:await W3($);return{menu:Q,error:U}},W=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)=>W(await B(),U),apply:async(U,H)=>{let V=await B(),{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 W(V,H),ok:!1,code:"vault-local-action",text:r1};if(X.refuseApply)return{...await W(V,H),ok:!1,...X.refuseApply};return j.apply(U,H)}}}var PZ="openai",e6="OpenAI accounts",A1="main",Z7="that account is already your main account, so it was not added again",o=J1("commands"),$7=new Set(["__proto__","constructor","prototype"]);function r9(Z,$){let X={version:1,accounts:[],killswitch:Z},J=m(Z.accounts)?Object.keys(Z.accounts):[],z={};for(let B of new Set([A1,...$,...J])){if($7.has(B))continue;let W=NZ(X,B===A1?void 0:B);z[B]={primary:W.primary,secondary:W.secondary}}let G=NZ(X,void 0),Q={...Z};return delete Q.main,Q.accounts=z,Q.defaults={primary:G.primary,secondary:G.secondary},Q.schema=LZ,Q}function o9(Z,$){let X=m(Z.accounts)?{...Z.accounts}:{};for(let z of new Set([A1,...$])){if($7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:KZ.primary,secondary:KZ.secondary}}let J=m(Z.defaults)?Z.defaults:{primary:KZ.primary,secondary:KZ.secondary};return{...Z,accounts:X,defaults:J,schema:LZ}}function i6(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!==LZ)Z.killswitch=r9(J,$),X=!0;return X}async function r6(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((X)=>X.id):[]}function j4(Z){let $=async()=>{let J=await Z.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return i6(z,await r6(Z)),{...J,settings:z}},X=async(J,z)=>{let G=await r6(Z);return Z.updateSettings(async(Q)=>{i6(Q,G);let B=await J(Q)??Q;if(m(B.killswitch)&&B.killswitch.schema!==LZ)B.killswitch=o9(B.killswitch,G);return B},z)};return new Proxy(Z,{get(J,z){if(z==="readSettings")return $;if(z==="updateSettings")return X;let G=Reflect.get(J,z,J);return typeof G==="function"?G.bind(J):G}})}function t9(Z,$){let X=(W,U)=>$.rowLocks?$.rowLocks(W):U,J=(W,U)=>{let H=X(W,U?.extraLocks);return{...U??{},...H?{extraLocks:H}:{}}},z=(W,U,H,V)=>Z.replace(W,U,H,J(W,V)),B={add:async(W,U)=>{let H=await Z.read(),j=(H.status==="ready"?H.rows:[]).filter((F)=>F.type==="oauth"&&!F.invalid),D=W.identity?j.find((F)=>F.identity===W.identity):void 0;if(D?.id===A1)throw new a("main-account",Z7);let Y=D??j.find((F)=>F.id===W.id&&F.id!==A1);if(!Y||W.credential.type!=="oauth")return Z.add(W,U);let q=await z(Y.id,W.credential,W.identity!==void 0?{identity:W.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:z,enable:(W,U)=>Z.enable(W,J(W,U)),disable:(W,U,H)=>Z.disable(W,U,J(W,H)),remove:(W,U)=>Z.remove(W,J(W,U))};return new Proxy(Z,{get(W,U){if(Object.hasOwn(B,U))return B[U];let H=Reflect.get(W,U,W);return typeof H==="function"?H.bind(W):H}})}async function Uz(Z,$,X){await j4(Z).updateSettings((J)=>{X(J);return},$?{extraLocks:$}:{})}var e9=["version","accounts","commonAuthPool"];function Vz(Z,$){return async(X)=>{let J;if(await j4(Z).updateSettings((z)=>{let G={...z,version:1,accounts:[]},Q=X(G)??G;J=Q;let B={...Q};for(let W of e9)delete B[W];return B},$?{extraLocks:$}:{}),!J)throw Error("the settings write did not run");return J}}var Z$="migration";function o6(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:PZ,title:e6,sections:[{id:Z$,slot:"extra",title:"Accounts are moving",lines:$,items:Z.map((J,z)=>({id:`blocker-${z}`,label:J.pid==="unknown"?"processes that could not be read":`pid ${J.pid}`,detail:`version ${J.version}`,actions:[]})),actions:[]}]};return H4(X)}var $$=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function X$(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if($$.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function Y4(Z,$,X){if(Array.isArray(Z))return Z.map((z,G)=>Y4(z,`${$}[${G}]`,X));if(!m(Z))return Z;let J={};for(let[z,G]of Object.entries(Z)){if(X$(z)){X.push(`${$}.${z}`);continue}J[z]=Y4(G,`${$}.${z}`,X)}return J}function H4(Z){let $=[],X=Y4(Z,"menu",$);if($.length>0)o.warn("credential-shaped field stripped before RPC",{fields:$});return X}function J$(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 z$(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,z=X.headless===!0,G=await Z.begin({...J!==void 0?{label:J}:{},headless:z}),Q=z?`Open this verification URL:
6
+
7
+ ${G.url}
8
+
9
+ Then enter the code: ${G.instructions.match(/Enter code: (.+)/)?.[1]??G.instructions}
10
+
11
+ The account is added when you finish.`:`Open this URL and complete sign-in:
12
+
13
+ ${G.url}
14
+
15
+ ${G.instructions}
16
+
17
+ The account is added when you finish.`,B=G.completion.then(async(W)=>{if($&&await $.authority()!=="local")throw new a("vault-local-action",r1);let U=await Z.mainIdentity?.();if(W.id===A1||W.accountId&&U&&W.accountId===U)throw o.warn("account add rejected (main identity)",{id:W.id}),new a("main-account",Z7);return o.info("account added",{id:W.id}),J$(W)});return{status:"pending",message:Q,completion:B}}}}function Yz(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:z})=>{if(!z.sessionId)return"No current session.";return await Z.clearPin?.(z.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 Hz(Z){let{vault:$}=Z;return{id:"vault",title:"Vault",build:async()=>{let X=await $.status(),J=await $.authority()!=="local",z=$.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}`,J6(X.host,X.name,X.enrollment),...$3(X.name,X.enrollment),...J?[X.accounts.length===0?oZ(X.name,$.grantReach()):`The vault serves ${X.accounts.length} OpenAI account${X.accounts.length===1?"":"s"}; ${z} 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((G)=>({id:G.routeId,label:j1(G),group:"Accounts",status:G.enabled?G.state:"disabled",detail:[G.credentialType==="api_key"?"API key":"login",G.state==="active"?"active":`vault state ${G.state}`,G.enabled?"enabled":"disabled here"].join(", "),actions:[G.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(G.routeId),await Z.changed?.(),`${j1(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(G.routeId),await Z.changed?.(),`${j1(G)} 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:G})=>{let Q=await $.connectStep();if(Q.state!=="pending"&&Q.state!=="busy")return await Z.changed?.(),a3($,Q);return $.waitForApproval(Z.wait).then(async(B)=>{await Z.changed?.();let W=a3($,B);G.notify(W.text,W.ok?"info":"warning")}).catch((B)=>{G.notify(`Connecting to the vault failed: ${B instanceof Error?B.message:String(B)}`,"error")}),{ok:!0,text:[...$3($.name,Q),"Waiting for the approval; you are told here when it lands."].join(`
18
+ `)}}}]}}}}async function t6(Z,$,X){if(!N1($))return r($,"invalid_account_key","That account cannot take a reset credit.");let J;try{let z=(await Z.loadAccounts({configPath:Z.configPath,statePath:Z.statePath}))?.reset?.[$];if(X||z&&Object.hasOwn(z,"inFlight"))J=(await Z.resolveResetTarget($)).chatgptAccountId;else{let Q=await J7($,Z);if(!Q.eligible)return r($,"not_eligible",z7(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 G=await L6({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)=>qZ({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:G.outcome.kind}),G7(G,Z,J)}catch(z){let G=V$($,z,J);return o.info("reset redemption outcome",{accountKey:$,code:G.code}),G}}function jz(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===A1?"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 J7($,Z);return{ok:X.eligible,text:`${U$(X)}
19
+
20
+ ${z7(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 t6(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 t6(Z,$,!0);return{ok:X,text:J}}}]}))})}}var G$=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],Q$=["primary","secondary"];function qz(Z){let $=new Set(Z.unavailableSections),X=(U)=>({title:U,build:async()=>({lines:["Not available on OpenCode 2 yet."]})}),J=[...Z.extras??[]];if($.has("reset")){let U={id:"reset",...X("Reset credits")},H=J.findIndex((V)=>V.id==="reset");if(H<0)J.unshift(U);else J[H]=U}let z={command:PZ,title:e6,store:U4(j4(t9(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:z$(Z.login,Z.vault)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:G$,formerMainId:A1},limits:{labels:Q$},...$.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}:{}},G=Z.vault?V4(z,Z.vault,{refresh:!Z.readOnly,...Z.readOnly?{refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}:{}}):y1(z),Q=Z.vault?V4(z,Z.vault,{refresh:!1,refuseApply:{code:"unavailable",text:"Not available on OpenCode 2 yet."}}):void 0,B=(U)=>{let{sessionId:H}=U,V=U.notify.bind(U);return{...H!==void 0?{sessionId:H}:{},notify:V}},W=async(U)=>{if(Z.vault&&await Z.vault.authority()!=="local")return U;let H=await Z.store.read().catch(()=>{return});if(H?.status!=="ready")return U;return{...U,menu:n6(U.menu,new Map(H.rows.map((V)=>[V.id,V.quota])))}};return{command:PZ,async open(U){let H=B(U),V=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(V&&!V.migrated)return{command:PZ,menu:o6(V.blockers)};let j=await G.open(H);return W({...j,menu:H4(j.menu)})},async apply(U,H){let V=B(H),j=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(j&&!j.migrated)return{command:PZ,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:o6(j.blockers)};if(Z.readOnly&&Z.vault)return G.apply(U,V);if(Z.readOnly||Z.allowAction&&!Z.allowAction(U)||$.has(U.sectionId)){if(Q)return Q.apply(U,V);return{...await G.open(V),ok:!1,code:"unavailable",text:"Not available on OpenCode 2 yet."}}let D=await G.apply(U,V);if(D.ok)await Z.afterApply?.();return W({...D,menu:H4(D.menu)})}}}function X7(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((X)=>X!==void 0);return $.length>0?Math.max(...$):void 0}function B$(Z,$){let X=[Z.primary,Z.secondary].filter((z)=>z!==void 0),J=X.filter((z)=>DZ(z,$));return(J.length>0?J:X).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function W$(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)=>!DZ(J,$))}async function J7(Z,$){let X;try{X=await $.resolveResetTarget(Z);let J=X.accountKey==="main"?void 0:X.chatgptAccountId,[z,G]=await Promise.all([qZ({accessToken:X.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:X.chatgptAccountId}),r3($.fetchImpl,X.accessToken,J)]),Q=G3(G.credits),B=P6(G.credits),W=G.availableCount??z.resetCreditsAvailable??(B>0?B:void 0),U=z.resetCreditsApplicable,H=i3(z,$.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:X7(z),resetTime:B$(z,$.now()),availableCount:W,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 U$(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 z7(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 V$(Z,$,X){if($ instanceof n){let z={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
+ ${z[$.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 k1)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 G7(Z,$,X){let{accountKey:J}=Z.target,z=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return r(J,z,`## Reset credit result
36
+
37
+ Account: **${Z.target.label}** (\`${J}\`)
38
+
39
+ The server outcome recorded as \`${z}\`, 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(z==="reset"||z==="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 B=!Q.ok&&Q.error!==void 0;if(B)o.warn("reset quota re-check failed",{accountKey:J,error:Q.error});let W=J==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(J),U=Q.ok&&W$(W?.quota,$.now()),H=W?.quota.resetCreditsApplicable,V=U?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${z}\`).`,j=B?`
40
+
41
+ quota re-check failed — see log.`:"";return r(J,z,`## Reset credit result
42
+
43
+ Account: **${Z.target.label}** (\`${J}\`)
44
+
45
+ Code: \`${z}\`
46
+
47
+ ${V}${j}${H===void 0?"":`
48
+
49
+ Remaining applicable credits: **${H}**`}`,{verifiedFresh:U,afterUsedPercent:X7(W?.quota??{}),remainingCredits:H})}if(z==="ambiguous_local")return r(J,z,`## Reset credit result
50
+
51
+ Account: **${Z.target.label}** (\`${J}\`)
52
+
53
+ Code: \`${z}\`
54
+
55
+ ${Z.retrySafety}`,{retryGuidance:Z.retrySafety});if(z==="ambiguous"||z==="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,z,`## Reset credit result
56
+
57
+ Account: **${Z.target.label}** (\`${J}\`)
58
+
59
+ The redemption outcome is unknown (\`${z}\`).
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 G={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,z,`## Reset credit result
62
+
63
+ Account: **${Z.target.label}** (\`${J}\`)
64
+
65
+ Code: \`${z}\`
66
+
67
+ ${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}var q4=J1("quota"),Q7="the account holds a tombstone from the removed vault custody, not a credential";function Y$(Z){return Z?.status===401}async function Lz(Z,$={}){let X=Z.whamFn;if(!X)throw Error("whamFn is required for refreshAllQuota");let J=[],z=Z.logger??q4,G=(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)z.debug("quota refresh succeeded",q);else z.warn("quota refresh failed",q)},Q=Z.skipFresherThanMs,B=!1,W;if(Q!==void 0)try{W=await Z.readSidebarState()}catch{}let U=new Map(W?.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(V7(Y)){if(D=Y7(V),!D)G({account:"main",ok:!1,error:CZ(Y)?Q7:"main account row is missing from the account pool"})}else if(Y.type==="oauth"){let q=W&&j!==void 0&&W.main.mainAccountId===j?W.main.quota:void 0;if(H(Z.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.checkedAt))G({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())G({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),B=!0,G({account:"main",ok:!0})}else if(!J.some((N)=>N.account==="main"))G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(Y){G({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)&&U7(V,Y)){if($.accountKey)G({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)G({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?W&&F!==void 0&&W.main.mainAccountId===F?W.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)){G({account:Y.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(Y.id,Y.access))){G({account:Y.id,ok:!0});continue}let M=Y.lastRefreshError;if(B7(M,Y.refresh,Z.now())){G({account:Y.id,ok:!1,error:W7(M,Z.now()),permanent:!0});continue}if(CZ(Y)){G({account:Y.id,ok:!1,error:Q7});continue}let C;try{C=q?await Z.fallbackManager.refreshAccount(Y,V,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(Y,V)}catch(T){q4.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()){G({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(!Y$(T))throw T;if(q4.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){G({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),B=!0,G({account:Y.id,ok:!0})}catch(L){G({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||B){let Y=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,Y)}return J}import{types as H$}from"node:util";var j$=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,q$=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function F7(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 D$(Z,$){if(!$)return Z;let X=Z.split($).join("[credential]"),J=$.replace(/\s/g,"");if(!J)return X;let z=X.replace(/\s/g,"");if(!z.includes(J))return X;let G=[];for(let W=0;W<X.length;W++){let U=X[W]??"";if(!/\s/.test(U))G.push(W)}let Q=[],B=0;for(let W=z.indexOf(J);W>=0;W=z.indexOf(J,W+J.length)){let U=G[W]??B,H=(G[W+J.length-1]??U)+1;Q.push(X.slice(B,U),"[credential]"),B=H}return Q.length?Q.join("")+X.slice(B):X}function H7(Z,$){let X=D$(Z,$);return D7(X).replaceAll("***REDACTED***","[credential]")}function o1(Z,$){let X=H7(Z,$),J=F7(X),z=H7(J,$);return z===J?X:z}function j7(Z){let $=/^(-?)(0|[1-9]\d*)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(Z);if(!$)return;let X=$[3]??"",J=($[2]??"")+X,z=0;while(J[z]==="0")z++;if(z===J.length)return"0";let G=J.length;while(J[G-1]==="0")G--;let Q=$[4]??"0",B=Q.startsWith("-")||Q.startsWith("+")?1:0;while(Q[B]==="0")B++;let W=Q.slice(B)||"0";if(W.length>16)return;let U=BigInt((Q.startsWith("-")?"-":"")+W)-BigInt(X.length)+BigInt(J.length-G);return`${$[1]}${J.slice(z,G)}e${U}`}function M7(Z,$){let X=$?j7($):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&&j7(J)===X||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===$)?'"[credential]"':J;let z=F7(J.slice(1,-1)),G=o1(z,$);return G===z?J:JSON.stringify(G)})}function F4(Z,$){let X=M7(Z,$);try{return JSON.parse(Z),X}catch{return o1(X,$)}}var F$=16384,M$=65536,N$=[/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 K$(Z){try{let $=g(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let X=0,J,z=!0,G=!1,Q;for(let B of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let W=B[0];if(W==="{"||W==="["){X++;continue}if(W==="}"||W==="]"){X--;continue}if(X!==1)continue;if(W===","){z=!0,G=!1,J=void 0;continue}if(W===":"){G=!0;continue}if(z&&W.startsWith('"')){J=JSON.parse(W),z=!1;continue}if(G&&J==="request_id"&&!W.startsWith('"'))Q=W;G=!1}return Q}catch{return}}function P$(Z,$){let X=F4(Z,$);if(Buffer.byteLength(X,"utf8")<=M$)return X;let J=N$.flatMap((G)=>G.exec(X)?.[0]??[]);for(let G of["FreeUsageLimitError","GoUsageLimitError"])if(X.includes(G))J.push(G);let z={retry:J};try{let G=JSON.parse(X);if(g(G,"type")==="error")z.type="error";let Q=g(G,"error"),B={};for(let U of["code","type"]){let H=g(Q,U);if(typeof H==="string")B[U]=H.slice(0,256)}if(Object.keys(B).length)z.error=B;let W={};for(let U of["workspace","limitName"]){let H=g(g(G,"metadata"),U);if(typeof H==="string")W[U]=H.slice(0,256)}if(Object.keys(W).length)z.metadata=W}catch{}return JSON.stringify(z)}function V3(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let X=0;$&&X<16;X++){if(H$.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function g(Z,$){if(!V3(Z))return;let X=Object.getOwnPropertyDescriptor(Z,$);return X&&"value"in X?X.value:void 0}function _Z(Z,$){return o1(Z,$).slice(0,F$)}function t1(Z,$){let X=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!X)throw Error(`Missing native ${$} accessor`);return X}var L$=t1(DOMException.prototype,"message"),C$=t1(DOMException.prototype,"name");function D4(Z,$){let X=g(Z,"message"),J=g(Z,"name");if(V3(Z)&&Z instanceof DOMException)try{X=L$.call(Z),J=C$.call(Z)}catch{}let z=Error(_Z(typeof X==="string"?X:typeof Z==="string"?Z:"Provider request failed",$));for(let V of Object.getOwnPropertyNames(z))if(V!=="message")Reflect.deleteProperty(z,V);Object.defineProperty(z,"name",{value:typeof J==="string"?_Z(J,$):"Error",configurable:!0,writable:!0});let G=(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"?_Z(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))G(Z,z,V)}for(let V of["code","type","isRetryable"])G(Z,z,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"])G(j,D,q);let Y=g(j,"error");if(V3(Y)){let q=Object.create(null);for(let F of["type","code","message","resets_at","resets_in_seconds"])G(Y,q,F);D.error=q}if(Object.keys(D).length)Object.defineProperty(z,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]=_Z(D,$)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let B=g(Z,"responseBody");if(typeof B==="string")Object.defineProperty(z,"responseBody",{value:P$(B,$),enumerable:!0});let W=g(Z,"request_id"),U=g(Q,"x-request-id"),H=typeof W==="string"?W:typeof U==="string"?U:typeof B==="string"?K$(F4(B,$)):void 0;if(typeof H==="string")Object.defineProperty(z,"request_id",{value:_Z(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(z,j,{value:!0})}return z}function _$(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!j$.test(Z)&&!q$.test(Z)))return Z;let X;try{X=JSON.parse(Z)}catch{return Z}if(X?.type==="error"||X?.error||X?.response?.error)return M7(Z,$);return Z}var T$=t1(Response.prototype,"status"),O$=t1(Response.prototype,"statusText"),A$=t1(Response.prototype,"headers"),S$=t1(Response.prototype,"body"),R$=Response.prototype.text,q7=Headers.prototype.entries;async function Oz(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)+_$(N,$))};if(!V3(Z))throw Error("Invalid provider response");let J=T$.call(Z),z=A$.call(Z),G=S$.call(Z),Q=new Headers;for(let[Y,q]of q7.call(z))Q.append(Y,q);let B={status:J,statusText:o1(O$.call(Z),$),headers:Q};if(J<200||J>299){for(let[q,F]of q7.call(z)){if(o1(q,$?.toLowerCase())!==q){B.headers.delete(q);continue}try{B.headers.set(q,o1(F,$))}catch{B.headers.delete(q)}}B.headers.delete("content-length");let Y=await R$.call(Z);return new Response(F4(Y,$),B)}if(!G||X==="http")return Z;B.headers.delete("content-length");let W=ReadableStream.prototype.getReader.call(G),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 W.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(D4(q,$))}},async cancel(Y){try{await W.cancel(Y)}catch(q){throw D4(q,$)}finally{W.releaseLock()}}}),B)}catch(J){throw D4(J,$)}}function Rz(Z,$,X){let J=Z.get($.sessionId),z=new Set($.validPinnedAccountIds);if(J&&!$.excludeAccountIds.includes(J.accountId)&&N7(J,z,$.wireAccountIdByAccount[J.accountId])){if($.persist){let W=$.quotaCheckedAtByAccount[J.accountId];X($.sessionId,{accountId:J.accountId,inputBytes:$.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...W!==void 0?{quotaCheckedAt:W}:{}})}return{accountId:J.accountId}}let G=new Map(Object.entries($.quotaCheckedAtByAccount)),Q=K7(Z,G,$.sessionId),B=$.select(Q);if(!B)return;if($.persist){let W=$.wireAccountIdByAccount[B.accountId];X($.sessionId,{accountId:B.accountId,inputBytes:$.requestBytes,...W!==void 0?{wireIdentity:W}:{},...B.quotaCheckedAt!==void 0?{quotaCheckedAt:B.quotaCheckedAt}:{}})}return{accountId:B.accountId}}import{statSync as E$}from"node:fs";var _7=30000,I$=8,b$=1800000;function T7(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function kz(Z){try{let $=E$(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function fz(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function y$(Z,$){try{return P7(Z,$)}catch{return Z}}function hz(Z,$,X){let J=T7($);Z.set(J,[...Z.get(J)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:X}].slice(-I$))}function vz(Z,$,X){let J=Z;for(let z of $.get(T7(Z))??[]){if(!(X-z.observation.checkedAt<=b$)||z.credentialEpoch!==Z.credentialEpoch||z.identity!==Z.identity)continue;J={...J,quota:y$(J.quota,z.observation)}}return J}function gz(Z,$,X,J){let z=TZ(Z);if(typeof $?.status==="number"||L7($)){let Q=C7({error:$,now:X,refreshToken:Z,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:Q.nextRetryAt,tokenHash:z,retryCount:Q.retryCount}}return{nextRetryAt:X+_7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function xz(Z,$,X,J){let z=new Map;for(let G of Z){if(J(G,X))continue;let Q=$.get(G.id);z.set(G.id,Q&&Q.nextRetryAt>X?Q.nextRetryAt:X+_7)}return z}import{realpathSync as O7}from"node:fs";import{homedir as k$}from"node:os";import{basename as f$,dirname as h$,join as H3,resolve as E7}from"node:path";function v$(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return H3(process.env.XDG_CONFIG_HOME||H3(k$(),".config"),"opencode")}function I7(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||H3(v$(),S7)}function Y3(Z,$){let X=E7(Z);return $==="win32"||$==="darwin"?X.toLowerCase():X}function A7(Z){try{return O7.native(Z)}catch{try{return H3(O7.native(h$(Z)),f$(Z))}catch{return}}}function g$(Z,$,X=process.platform){if(Y3(Z,X)===Y3($,X))return!0;let J=A7(Z),z=A7($);return J!==void 0&&z!==void 0&&Y3(J,X)===Y3(z,X)}function x$(Z=I7()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(g$(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${E7(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}return R7(Z)}function DG(Z=I7()){return{configPath:Z,statePath:x$(Z)}}import{createHash as s$}from"node:crypto";import{readFileSync as a$}from"node:fs";import{readFile as n$}from"node:fs/promises";import{resolve as i$}from"node:path";import{createHash as m$}from"node:crypto";import{readFile as w$}from"node:fs/promises";import{homedir as u$}from"node:os";import{join as b7,resolve as p$}from"node:path";var l$="openai",y7=250,AZ="main-refresh";function N4(Z){if(typeof Z.access!=="string"||typeof Z.refresh!=="string")return;let $=Buffer.from(Z.access),X=Buffer.from(Z.refresh),J=(z)=>{let G=Buffer.alloc(4);return G.writeUInt32BE(z.length),G};return m$("sha256").update(J($)).update($).update(J(X)).update(X).digest("hex")}function x7(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 m7(Z){let $=x7(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function k7(Z){if(v1(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=x7(Z);if(!$)return{kind:"indeterminate"};return CZ($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function f7(Z){return Z.auth.get({path:{id:l$}})}async function h7(Z){return Object.keys(await Z.auth.all()).length>0}async function w7(Z){let $=await f7(Z.client);if($!==void 0)return k7($);let X=await h7(Z.client),J=Z.now();if(await Z.sleep(y7),Z.now()-J<y7)return{kind:"indeterminate"};let z=await f7(Z.client);if(z!==void 0)return k7(z);let G=await h7(Z.client);return X&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function j3(Z=process.env,$=u$()){let X=Z.XDG_DATA_HOME||b7($,".local","share");return b7(X,"opencode","auth.json")}function v1(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var v7=(Z)=>Z===void 0||typeof Z==="string";function d$(Z){if(!v1(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&&v7(Z.accountId)&&v7(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||v1(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 M4(Z,$=process.env){let X=$.OPENCODE_AUTH_CONTENT;if(X)try{let z=JSON.parse(X);return v1(z)?z:{}}catch{}let J;try{J=JSON.parse(await w$(Z,"utf8"))}catch{return{}}if(!v1(J))return{};return Object.fromEntries(Object.entries(J).filter(([,z])=>d$(z)))}function g7(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class q3 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function c$(Z){let $=Z.env??process.env,X=Z.path??j3($),J=new Map;return{path:p$(X),migrationDisabledReason:()=>g7($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await M4(X,$))[z.path.id];return J.set(z.path.id,JSON.stringify(G)),G},async all(){return M4(X,$)},async set(z){if(g7($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await M4(X,$))[z.path.id];if(OZ(z.body)&&(!J.has(z.path.id)||J.get(z.path.id)!==JSON.stringify(G)))throw new q3;let Q=await Z.set(z);if(v1(Q)&&"error"in Q&&Q.error!==void 0)throw Error(`OpenCode refused the write of its ${z.path.id} login: ${JSON.stringify(Q.error)}`);return Q}}}function _G(Z,$={}){let X=v1(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:c$({...$,set:(z)=>J.call(X,z)})}}var e1="openai",r$="common-auth-placeholder:v1:openai",SZ=Object.freeze({type:"oauth",access:"",refresh:r$,expires:0});function OZ(Z){if(!t(Z))return!1;return Z.type===SZ.type&&Z.access===SZ.access&&Z.refresh===SZ.refresh&&Z.expires===SZ.expires}var D3="openaiAuthPool",o$=120000,i7="pool-migration",t$="slot-transfer-origin-unknown",e$="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.",P3=Object.freeze({mainRefreshTtlMs:o$,fallbackTtlMs:a7,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function F3(Z,$,X){return Z.kind==="placeholder"&&!$&&!X.pending}class g1 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 Z0(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:{...P3,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:YZ({provider:e1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:N3,now:$,...Z.store}),onStep:async(X)=>{await Z.onStep?.(X)}}}async function $Z(Z){let $;try{$=await n$(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,z){let G=performance.now();for(;;){if(z?.aborted)throw new g1($);let Q=await R1({name:$,path:X,ttlMs:J,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(Q){if(!z?.aborted)return Q;throw await Q.release(),new g1($)}if(performance.now()-G>=Z.locks.timeoutMs)throw new g1($);await Z.sleep(Z.locks.retryMs)}}async function hG(Z,$,X={}){let J={...P3,...X},z=performance.now();for(;;){let G=await R1({name:AZ,path:Z,ttlMs:J.mainRefreshTtlMs,renew:J.renew,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}});if(G)try{return await $()}finally{await G.release().catch(()=>{})}if(performance.now()-z>=J.timeoutMs)throw new g1(AZ);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 z=await RZ(Z,"save",Z.paths.statePath,X);try{let G=await $Z(Z.paths.configPath);if(!await $(G))return;await b1(Z.paths.configPath,G,{beforeRename:async()=>{await J.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await J.release().catch(()=>{})}}function $0(Z){if(!t(Z))return;let{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:z}=Z,{credentialFingerprint:G,carryLegacyMain:Q,recordedAt:B,identity:W}=Z;if(typeof $!=="string"||!$)return;if(X!=="add"&&X!=="rotate"&&X!=="replace")return;if(J!==null&&typeof J!=="string")return;if(typeof z!=="string")return;if(typeof G!=="string")return;return{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:z,credentialFingerprint:G,...typeof W==="string"&&W?{identity:W}:{},carryLegacyMain:Q===!0,recordedAt:typeof B==="number"?B:0}}function r7(Z,$){if(!t(Z)||!$)return!1;return G1(Z).pending?.credentialFingerprint===Z1({type:"oauth",refresh:$})}function vG(Z,$){let X;try{X=JSON.parse(a$(Z,"utf8"))}catch{return!1}return r7(X,$)}class X0 extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var J0=600000;async function gG(Z,$,X={}){let J=X.now??Date.now,z=(W)=>{let U=G1(W).pending;return U&&r7(W,$)&&J()-U.recordedAt>=J0?U:void 0},G=z(await $Z(Z.configPath));if(!G)return!1;let Q={...P3,...X.legacyLocks},B=await R1({name:i7,path:Z.configPath,ttlMs:Q.mainRefreshTtlMs});if(!B)return!1;try{let W=await $Z(Z.configPath),U=G1(W).migratedAt!==void 0,H=await YZ({provider:e1,configPath:Z.configPath,statePath:Z.statePath,quota:N3,now:J}).read();if(U&&H.status!=="ready")return!1;let V;if(H.status==="ready"){let D=H.rows.find((q)=>q.id===G.rowId&&!q.invalid),Y=D?.fingerprint??null;if(U&&D&&Y===G.credentialFingerprint)return!1;if(D&&Y!==G.credentialFingerprint&&Y!==G.rowFingerprint)V=X.slotAccess!==void 0?N4({type:"oauth",access:X.slotAccess,refresh:$}):G.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=z(D);if(!q||q.recordedAt!==G.recordedAt)return!1;let{pending:F,...N}=Y;return L3(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:G.rowId,recordedAt:G.recordedAt});return j}finally{await B.release().catch(()=>{})}}function G1(Z){let $=Z[D3];if(!t($))return{};let X=$0($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...X?{pending:X}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function L3(Z,$){let J={...t(Z[D3])?Z[D3]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete J[z];Object.assign(J,$),Z[D3]=J}function z0(Z){let $=Z?eZ(Z):void 0;return $?Z3($):void 0}function G0(Z){let $=N4({type:"oauth",...Z}),X=z0(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:Z1({type:"oauth",refresh:Z.refresh}),...X?{identity:X}:{}}}function o7(Z){if(OZ(Z))return{kind:"placeholder",...t(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=m7(Z);if(!$?.refresh.trim())return{kind:"empty"};return G0($)}async function IZ(Z){let $=await w7({client:{auth:{get:(X)=>Z.slot.get(X),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return o7($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function xG(Z,$){if(!OZ($))return!1;let X=await $Z(Z.configPath),J=await YZ({provider:e1,configPath:Z.configPath,statePath:Z.statePath,quota:N3}).read();if(J.status==="error")return!1;let z=J.status==="ready"?J.rows.some((G)=>G.id==="main"):J.roster.some((G)=>t(G)&&G.id==="main");return F3({kind:"placeholder"},z,G1(X))}async function Q0(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let X=await IZ(Z);if(X.kind!=="real")return X;if(!await t7(Z,X.credential.refresh))return X;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function t7(Z,$){let X=await K3(Z.paths),J=X?.refresh?.mainRefreshLeaseUntil;return Boolean(J&&J>Z.now()&&X?.refresh?.mainRefreshLeaseTokenHash===TZ($))}function B0(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function W0(Z,$,X,J,z){let G=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,...G,carryLegacyMain:Z==="migrate"&&Q.id==="main"};let B=$.find((H)=>H.id==="main");if(!B||!B.invalid&&!B.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,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,...G,carryLegacyMain:Z==="migrate"&&H.id==="main"}}let W=new Set($.map((H)=>H.id));return{rowId:J??(X.identity&&B0(X.identity)&&!W.has(X.identity)?X.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function U0(Z,$,X,J,z,G,Q){let B=$.pending;if(B){let W=X.find((V)=>V.id===B.rowId&&!V.invalid),U=W?.fingerprint??null,H=J.kind==="real"&&J.fingerprint===B.slotFingerprint;if(W&&U===B.credentialFingerprint)return{kind:"finish",record:B};if((W||B.rowFingerprint===null)&&U===B.rowFingerprint)return H&&J.kind==="real"?{kind:"transfer",record:B,credential:J.credential,fresh:!1}:{kind:"drop-record"};if(!W)return{kind:"drop-record"};return H?{kind:"ambiguous",record:B}:{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:{...W0(Z,X,J,z,Q),slotFingerprint:J.fingerprint,credentialFingerprint:J.credentialFingerprint,recordedAt:G},credential:J.credential,fresh:!0}}async function V0(Z,$,X){let J={type:"oauth",access:X.access,refresh:X.refresh,...X.expires!==void 0?{expires:X.expires}:{}},z=$.identity?{identity:$.identity}:{},G={extraLocks:M3(Z.paths,$.rowId,Z.locks)};if($.operation==="add")await Z.store.add({id:$.rowId,credential:J,...z},G);else if($.operation==="replace")await Z.store.replace($.rowId,J,z,G);else{let Q=await Z.store.read(),B=Q.status==="ready"?Q.rows.find((W)=>W.id===$.rowId):void 0;await Z.store.rotate($.rowId,J,B?.identity===void 0?z:{},G)}}async function Y0(Z,$){let X=await Z.store.read();if(X.status!=="ready")return;let J=X.rows.find((z)=>z.id===$.rowId&&!z.invalid);return J?.fingerprint===$.credentialFingerprint?J:void 0}function H0(Z,$){let X=[],J=[["primary",Z.primary],["secondary",Z.secondary]],z=0;for(let[B,W]of J){if(!W||!Number.isFinite(W.checkedAt)||!Number.isFinite(W.usedPercent))continue;z=Math.max(z,W.checkedAt),X.push({checkedAt:W.checkedAt,readings:[{label:B,usedPercent:W.usedPercent,...typeof W.resetsAt==="string"?{resetsAt:W.resetsAt}:{},...Number.isFinite(W.windowMinutes)?{windowMinutes:W.windowMinutes}:{}}]})}let G=$??(z||void 0),Q=Z.spendControl;if(G!==void 0&&Q)X.push({checkedAt:G,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(G!==void 0&&Z.spendControlCleared)X.push({checkedAt:G,budget:{kind:"cleared"}});return X.sort((B,W)=>B.checkedAt-W.checkedAt)}async function j0(Z,$){let X=await K3(Z.paths);if(!X)return;let J=X.quota?.mainQuotaToken,z=$.credential?.type==="oauth"?$.credential.access:void 0,Q=!J||z!==void 0&&J===d7(z)?X.quota?.mainQuota:void 0;if(Q&&$.credentialEpoch!==void 0){let H={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let V of H0(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 B=X.refresh?.mainLastRefreshError,W=X.accounts.find((H)=>H.id===$.id);if(!W||!c7(W)||W.corrupt)return;if(!B&&!Q)return;let U={...X,accounts:[{...W,...W.lastRefreshError||!B?{}:{lastRefreshError:B},...W.quota||!Q?{}:{quota:Q}}]};try{await s7(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 ZZ(Z,$,X={}){await EZ(Z,(J)=>{let z=G1(J);if(delete J.mainAccountId,$==="migrate"&&z.migratedAt===void 0)q0(J);return L3(J,{...z.migratedAt!==void 0||$==="migrate"?{migratedAt:z.migratedAt??Z.now()}:{},...X.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:X.declinedSlotFingerprint}:z.declinedSlotFingerprint!==void 0?{declinedSlotFingerprint:z.declinedSlotFingerprint}:{}}),!0})}function q0(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 P4(Z){await EZ(Z,($)=>{let X=G1($);if(!X.pending)return!1;let{pending:J,...z}=X;return L3($,z),!0})}async function D0(Z,$){await EZ(Z,(X)=>{let J=G1(X);if($.identity)X.mainAccountId=$.identity;return L3(X,{...J,pending:$}),!0})}async function F0(Z,$,X,J){let z=await RZ(Z,AZ,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await M0(Z,$,X,J)}finally{await z.release().catch(()=>{})}}async function M0(Z,$,X,J){let z=(U)=>({status:"completed",rowId:X.rowId,operation:J,placeholder:U}),G=await IZ(Z);if(G.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(G.kind==="placeholder"){if(G.origin===void 0)return{status:"untagged-placeholder"};if(G.origin!==K4(Z))return{status:"foreign-placeholder"};return await ZZ(Z,$),await Z.onStep("after-record-clear"),z("already-present")}if(Object.keys(await Z.slot.all()).length===0)return{status:"retry",reason:"torn-read"};if(G.kind==="real"&&G.fingerprint!==X.slotFingerprint&&X.identity!==void 0&&G.identity===X.identity)return await P4(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==X.slotFingerprint)return await ZZ(Z,$),await Z.onStep("after-record-clear"),z("slot-moved-on");await Z.onStep("before-placeholder-write");let Q=await Z.slot.get({path:{id:e1}}),B=Q===void 0||Q===null?void 0:o7(Q);if(B?.kind!=="real"||B.fingerprint!==X.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:e1},body:{...SZ,accountId:K4(Z)}})}catch(U){if(U instanceof q3)return{status:"retry",reason:"slot-changed"};throw U}await Z.onStep("after-placeholder-write");let W=await Z.slot.get({path:{id:e1}});if(!OZ(W))return{status:"retry",reason:"placeholder-overwritten"};if(t(W)&&W.accountId===void 0)return{status:"untagged-placeholder"};if(t(W)&&W.accountId!==K4(Z))return{status:"foreign-placeholder"};return await ZZ(Z,$),await Z.onStep("after-record-clear"),z("written")}async function N0(Z,$,X){let{record:J}=X;if(X.fresh)await D0(Z,J),await Z.onStep("after-record-write");if(await t7(Z,X.credential.refresh))return{status:"restart"};let z=await IZ(Z);if(z.kind!=="real"||z.fingerprint!==J.slotFingerprint)return{status:"restart"};return await V0(Z,J,X.credential),await Z.onStep("after-row-write"),e7(Z,$,J,X.fresh?J.operation:"resumed")}async function e7(Z,$,X,J){let z=await Y0(Z,X);if(!z)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),X.carryLegacyMain)await j0(Z,z),await Z.onStep("after-carry-over");let G=await F0(Z,$,X,J);if(G.status==="untagged-placeholder"){await Z.store.disable(X.rowId,t$,{extraLocks:M3(Z.paths,X.rowId,Z.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await ZZ(Z,$);let Q=`${Z.paths.configPath}\x00${X.rowId}`;if(!l7.has(Q))l7.add(Q),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${e$}`,{rowId:X.rowId});return{status:"refused",reason:"placeholder-origin-unknown"}}if(G.status!=="foreign-placeholder")return G;return await Z.store.remove(X.rowId,{extraLocks:M3(Z.paths,X.rowId,Z.locks),protect:(Q,B)=>B.row?.fingerprint!==X.credentialFingerprint?"the transfer row changed before rollback":void 0}),await P4(Z),await L4(Z),{status:"refused",reason:"placeholder-without-main"}}var u7=new Set,p7=new Set,l7=new Set;function K4(Z){return`openai-auth-pool:${s$("sha256").update(i$(Z.paths.configPath)).digest("hex")}`}async function K0(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function Z8(Z,$,X){let J=Z0(Z),z=J.slot.migrationDisabledReason?.();if(z){let U=J.slot.path??j3();if(!p7.has(U))p7.add(U),J.log.info("account pool migration is off: the host login slot is read-only",{reason:z});return{status:"slot-read-only",reason:z}}let G;try{G=await $Z(J.paths.configPath)}catch(U){return{status:"error",reason:U instanceof Error?U.message:String(U)}}let Q=await $8(J,$,G);if(Q){if(Q.status==="already-migrated"&&"mainAccountId"in G)await L4(J);return Q}if(X){let U=await K0(X);if(U.length>0){let H=`${J.paths.configPath}\x00${U.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!u7.has(H))u7.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 B,W;try{W=await RZ(J,"pool-slot-transfer",J.slot.path??j3(),J.locks.mainRefreshTtlMs,Z.signal),B=await RZ(J,i7,J.paths.configPath,J.locks.mainRefreshTtlMs,Z.signal)}catch(U){if(await W?.release().catch(()=>{}),U instanceof g1)return{status:"retry",reason:"lock-contention"};throw U}try{return await P0(J,$)}catch(U){if(U instanceof g1)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 B?.release().catch(()=>{}),await W?.release().catch(()=>{})}}async function $8(Z,$,X){let J=G1(X);if(J.pending)return;if($==="migrate"&&J.migratedAt!==void 0){let z=await Z.store.read();if(z.status==="ready"&&!z.rows.some((G)=>G.id==="main")&&!J.pending&&F3(await IZ(Z),z.rows.some((G)=>G.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 P0(Z,$){let X;for(let J=0;J<4;J++){let z=await $Z(Z.paths.configPath),G=await $8(Z,$,z);if(G){if(G.status==="already-migrated")await L4(Z);return G}let Q=await Z.store.read(),B=G1(z);if(Q.status==="pending-migration"){if(F3(await IZ(Z),Q.roster.some((V)=>t(V)&&V.id==="main"),B))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 W=await Q0(Z);if(W.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(W.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(F3(W,Q.rows.some((V)=>V.id==="main"),B))return{status:"refused",reason:"placeholder-without-main"};let U=U0($,B,Q.rows,W,X,Z.now(),Z.newId);if(U.kind==="nothing"){if($==="migrate")await ZZ(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:U.slot}}if(U.kind==="drop-record"){await P4(Z),await Z.onStep("after-record-clear");continue}if(U.kind==="ambiguous")return await ZZ(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 e7(Z,$,U.record,"resumed"):await N0(Z,$,U);if(H.status!=="restart")return H}return{status:"retry",reason:"unsettled"}}async function L4(Z){await EZ(Z,($)=>{if(!("mainAccountId"in $))return!1;if(G1($).pending)return!1;return delete $.mainAccountId,!0})}function mG(Z){return Z8(Z,"migrate",Z.fence)}function wG(Z){return Z8(Z,"adopt")}class X8 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function M3(Z,$,X={}){let J={...P3,...X},z={renew:J.renew,timeoutMs:J.timeoutMs,retryMs:J.retryMs,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}};return[{name:AZ,path:Z.configPath,ttlMs:J.mainRefreshTtlMs,...z},{name:n7($),path:Z.configPath,ttlMs:J.fallbackTtlMs,...z}]}async function uG(Z,$,X,J={}){let z=Z.now??Date.now,G=Z.sleep??((W)=>new Promise((U)=>setTimeout(U,W))),Q=Z.leaseWait??{timeoutMs:4000,pollMs:50},B=async(W,U)=>{let H=TZ(W.refresh),V=async()=>{let j=await K3(Z.paths),D=j?.refresh?.mainRefreshLeaseUntil;return Boolean(D&&D>z()&&j?.refresh?.mainRefreshLeaseTokenHash===H)};if(await V()){let j=z()+Q.timeoutMs;while(z()<j&&await V())await G(Q.pollMs);throw new X8}return X(W,U)};return Z.store.refresh($,B,{...J,extraLocks:M3(Z.paths,$,Z.legacyLocks)})}
69
+ export{YZ as pa,a as qa,W9 as ra,m as sa,Z6 as ta,D9 as ua,$J as va,XJ as wa,M9 as xa,JJ as ya,zJ as za,K9 as Aa,$3 as Ba,J6 as Ca,a3 as Da,t3 as Ea,Z4 as Fa,h1 as Ga,$4 as Ha,i1 as Ia,FZ as Ja,l9 as Ka,a9 as La,n9 as Ma,r1 as Na,i9 as Oa,PZ as Pa,t9 as Qa,Uz as Ra,Vz as Sa,Yz as Ta,Hz as Ua,jz as Va,qz as Wa,Rz as Xa,T7 as Ya,kz as Za,fz as _a,y$ as $a,hz as ab,vz as bb,gz as cb,xz as db,Lz as eb,o1 as fb,D4 as gb,_$ as hb,Oz as ib,x$ as jb,DG as kb,r$ as lb,SZ as mb,t$ as nb,e$ as ob,hG as pb,vG as qb,X0 as rb,gG as sb,G1 as tb,xG as ub,mG as vb,wG as wb,M3 as xb,uG as yb,AZ as zb,k7 as Ab,j3 as Bb,g7 as Cb,q3 as Db,_G as Eb};
@@ -0,0 +1,2 @@
1
+ import{$e as k,Ue as q,We as _,Ye as A,Ze as w,bf as p}from"./index-5230x6s8.js";import{appendFileSync as QJ,chmodSync as UJ,existsSync as W,renameSync as g,statSync as ZJ}from"node:fs";import{open as $J}from"node:fs/promises";import{dirname as VJ,resolve as IJ}from"node:path";var i=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,e=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function JJ(J){return J instanceof Error||Object.prototype.toString.call(J)==="[object Error]"}function T(J={}){let H=[e,...J.extraValuePatterns??[]].map((G)=>new RegExp(G.source,G.flags.includes("g")?G.flags:`${G.flags}g`));function Z(G){let U=G.toLowerCase().replace(/[-_]/g,"");return i.test(G)||U.includes("apikey")||U.endsWith("secret")||U.endsWith("password")||U.endsWith("token")&&!U.endsWith("tokens")||!!J.extraSecretKeys?.(U)}function $(G){let U=G,V=[["name",G.name],["message",G.message],["stack",G.stack]];for(let j of["code","status","cause"])if(U[j]!==void 0)V.push([j,U[j]]);let Y=new Set(V.map(([j])=>j));for(let j of Object.entries(G))if(!Y.has(j[0]))V.push(j);return V}function B(G,U,V,Y=0){if(typeof G==="string")return H.reduce((j,C)=>j.replace(C,"***REDACTED***"),G);if(!G||typeof G!=="object")return G;if(V.has(G))return"[Circular]";V.add(G);try{if(Array.isArray(G))return G.map((N)=>B(N,U,V,Y));let j=JJ(G);if(j&&Y>=8)return"[Truncated]";let C=j?Y+1:Y;return Object.fromEntries((j?$(G):Object.entries(G)).map(([N,z])=>[N,U&&Z(N)?"***REDACTED***":B(z,U,V,C)]))}finally{V.delete(G)}}return{redact:(G)=>B(G,!0,new WeakSet),redactStrings:(G)=>B(G,!1,new WeakSet)}}var E=T(),GJ=E.redact,HJ=E.redactStrings;var D={error:0,warn:1,info:2,debug:3,trace:4},h=5242880,m=3;function b(J){try{UJ(J,384)}catch{}}function jJ(J){try{if(!(W(J)&&ZJ(J).size>=h))return;for(let Z=m-1;Z>=1;Z--)if(W(`${J}.${Z}`)){let $=`${J}.${Z+1}`;g(`${J}.${Z}`,$),b($)}let H=`${J}.1`;g(J,H),b(H)}catch{}}async function M(J){let{file:H,handle:Z}=J;if(J.file=void 0,J.handle=void 0,H&&Z)await _(H,"log-close",()=>Z.close())}async function y(J,H){await w(VJ(H));try{await A(H,"file",!0)}catch(Z){if(Z.code!=="ENOENT")throw Z;try{await k(H,"")}catch($){if($.code!=="EEXIST")throw $;await A(H,"file",!0)}}return J.handle=await _(H,"log-open",()=>$J(H,"a")),J.file=H,J.handle}async function XJ(J,H,Z){H=IJ(H);try{if(J.file!==H)await M(J);let $=J.handle??await y(J,H);if((await _(H,"log-stat",()=>$.stat())).size>=h){await M(J);for(let G=m-1;G>=0;G--){let U=G===0?H:`${H}.${G}`,V=`${H}.${G+1}`;try{await A(U,"file",!0)}catch(Y){if(Y.code==="ENOENT")continue;throw Y}try{await A(V,"file",!0)}catch(Y){if(Y.code!=="ENOENT")throw Y}await p(U,V),await A(V,"file")}$=await y(J,H)}await _(H,"log-append",()=>$.appendFile(Z,"utf8"))}catch($){throw await M(J).catch(()=>{}),$}}function YJ(J){try{return` ${JSON.stringify(J)}`}catch{return" [unserializable]"}}function BJ(J){let H,Z,$,B=T(),G,U=[],V,Y=Promise.resolve(),j,C={};function N(Q){let I=Y.then(Q);return Y=I.catch((X)=>{j=X}),I}function z(Q){if(q&&Q.file!==H)N(()=>M(C)).catch(()=>{});H=Q.file,Z=Q.level,B=T(Q),G=Q.captureSink}function s(Q){if(Q===void 0||Q in D)$=Q}function o(){if(H===void 0)return;return(typeof H==="function"?H():H)||void 0}function t(){if($)return $;let Q=typeof Z==="function"?Z():Z;if(Q&&Q in D)return Q;return"info"}function R(Q=!0){if(V)clearTimeout(V),V=void 0;if(!U.length){if(q)return N(async()=>{if(Q)await M(C);if(j)throw j});return}let I;try{I=o()}catch{if(U=[],q&&Q)return N(()=>M(C));return}let X=U.join("");if(U=[],!I){if(q&&Q)return N(()=>M(C));return}if(q)return N(async()=>{try{await XJ(C,I,X)}finally{if(Q)await M(C)}});try{if(jJ(I),W(I))b(I);QJ(I,X,{encoding:"utf8",mode:384})}catch{}}function a(){if(!V)V=setTimeout(()=>{V=void 0;let Q=R(!1);if(Q instanceof Promise)Q.catch(()=>{})},500)}function x(Q,I,X,P){if(H===void 0&&G===void 0)return;try{if(D[I]>D[t()])return;let S=B.redactStrings(X),K;try{K=B.redact(P)}catch{K="[unserializable]"}let r=`[${new Date().toISOString()}] ${I.toUpperCase()} [${Q}] ${S}`+(P===void 0?"":YJ(K))+`
2
+ `;try{G?.({channel:Q,level:I,message:S,data:K})}catch{}if(H===void 0)return;if(U.push(r),U.length>=50){let F=R(!1);if(F instanceof Promise)F.catch(()=>{})}else a()}catch{}}function n(Q){return{error:(I,X)=>x(Q,"error",I,X),warn:(I,X)=>x(Q,"warn",I,X),info:(I,X)=>x(Q,"info",I,X),debug:(I,X)=>x(Q,"debug",I,X),trace:(I,X)=>x(Q,"trace",I,X)}}function l(){if(q)N(()=>M(C)).catch(()=>{});if(j=void 0,U=[],V)clearTimeout(V),V=void 0;H=void 0,Z=void 0,$=void 0,B=T(),G=void 0}if(J)z(J);return{configure:z,createLogger:n,setLogLevel:s,flushLogs:R,reset:l}}var O=BJ();function L(J){O.configure(J);let{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}=O;return{configure:H,createLogger:Z,setLogLevel:$,flushLogs:B}}function v(J){O.setLogLevel(J)}function u(){return O.flushLogs()}function c(J){return O.createLogger(J)}function f(J){return J==="chatgptaccountid"||J==="email"||J==="orgname"||J==="organizationname"}var d=T({extraSecretKeys:f}),kJ=d.redact,pJ=d.redactStrings;function hJ(J){L({...J,extraSecretKeys:f})}function uJ(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;try{return JSON.stringify(J)}catch{return String(J)}}function fJ(J){return"notify"in J}import{basename as MJ,dirname as TJ,join as qJ}from"node:path";var AJ="openai-auth.json",xJ="openai-auth-state.json";function oJ(J){return MJ(J)===AJ?qJ(TJ(J),xJ):`${J}.state.json`}import{spawn as _J}from"node:child_process";function nJ(J,H=process.platform,Z=_J){try{if(H==="win32"){let B=`Start-Process '${J.replaceAll("'","''")}'`,G=Buffer.from(B,"utf16le").toString("base64"),U=Z("powershell.exe",["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-EncodedCommand",G],{stdio:"ignore",windowsHide:!0});return U.on("error",()=>{}),U.unref(),U.pid!==void 0}let $=Z(H==="darwin"?"open":"xdg-open",[J],{stdio:"ignore"});return $.on("error",()=>{}),$.unref(),$.pid!==void 0}catch{return!1}}export{T as Ie,GJ as Je,v as Ke,u as Le,c as Me,pJ as Ne,hJ as Oe,AJ as Pe,oJ as Qe,uJ as Re,fJ as Se,nJ as Te};