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