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