@cortexkit/opencode-openai-auth 1.0.2 → 1.0.4

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 (91) hide show
  1. package/README.md +12 -60
  2. package/dist/bin.js +13 -0
  3. package/dist/index-2hch7e8n.js +8 -0
  4. package/dist/{index-766sfrh5.js → index-45qgkb0m.js} +1 -1
  5. package/dist/index-5dg931q0.js +65 -0
  6. package/dist/index-99esnzg0.js +157 -0
  7. package/dist/index-9reyazwh.js +2 -0
  8. package/dist/index-bgq9d21h.js +2 -0
  9. package/dist/index-dryydk6b.js +2 -0
  10. package/dist/index-egrty6tz.js +12 -0
  11. package/dist/index-envpbt0k.js +3 -0
  12. package/dist/index-jye6vccc.js +2 -0
  13. package/dist/index-k4eacw7x.js +2 -0
  14. package/dist/{index-hy9030jh.js → index-yeyp8t0k.js} +1 -1
  15. package/dist/index-yf6arn5w.js +2 -0
  16. package/dist/index.d.ts +2 -56
  17. package/dist/index.js +1 -1
  18. package/dist/map-CCbSZIhT.d.ts +56 -0
  19. package/dist/{pool-lifecycle-DbDmgabd.d.ts → pool-lifecycle-DqKq8Eej.d.ts} +104 -790
  20. package/dist/{port-file-Do3lQIEk.d.ts → port-file-CZ9MIdy2.d.ts} +1 -1
  21. package/dist/{protocol-BOBdkqqm.d.ts → protocol-CSIDDBDf.d.ts} +1 -1
  22. package/dist/rpc/port-file.d.ts +1 -1
  23. package/dist/rpc/port-file.js +1 -1
  24. package/dist/rpc/protocol.d.ts +1 -1
  25. package/dist/rpc/protocol.js +1 -1
  26. package/dist/rpc/rpc-client.d.ts +3 -3
  27. package/dist/rpc/rpc-client.js +1 -1
  28. package/dist/rpc/rpc-dir.js +1 -1
  29. package/dist/{sidebar-state-D6cUKgkm.d.ts → sidebar-state-BCxFpH68.d.ts} +5 -3
  30. package/dist/sidebar-state.d.ts +1 -1
  31. package/dist/sidebar-state.js +1 -1
  32. package/dist/token-util-gmn5yaqc.js +1 -0
  33. package/dist/{token-ypk61xj0.js → token-vykm9bxh.js} +1 -1
  34. package/dist/tui-preferences.d.ts +2 -1
  35. package/dist/tui-preferences.js +3 -3
  36. package/dist/tui.d.ts +2 -2
  37. package/dist/v2/server.d.ts +1 -1
  38. package/dist/v2/server.js +3 -4
  39. package/package.json +13 -8
  40. package/src/tui-compiled/raw/logger.js +10 -2
  41. package/src/tui-compiled/raw/shared/053cc17b5419261e-codec.js +2 -1
  42. package/src/tui-compiled/raw/shared/0766d78c6f481f18-watcher.js +26 -10
  43. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +302 -0
  44. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
  45. package/src/tui-compiled/raw/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  46. package/src/tui-compiled/raw/shared/458b934e92490331-mutate.js +2 -2
  47. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +4 -0
  48. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +21 -5
  49. package/src/tui-compiled/raw/shared/7211cfec06a298bc-atomic-write.js +21 -0
  50. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +36 -1
  51. package/src/tui-compiled/raw/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  52. package/src/tui-compiled/raw/shared/c14988621dc60a75-port-file.js +30 -8
  53. package/src/tui-compiled/raw/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  54. package/src/tui-compiled/raw/shared/c852a15cfe489d12-pool.js +3 -0
  55. package/src/tui-compiled/raw/shared/cd94316a888b0a8e-schema.js +3 -2
  56. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +1 -1
  57. package/src/tui-compiled/raw/shared/d7dcba96fea1685c-engine.js +126 -11
  58. package/src/tui-compiled/raw/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  59. package/src/tui-compiled/raw/shared/ec971142548df90e-index.js +1 -0
  60. package/src/tui-compiled/raw/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  61. package/src/tui-compiled/raw/sidebar-state.js +3 -3
  62. package/src/tui-compiled/runtime/logger.js +10 -2
  63. package/src/tui-compiled/runtime/shared/053cc17b5419261e-codec.js +2 -1
  64. package/src/tui-compiled/runtime/shared/0766d78c6f481f18-watcher.js +26 -10
  65. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +302 -0
  66. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
  67. package/src/tui-compiled/runtime/shared/43fc9e6b994519c7-refresh-lock.js +5 -0
  68. package/src/tui-compiled/runtime/shared/458b934e92490331-mutate.js +2 -2
  69. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +4 -0
  70. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +21 -5
  71. package/src/tui-compiled/runtime/shared/7211cfec06a298bc-atomic-write.js +21 -0
  72. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +36 -1
  73. package/src/tui-compiled/runtime/shared/a09b6a533c11858f-tui-preferences.js +6 -4
  74. package/src/tui-compiled/runtime/shared/c14988621dc60a75-port-file.js +30 -8
  75. package/src/tui-compiled/runtime/shared/c64d7afbc14ca125-sidebar-file.js +17 -8
  76. package/src/tui-compiled/runtime/shared/c852a15cfe489d12-pool.js +3 -0
  77. package/src/tui-compiled/runtime/shared/cd94316a888b0a8e-schema.js +3 -2
  78. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +1 -1
  79. package/src/tui-compiled/runtime/shared/d7dcba96fea1685c-engine.js +126 -11
  80. package/src/tui-compiled/runtime/shared/e8cd4929507508d8-refresh-file-lock.js +254 -37
  81. package/src/tui-compiled/runtime/shared/ec971142548df90e-index.js +1 -0
  82. package/src/tui-compiled/runtime/shared/fbcdcd0f925e74c0-rpc-client.js +15 -1
  83. package/src/tui-compiled/runtime/sidebar-state.js +3 -3
  84. package/dist/index-8kj7sa1p.js +0 -12
  85. package/dist/index-b3q3j39x.js +0 -2
  86. package/dist/index-bmd7x5aq.js +0 -2
  87. package/dist/index-eqh53k8v.js +0 -2
  88. package/dist/index-jyr8y8k4.js +0 -7
  89. package/dist/index-m9d2bfkn.js +0 -222
  90. package/dist/index-rv08jmd4.js +0 -2
  91. package/dist/token-util-wdza526f.js +0 -1
@@ -0,0 +1,157 @@
1
+ import{kd as p$,ld as l$,md as o0,nd as wZ,od as W3,pd as p6,qd as $0,rd as E6,sd as _Z,td as c,ud as b3,vd as u$,wd as c6}from"./index-yf6arn5w.js";import{Ad as W8,Bd as w,Cd as x3,Dd as q9,Ed as t0,xd as V9,yd as n,zd as j9}from"./index-2hch7e8n.js";import{Sd as c9,Vd as v,Wd as u7,Yd as W$,Zd as Y$,_d as WZ}from"./index-k4eacw7x.js";import{be as RZ,ce as R0,ee as E0,ge as y8,he as _1,le as b0}from"./index-dryydk6b.js";function d$(Z,$,X){let J=$.rateLimitMarks?.get(Z);if(J!==void 0&&X<J)return{id:Z,reason:"rate-limited",until:J};let z=$.refreshBackoff?.get(Z);if(z!==void 0&&X<z)return{id:Z,reason:"refresh-backoff",until:z};return}function L2(Z,$,X,J){if($.limits.length===0)return{id:Z,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of X)if(!$.limits.some((B)=>B.label===G))return{id:Z,stage:1,gate:3,reason:"unknown-window",window:{scope:$.scope,label:G},pullRequested:!0};let z=$.limits.filter(u$);for(let G of z)if(c6(G,J)===void 0)return{id:Z,stage:1,gate:4,reason:"unknown-reset",window:{scope:G.scope,label:G.label},pullRequested:!0};for(let G of z){let B=c6(G,J);if(B!==void 0&&typeof G.resetsAt==="string")return{id:Z,stage:1,gate:5,reason:"exhausted",window:{scope:G.scope,label:G.label},resetsAt:G.resetsAt,resetAtMs:B}}return}function l1(Z){let $=Z.scope??p$,X=Z.requiredLabels??l$,J=[],z=[],G=[];for(let j of Z.rows){let D=d$(j.id,Z,Z.now);if(D){J.push(D);continue}if(j.kind==="api-key"){G.push({id:j.id,kind:j.kind});continue}let H=c(j.quota,$),q=L2(j.id,H,X,Z.now);if(q){z.push(q);continue}G.push({id:j.id,kind:j.kind,projection:H})}let B=new Map(G.flatMap((j)=>{let D=b3(j.projection,Z.now);return D?[[j.id,D]]:[]})),Q=B.size>0&&B.size===G.length,W=[];for(let j of G){let D=B.get(j.id);if(D===void 0)W.push(j);else if(Q)W.push({...j,lastPath:!0});else z.push({id:j.id,stage:2,reason:"budget-spent",...D})}let Y=new Map(Z.rows.map((j,D)=>[j.id,D])),U=(j,D)=>(Y.get(j.id)??0)-(Y.get(D.id)??0);z.sort(U);let V=z.filter((j)=>("pullRequested"in j)).map((j)=>j.id);for(let j of V)Z.requestPull?.(j);return{admitted:W,refused:z,excluded:J,pulls:V}}var I3="main";function s6(Z){switch(Z){case"sticky-balanced":return{mode:"sticky-balanced",placement:"roster"};case"main-first":return{mode:"ordered",placement:"main-first"};case"fallback-first":return{mode:"ordered",placement:"fallback-first"};default:return{mode:"ordered",placement:"roster"}}}function y3(Z,$,X=I3){if($==="roster"||!Z.includes(X))return[...Z];let J=Z.filter((z)=>z!==X);return $==="main-first"?[X,...J]:[...J,X]}function _2(Z){let $=l1(Z),X=new Set($.admitted.map((z)=>z.id));return{order:y3(Z.rows.map((z)=>z.id),Z.placement??"roster",Z.formerMainId).filter((z)=>X.has(z)&&Z.killswitch?.get(z)!==!1),admission:$}}function O2(Z,$,X){let J=$.at(-1);if(J!==void 0){if(J.status===void 0||!X.includes(J.status))return}let z=new Set($.map((G)=>G.id));return Z.find((G)=>!z.has(G))}function u1(Z,$,X){if(!$.has(Z.accountId))return!1;return!(typeof Z.wireIdentity==="string"&&typeof X==="string"&&Z.wireIdentity!==X)}function i6(Z,$,X){let J=new Map;for(let[z,G]of Z){if(z===X)continue;if(G.quotaCheckedAt!==$.get(G.accountId))continue;J.set(G.accountId,(J.get(G.accountId)??0)+(G.inputBytes??0))}return J}var r6=900000,s$=0.016666666666666666,a6=0.000001;function k3(Z,$){for(let X of[Z?.checkedAt,$])if(typeof X==="number"&&Number.isFinite(X))return X;return}function i$(Z){if(Z===401||Z===403)return"permanent";if(Z===void 0||Z===0||!Number.isFinite(Z)||Z>=500&&Z<=599||Z===429)return"transient";return"healthy"}function a$(Z){return Z.limits.filter(($)=>$.kind==="reading").sort(($,X)=>{let J=$.windowMinutes!==void 0,z=X.windowMinutes!==void 0;if(J!==z)return J?-1:1;if(J&&z)return(X.windowMinutes??0)-($.windowMinutes??0);return 0})}function C2(Z){let $=(Z.classifyStatus??i$)(Z.status);if($==="permanent")return{action:"migrate",reason:"permanent"};if(!Z.quota)return{action:"retain",reason:"unknown"};let X=k3(Z.quota,Z.quotaCheckedAt);if(X===void 0||!Number.isFinite(X)||Z.now-X>r6)return{action:"retain",reason:"stale"};if(Z.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let z of a$(Z.quota)){let G=z.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:z.scope,label:z.label},...typeof z.resetsAt==="string"?{resetsAt:z.resetsAt}:{}}}let J=b3(Z.quota,Z.now);if(J)return{action:"migrate",reason:"exhausted",resetsAt:J.resetsAt};return{action:"retain",reason:$}}function n6(Z,$,X){let J=Math.max(0,Z.remainingPercent-$);if(J<=0)return 0;if(!Z.resetsAt)return J;let z=Date.parse(Z.resetsAt);if(!Number.isFinite(z)||z<=X)return J;let G=Math.max((z-X)/3600000,s$);return J/G}function c$(Z,$){if(Z<$)return-1;if(Z>$)return 1;return 0}function T2(Z,$){if(!Z.quota)return;let X=k3(Z.quota,Z.quotaCheckedAt);if(X===void 0||$-X>r6)return;let J=a$(Z.quota).map((B)=>n6({remainingPercent:B.remainingPercent??Number.NaN,...B.resetsAt===void 0?{}:{resetsAt:B.resetsAt}},Z.reservePercent[B.label]??0,$)),z=Z.quota.budget;if(z&&typeof z.remainingPercent==="number"&&Number.isFinite(z.remainingPercent))J.push(n6({remainingPercent:z.remainingPercent,...z.resetsAt===void 0?{}:{resetsAt:z.resetsAt}},0,$));let G=J.length>0?Math.min(...J):0;return G>0?{candidate:Z,quotaCheckedAt:X,weight:G}:void 0}function n$(Z){let $=Z.candidates.filter((z)=>z.killswitchPasses!==!1);if(Z.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if($.length===0)return;let X=$.map((z)=>T2(z,Z.now)).filter((z)=>z!==void 0);if(X.length>0){X.sort((G,B)=>{let Q=((Z.pendingBytes.get(G.candidate.accountId)??0)+Z.requestBytes)/Math.max(G.weight,a6),W=((Z.pendingBytes.get(B.candidate.accountId)??0)+Z.requestBytes)/Math.max(B.weight,a6);return Q-W||G.candidate.configuredOrder-B.candidate.configuredOrder||c$(G.candidate.accountId,B.candidate.accountId)});let z=X[0];if(z)return{accountId:z.candidate.accountId,quotaCheckedAt:z.quotaCheckedAt,source:"weighted"}}Z.onEmptyWeightedSet?.();let J=[...$].sort((z,G)=>{let B=(z.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-B||z.configuredOrder-G.configuredOrder||c$(z.accountId,G.accountId)})[0];if(!J)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:J.accountId,quotaCheckedAt:k3(J.quota,J.quotaCheckedAt),source:"mode-fallback"}}function S2(Z){let $=l1(Z),X=new Map($.admitted.map((H)=>[H.id,H])),J=new Map($.refused.map((H)=>[H.id,H])),z=new Set($.excluded.map((H)=>H.id)),G=new Set(Z.rows.map((H)=>H.id)),B=Z.pin!==void 0&&u1(Z.pin,G,Z.identities?.get(Z.pin.accountId));if(B&&Z.pin){let H=X.get(Z.pin.accountId);if(H&&Z.killswitch?.get(H.id)!==!1)return{outcome:"dispatch",accountId:H.id,source:"pin",...H.projection?.checkedAt===void 0?{}:{quotaCheckedAt:H.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:$}}let Q=Z.pin?J.get(Z.pin.accountId):void 0,W=B&&Z.pin!==void 0&&Z.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(Z.killswitch?.get(Z.pin.accountId)===!1||Q?.reason==="exhausted"||Q?.reason==="budget-spent"),Y=(H)=>{return(typeof Z.rowReservePercent==="function"?Z.rowReservePercent(H):Z.rowReservePercent?.get(H.id))??Z.reservePercent??{}},U=Z.scope,V=Z.rows.map((H,q)=>({row:H,configuredOrder:q})).filter(({row:H})=>!z.has(H.id)).map(({row:H,configuredOrder:q})=>{let N=Z.killswitch?.get(H.id),M=Z.resetCreditsApplicable?.get(H.id);return{accountId:H.id,quota:H.kind==="api-key"?void 0:X.get(H.id)?.projection??c(H.quota,U),reservePercent:Y(H),configuredOrder:q,...M===void 0?{}:{resetCreditsApplicable:M},...N===void 0?{}:{killswitchPasses:N}}}),j=[],D=B?{action:"retain"}:Z.pin?{action:"clear"}:{action:"none"};while(V.length>0){let H=n$({candidates:V,pendingBytes:Z.pendingBytes??new Map,requestBytes:Z.requestBytes,now:Z.now,...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}});if(!H)break;let q=J.get(H.accountId);if(q){j.push(q),V=V.filter((M)=>M.accountId!==H.accountId);continue}let N=Z.identities?.get(H.accountId);return{outcome:"dispatch",accountId:H.accountId,source:H.source,...H.quotaCheckedAt===void 0?{}:{quotaCheckedAt:H.quotaCheckedAt},pin:B&&!W?{action:"retain"}:{action:"assign",pin:{accountId:H.accountId,inputBytes:Z.requestBytes,...N===void 0?{}:{wireIdentity:N},...H.quotaCheckedAt===void 0?{}:{quotaCheckedAt:H.quotaCheckedAt}}},refusedSelections:j,admission:$}}return{outcome:"no-admissible-account",pin:D,refusedSelections:j,admission:$}}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 f3 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 K1="identity-contradicted: ",o6="duplicate-identity";function xZ(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 d1(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 F1(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))xZ(Z,z.id,"duplicate-identity"),J.push(z.id);return J}function nZ(Z,$,X){let J=Z.rosterRow($);if(!J)return[];return J.accountId=X,F1(Z,X)}import{setTimeout as d2}from"node:timers/promises";import{AsyncLocalStorage as A2}from"node:async_hooks";var r$=new A2;function s(Z){if(r$.getStore()!==void 0)throw new f3(Z)}function PZ(Z,$){return r$.run(Z,async()=>await $())}async function o$(Z,$,X,J,z){if(!$)return;try{await PZ(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 t6=Object.freeze({ttlMs:1e4,timeoutMs:15000,retryMs:50,renew:!0});async function R2(Z,$,X){let J=(B)=>{try{let Q=X.onLockEvent?.({type:B,name:Z.name,path:Z.path});if(Q&&(typeof Q==="object"||typeof Q==="function")&&"then"in Q&&typeof Q.then==="function")Promise.resolve(Q).catch(()=>{})}catch{}},z={...$,...E2(Z)},G=performance.now();for(;;){let B=await w({name:Z.name,path:Z.path,ttlMs:z.ttlMs,now:X.now,renew:z.renew,onContended:()=>J("contended"),...X.onRenewalTimer?{onRenewalTimer:(Y)=>X.onRenewalTimer?.({name:Z.name,path:Z.path},Y)}:{},...z.renewIntervalMs!==void 0?{renewIntervalMs:z.renewIntervalMs}:{},...X.onLockStep?{onStep:(Y)=>X.onLockStep?.({name:Z.name,path:Z.path},Y)}:{}});if(B){J("acquired");let Y={name:Z.name,path:Z.path,assertOwned:()=>B.assertOwned(),release:async()=>{await B.release(),J("released")}};try{await Y.assertOwned()}catch(U){throw await Y.release(),U}return Y}let Q=z.timeoutMs-(performance.now()-G);if(Q<=0)throw new x3({target:Z.path,name:Z.name,timeoutMs:z.timeoutMs});let W=Math.floor(Math.random()*(z.retryMs+1));await new Promise((Y)=>setTimeout(Y,Math.min(z.retryMs+W,Q)))}}function E2(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 hZ{defaults;env;held=[];constructor(Z,$){this.defaults=Z,this.env=$}async acquire(Z){let $=await R2(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 rZ(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 c1}from"node:crypto";var y="commonAuthPool",vZ=1,qZ="rows",h3="retiredEpochs",s1=1,e6=300000,b=y;function b2(Z){let $=JSON.parse(JSON.stringify(Z)),X=(J)=>{if(Array.isArray(J))return`[${J.map(X).join(",")}]`;if(_(J))return`{${Object.keys(J).sort().map((z)=>`${JSON.stringify(z)}:${X(J[z])}`).join(",")}}`;return JSON.stringify(J)};return X($)}function oZ(Z){return c1("sha256").update(b2(Z)).digest("hex")}function t$(Z){if(!_(Z)||Object.keys(Z).length!==1||typeof Z.reservation!=="string"||!Z.reservation)return;return{reservation:Z.reservation}}function I2(Z){if(!_(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 a="commonAuthProviderState";function _(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var y2=new Set(["__proto__","constructor","prototype"]);function N1(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(y2.has(Z))return"id is a reserved object key";return}function Z8(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 e$(Z){return Z.type==="oauth"?`oauth\x00${Z.refresh}`:`api\x00${Z.apiKey}`}function DZ(Z){return c1("sha256").update(e$(Z)).digest("hex")}function LZ(Z){return c1("sha256").update(`credential-stamp\x00${e$(Z)}`).digest("hex")}function AZ(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 c1("sha256").update(`credential-dispatch\x00${JSON.stringify($)}`).digest("hex")}function $8(Z,$,X,J={}){return{credentialEpoch:$,digest:LZ(Z),dispatch:AZ(Z),binding:{...X},...J.replace?{replace:!0}:{},...J.providerState!==void 0?{providerState:J.providerState}:{}}}function M1(Z,$){let X=Z?.credentialBound?Z.credentialBound($):$;return c1("sha256").update(`provider-state\x00${JSON.stringify(X??null)}`).digest("hex")}function i1(Z,$,X,J){if(!$||X===void 0)return;if(!_(Z)||!Object.hasOwn(Z,a))return;let z=ZZ(Z[b]);if(!z||z.providerState===void 0||z.digest!==LZ($)||z.credentialEpoch!==X||z.binding?.identity!==J)return;return z.providerState}function l(Z){return Number.isSafeInteger(Z)&&Z>=1}function ZZ(Z){if(!_(Z))return;let $=Z.credentialEpoch;if(!l($))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?I2(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(!_(z))return;if("identity"in z&&(typeof z.identity!=="string"||!z.identity))return;if("baseURL"in z&&!Z8(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 k2(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 f2(Z,$,X,J){if(!Z)return"none";if(!_(J)||!Object.hasOwn(J,b))return"missing";let z=ZZ(J[b]);if(!z)return"malformed";if(z.digest!==LZ(Z))return"mismatched";if(z.dispatch===void 0)return"legacy";if(z.credentialEpoch!==$)return"mismatched";if(!z.binding||!k2(z.binding,Z,X))return"mismatched";if(z.dispatch!==AZ(Z))return"mismatched";return"bound"}function Z9(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(!_($))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(!_(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>vZ)return{status:"error",reason:`${y}.schemaVersion ${J} is newer than ${vZ}`};if(qZ in X&&!_(X[qZ]))return{status:"error",reason:`${y}.${qZ} is not an object`};return{status:"ready",exists:!0,config:$}}function $9(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(!_(Z.value))return{status:"error",reason:"state root is not an object"};if("accounts"in Z.value&&!_(Z.value.accounts))return{status:"error",reason:"state accounts is not an object"};return{status:"ready",exists:!0,state:Z.value}}function P1(Z){return Array.isArray(Z.accounts)?Z.accounts:[]}function X9(Z){let $=Z[y];if(!_($))return{};let X=$[qZ];return _(X)?X:{}}function x2(Z){return _(Z.accounts)?Z.accounts:{}}function h2(Z){if(!_(Z))return"not an object";let $=N1(Z.id);if($)return $;if(Z.type==="api")return Z8(Z.baseURL)?void 0:"invalid baseURL";if(Z.type==="oauth")return;return"unknown type"}function v2(Z,$){if(!_(Z))return;let X=Z.credentialEpoch;if(!l(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&&!t$(Z.staged))return;return{credentialEpoch:X,needsFirstReading:Z.needsFirstReading===!0,...typeof Z.disabledReason==="string"?{disabledReason:Z.disabledReason}:{},..."quota"in Z?{quota:J}:{}}}function g2(Z,$){if(!_($))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 v3(Z,$){return P1(Z).find((X)=>_(X)&&X.id===$)}function J9(Z){if(!_(Z[y]))Z[y]={};return Z[y]}function X8(Z){let $=J9(Z);if(!_($[qZ]))$[qZ]={};return $[qZ]}function gZ(Z,$){let X=X9(Z),J=Object.hasOwn(X,$)?X[$]:void 0;return _(J)?J:void 0}function g3(Z,$,X){Object.defineProperty(X8(Z),$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function z9(Z,$){let X=Z[y];if(!_(X))return;let J=X[h3];if(!_(J)||!Object.hasOwn(J,$))return;let z=J[$];return l(z)?z:void 0}function G9(Z,$){let X=gZ(Z,$)?.credentialEpoch;return l(X)?X:void 0}function m3(Z,$){return Math.max(z9(Z,$)??0,G9(Z,$)??0)+1}function B9(Z,$){let X=[...$];if(X.length===0)return;let J=J9(Z),z=_(J[h3])?J[h3]:{},G={},B=(Q,W)=>Object.defineProperty(G,Q,{value:W,enumerable:!0,writable:!0,configurable:!0});for(let[Q,W]of Object.entries(z))if(l(W))B(Q,W);for(let Q of X)B(Q,Math.max(z9(Z,Q)??0,G9(Z,Q)??1));J[h3]=G}function mZ(Z,$,X,J){let z=X9(Z),G=x2($),B=new Set,Q=[];for(let W of P1(Z)){let Y=h2(W),U=_(W)&&typeof W.id==="string"?W.id:void 0,V=U===void 0?void 0:z[U],j=_(V)&&Object.hasOwn(V,"staged"),D=j?t$(V.staged):void 0;if(Y||!_(W)||U===void 0||B.has(U)){if(U!==void 0&&!B.has(U))B.add(U);if(U!==void 0)Q.push({id:U,type:_(W)&&W.type==="api"?"api":"oauth",enabled:!1,needsFirstReading:!0,hasEntry:Object.hasOwn(z,U),candidate:!1,invalid:"roster",stamp:"none",...D?{staged:D}:{}});continue}B.add(U);let H=W.type==="api"?"api":"oauth",q=Object.hasOwn(z,U),N=q?v2(z[U],X):void 0,M=g2(W,G[U]),O=W.enabled!==!1,S=N?N.credentialEpoch:q?void 0:1,F=typeof W.accountId==="string"&&W.accountId?W.accountId:void 0,K={id:U,type:H,enabled:O,needsFirstReading:N?N.needsFirstReading:H==="oauth",hasEntry:q,candidate:!1,...typeof W.label==="string"?{label:W.label}:{},...typeof W.addedAt==="number"?{addedAt:W.addedAt}:{},...F!==void 0?{identity:F}:{},...M?{credential:M,fingerprint:DZ(M)}:{},...N?{credentialEpoch:N.credentialEpoch}:{},...D?{staged:D}:{},...N?.disabledReason!==void 0?{disabledReason:N.disabledReason}:{},...N&&"quota"in N?{quota:N.quota}:{},...m2(G[U],M,S,F,J),stamp:f2(M,S,F,G[U])};if(q&&!N)K.invalid="entry";else K.candidate=O&&M!==void 0&&!j;Q.push(K)}return Q}function m2(Z,$,X,J,z){if(!_(Z)||!Object.hasOwn(Z,a))return{};let G=i1(Z,$,X,J);if(G===void 0)return{providerStateDropped:"uncovered"};let B=Z[a];if(!z?.validate(B))return{providerStateDropped:"invalid"};if(M1(z,B)!==G)return{providerStateDropped:"uncovered"};return{providerState:B}}function x(Z){return Z.identity??Z.id}function a1(Z,$){if(Z===void 0||Z>$+e6)return $;return Math.max($,Z+1)}function J8(Z,$){return a1(Z,$)>$+e6}function L1(Z){let{id:$,credential:X,identity:J,label:z,addedAt:G}=Z;return{id:$,...z!==void 0?{label:z}:{},type:X.type,addedAt:G,...J!==void 0?{accountId:J}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}}}function Q9(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 W9(Z,$){if(Z.type==="api")return{...Z,baseURL:Z.baseURL.trim(),authHeader:Z.authHeader??"authorization-bearer"};return{...Z,...$!==void 0?{lastRefreshedAt:$}:{}}}function Y9(Z,$={}){if(!_(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)&&!Z8(Z.baseURL))return"api credential needs a valid baseURL";return}return"credential type must be oauth or api"}var w3="transition",H9="transitionMark";function w2(Z){if(!_(Z))return;let $=Z[w3];if(!_($))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 n1(Z,$,X){if(X.enabled)d1(Z,$);else xZ(Z,$,X.reason??"");if(!Z.rosterRow($))return;let J=Z.entry($)??{credentialEpoch:1,needsFirstReading:!0};if(Z.setEntry($,{...J,[H9]:X.mark}),!X.enabled)return;let z=Z.rows().find((G)=>G.id===$);if(z?.type==="oauth"&&z.identity!==void 0)F1(Z,z.identity)}function p2(Z,$){if(Z.type!=="api")return Z;return{...Z,...$.baseURL!==void 0?{baseURL:$.baseURL}:{},...$.authHeader!==void 0?{authHeader:$.authHeader}:{}}}function l2(Z){if(!Z.binding)return!1;return Z.replace===!0||Z.dispatch===void 0}function u2(Z,$,X,J={}){let z=_($.accounts)?$.accounts:{},G=new Map;for(let B of mZ(Z,$,X)){if(B.invalid||B.staged||!B.credential)continue;let Q=Object.hasOwn(z,B.id)?z[B.id]:void 0;if(!_(Q))continue;let W=ZZ(Q[b]);if(!W?.binding)continue;if(W.digest!==LZ(B.credential))continue;let Y=B.credentialEpoch??1;if(W.credentialEpoch>Y){if(!l2(W))continue;if(J.requireCredentialStamps){if(W.dispatch===void 0)continue;if(W.dispatch!==AZ(p2(B.credential,W.binding)))continue}G.set(B.id,{kind:"replace",stamp:{...W,binding:W.binding}})}else if(W.credentialEpoch===Y&&W.dispatch!==void 0&&W.dispatch===AZ(B.credential)&&W.binding.identity!==void 0&&B.identity===void 0)G.set(B.id,{kind:"identity",identity:W.binding.identity});else if(W.credentialEpoch===Y&&W.binding.identity===B.identity){if(J.requireCredentialStamps&&W.dispatch!==AZ(B.credential))continue;let U=w2(Q[b]);if(U&&gZ(Z,B.id)?.[H9]!==U.mark)G.set(B.id,{kind:"transition",transition:U})}}return G}function z8(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(K1))delete G.disabledReason;Z.setEntry($,G);let B=Z.rosterRow($);if(!B)return;if(J.identity!==void 0)B.accountId=J.identity;else delete B.accountId;if(J.baseURL!==void 0)B.baseURL=J.baseURL;if(J.authHeader!==void 0)B.authHeader=J.authHeader}function G8(Z,$,X,J={}){let z=u2(Z,$,X,J);if(z.size===0)return{config:Z,torn:[]};let G=structuredClone(Z),B={rows:()=>mZ(G,$,X),rosterRow:(Q)=>v3(G,Q),entry:(Q)=>gZ(G,Q),setEntry:(Q,W)=>g3(G,Q,W)};for(let[Q,W]of z)if(W.kind==="replace")z8(B,Q,W.stamp.credentialEpoch,W.stamp.binding);for(let[Q,W]of z)if(W.kind==="identity")nZ(B,Q,W.identity);else if(W.kind==="transition")n1(B,Q,W.transition);else if(W.stamp.binding.identity!==void 0)F1(B,W.stamp.binding.identity);return{config:G,torn:[...z.keys()]}}function B8(Z,$,X,J={}){let{config:z,torn:G}=G8(Z,$,X,J),B=mZ(z,$,X,J.providerState);for(let Q of B){if(G.includes(Q.id))Q.torn=!0,Q.candidate=!1;if(J.requireCredentialStamps&&Q.stamp!=="bound")Q.unbound=!0,Q.candidate=!1}return B}async function Q8(Z){try{return await _1(Z,RZ)}catch($){if($.code==="ENOENT")return;throw $}}function U9(Z){if(Z===void 0)return{exists:!1};try{return{exists:!0,value:JSON.parse(Z)}}catch($){return{exists:!0,parseError:$}}}async function r(Z){for(let $=0;$<3;$++){let X=await Q8(Z.configPath),J=await Q8(Z.statePath),z=await Q8(Z.configPath);if(X!==z){if($<2)await d2(2+Math.floor(Math.random()*4));continue}let G=Z9(U9(X));if(G.status==="error")return{status:"error",file:"config",reason:G.reason};let B=$9(U9(J));if(B.status==="error")return{status:"error",file:"state",reason:B.reason};if(G.status==="pending-migration")return{status:"pending-migration",config:G.config};return{status:"ready",configExists:G.exists,stateExists:B.exists,config:G.config,state:B.state,rows:B8(G.config,B.state,Z.codec,{requireCredentialStamps:Z.requireCredentialStamps===!0,...Z.providerState?{providerState:Z.providerState}:{}})}}return{status:"error",file:"config",kind:"snapshot-contended",retryable:!0,reason:"The store was changing; retry the operation once writes settle."}}function KZ(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 D9{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 B8(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)?.[b];return _($)&&Object.hasOwn($,"staged")?$.staged:void 0}assertNotStaged(Z){rZ(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(),v3(this.config,Z)}dropRosterRows(Z){let $=this.roster(),X=$.filter((J)=>!(_(J)&&J.id===Z));return this.config.accounts=X,$.length-X.length}entries(){return X8(this.config)}entry(Z){return this.entries(),gZ(this.config,Z)}setEntry(Z,$){g3(this.config,Z,$)}async completeTorn(){let{config:Z,torn:$}=G8(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 $=_(this.state.accounts)?this.state.accounts:{},X=Object.hasOwn($,Z)?$[Z]:void 0;return _(X)?X:void 0}dropStateAccount(Z){if(_(this.state.accounts)&&Object.hasOwn(this.state.accounts,Z))delete this.state.accounts[Z]}setStateAccount(Z,$){if(!_(this.state.accounts))this.state.accounts={};Object.defineProperty(this.state.accounts,Z,{value:$,enumerable:!0,writable:!0,configurable:!0})}async commitConfig(Z={}){let $=this.roster(),X=new Set;for(let W of $)if(_(W)&&typeof W.id==="string")X.add(W.id);let J=new Set;for(let W of P1(this.snapshot.config))if(_(W)&&typeof W.id==="string"&&!X.has(W.id))J.add(W.id);for(let W of Object.keys(this.entries()))if(!X.has(W))J.add(W);B9(this.config,J);let z=this.entries(),G={};for(let[W,Y]of Object.entries(z))if(X.has(W))Object.defineProperty(G,W,{value:Y,enumerable:!0,writable:!0,configurable:!0});let B=this.config[y],Q={...this.config,version:s1,accounts:$,[y]:{...B,schemaVersion:vZ,[qZ]:G}};await this.write(this.ctx.configPath,Q,"config",Z.counted??!0,Z.durable??!1,()=>{if(Z.publicationDecision)this.markPublicationDecision();for(let W of J)this.ctx.removedIds.add(W);this.config=Q}),this.config=Q}async commitState(Z,$={}){let X={...this.state,version:s1,accounts:_(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 W8(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 W8(this.ctx.configPath)}async write(Z,$,X,J=!0,z=!1,G){await j9(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 K9(Z,$){let X=new hZ(Z.lockDefaults,Z.lockEnv),J={writes:0};try{for(let Q of Z.storeLocks)await X.acquire(Q);let z=await r(Z);if(z.status==="error")throw KZ(z,"initialize",void 0);if(z.status==="ready")return"already-ready";let G={};for(let[Q,W]of Object.entries(z.config))if(!$.includes(Q))G[Q]=W;G.version=s1,G[y]={schemaVersion:vZ,[qZ]:{}};let B={operation:"initialize",rowId:void 0};return await n(Z.configPath,G,{beforeRename:async()=>{await Z.onStep?.("before-config-write",B),await X.assertAll()}}),J.writes++,await Z.onStep?.("after-config-write",B),"initialized"}catch(z){throw O1(z,"initialize",void 0,J)}finally{await X.releaseAll()}}async function g(Z,$,X,J,z,G={}){let B=$.held.length;try{for(let Y of Z.storeLocks)await $.acquire(Y);let Q=await r(Z);if(Q.status!=="ready")throw KZ(Q,J.operation,J.rowId,X.writes>0?"after-first-write":"before-first-write");let W=new D9(Z,Q,$,X,J);if(J.rowId!==void 0&&!["add","remove","pull","publishRoster","enable","disable"].includes(J.operation))W.assertNotStaged(J.rowId);if(G.completeTorn??!0)await W.completeTorn();return await z(W)}finally{await $.releaseTo(B)}}function O1(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 V9)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 B={operation:$,...X!==void 0?{rowId:X}:{},phase:z,...G?{committed:G}:{},cause:Z};if(Z instanceof q9)return new E({...B,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 x3)return new E({...B,retryable:!0,kind:"lock-contention",message:Z.message});return new E({...B,retryable:!1,kind:"unexpected",message:Z instanceof Error?Z.message:String(Z)})}async function i(Z,$,X,J,z){let G=new hZ(Z.lockDefaults,Z.lockEnv),B={writes:0};try{return await z(G,B)}catch(Q){let W=O1(Q,$,X,B);if(W.kind!=="after-persist-hook")await o$($,J,X,W,Z.logger);throw W}finally{await G.releaseAll()}}function zZ(Z,$){return{...Z.rowLockOptions,name:`row-${encodeURIComponent(x($))}`,path:Z.ctx.statePath}}async function EZ(Z,$,X){let J=await r(Z.ctx);if(J.status!=="ready")throw KZ(J,$,X);let z=J.rows.find((Y)=>Y.id===X),G=gZ(J.config,X),B=J.state.accounts,Q=_(B)&&Object.hasOwn(B,X)?B[X]:void 0,W=_(Q)?Q[b]:void 0;if(z&&!["enable","disable"].includes($)&&G&&Object.hasOwn(G,"staged"))rZ($,X,G.staged);if(!z&&_(W)&&Object.hasOwn(W,"staged"))rZ($,X,W.staged);if(!z)throw FZ($,X);return{result:J,row:z}}function FZ(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 o(Z,$){if($.unbound)throw L(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 L(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 p3(Z,$,X,J){let{ctx:z}=Z,G=new hZ(z.lockDefaults,z.lockEnv),B={writes:0};try{if(!l(X?.credentialEpoch))throw L("pull",$,"invalid-input","the credential epoch the reading was issued for must be a positive safe integer");await g(z,G,B,{operation:"pull",rowId:$},async(Q)=>{Q.assertNotStaged($);let W=Q.row($);if(!W)throw FZ("pull",$);if(W.invalid)throw L("pull",$,"invalid-row",`row ${$} is invalid`);if(!W.credential)throw L("pull",$,"no-credential",`row ${$} holds no credential`);o("pull",W);let Y=Q.entry($);if(W.torn||!Y||Y.credentialEpoch!==X.credentialEpoch||W.identity!==X.identity)throw new E({operation:"pull",rowId:$,phase:"pull",retryable:!0,kind:"attribution",message:`quota for ${$} was issued for a credential the row no longer holds`});let U=z.codec.merge(Y.quota,J);if(!z.codec.validate(U))throw L("pull",$,"invalid-quota","the quota codec rejected the merged map");Q.setEntry($,{...Y,quota:U,needsFirstReading:!1}),await Q.commitConfig()},{completeTorn:!1})}catch(Q){throw O1(Q,"pull",$,B)}finally{await G.releaseAll()}}function bZ(Z,$,X,J,z="the provider state"){if(!Z)throw L($,X,"invalid-input","the store was opened without a provider-state codec");let G;try{let B=JSON.stringify(J);G=B===void 0?void 0:JSON.parse(B)}catch{G=void 0}if(G===void 0)throw L($,X,"invalid-provider-state",`${z} cannot be stored as JSON`);if(!Z.validate(G))throw L($,X,"invalid-provider-state",`the provider-state codec rejected ${z}`);return G}function r1(Z,$,X,J,z){if(J===void 0||!Z?.merge)return{kind:"set",value:z};return{kind:"set",value:bZ(Z,$,X,Z.merge(structuredClone(J),structuredClone(z)),"the merged provider state")}}function F9(Z,$,X,J,z){let G=Z?.onReplace,B=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(B===void 0)return{kind:"clear"};if(!G)return{kind:"set",value:B};return{kind:"set",value:bZ(Z,"replace",$.id,B,"the provider state onReplace returned")}}function N9(Z,$,X,J,z){if($.kind==="set")return M1(Z,$.value);if($.kind==="clear")return;return i1(X,J?.credential,z,J?.identity)}async function M9(Z,$,X,J,z={}){s("updateProviderState");let{ctx:G}=Z,B="updateProviderState";return i(G,B,$,z.onFailure,async(Q,W)=>{let Y=G.providerState;if(!Y)throw L(B,$,"invalid-input","the store was opened without a provider-state codec");if(typeof J!=="function")throw L(B,$,"invalid-input","a mutator is required");let U=_(X)?X.credentialEpoch:void 0;if(!l(U))throw L(B,$,"invalid-input","the credential epoch the provider state was read at is required");let{row:V}=await EZ(Z,B,$);await Q.acquire(zZ(Z,V));for(let j of z.extraLocks??[])await Q.acquire(j);return g(G,Q,W,{operation:B,rowId:$},async(j)=>{let D=j.row($);if(!D)throw FZ(B,$);if(x(D)!==x(V))throw L(B,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0);if(D.invalid)throw L(B,$,"invalid-row",`row ${$} failed validation`);if(!D.credential)throw L(B,$,"no-credential",`row ${$} holds no credential`);if(o(B,D),(D.credentialEpoch??1)!==U||D.identity!==X.identity)throw L(B,$,"attribution",`the provider state for ${$} was read for a credential or account the row no longer holds`,!0);let q=await Y8(j,Y,B,D,J);if(q.kind!=="changed")return{id:$,outcome:"unchanged",...q.kind==="unchanged"&&q.value!==void 0?{providerState:q.value}:{}};return j.setStateAccount($,q.account),await j.commitState(),q.value===void 0?{id:$,outcome:"cleared"}:{id:$,outcome:"updated",providerState:q.value}})})}var P9=Symbol.for("@cortexkit/common-auth/store/decline-transition");async function Y8(Z,$,X,J,z,G=!1){let{id:B,credential:Q}=J;if(!Q)throw L(X,B,"no-credential",`row ${B} holds no credential`);let W=J.credentialEpoch??1,Y=Z.stateAccount(B),U=Y?.[b],V=ZZ(U);if(!_(U)||!V?.binding||V.digest!==LZ(Q)||V.credentialEpoch!==W||V.binding.identity!==J.identity)throw L(X,B,"unbound-credential",`row ${B}'s credential carries no stamp of this store to bind a provider state to (stamp ${J.stamp}); rotate or replace it first`);let j=J.providerState===void 0?void 0:structuredClone(J.providerState),D=await PZ(X,()=>z(j,J));if(G&&D===P9)return{kind:"declined"};let H=D===void 0?void 0:bZ($,X,B,D,"the provider state the mutator returned"),q=Y!==void 0&&Object.hasOwn(Y,a);if(H===void 0?!q:J.providerState!==void 0&&JSON.stringify(J.providerState)===JSON.stringify(H))return{kind:"unchanged",...H!==void 0?{value:H}:{}};let N={...Y};if(H===void 0){delete N[a];let M={...U};delete M.providerState,N[b]=M}else{N[a]=H;let M=M1($,H);if(V.providerState!==M)N[b]={...U,providerState:M}}return{kind:"changed",...H!==void 0?{value:H}:{},account:N}}import{randomUUID as L9}from"node:crypto";async function c3(Z,$,X){if(!X)return;let J=Z.rows().map((G)=>{let{id:B,type:Q,label:W,enabled:Y,disabledReason:U,identity:V,credentialEpoch:j,stamp:D,staged:H,torn:q,invalid:N}=G;return{id:B,type:Q,label:W,enabled:Y,disabledReason:U,identity:V,credentialEpoch:j,stamp:D,staged:H,torn:q,invalid:N}}),z=await PZ(Z.info.operation,()=>X({id:$,row:J.find((G)=>G.id===$),rows:J,config:structuredClone(Z.snapshot.config)}));if(z!==void 0)throw L(Z.info.operation,$,"row-protected",z)}var c2=["access","refresh","expires","lastRefreshedAt","apiKey"];function s2(Z){return{baseURL:String(Z.baseURL).trim(),authHeader:Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer"}}function i2(Z,$,X){if(X.type!=="api")return X;let J=Z.rosterRow($);if(!_(J)){if(X.baseURL===void 0)throw L(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"}:s2(J),B=X.baseURL?.trim()??G.baseURL,Q=X.authHeader??G.authHeader;if(B!==G.baseURL||Q!==G.authHeader)throw L(Z.info.operation,$,"endpoint-mismatch",`row ${$} sends its key to another endpoint or header; a key for another endpoint is a replacement`);return{...X,baseURL:B,authHeader:Q}}function _9(Z,$,X,J){let z=Z.rosterRow($),G=Z.row($),B=J??(G?G.identity:_(z)&&typeof z.accountId==="string"&&z.accountId?z.accountId:void 0);return{...B!==void 0?{identity:B}:{},...X.type==="api"?{baseURL:X.baseURL,authHeader:X.authHeader??"authorization-bearer"}:{}}}function l3(Z,$,X,J,z={}){let G=i2($,X,J),B=$.stateAccount(X),Q=z.providerState??{kind:"keep"},W=$.row(X)?.credentialEpoch??$.entry(X)?.credentialEpoch,Y=typeof W==="number"?W:1,U=N9(Z.ctx.providerState,Q,B,B&&Object.hasOwn(B,a)?$.row(X):void 0,Y),V=typeof B?.lastRefreshedAt==="number"?B.lastRefreshedAt:void 0,j=G.type==="oauth"?z.stamp??a1(V,Z.ctx.now()):void 0,D={...B??{}};for(let N of c2)delete D[N];if(z.clearErrors)delete D.lastRefreshError,delete D.lastQuotaRefreshError,delete D.quota;if(Q.kind==="clear")delete D[a];else if(Q.kind==="set")D[a]=Q.value;let H=W9(G,j),q={...D,...Q9(G,j),[b]:{...z.staged?{staged:z.staged}:{},...z.transition!==void 0?{[w3]:z.transition}:{},...$8(H,Y,z.binding??_9($,X,H,z.identity),{replace:z.binding!==void 0,...U!==void 0?{providerState:U}:{}})}};return{stored:H,account:q}}async function u3(Z,$,X){return Z.setStateAccount($,X.account),await Z.commitState(X.stored),X.stored}async function s3(Z,$,X,J,z={}){return u3($,X,l3(Z,$,X,J,z))}async function a2(Z,$,X){if(!$.credential||$.stamp!=="bound")return;let J=Z.stateAccount($.id),z=i1(J,$.credential,$.credentialEpoch??1,$.identity);Z.setStateAccount($.id,{...J??{},[b]:$8($.credential,$.credentialEpoch??1,_9(Z,$.id,$.credential,X),z!==void 0?{providerState:z}:{})}),await Z.commitState()}function U8(Z,$,X){let J=Z==="add"?N1($):void 0;if(J)throw L(Z,$,"invalid-input",J);let z=Y9(X,{baseURLOptional:Z==="rotate"});if(z)throw L(Z,$,"invalid-input",z)}function i3(Z,$,X,J){if(!X)throw FZ(Z,$);if(X.invalid)throw L(Z,$,"invalid-row",`row ${$} failed validation`);if(J&&J.type!==X.type)throw L(Z,$,"type-mismatch",`row ${$} holds a ${X.type} credential`);return X}function T1(Z,$,X){if(X!==void 0&&!l(_(X)?X.credentialEpoch:void 0))throw L(Z,$,"invalid-input","the attribution must name a credential epoch that is a positive safe integer")}function a3(Z,$,X,J){if(!X)throw FZ(Z,$);if(X.invalid)throw L(Z,$,"invalid-row",`row ${$} failed validation`);if((X.credentialEpoch??1)!==J.credentialEpoch||X.identity!==J.identity)throw L(Z,$,"attribution",`the ${Z} of ${$} was issued for a credential or account the row no longer holds`,!0)}function d3(Z,$){return L(Z,$,"identity-mismatch",`row ${$} is recorded for another account; a credential of a different account is a replacement`)}function o1(Z,$){return L(Z,$,"row-key-changed",`row ${$}'s wire identity changed while its lock was being taken`,!0)}function n2(Z,$,X,J){let{id:z,credential:G,identity:B}=X;if(!Z.ctx.requireCredentialStamps||$.rosterRow(z)||!C1($.state,z))return;let Q=()=>{throw L("add",z,"unbound-credential",`orphan ${z} cannot be bound to this add's material; remove it explicitly before adding different material`)},W=$.stateAccount(z),Y=ZZ(W?.[b]);if(!Y?.binding||Y.dispatch===void 0||Y.replace)return Q();if(G.type==="api"&&(Y.binding.baseURL===void 0||Y.binding.authHeader===void 0))return Q();let U=G.type==="api"?{...G,baseURL:Y.binding.baseURL,authHeader:Y.binding.authHeader}:G,[V]=mZ({accounts:[L1({id:z,credential:U,identity:Y.binding.identity,addedAt:0})],[y]:{rows:{[z]:{credentialEpoch:m3($.config,z)}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!V?.credential||V.invalid||V.stamp!=="bound")return Q();if(B!==void 0&&B!==V.identity)return Q();if(LZ(G)!==Y.digest)return Q();if(G.type==="api"){if(G.baseURL.trim()!==Y.binding.baseURL)return Q();if((G.authHeader??"authorization-bearer")!==Y.binding.authHeader)return Q()}else if(AZ(G)!==Y.dispatch)return Q();if(Y.providerState!==void 0&&V.providerState===void 0)return Q();if(J!==void 0&&M1(Z.ctx.providerState,J)!==Y.providerState)return Q();return V}function r2(Z,$,X,J){let{id:z,credential:G,identity:B,label:Q}=X,W=$.rosterRow(z),Y=()=>{throw L("add",z,W?"id-exists":"unbound-credential",`row ${z} does not match this staged add`)},U=$.stateAccount(z),V=ZZ(U?.[b]),j=V?.staged;if(!V?.binding||!j||V.replace||V.dispatch===void 0)return Y();if(W&&(W.type!==G.type||W.label!==Q||W.accountId!==B))return Y();if(j.reservation!==X.stage?.reservation||j.label!==Q||j.disabledReason!==X.disabled?.reason||V.binding.identity!==B)return Y();let D=J===void 0?void 0:oZ(J),H=U?.[a],q=H===void 0?void 0:oZ(H);if(j.providerState!==D||j.providerState!==q)return Y();if(LZ(G)!==V.digest||AZ(G)!==V.dispatch)return Y();let N=W?$.config:{accounts:[{...L1({id:z,credential:G.type==="api"?{...G,baseURL:V.binding.baseURL??"",authHeader:V.binding.authHeader}:G,identity:V.binding.identity,label:j.label,addedAt:0}),enabled:!1}],[y]:{rows:{[z]:{credentialEpoch:V.credentialEpoch,disabledReason:j.disabledReason,staged:{reservation:j.reservation}}}}},M=mZ(N,$.state,Z.ctx.codec,Z.ctx.providerState).find((O)=>O.id===z);if(!M?.credential||M.invalid||M.stamp!=="bound"||M.type!==G.type||M.enabled||M.label!==j.label||M.identity!==V.binding.identity||M.disabledReason!==j.disabledReason||M.staged?.reservation!==j.reservation)return Y();if(W)return{id:z,outcome:"exists",credential:M.credential,credentialEpoch:V.credentialEpoch};if(m3($.config,z)!==V.credentialEpoch)return Y();return $.roster().push({...L1({id:z,credential:G,identity:B,label:Q,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:M.credential,credentialEpoch:V.credentialEpoch}))}async function O9(Z,$,X={}){s("add");let{ctx:J}=Z,{id:z,credential:G,identity:B,label:Q}=$,W=$.stage!==void 0||$.disabled!==void 0,Y=await i(J,"add",z,X.onFailure,async(U,V)=>{U8("add",z,G);let j=X.onExisting??"rotate";if($.stage!==void 0&&j==="rotate")throw L("add",z,"invalid-input","a staged add needs onExisting: 'refuse' or 'stage-duplicate'");if(!["rotate","refuse","stage-duplicate"].includes(j)||$.stage!==void 0&&(Q!==void 0&&typeof Q!=="string"||B!==void 0&&(typeof B!=="string"||!B))||$.disabled!==void 0&&(!_($.disabled)||typeof $.disabled.reason!=="string")||$.stage!==void 0&&(!_($.stage)||typeof $.stage.reservation!=="string"||!$.stage.reservation||!$.disabled)||j==="stage-duplicate"&&(!$.disabled||!$.stage))throw L("add",z,"invalid-input","staging requires a reservation and a disabled reason");let D=$.providerState===void 0?void 0:bZ(J.providerState,"add",z,$.providerState);if(await U.acquire(zZ(Z,{id:z,identity:B})),G.type==="oauth")await U.acquire(X.providerLock??Z.providerLock);for(let H of X.extraLocks??[])await U.acquire(H);return g(J,U,V,{operation:"add",rowId:z},async(H)=>{await c3(H,z,X.protect);let q=_(H.state.accounts)?H.state.accounts:{},N=Object.entries(q).find(([h,f])=>{if(h===z||H.rosterRow(h)||!_(f))return!1;let m=f[b];if(!_(m)||!Object.hasOwn(m,"staged"))return!1;return G.type==="oauth"?f.refresh===G.refresh:typeof f.apiKey==="string"&&f.apiKey.trim()===G.apiKey.trim()});if(N)throw L("add",N[0],"row-staged",`orphan ${N[0]} reserves this secret until its staged add is replayed or removed`);if(J.removedIds.has(z))throw L("add",z,"id-removed",`id ${z} was removed from the roster in this process and is not reused`);if($.stage&&j!=="rotate"&&(H.rosterRow(z)||C1(H.state,z)))return r2(Z,H,$,D);if(j==="rotate"){H.assertNotStaged(z);let h=H.rows().find((f)=>f.fingerprint===DZ(G));if(h)H.assertNotStaged(h.id)}if(j==="refuse"){let h=H.rows().find((d)=>d.fingerprint===DZ(G)||d.id===z&&d.credential),f=_(H.state.accounts)?H.state.accounts:{},m=Object.entries(f).find(([,d])=>{if(!_(d))return!1;if(G.type==="oauth")return d.refresh===G.refresh;return typeof d.apiKey==="string"&&d.apiKey.trim()===G.apiKey.trim()})?.[0],JZ=h?.id??m??z;if(h||m!==void 0||C1(H.state,z))throw L("add",JZ,"credential-exists",`row ${JZ} already holds this secret or id`)}if(j==="stage-duplicate"&&(H.rosterRow(z)||C1(H.state,z)))throw L("add",z,"id-exists",`row ${z} already exists`);let M=n2(Z,H,$,D),O=H.rows(),S=DZ(G),F=j==="rotate"&&!M&&O.find((h)=>h.invalid===void 0&&h.fingerprint===S);if(F){if(H.assertNotStaged(F.id),o("add",F),B!==void 0&&F.identity!==void 0&&B!==F.identity)throw d3("add",F.id);let h=l3(Z,H,F.id,G,{...D!==void 0?{providerState:r1(J.providerState,"add",F.id,F.providerState,D)}:{}});await H.completeTorn(),H.assertNotStaged(F.id);let f=await u3(H,F.id,h);return{id:F.id,outcome:"rotated",credential:f,credentialEpoch:F.credentialEpoch??1}}let K=O.find((h)=>h.id===z);if(K){if(K.invalid)throw L("add",z,"invalid-row",`row ${z} is invalid`);if(K.credential)throw L("add",z,"id-exists",`row ${z} already holds a credential`);if(o("add",K),K.type!==G.type)throw L("add",z,"type-mismatch",`row ${z} is a ${K.type} row`);if(B!==void 0&&K.identity!==void 0&&B!==K.identity)throw d3("add",z);if(!K.hasEntry)H.setEntry(z,{credentialEpoch:1,needsFirstReading:G.type==="oauth"});let h=l3(Z,H,z,G,{clearErrors:!0,...D!==void 0?{providerState:{kind:"set",value:D}}:{}});await H.completeTorn();let f=await u3(H,z,h);if(!K.hasEntry)await H.commitConfig();return{id:z,outcome:"completed",credential:f,credentialEpoch:K.credentialEpoch??1}}let P=m3(H.config,z);if(!l(P))throw L("add",z,"id-removed",`id ${z} has held every credential epoch and is not reused; add the credential under another id`);let C=M?.identity??B;H.roster().push(L1({id:z,credential:G,...C!==void 0?{identity:C}:{},...Q!==void 0?{label:Q}:{},addedAt:J.now()})),H.setEntry(z,{credentialEpoch:P,needsFirstReading:G.type==="oauth",...$.stage?{staged:{reservation:$.stage.reservation}}:{}});let k="added";if($.disabled)xZ(H,z,$.disabled.reason),k="added-disabled";if(!$.disabled&&C!==void 0&&G.type==="oauth"){if(O.find((f)=>f.invalid===void 0&&f.type==="oauth"&&f.enabled&&f.identity===C))xZ(H,z,o6),k="added-disabled"}if(M?.credential)return await H.commitConfig(),{id:z,outcome:k,credential:M.credential,credentialEpoch:M.credentialEpoch??P};H.dropStateAccount(z);let t=l3(Z,H,z,G,{...$.stage&&$.disabled?{staged:{reservation:$.stage.reservation,disabledReason:$.disabled.reason,...Q!==void 0?{label:Q}:{},...D!==void 0?{providerState:oZ(D)}:{}}}:{},...D!==void 0?{providerState:{kind:"set",value:D}}:{}});if(j==="rotate")await H.completeTorn();let e=await u3(H,z,t);return await H.commitConfig(),{id:z,outcome:k,credential:e,credentialEpoch:P}},{completeTorn:!1})});if(!W&&G.type==="oauth"&&(Y.outcome==="added"||Y.outcome==="completed"))Z.firePull(Y.id,"add");return Y}async function C9(Z,$,X,J={},z={}){s("replace");let{ctx:G}=Z,B=await i(G,"replace",$,z.onFailure,async(Q,W)=>{U8("replace",$,X),T1("replace",$,z.attribution);let Y=J.providerState===void 0?void 0:bZ(G.providerState,"replace",$,J.providerState),{row:U}=await EZ(Z,"replace",$);if(await Q.acquire(zZ(Z,U)),X.type==="oauth")await Q.acquire(z.providerLock??Z.providerLock);for(let V of z.extraLocks??[])await Q.acquire(V);return g(G,Q,W,{operation:"replace",rowId:$},async(V)=>{if(z.attribution!==void 0)a3("replace",$,V.row($),z.attribution),await V.completeTorn();let j=i3("replace",$,V.row($),X);if(x(j)!==x(U))throw o1("replace",$);let D=V.entry($)?.credentialEpoch,H=(typeof D==="number"?D:1)+1;if(!l(H))throw L("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=F9(G.providerState,j,H,J.identity,Y),N={...J.identity!==void 0?{identity:J.identity}:{},...X.type==="api"?{baseURL:X.baseURL.trim(),authHeader:X.authHeader??"authorization-bearer"}:{}};if(z8(V,$,H,N),J.identity!==void 0)F1(V,J.identity);let M=await s3(Z,V,$,X,{clearErrors:!0,binding:N,providerState:q});return await V.commitConfig(),{id:$,credential:M,credentialEpoch:H}},{completeTorn:z.attribution===void 0})});if(X.type==="oauth")Z.firePull($,"replace");return B}async function T9(Z,$,X,J={},z={}){s("rotate");let{ctx:G}=Z;return i(G,"rotate",$,z.onFailure,async(B,Q)=>{U8("rotate",$,X),T1("rotate",$,z.attribution);let W=J.providerState===void 0?void 0:bZ(G.providerState,"rotate",$,J.providerState),{row:Y}=await EZ(Z,"rotate",$);if(await B.acquire(zZ(Z,Y)),J.identity!==void 0&&X.type==="oauth")await B.acquire(z.providerLock??Z.providerLock);for(let U of z.extraLocks??[])await B.acquire(U);return g(G,B,Q,{operation:"rotate",rowId:$},async(U)=>{if(z.attribution!==void 0)a3("rotate",$,U.row($),z.attribution),await U.completeTorn();let V=i3("rotate",$,U.row($),X);if(x(V)!==x(Y))throw o1("rotate",$);if(o("rotate",V),J.identity!==void 0&&V.identity!==void 0&&J.identity!==V.identity)throw d3("rotate",$);let j=J.identity!==void 0&&V.identity===void 0?J.identity:void 0,D=await s3(Z,U,$,X,{identity:j,...W!==void 0?{providerState:r1(G.providerState,"rotate",$,V.providerState,W)}:{}}),H=!1;if(!V.hasEntry)U.setEntry($,{credentialEpoch:1,needsFirstReading:V.type==="oauth"}),H=!0;if(J.identity!==void 0&&V.identity!==J.identity)nZ(U,$,J.identity),H=!0;if(H)await U.commitConfig();return{id:$,credential:D}},{completeTorn:z.attribution===void 0})})}async function S9(Z,$,X,J,z){s($);let{ctx:G}=Z,B=G.providerState,Q=z.attribution,W=z.providerState;return i(G,$,X,z.onFailure,async(Y,U)=>{if(T1($,X,Q),W!==void 0){if(typeof W!=="function")throw L($,X,"invalid-input","the provider-state mutator must be a function");if(Q===void 0)throw L($,X,"invalid-input","a provider-state change needs the attribution of the credential it is for");if(!B)throw L($,X,"invalid-input","the store was opened without a provider-state codec")}let{row:V}=await EZ(Z,$,X);await Y.acquire(zZ(Z,V));for(let j of z.extraLocks??[])await Y.acquire(j);return g(G,Y,U,{operation:$,rowId:X},async(j)=>{await c3(j,X,z.protect),j.assertNotStaged(X);let D=j.row(X),H=J.enabled?i3("enable",X,D):D;if(!H||!j.rosterRow(X))throw FZ($,X);if(x(H)!==x(V))throw o1($,X);if(Q!==void 0)a3($,X,H,Q);if(J.enabled&&H.disabledReason?.startsWith(K1))throw L("enable",X,"identity-contradicted",`row ${X} needs an identity-validated credential replacement before it can be enabled`);let q=!J.enabled||!H.enabled||H.disabledReason!==void 0;if(J.enabled&&q&&H.type==="oauth"){let F=H.identity===void 0?void 0:j.rows().find((K)=>K.id!==X&&K.invalid===void 0&&K.type==="oauth"&&K.enabled&&K.identity===H.identity);if(F)throw L("enable",X,"duplicate-identity",`row ${F.id} is enabled with the same identity as row ${X}`)}if(W===void 0||B===void 0){if(await j.completeTorn(),!q)return{id:X};if(J.enabled)d1(j,X);else xZ(j,X,J.reason);return await j.commitConfig(),{id:X}}if(!H.credential)throw L($,X,"no-credential",`row ${X} holds no credential`);o($,H);let N=await Y8(j,B,$,H,W,!0);if(N.kind==="declined")return{id:X,declined:!0};await j.completeTorn();let M={id:X,providerStateOutcome:N.kind==="unchanged"?"unchanged":N.value===void 0?"cleared":"updated",...N.value!==void 0?{providerState:N.value}:{}};if(N.kind==="unchanged"){if(q){if(J.enabled)d1(j,X);else xZ(j,X,J.reason);await j.commitConfig()}return M}if(!q)return j.setStateAccount(X,N.account),await j.commitState(),M;let O=J.enabled?{mark:L9(),enabled:!0}:{mark:L9(),enabled:!1,reason:J.reason},S=N.account[b];return j.setStateAccount(X,{...N.account,[b]:{...S,[w3]:O}}),await j.commitState(),n1(j,X,O),await j.commitConfig(),M},{completeTorn:!1})})}function A9(Z,$,X,J={}){return S9(Z,"disable",$,{enabled:!1,reason:X},J)}function R9(Z,$,X={}){return S9(Z,"enable",$,{enabled:!0},X)}async function E9(Z,$,X={}){s("remove");let{ctx:J}=Z;return i(J,"remove",$,X.onFailure,async(z,G)=>{if(typeof $!=="string"||$.length===0)throw L("remove",$,"invalid-input","id must be non-empty");let B=X.attribution;if(T1("remove",$,B),X.staged!==void 0&&(!_(X.staged)||typeof X.staged.reservation!=="string"||!X.staged.reservation))throw L("remove",$,"invalid-input","a staged removal needs a reservation");let Q=await r(J);if(Q.status!=="ready")throw KZ(Q,"remove",$);let W=Q.rows.find((U)=>U.id===$);if(!W&&!C1(Q.state,$))throw FZ("remove",$);let Y=x(W??{id:$});await z.acquire(zZ(Z,W??{id:$}));for(let U of X.extraLocks??[])await z.acquire(U);return g(J,z,G,{operation:"remove",rowId:$},async(U)=>{let V=U.reservation($);if(V!==void 0){if(!_(V)||!X.staged||V.reservation!==X.staged.reservation)throw L("remove",$,"row-staged",`row ${$} is reserved for roster publication`)}else if(X.staged)throw L("remove",$,"attribution",`row ${$} is no longer reserved`);let j=U.row($),D=C1(U.state,$);if(!j&&!D)throw FZ("remove",$);if(x(j??{id:$})!==Y)throw o1("remove",$);if(B!==void 0)if(j)n3($,j,B);else o2(Z,U,$,B);let H=X.protect;if(H){let q={row:j,config:U.snapshot.config,state:U.snapshot.state},N=await PZ("remove",()=>H($,q));if(N!==void 0)throw L("remove",$,"row-protected",N)}if(j){if(B===void 0)await U.completeTorn();U.dropRosterRows($),await U.commitConfig()}if(D)U.dropStateAccount($),await U.commitState();return{id:$,outcome:j?"removed":"completed"}},{completeTorn:!1})})}function n3(Z,$,X,J="remove"){if(a3(J,Z,$,X),$.torn)throw L(J,Z,"attribution",`row ${Z} is between the writes of another operation; retry once it completes`,!0);if($.stamp!=="bound")throw L(J,Z,"unbound-credential",`row ${Z}'s credential is not bound to its stamp, so the removal cannot be attributed to it`)}function o2(Z,$,X,J){let z=()=>L("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),B=ZZ(G?.[b]);if(!G||!B?.binding||B.dispatch===void 0||B.replace)throw z();let Q;if(typeof G.apiKey==="string"){if(B.binding.baseURL===void 0||B.binding.authHeader===void 0)throw z();Q={type:"api",apiKey:G.apiKey,baseURL:B.binding.baseURL,authHeader:B.binding.authHeader}}else if(typeof G.refresh==="string")Q={type:"oauth",refresh:G.refresh};else throw z();let[W]=mZ({accounts:[L1({id:X,credential:Q,identity:B.binding.identity,addedAt:0})],[y]:{rows:{[X]:{credentialEpoch:B.credentialEpoch}}}},$.state,Z.ctx.codec,Z.ctx.providerState);if(!W?.credential||W.invalid||W.stamp!=="bound")throw z();if(B.credentialEpoch!==J.credentialEpoch||B.binding.identity!==J.identity)throw L("remove",X,"attribution",`orphan ${X} was written for a credential or account other than the one this removal was decided for`,!0)}function C1(Z,$){let X=Z.accounts;return _(X)&&Object.hasOwn(X,$)}function H8(Z){return _(Z)&&typeof Z.id==="string"?Z.id:void 0}function t2(Z,$){if(!Array.isArray($))return"ids must be an array of roster ids";let X=new Set;for(let G of Z){let B=H8(G);if(B!==void 0)X.add(B)}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 e2(Z,$){let X=new Map;for(let G of Z){let B=H8(G);if(B===void 0)continue;let Q=X.get(B);if(Q)Q.push(G);else X.set(B,[G])}let J=$.flatMap((G)=>X.get(G)??[]),z=0;return Z.map((G)=>H8(G)===void 0?G:J[z++])}async function b9(Z,$,X={}){s("reorder");let{ctx:J}=Z,z=X.onFailure;return i(J,"reorder",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let Q of X.extraLocks??[])await G.acquire(Q);return g(J,G,B,{operation:"reorder",rowId:void 0},async(Q)=>{let W=Q.roster(),Y=t2(W,$);if(Y)throw new E({operation:"reorder",phase:"before-first-write",retryable:!1,kind:"invalid-order",message:Y});let U=[...$],V=e2(W,U);if(V.every((j,D)=>j===W[D]))return{ids:U,outcome:"unchanged"};return Q.config.accounts=V,await Q.commitConfig(),{ids:U,outcome:"reordered"}},{completeTorn:!1})})}async function I9(Z,$,X,J,z={}){return s("recordIdentity"),i(Z.ctx,"recordIdentity",$,z.onFailure,async(G,B)=>{if(typeof X!=="string"||X.length===0)throw L("recordIdentity",$,"invalid-input","identity must be non-empty");let Q=_(J)?J.credentialEpoch:void 0;if(!l(Q))throw L("recordIdentity",$,"invalid-input","the credential epoch the identity lookup was issued for is required");let{row:W}=await EZ(Z,"recordIdentity",$);await G.acquire(zZ(Z,W)),await G.acquire(z.providerLock??Z.providerLock);for(let Y of z.extraLocks??[])await G.acquire(Y);return g(Z.ctx,G,B,{operation:"recordIdentity",rowId:$},async(Y)=>{let U=i3("recordIdentity",$,Y.row($));if(x(U)!==x(W))throw o1("recordIdentity",$);if(o("recordIdentity",U),(U.credentialEpoch??1)!==Q)throw L("recordIdentity",$,"attribution",`the identity for ${$} was looked up for a credential the row no longer holds`,!0);if(U.identity!==void 0&&U.identity!==X)throw d3("recordIdentity",$);if(U.identity===void 0)await a2(Y,U,X);let V=nZ(Y,$,X);return await Y.commitConfig(),{id:$,disabled:V}})})}function k9(Z){let $=Z[y];return _($)&&_($.publications)?$.publications:{}}function f9(Z,$){let X=k9(Z);if(!Object.hasOwn(X,$))return;let J=X[$];if(!_(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)=>!_(z)||typeof z.id!=="string"||!l(z.credentialEpoch))||J.finalized.some((z)=>!_(z)||typeof z.id!=="string"||!l(z.credentialEpoch)||typeof z.reservation!=="string"||!z.reservation||typeof z.enabled!=="boolean"))throw L("publishRoster",$,"invalid-input","the stored publication receipt is malformed");return structuredClone(J)}async function x9(Z,$){let X=await r(Z.ctx);if(X.status!=="ready")throw KZ(X,"publishRoster",$);return f9(X.config,$)}function Z5(Z,$){let X=()=>{throw L("publishRoster",$?.operationId??"","invalid-input","the publication plan is invalid")};if(!_($)||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(!_(z)||typeof z.id!=="string"||N1(z.id)||J.has(z.id)||!z.attribution)X();if(J.add(z.id),T1("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"||N1(z))||new Set($.order).size!==$.order.length)X()}function h9(Z,$){Z.entries();let X=Z.config[y],J={...k9(Z.config)};Object.defineProperty(J,$.operationId,{value:$,enumerable:!0,writable:!0,configurable:!0}),X.publications=J,delete X.publicationOrder}function $5(Z,$,X){let J=new Set;for(let B of P1(Z.config)){if(!_(B)||typeof B.id!=="string")continue;if(J.has(B.id))throw L("publishRoster",$.operationId,"invalid-input","publication needs a roster of unique named rows");J.add(B.id)}let z=new Set($.remove.map((B)=>B.id)),G=X.filter((B)=>B.invalid!=="roster"&&!z.has(B.id));if(G.length!==$.order.length||$.order.some((B)=>!G.some((Q)=>Q.id===B))||G.some((B)=>!$.order.includes(B.id)))throw L("publishRoster",$.operationId,"invalid-input","order must name exactly the surviving roster");return G}async function y9(Z,$){await Z.assertAll();for(let J of $.removed)if(ZZ(Z.stateAccount(J.id)?.[b])?.credentialEpoch===J.credentialEpoch&&!Z.rosterRow(J.id))Z.dropStateAccount(J.id);for(let J of $.finalized){let z=Z.stateAccount(J.id),G=ZZ(z?.[b]);if(z&&G?.credentialEpoch===J.credentialEpoch&&G.staged?.reservation===J.reservation){let B={...z[b]};delete B.staged,Z.setStateAccount(J.id,{...z,[b]:B})}}await Z.commitState(void 0,{durable:!0});let X={...$,phase:"cleaned"};return h9(Z,X),await Z.commitConfig({durable:!0}),X}async function v9(Z,$,X={}){return s("publishRoster"),i(Z.ctx,"publishRoster",$?.operationId??"",X.onFailure,async(J,z)=>{if(!_($)||typeof $.operationId!=="string"||!$.operationId)throw L("publishRoster",$?.operationId??"","invalid-input","the publication needs an operation id");$=structuredClone($);let G=oZ($),B=[...Array.isArray($.remove)?$.remove:[],...Array.isArray($.finalize)?$.finalize:[]].filter((Q)=>_(Q)&&typeof Q.id==="string");for(let Q=0;;Q++){let W=await r(Z.ctx);if(W.status!=="ready")throw KZ(W,"publishRoster",$.operationId);let Y=new Map(B.map(({id:V})=>[V,x(W.rows.find((j)=>j.id===V)??{id:V})]));for(let V of[...new Set(Y.values())].sort())await J.acquire(zZ(Z,{id:V}));await J.acquire(X.providerLock??Z.providerLock);for(let V of X.extraLocks??[])await J.acquire(V);let U=await g(Z.ctx,J,z,{operation:"publishRoster",rowId:$.operationId},async(V)=>{let j=V.rows();if(B.some(({id:K})=>x(j.find((P)=>P.id===K)??{id:K})!==Y.get(K)))return;let D=f9(V.config,$.operationId);if(D){if(D.planDigest!==G)throw L("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 y9(V,D)}}Z5(Z,$);let H=$5(V,$,j),q=[];for(let K of $.remove){V.assertNotStaged(K.id);let P=j.find((C)=>C.id===K.id);if(!P)throw L("publishRoster",K.id,"attribution","the removed row no longer exists");if(n3(K.id,P,K.attribution,"publishRoster"),!P.credential||K.fingerprint!==void 0&&DZ(P.credential)!==K.fingerprint)throw L("publishRoster",K.id,"attribution","the removed secret no longer matches");q.push(P)}let N=[];for(let K of $.finalize){let P=j.find((f)=>f.id===K.id),C=ZZ(V.stateAccount(K.id)?.[b]);if(!P||P.staged?.reservation!==K.reservation||C?.staged?.reservation!==K.reservation||P.enabled)throw L("publishRoster",K.id,"row-staged","the finalized row is not disabled under this reservation");let k=V.stateAccount(K.id),t=V.rosterRow(K.id),e=k?.[a],h=e===void 0?void 0:oZ(e);if(!C?.staged||C.staged.label!==t?.label||C.staged.disabledReason!==P.disabledReason||C.staged.providerState!==h)throw L("publishRoster",K.id,"row-staged","the staged label, disabled reason or full provider state no longer matches its stamp");n3(K.id,P,K.attribution,"publishRoster"),N.push(P)}let M=H.find((K)=>K.torn);if(M)throw L("publishRoster",$.operationId,"attribution",`Row ${M.id} has an interrupted write; complete it with a normal store operation before publishing.`,!1);let O=new Set;for(let K of H){if(!($.finalize.find((C)=>C.id===K.id)?.enabled??K.enabled)||K.type!=="oauth"||K.identity===void 0)continue;if(O.has(K.identity))throw L("publishRoster",K.id,"invalid-input","the final enabled roster repeats a known identity");O.add(K.identity)}for(let K of H)if(K.identity!==void 0&&K.fingerprint!==void 0&&H.some((P)=>P.id!==K.id&&P.identity!==void 0&&P.identity!==K.identity&&P.fingerprint===K.fingerprint))throw L("publishRoster",K.id,"attribution","the resulting pool gives the same secret different known identities");for(let K of N)if(K.identity!==void 0&&q.some((P)=>P.identity!==void 0&&P.identity!==K.identity&&P.fingerprint===K.fingerprint))throw L("publishRoster",K.id,"attribution","the staged secret belonged to a different known identity");await c3(V,$.operationId,X.protect);let S={operationId:$.operationId,planDigest:G,phase:"committed",removed:q.map((K)=>({id:K.id,credentialEpoch:K.credentialEpoch??1})),finalized:$.finalize.map((K,P)=>({id:K.id,credentialEpoch:N[P]?.credentialEpoch??1,reservation:K.reservation,enabled:K.enabled}))};for(let K of $.remove)V.dropRosterRows(K.id);for(let K of $.finalize){let P=V.rosterRow(K.id);P.enabled=K.enabled;let C={...V.entry(K.id)};if(delete C.staged,K.enabled)delete C.disabledReason;else C.disabledReason=K.disabledReason;V.setEntry(K.id,C)}let F=V.roster().filter((K)=>!_(K)||typeof K.id!=="string"||j.find((P)=>P.id===K.id)?.invalid==="roster");return V.config.accounts=[...$.order.map((K)=>V.rosterRow(K)),...F],h9(V,S),await V.syncState(),await V.commitConfig({durable:!0,publicationDecision:!0}),{outcome:"published",receipt:await y9(V,S)}},{completeTorn:!1});if(U)return U;if(await J.releaseAll(),Q>=1)throw L("publishRoster",$.operationId,"row-key-changed","a named row changed lock key twice during publication",!0)}})}class V8{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 hZ(J.lockDefaults,J.lockEnv),G={writes:0};try{let B=await g(J,z,G,{operation:"pull",rowId:Z},async(W)=>{if(W.reservation(Z)!==void 0)return;await W.completeTorn();let Y=W.row(Z);if(Y?.unbound&&Y.enabled&&Y.type==="oauth"&&Y.credential&&!Y.invalid)o("pull",Y);if(!Y?.candidate||Y.type!=="oauth")return;if(!Y.hasEntry)W.setEntry(Z,{credentialEpoch:1,needsFirstReading:!0}),await W.commitConfig();let U=W.row(Z);if(!U?.credential||U.credentialEpoch===void 0)return;return{id:Z,credential:U.credential,credentialEpoch:U.credentialEpoch,...U.identity!==void 0?{identity:U.identity}:{},reason:$}},{completeTorn:!1});if(await z.releaseAll(),!B){this.firedAtLoad.delete(Z);return}await J.hold?.("pull-before-request",Z);let Q;try{Q=await this.hook?.(B)}catch(W){throw new E({operation:"pull",rowId:Z,phase:"pull",retryable:!0,kind:"pull",message:"the quota pull rejected",cause:W})}await p3(X,Z,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(B){this.firedAtLoad.delete(Z);let Q=O1(B,"pull",Z,G);if(this.onFailure)try{await this.onFailure(Z,Q)}catch(W){this.logger?.warn("pull failure hook threw",{rowId:Z,error:W instanceof Error?W.message:String(W)})}else this.logger?.warn("quota pull failed",{rowId:Z,kind:Q.kind})}finally{await z.releaseAll()}}}import{randomUUID as X5}from"node:crypto";function j8(Z,$){if(rZ("refresh",Z,$?.staged),!$)throw L("refresh",Z,"unknown-row",`no row ${Z} in the pool`);if($.invalid)throw L("refresh",Z,"invalid-row",`row ${Z} is invalid`);if($.type!=="oauth"||$.credential?.type!=="oauth")throw L("refresh",Z,"no-credential",`row ${Z} holds no OAuth credential`);if(!$.enabled)throw L("refresh",Z,"row-disabled",`row ${Z} is disabled`);return $}function g9(Z){return L("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 m9(Z,$,X,J={}){s("refresh");let{ctx:z}=Z;return i(z,"refresh",$,J.onFailure,async(G,B)=>{let{row:Q}=await EZ(Z,"refresh",$);j8($,Q);let W=await J.refuse?.(Q);if(W!==void 0)return{status:"refused",rowId:$,reason:W};let Y=x(Q),U;for(let H=0;;H++){await G.acquire(zZ(Z,{id:$,identity:Y===$?void 0:Y})),await G.acquire(J.providerLock??Z.providerLock);for(let M of J.extraLocks??[])await G.acquire(M);let N=await g(z,G,{writes:0},{operation:"refresh",rowId:$},async(M)=>{let O=j8($,M.row($));if(o("refresh",O),!O.hasEntry)M.setEntry($,{credentialEpoch:1,needsFirstReading:!0}),await M.commitConfig(),O=j8($,M.row($));if(x(O)!==Y)return{keyNow:x(O)};let S=await J.refuse?.(O);if(S!==void 0)return{refused:S};return{row:O,credential:O.credential,credentialEpoch:O.credentialEpoch,identity:O.identity}});if("refused"in N)return{status:"refused",rowId:$,reason:N.refused};if("keyNow"in N){if(await G.releaseAll(),H>=1)throw L("refresh",$,"row-key-changed",`row ${$}'s wire identity changed twice while its lock was held`,!0);Y=N.keyNow;continue}U=N;break}if(J8(U.credential.lastRefreshedAt,z.now()))throw g9($);await z.hold?.("refresh-before-provider",$),await G.assertAll();let V;try{V=await X(U.credential,U.row)}catch(H){throw new E({operation:"refresh",rowId:$,phase:"before-first-write",retryable:!0,kind:"provider",message:"the provider refresh failed",cause:H})}if(typeof V?.refresh!=="string"||!V.refresh.trim())throw L("refresh",$,"provider","the provider returned no refresh token",!0);let j=V.providerState===void 0?void 0:bZ(z.providerState,"refresh",$,V.providerState,"the provider state the provider returned"),D=await g(z,G,B,{operation:"refresh",rowId:$},async(H)=>{let q=H.row($),N=H.entry($);if(!q||q.invalid||!N||N.credentialEpoch!==U.credentialEpoch||q.identity!==U.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`});o("refresh",q);let M=await J.refuse?.(q);if(M!==void 0)return{refused:M};let O=z.now(),S=q.credential?.type==="oauth"?q.credential.lastRefreshedAt:void 0;if(J8(S,O))throw g9($);let F={type:"oauth",access:V.access,refresh:V.refresh,expires:V.expires},K=q.identity!==void 0&&V.identity!==void 0&&q.identity!==V.identity?{expectedIdentity:q.identity,returnedIdentity:V.identity}:void 0,P=K?{mark:X5(),enabled:!1,reason:`${K1}${JSON.stringify(K)}`}:void 0,C=q.identity===void 0&&V.identity?V.identity:void 0,k=await s3(Z,H,$,F,{stamp:a1(S,O),transition:P,identity:C,...j!==void 0?{providerState:r1(z.providerState,"refresh",$,q.providerState,j)}:{}});if(P!==void 0)n1(H,$,P),await H.commitConfig();let t=q.identity;if(C!==void 0)nZ(H,$,C),t=C,await H.commitConfig();return{stored:k,identity:t,contradiction:K,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 H=J.onPersisted;await PZ("refresh",()=>H($,D.stored))}catch(H){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:H})}return{status:"rotated",rowId:$,credential:D.stored,...D.identity!==void 0?{identity:D.identity}:{}}})}import{isDeepStrictEqual as J5}from"node:util";var o3=Object.freeze(["version","accounts",y]);function q8(Z){let $={};for(let[X,J]of Object.entries(Z))if(!o3.includes(X))r3($,X,J);return $}function r3(Z,$,X){Object.defineProperty(Z,$,{value:X,enumerable:!0,writable:!0,configurable:!0})}function z5(Z,$){let X={};for(let[J,z]of Object.entries(Z))if(o3.includes(J))r3(X,J,z);else if(Object.hasOwn($,J))r3(X,J,$[J]);for(let[J,z]of Object.entries($))if(!Object.hasOwn(Z,J))r3(X,J,z);return X}function w9(Z){return new E({operation:"updateSettings",phase:"before-first-write",retryable:!1,kind:"invalid-input",message:Z})}async function p9(Z){let $=await r(Z.ctx);if($.status==="error")return $;return{status:$.status,settings:q8($.config)}}async function l9(Z,$,X={}){s("updateSettings");let{ctx:J}=Z,z=X.onFailure;return i(J,"updateSettings",void 0,z&&((G,B)=>z(B)),async(G,B)=>{for(let W of X.extraLocks??[])await G.acquire(W);let Q=G.held.length;try{for(let N of J.storeLocks)await G.acquire(N);let W=await r(J);if(W.status!=="ready")throw KZ(W,"updateSettings",void 0);let Y=q8(W.config),U=structuredClone(Y),V=await PZ("updateSettings",()=>$(U)),j=V===void 0?U:V;if(!_(j))throw w9("the settings mutator must produce an object");let D=o3.filter((N)=>Object.hasOwn(j,N));if(D.length>0)throw w9(`settings cannot set the pool-owned key(s) ${D.join(", ")}`);if(J5(j,Y))return{settings:Y,outcome:"unchanged"};let H=z5(W.config,j),q={operation:"updateSettings",rowId:void 0};return await n(J.configPath,H,{beforeRename:async()=>{await J.onStep?.("before-config-write",q),await G.assertAll()}}),B.writes++,await J.onStep?.("after-config-write",q),{settings:q8(H),outcome:"updated"}}finally{await G.releaseTo(Q)}})}var u9=new Map;function G5(Z){let $=u9.get(Z);if(!$)$={removedIds:new Set,firedAtLoad:new Set},u9.set(Z,$);return $}function d9(Z){if(Z.status==="ready")return{status:"ready",schemaVersion:vZ,rows:Z.rows};if(Z.status==="pending-migration")return{status:"pending-migration",roster:Array.isArray(Z.config.accounts)?Z.config.accounts:[]};return Z}function t1(Z){let $=G5(Z.configPath),X={...t6,...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:{now:Z.now??Date.now,...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 V8(()=>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:(B,Q)=>z.fire(B,Q)};return{async load(){let B=await r(J);if(B.status==="ready"){for(let Q of B.rows)if((Q.candidate||Q.torn&&Q.enabled)&&Q.type==="oauth"&&Q.needsFirstReading)z.fire(Q.id,"load")}return d9(B)},async read(){return d9(await r(J))},async initialize(B={}){return{status:await K9(J,B.dropKeys??[])}},add:(B,Q)=>O9(G,B,Q),publishRoster:(B,Q)=>v9(G,B,Q),publication:(B)=>x9(G,B),replace:(B,Q,W,Y)=>C9(G,B,Q,W,Y),rotate:(B,Q,W,Y)=>T9(G,B,Q,W,Y),updateProviderState:(B,Q,W,Y)=>M9(G,B,Q,W,Y),disable:(B,Q,W)=>A9(G,B,Q,W),enable:(B,Q)=>R9(G,B,Q),remove:(B,Q)=>E9(G,B,Q),reorder:(B,Q)=>b9(G,B,Q),readSettings:()=>p9(G),updateSettings:(B,Q)=>l9(G,B,Q),recordIdentity:(B,Q,W,Y)=>I9(G,B,Q,W,Y),refresh:(B,Q,W)=>m9(G,B,Q,W),recordQuota:(B,Q,W)=>p3(G,B,Q,W),requestReading:(B)=>z.fire(B,"admission"),pullsSettled:()=>z.settled()}}var B5=[/\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 F8(Z={}){let{redactStrings:$}=c9({...Z,extraValuePatterns:[...B5,...Z.extraValuePatterns??[]]});return(X)=>$(X)}class GZ extends Error{code;constructor(Z,$,X){super($,X);this.name="CommandError",this.code=Z}}var s9=/^[a-z][a-z0-9-]{0,63}$/,D8={code:"action-failed",text:"That action failed."},Q5=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 e1(Z){if(Z instanceof GZ)return{code:s9.test(Z.code)?Z.code:D8.code,text:Z.message};if(Z instanceof E)return{code:`pool-${Z.kind}`,text:Q5.has(Z.kind)?Z.message:`The account pool could not do that (${Z.kind}).`};return D8}var i9="This cannot be undone. Continue?",W5=new Set(["access","refresh","apikey","password","authheader","credential","credentials"]);function Y5(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");return W5.has($)||$.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function H5(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function K8(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)=>K8(z,`${$}[${G}]`,X));if(!H5(Z))return Z;let J={};for(let[z,G]of Object.entries(Z)){if(Y5(z)){X.dropped.push(`${$}.${z}`);continue}Object.defineProperty(J,z,{value:K8(G,`${$}.${z}`,X),enumerable:!0,writable:!0,configurable:!0})}return J}function a9(Z,$,X){let J={redact:X.redact,dropped:[],redacted:[]},z=K8(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 U5(Z){return{value:String(Z.value),label:String(Z.label)}}function V5(Z){switch(Z.kind){case"choice":return{kind:"choice",id:Z.id,label:Z.label,choices:(Z.choices??[]).map(U5),...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 N8(Z){if(Z.irreversible===!0)return{message:Z.confirm||i9,irreversible:!0};if(Z.confirm)return{message:Z.confirm,irreversible:!1};return}function n9(Z){let $=N8(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(V5),...$?{confirm:$}:{}}}function j5(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 q5(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:j5(Z.account)}:{},...Z.facts!==void 0?{facts:Z.facts}:{},actions:(Z.actions??[]).map(n9)}}function D5(Z){let{content:$}=Z;return{id:Z.id,slot:Z.slot,title:Z.title,lines:($.lines??[]).map(String),items:($.items??[]).map(q5),actions:($.actions??[]).map(n9),...$.facts!==void 0?{facts:$.facts}:{}}}function r9(Z,$,X){return{command:Z,title:$,sections:X.map(D5)}}function o9(Z,$,X,J){return a9({command:Z,menu:r9(Z,$,X)},Z,J)}function t9(Z,$,X,J,z){return a9({command:Z,ok:J.ok,text:String(J.text),...!J.ok&&J.code!==void 0?{code:s9.test(J.code)?J.code:"refused"}:{},...J.needsConfirmation?{needsConfirmation:!0}:{},menu:r9(Z,$,X)},Z,z)}var X0="disabled from the command menu";function K5(Z){return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)}function IZ(Z){return K5(Z)?{...Z}:{}}function F5(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 N5(Z,$){return Z.label??$??Z.id}function t3(Z,$){return wZ(Z.quota)?c(Z.quota,$):void 0}function J0(Z,$){return`${Z} ${$}${Z===1?"":"s"}`}var Z3="Actions";function M5(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 e9(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 Z0(Z){return e1(Z).text}async function P5(Z){let $=await Z.read(),X=await Z.readSettings();return{load:$,rows:F5($),settings:X.status==="error"?{}:X.settings}}function e3(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:N5(Z,X)}}function L5(Z,$){let{store:X,extraLocks:J}=Z,z=J?{extraLocks:J}:{},G=$.rows.map((V)=>V.id),B=M5($.load),Q=$.rows.filter((V)=>V.enabled).length,W=$.rows.map((V,j)=>{let{account:D,name:H}=e3(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(" · "),N=V.invalid?"invalid":V.enabled?"enabled":"disabled",M=[];if(!V.invalid&&V.enabled)M.push({id:"disable",label:"Disable",run:async()=>{return await X.disable(V.id,X0,z),`Disabled ${H}.`}});if(!V.invalid&&!V.enabled)M.push({id:"enable",label:"Enable",run:async()=>{return await X.enable(V.id,z),`Enabled ${H}.`}});if(G.length>1)M.push({id:"move",label:"Move",knobs:[{kind:"choice",id:"position",label:"Position",choices:G.map((O,S)=>({value:String(S+1),label:String(S+1)})),value:String(j+1)}],run:async({values:O})=>{let S=Number(O.position),F=G.filter((P)=>P!==V.id);return F.splice(S-1,0,V.id),(await X.reorder(F,z)).outcome==="unchanged"?`${H} is already at position ${S}.`:`Moved ${H} to position ${S}.`}});return M.push({id:"remove",label:"Remove",irreversible:!0,confirm:`Remove ${H}? Its stored credential is deleted.`,run:async()=>{return await X.remove(V.id,{...z,...Z.accounts?.protect?{protect:Z.accounts.protect}:{}}),`Removed ${H}.`}}),{id:V.id,label:H,detail:q,group:"Accounts",status:N,account:D,actions:M}}),Y=Z.accounts?.login,U=[];if(Y&&!B)U.push({id:"add",label:Y.label??"Add account",group:Z3,knobs:Y.knobs??[],run:async({values:V,invocation:j})=>{let D=await Y.run(V,j);if(D.status==="cancelled")return{ok:!1,text:D.message??"Login cancelled."};if(D.status==="ready"){let H=await X.add(D.account,z);return e9(D.account.label??H.id,H)}return D.completion.then(async(H)=>{if(!H){j.notify("Login cancelled.","warning");return}let q=await X.add(H,z);j.notify(e9(H.label??q.id,q))},(H)=>{j.notify(`Adding the account failed: ${Z0(H)}`,"error")}).catch((H)=>{j.notify(`Adding the account failed: ${Z0(H)}`,"error")}),D.message}});return{id:"accounts",slot:"accounts",title:"Accounts",content:{lines:B?[B]:[$.rows.length===0?"No accounts yet":`${J0($.rows.length,"account")}, ${Q} enabled`],items:B?[]:W,actions:U}}}function _5(Z,$){let X=Z.quota?.scope??"all",J=Z.now(),z=X==="all"?"Accounts":`Accounts · ${X}`,G=async(U,V)=>{if(Z.quota?.check)await Z.quota.check(U,V);else{for(let j of U)Z.store.requestReading(j);await Z.store.pullsSettled()}},B=$.rows.filter((U)=>U.candidate),Q=B.map((U)=>{let{account:V,name:j}=e3(U,Z),D=t3(U,X);return{id:U.id,label:j,group:z,status:_Z(D,{now:J,form:"compact"}),detail:_Z(D,{now:J,form:"full"}),account:V,actions:[{id:"check",label:"Check this account",run:async({invocation:H})=>{return await G([U.id],H),`Checked quota for ${j}.`}}]}}),W=$.rows.filter((U)=>!U.candidate).map((U)=>{let{name:V}=e3(U,Z),j=U.invalid?"invalid":!U.enabled?"disabled":U.credential===void 0?"no credential":"unavailable",D=_Z(t3(U,X),{now:J,form:"compact"});return`${V} (${j}): ${D}`}),Y=[];if(B.length>0)Y.push({id:"check",label:"Check now",description:"Checks every account that can be checked.",group:Z3,run:async({invocation:U})=>{let V=B.map((j)=>j.id);return await G(V,U),`Checked quota for ${J0(V.length,"account")}.`}});return{id:"quota",slot:"quota",title:"Quota",content:{lines:$.rows.length===0?["No accounts yet"]:W,items:Q,actions:Y}}}function O5(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"}],B=IZ($.settings.routing).mode,Q=typeof B==="string"&&G.some((H)=>H.value===B)?B:"ordered",W=s6(Q),Y=$.rows.map((H)=>H.id),U=y3(Y,W.placement,Z.routing?.formerMainId??I3),j=[`Mode: ${G.find((H)=>H.value===Q)?.label??Q}`];if(Y.length>0)j.push(`Roster order: ${Y.join(", ")}`);if(W.mode==="ordered"&&U.join()!==Y.join())j.push(`Tried in order: ${U.join(", ")}`);let D=[{id:"mode",label:"Change mode",group:Z3,knobs:[{kind:"choice",id:"mode",label:"Mode",choices:G,value:Q}],run:async({values:H})=>{let q=String(H.mode);return await X.updateSettings((N)=>{N.routing={...IZ(N.routing),mode:q};return},z),`Routing mode set to ${G.find((N)=>N.value===q)?.label??q}.`}}];if(Y.length>1)D.push({id:"order",label:"Set order",group:Z3,knobs:[{kind:"text",id:"order",label:"Account ids, first to last",value:Y.join(", "),required:!0}],run:async({values:H})=>{let q=String(H.order).split(/[\s,]+/).filter((M)=>M.length>0),N=await X.reorder(q,z);return N.outcome==="unchanged"?"The order is unchanged.":`Order set to ${N.ids.join(", ")}.`}});return{id:"routing",slot:"routing",title:"Routing",content:{lines:j,actions:D}}}function C5(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 t3(z,X)?.limits??[])if(!J.includes(G.label))J.push(G.label);return J.length>0?J:["primary"]}function T5(Z,$){let X=Z.quota?.scope??"all",J=new Map;for(let z of $.rows)for(let G of t3(z,X)?.limits??[])if(G.windowMinutes!==void 0&&!J.has(G.label))J.set(G.label,$0(G));return(z)=>J.get(z)??z}function S5(Z,$){let{store:X,extraLocks:J}=Z,z=J?{extraLocks:J}:{},G=IZ($.settings.killswitch),B=G.enabled===!0,Q=IZ(G.accounts),W=C5(Z,$),Y=T5(Z,$),U=B?"on":"off",V=$.rows.map((j)=>{let{account:D,name:H}=e3(j,Z),q=IZ(Q[j.id]),N=W.filter((M)=>typeof q[M]==="number");return{id:j.id,label:H,group:`Floors · killswitch ${U}`,status:N.length===0?"no floors":N.map((M)=>`${Y(M)} ≥${q[M]}%`).join(" · "),account:D,actions:[{id:"floors",label:"Set floors",knobs:W.map((M)=>({kind:"number",id:M,label:`Minimum % left for ${Y(M)}`,min:0,max:100,...typeof q[M]==="number"?{value:q[M]}:{}})),run:async({values:M})=>{return await X.updateSettings((O)=>{let S=IZ(O.killswitch),F=IZ(S.accounts),K=IZ(F[j.id]);for(let P of W){let C=M[P];if(typeof C==="number")K[P]=C;else if(C===null)delete K[P]}if(Object.keys(K).length>0)F[j.id]=K;else delete F[j.id];if(Object.keys(F).length>0)S.accounts=F;else delete S.accounts;O.killswitch=S;return},z),`Floors updated for ${H}.`}}]}});return{id:"limits",slot:"limits",title:"Limits",content:{lines:[`Killswitch ${U}`],items:V,actions:[{id:"killswitch",label:B?"Turn killswitch off":"Turn killswitch on",description:"With the killswitch on, an account whose quota falls below one of its floors is not used.",group:Z3,knobs:[{kind:"toggle",id:"enabled",label:"Killswitch",value:!B}],run:async({values:j})=>{let D=j.enabled===!0;return await X.updateSettings((H)=>{H.killswitch={...IZ(H.killswitch),enabled:D};return},z),`Killswitch ${D?"on":"off"}.`}}]}}}async function z0(Z){let $=await P5(Z.store);return[L5(Z,$),_5(Z,$),O5(Z,$),S5(Z,$)]}var A5=new Set(["accounts","quota","routing","limits","cache","diagnostics"]),M8=["accounts","quota","routing","limits"];function G0(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 R5(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 E5(Z,$){let X={};for(let J of Z){let z=$&&Object.hasOwn($,J.id)?$[J.id]:void 0,G=R5(J,z);if("problem"in G)return G;X[J.id]=G.value}return{values:X}}function b5(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 tZ(Z){let $=Z.logger??v("commands"),X=F8(Z.redaction),J={logger:$,redact:X},z=Z.now??Date.now,G=Z.extras??[],B=Z.replace??{},Q=M8.filter((j)=>!B[j]);for(let j of M8)if(B[j]&&Z[j]!==void 0)throw Error(`the ${j} section is replaced; its built-in options cannot also be given`);let W=Z.store;if(Q.length>0&&!W)throw Error(`a store is required for the built-in ${Q.join(", ")} section${Q.length>1?"s":""}`);let Y=new Set;for(let j of G){if(A5.has(j.id)||Y.has(j.id))throw Error(`extra section id ${j.id} is taken`);Y.add(j.id)}async function U(j,D,H,q){try{return{id:j,slot:D,title:H.title,content:await H.build(q)}}catch(N){return $.warn("command menu section failed to build",{command:Z.command,section:j,error:X(N instanceof Error?N.message:String(N))}),{id:j,slot:D,title:H.title,content:{lines:["This section could not be loaded."]}}}}async function V(j){let D=W&&Q.length>0?await z0({store:W,now:z,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.accounts?{accounts:Z.accounts}:{},...Z.quota?{quota:Z.quota}:{},...Z.routing?{routing:Z.routing}:{},...Z.limits?{limits:Z.limits}:{}}):[],H=[];for(let q of M8){let N=B[q];if(N)H.push(await U(q,q,N,j));else{let M=D.find((O)=>O.slot===q);if(M)H.push(M)}}if(Z.cache)H.push(await U("cache","cache",Z.cache,j));if(Z.diagnostics)H.push(await U("diagnostics","diagnostics",Z.diagnostics,j));for(let q of G)H.push(await U(q.id,"extra",q,j));return H}return{command:Z.command,async open(j){let D=G0(j,X);return o9(Z.command,Z.title,await V(D),J)},async apply(j,D){let H=G0(D,X),q=async(F)=>t9(Z.command,Z.title,await V(H),F,J),N=j.command===Z.command?b5(await V(H),j):void 0;if(!N)return q({ok:!1,code:"unavailable",text:"That action is no longer available."});let M=N8(N);if(M&&j.confirmed!==!0)return q({ok:!1,code:"needs-confirmation",text:M.message,needsConfirmation:!0});let O=E5(N.knobs??[],j.values);if("problem"in O)return q({ok:!1,code:"invalid-input",text:O.problem});let S;try{let F=await N.run({values:O.values,...j.itemId!==void 0?{itemId:j.itemId}:{},invocation:H});S=typeof F==="string"?{ok:!0,text:F}:{ok:F.ok,text:F.text,...F.ok?{}:{code:F.code??"refused"}}}catch(F){let K=e1(F);$.warn("command menu action failed",{command:Z.command,section:j.sectionId,action:j.actionId,code:K.code,error:X(F instanceof Error?F.message:String(F))}),S={ok:!1,...K}}return q(S)}}}function I5(Z){return Z===null||typeof Z==="string"||typeof Z==="boolean"||typeof Z==="number"&&Number.isFinite(Z)}function y5(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(!I5(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}:{}}}import{createHash as k5}from"node:crypto";var f5=86400000,x5=300000,h5=3600000,v5=60000,g5=900000,m5=300000;function P8(Z){return Z instanceof Error?Z.message:String(Z)}function L8(Z){let $=Z?.status;if(typeof $==="number")return $===429||$>=500;if(!(Z instanceof Error))return!1;return Z.name==="AbortError"||Z.name==="TimeoutError"||Z.message.includes("fetch failed")||"code"in Z&&(Z.code==="ECONNRESET"||Z.code==="ECONNREFUSED"||Z.code==="ETIMEDOUT"||Z.code==="UND_ERR_CONNECT_TIMEOUT")}function _8(Z){let $=P8(Z),X=Z?.status;if(typeof X==="number")return X===429||X>=500;if(!(Z instanceof Error))return!1;let J=Z.code;return Z.name==="AbortError"||Z.name==="TimeoutError"||$.includes("fetch failed")||J==="ECONNRESET"||J==="ECONNREFUSED"||J==="ETIMEDOUT"||J==="UND_ERR_CONNECT_TIMEOUT"}function eZ(Z){return k5("sha256").update(Z).digest("hex")}function Z6(Z){let $=eZ(Z.refreshToken),J=(Z.previous?.tokenHash===$?Z.previous.retryCount??0:0)+1,z,G=Z.error?.retryAfter;if(typeof G==="number"&&G>0)z=G*1000;else if(L8(Z.error))z=Math.min(h5,x5*2**Math.min(J-1,6));else z=f5;return{message:P8(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+z,retryCount:J,tokenHash:$}}function yZ(Z,$,X){if(!Z?.nextRetryAt||Z.nextRetryAt<=X)return!1;if(!$)return!0;return Z.tokenHash===eZ($)}function S1(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function $3(Z){let X=(Z.previous?.retryCount??0)+1,J,z=Z.error?.retryAfter;if(typeof z==="number"&&z>0)J=z*1000;else if(_8(Z.error))J=Math.min(g5,v5*2**Math.min(X-1,6));else J=m5;return{message:P8(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+J,retryCount:X}}function A1(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function O8(Z){if(!Z)return;let $=Number(Z);if(Number.isFinite($)&&$>0)return Math.ceil($);let X=Date.parse(Z);if(Number.isFinite(X)){let J=Math.ceil((X-Date.now())/1000);return J>0?J:void 0}return}import{createServer as B0}from"node:http";import{setTimeout as w5}from"node:timers/promises";var z6="app_EMoamEEZ73f0CkXaXp7hrann",X1="https://auth.openai.com",J3=1455,p5=3000,l5="cortexkit-opencode-openai-auth";function W0(Z){return`${l5}/${Z}`}var Y0="main",u5=`"${Y0}" is a reserved account id; choose a different label.`;function H0(Z){let $=new Uint8Array(Z),X=String.fromCharCode(...$);return btoa(X).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function d5(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((J)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[J%66]).join(""),X=H0(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:X}}function R1(Z){if(Z.length>16384)return;let $=Z.split(".");if($.length!==3)return;let X=$[1];if(!X||X.length>8192)return;try{return JSON.parse(Buffer.from(X,"base64url").toString())}catch{return}}function E1(Z){let $=Z.chatgpt_account_id;if(typeof $==="string"&&$.length>0)return $;let X=Z["https://api.openai.com/auth"];if(X&&typeof X==="object"&&!Array.isArray(X)&&typeof X.chatgpt_account_id==="string"&&X.chatgpt_account_id.length>0)return X.chatgpt_account_id;let J=Z.organizations;if(Array.isArray(J)){let z=J[0];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.id==="string"&&z.id.length>0)return z.id}return}function X6(Z){if(Z.id_token){let $=R1(Z.id_token),X=$&&E1($);if(X)return X}if(Z.access_token){let $=R1(Z.access_token);return $?E1($):void 0}return}function c5(Z){return typeof Z==="string"&&Z.toLowerCase()===Y0}function C8(Z){if(c5(Z))throw Error(u5);return Z}function s5(Z,$,X){let J=new URLSearchParams({response_type:"code",client_id:z6,redirect_uri:Z,scope:"openid profile email offline_access",code_challenge:$.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:X,originator:"opencode"});return`${X1}/oauth/authorize?${J.toString()}`}async function i5(Z,$,X){let J=await fetch(`${X1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:Z,redirect_uri:$,client_id:z6,code_verifier:X.verifier}).toString()});if(!J.ok)throw Error(`Token exchange failed: ${J.status}`);return await J.json()}function a5(Z){return Z.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var n5=`<!doctype html>
2
+ <html>
3
+ <head>
4
+ <title>CortexKit OpenAI Auth - Authorization Successful</title>
5
+ <style>
6
+ body {
7
+ font-family:
8
+ system-ui,
9
+ -apple-system,
10
+ sans-serif;
11
+ display: flex;
12
+ justify-content: center;
13
+ align-items: center;
14
+ height: 100vh;
15
+ margin: 0;
16
+ background: #131010;
17
+ color: #f1ecec;
18
+ }
19
+ .container {
20
+ text-align: center;
21
+ padding: 2rem;
22
+ }
23
+ h1 {
24
+ color: #f1ecec;
25
+ margin-bottom: 1rem;
26
+ }
27
+ p {
28
+ color: #b7b1b1;
29
+ }
30
+ </style>
31
+ </head>
32
+ <body>
33
+ <div class="container">
34
+ <h1>Authorization Successful</h1>
35
+ <p>You can close this window and return to OpenCode.</p>
36
+ </div>
37
+ <script>
38
+ setTimeout(() => window.close(), 2000)
39
+ </script>
40
+ </body>
41
+ </html>`,$6=(Z)=>`<!doctype html>
42
+ <html>
43
+ <head>
44
+ <title>CortexKit OpenAI Auth - Authorization Failed</title>
45
+ <style>
46
+ body {
47
+ font-family:
48
+ system-ui,
49
+ -apple-system,
50
+ sans-serif;
51
+ display: flex;
52
+ justify-content: center;
53
+ align-items: center;
54
+ height: 100vh;
55
+ margin: 0;
56
+ background: #131010;
57
+ color: #f1ecec;
58
+ }
59
+ .container {
60
+ text-align: center;
61
+ padding: 2rem;
62
+ }
63
+ h1 {
64
+ color: #fc533a;
65
+ margin-bottom: 1rem;
66
+ }
67
+ p {
68
+ color: #b7b1b1;
69
+ }
70
+ .error {
71
+ color: #ff917b;
72
+ font-family: monospace;
73
+ margin-top: 1rem;
74
+ padding: 1rem;
75
+ background: #3c140d;
76
+ border-radius: 0.5rem;
77
+ }
78
+ </style>
79
+ </head>
80
+ <body>
81
+ <div class="container">
82
+ <h1>Authorization Failed</h1>
83
+ <p>An error occurred during authorization.</p>
84
+ <div class="error">${a5(Z)}</div>
85
+ </div>
86
+ </body>
87
+ </html>`,J6=[],X3,kZ=new Map;function Q0(Z,$){return new Promise((X,J)=>{let z=(B)=>{Z.off("listening",G),J(B)},G=()=>{Z.off("error",z),X()};Z.once("error",z),Z.once("listening",G),Z.listen(J3,$)})}function U0(Z){Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}function Z1(){return kZ.size}function J1(Z){if(kZ.delete(Z),Z1()===0)$1()}async function r5(){let Z=`http://localhost:${J3}/auth/callback`;if(J6.length>0)return{port:J3,redirectUri:Z};if(X3)return X3;X3=(async()=>{let $=(G,B)=>{let Q=new URL(G.url||"/",`http://127.0.0.1:${J3}`);if(Q.pathname==="/auth/callback"){let W=Q.searchParams.get("code"),Y=Q.searchParams.get("state"),U=Q.searchParams.get("error"),V=Q.searchParams.get("error_description");if(U){let D=V||U;if(Y){let H=kZ.get(Y);if(H)H.reject(Error(D)),J1(Y);else if(Z1()===0)$1()}else if(Z1()===0)$1();B.writeHead(200,{"Content-Type":"text/html"}),B.end($6(D));return}if(!Y){if(Z1()===0)$1();B.writeHead(400,{"Content-Type":"text/html"}),B.end($6("Missing state parameter"));return}if(!W){if(Z1()===0)$1();B.writeHead(400,{"Content-Type":"text/html"}),B.end($6("Missing authorization code"));return}let j=kZ.get(Y);if(!j){if(Z1()===0)$1();B.writeHead(400,{"Content-Type":"text/html"}),B.end($6("Unknown state — authorization may have expired"));return}J1(Y),i5(W,Z,j.pkce).then((D)=>j.resolve(D)).catch((D)=>j.reject(D)),B.writeHead(200,{"Content-Type":"text/html"}),B.end(n5);return}if(Q.pathname==="/cancel"){let W=Q.searchParams.get("state"),Y=W?[W]:[...kZ.keys()];B.writeHead(200),B.end("Login cancelled");for(let U of Y){let V=kZ.get(U);if(!V)continue;V.reject(Error("Login cancelled")),J1(U)}if(Z1()===0)$1();return}B.writeHead(404),B.end("Not found")},X=B0($);await Q0(X,"127.0.0.1");let J=[X],z=B0($);try{await Q0(z,"::1"),J.push(z)}catch(G){let B=G.code;if(B!=="EADDRNOTAVAIL"&&B!=="EAFNOSUPPORT")throw U0(X),G}return J6=J,{port:J3,redirectUri:Z}})();try{return await X3}finally{X3=void 0}}function $1(){let Z=J6;J6=[];for(let $ of Z)U0($)}function o5(Z,$,X=300000,J){return new Promise((z,G)=>{if(J?.aborted){J1($),G(Error("Login cancelled"));return}let B=setTimeout(()=>{if(kZ.get($))J1($),G(Error("OAuth callback timeout — authorization took too long"))},X),Q=()=>{if(clearTimeout(B),kZ.get($))J1($),G(Error("Login cancelled"))};if(J)J.addEventListener("abort",Q);kZ.set($,{pkce:Z,state:$,resolve:(W)=>{if(clearTimeout(B),J)J.removeEventListener("abort",Q);z(W)},reject:(W)=>{if(clearTimeout(B),J)J.removeEventListener("abort",Q);G(W)}})})}async function t5(Z){let $=await fetch(`${X1}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":W0(Z)},body:JSON.stringify({client_id:z6})});if(!$.ok)throw Error("Failed to initiate device authorization");let X=await $.json();return{deviceData:X,url:`${X1}/codex/device`,instructions:`Enter code: ${X.user_code}`}}async function e5(Z,$,X){let J=Math.max(parseInt(Z.interval,10)||5,1)*1000,z=typeof Z.expires_in==="number"?Z.expires_in:parseInt(Z.expires_in||"",10),G=!Number.isNaN(z)&&z>0?z*1000:900000,B=Date.now();while(!0){if(X?.aborted)throw Error("Device authorization cancelled");if(Date.now()-B>G)throw Error("Device authorization expired");let Q=await fetch(`${X1}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":W0($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(Q.ok){let U=await Q.json(),V=await fetch(`${X1}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:U.authorization_code,redirect_uri:`${X1}/deviceauth/callback`,client_id:z6,code_verifier:U.code_verifier}).toString()});if(!V.ok)throw Error(`Token exchange failed: ${V.status}`);return await V.json()}if(Q.status!==403&&Q.status!==404)throw Error(`Device authorization failed: ${Q.status}`);let W=G-(Date.now()-B);if(W<=0)throw Error("Device authorization expired");let Y=Math.min(J+p5,W);try{await w5(Y,void 0,{signal:X})}catch(U){if(U instanceof Error&&U.name==="AbortError")throw Error("Device authorization cancelled");throw U}}}async function RW(Z){let{label:$,headless:X=!1,signal:J,version:z}=Z;if(C8($),X){let{deviceData:U,url:V,instructions:j}=await t5(z),D=(async()=>{let H=await e5(U,z,J),q=Date.now(),N=X6(H);return{id:C8($||N||crypto.randomUUID()),label:$||void 0,type:"oauth",access:H.access_token,refresh:H.refresh_token,expires:q+(H.expires_in??3600)*1000,enabled:!0,addedAt:q,lastUsed:q,lastRefreshedAt:q,accountId:N}})();return{url:V,instructions:j,completion:D}}let{redirectUri:G}=await r5(),B=await d5(),Q=H0(crypto.getRandomValues(new Uint8Array(32)).buffer),W=s5(G,B,Q),Y=(async()=>{try{if(J?.aborted)throw Error("Login cancelled");let U=await o5(B,Q,void 0,J),V=Date.now(),j=X6(U);return{id:C8($||j||crypto.randomUUID()),label:$||void 0,type:"oauth",access:U.access_token,refresh:U.refresh_token,expires:V+(U.expires_in??3600)*1000,enabled:!0,addedAt:V,lastUsed:V,lastRefreshedAt:V,accountId:j}}finally{J1(Q)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Y}}function G6(Z){if(Z==null||Z==="")return;let $=typeof Z==="number"?Z:Number(Z);if(Number.isFinite($)){let J=$<100000000000?$*1000:$,z=new Date(J);return Number.isNaN(z.getTime())?void 0:z.toISOString()}let X=new Date(Z);return Number.isNaN(X.getTime())?void 0:X.toISOString()}function T8(Z){let $=Number(Z);return Number.isFinite($)&&$>0?$:void 0}function V0(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function j0(Z,$){let X=Z.get($);if(X===null||X.trim()==="")return;let J=Number(X);if(!Number.isFinite(J)||J<0||J>100)return;let z=$.slice(0,-13),G=T8(Z.get(`${z}-window-minutes`)),B=G6(Z.get(`${z}-reset-at`)??void 0);if(J===0&&Z.get(`${z}-window-minutes`)==="0"&&!B)return;return{usedPercent:J,remainingPercent:100-J,resetsAt:B,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var K0=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function F0(Z,$){let X=Z.get($);if(X===null)return"absent";if(X.trim()==="")return"invalid";let J=Number(X);return Number.isFinite(J)&&J>=0&&J<=100?"valid":"invalid"}function bW(Z){if(K0.some((z)=>F0(Z,z)==="invalid"))return{};let $={},X=j0(Z,"x-codex-primary-used-percent");if(X)$.primary=X;let J=j0(Z,"x-codex-secondary-used-percent");if(J)$.secondary=J;return $}function IW(Z){let $=K0.map((X)=>F0(Z,X));return $.includes("valid")&&!$.includes("invalid")}function q0(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=T8(Z.window_minutes),X=G6(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!X)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:X,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$}:{}}}function yW(Z){let $={},X=q0(Z.rate_limits?.primary);if(X)$.primary=X;let J=q0(Z.rate_limits?.secondary);if(J)$.secondary=J;return $}function b1(Z){if(Z==null||Z==="")return;let $=Number(Z);return Number.isFinite($)&&$>=0?$:void 0}function D0(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=T8(Z.limit_window_seconds),X=G6(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!X)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:X,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$/60}:{}}}function N0(Z){let $={},X=D0(Z.rate_limit?.primary_window);if(X)$.primary=X;let J=D0(Z.rate_limit?.secondary_window);if(J)$.secondary=J;let z=V0(Z.rate_limit_reset_credits?.available_count);if(z!==void 0)$.resetCreditsAvailable=z;let G=V0(Z.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)$.resetCreditsApplicable=G;let B=Z.spend_control?.individual_limit;if(Z.spend_control===null||B===null)$.spendControlCleared=!0;if(B&&typeof Z.spend_control?.reached==="boolean"){let W=b1(B.limit),Y=b1(B.used),U=b1(B.remaining),V=b1(B.used_percent),j=b1(B.remaining_percent);if(W!==void 0&&Y!==void 0&&U!==void 0&&V!==void 0&&j!==void 0)$.spendControl={limit:W,used:Y,remaining:U,usedPercent:V,remainingPercent:j,resetsAt:G6(B.reset_at),unit:B.unit,source:B.source,reached:Z.spend_control.reached}}let Q=Z.credits;if(Q&&typeof Q.has_credits==="boolean"&&typeof Q.unlimited==="boolean"&&typeof Q.overage_limit_reached==="boolean"){let W=b1(Q.balance);$.credits={hasCredits:Q.has_credits,unlimited:Q.unlimited,overageLimitReached:Q.overage_limit_reached,...W!==void 0?{balance:W}:{}}}return $}import{ClaustrumClient as IX}from"@cortexkit/claustrum-client";import{resolve as M0}from"node:path";import{storeIdentity as ZX}from"@cortexkit/claustrum-client";import{SubcClient as $X}from"@cortexkit/subc-client";function P0(Z){let $=Z.identity??ZX(Z.projectRoot??process.cwd(),Z.storagePath??process.cwd());return{connectionFile:Z.connectionFile,async getUsage(){let X,J=!1,z,G=new Promise((Q,W)=>{z=setTimeout(()=>W(Error("insula usage timeout")),3000),z.unref?.()}),B=(async()=>{if(X=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}):await $X.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}),J)throw X.close(),Error("insula usage timeout");let Q=await X.routeOpen({kind:"management_surface",module_id:"insula"},$);return await X.request(Q,{method:"usage.get",params:{}})})();try{return await Promise.race([B,G])}finally{J=!0,clearTimeout(z),X?.close()}}}}var R8=60000,XX=4*R8,S8=new Map,B6=new Map;function A8(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}class L0{transport;key;#Z=[];#$;constructor(Z,$){this.transport=Z,this.key=$}refresh(Z){if(this.#$)return this.#$;for(let[X,J]of B6)if(Z-J>=R8)B6.delete(X);let $=B6.get(this.key);if($!==void 0&&Z-$<R8)return Promise.resolve();return B6.set(this.key,Z),this.#$=(async()=>{try{let X=await this.transport.getUsage();if(!A8(X)||!Array.isArray(X.result)||X.error!==void 0)throw Error("unavailable insula usage");this.#Z=X.result.filter((J)=>A8(J)&&typeof J.provider==="string")}catch{this.#Z=[]}})().finally(()=>{this.#$=void 0}),this.#$}current(Z,$,X){for(let J of this.#Z){if(J.provider!==Z||typeof J.account!=="string"||J.account.trim()!==$)continue;if(J.stale!==void 0||J.errorClass!==void 0||!A8(J.usage))continue;let z=typeof J.fetchedAt==="string"?Date.parse(J.fetchedAt):Number.NaN;if(!Number.isFinite(z)||X-z>=XX)continue;return{entry:J,context:{fetchedAt:z,...typeof J.source==="string"&&{source:J.source}}}}return}}function _0(Z,$){let X=JSON.stringify([M0(Z.connectionFile),M0($)]),J=S8.get(X);if(!J)J={source:new L0(Z,X),refs:0},S8.set(X,J);J.refs++;let z=!1;return{source:J.source,release(){if(z)return;if(z=!0,--J.refs===0)S8.delete(X)}}}import{ClaustrumCredentialError as AY}from"@cortexkit/claustrum-client";function E8(Z){let $=new AbortController,X=[],J=!1,z=()=>{if(J)return;J=!0;for(let{source:Q,listener:W}of X)Q.removeEventListener("abort",W);X.length=0},G=(Q)=>{if(J||$.signal.aborted)return;$.abort(Q),z()},B=Z.find((Q)=>Q.aborted);if(B)return $.abort(B.reason),{signal:$.signal,dispose:z};for(let Q of Z){if($.signal.aborted)break;let W=()=>G(Q.reason);if(X.push({source:Q,listener:W}),Q.addEventListener("abort",W,{once:!0}),Q.aborted)G(Q.reason)}return{signal:$.signal,dispose:z}}import{ClaustrumCredentialError as FX}from"@cortexkit/claustrum-client";import{createHash as JX,randomBytes as zX,randomUUID as GX}from"node:crypto";import{constants as O0}from"node:fs";import{chmod as BX,mkdir as QX,open as I0,readFile as b8,realpath as WX,rename as YX,stat as y0,unlink as k0}from"node:fs/promises";import{basename as f0,dirname as lZ,extname as C0,isAbsolute as T0,join as k8,resolve as HX}from"node:path";import{ClaustrumCredentialError as UX,ClaustrumClient as VX,writeEnrollmentTokenFile as jX}from"@cortexkit/claustrum-client";class T extends Error{kind;constructor(Z,$){super($);this.name="ClaustrumConsumerError",this.kind=Z}}var qX=1,W6=16384,x0=30000,f8=/^[0-9a-f]{64}$/,h0=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),v0=new Set(["pending_queue_full"]);function I8(Z){if(!(Z instanceof UX))return;if(h0.has(Z.code))return{code:Z.code,disposition:"terminal"};if(v0.has(Z.code))return{code:Z.code,disposition:"retry"};return{code:Z.code,disposition:Z.action==="retry"?"retry":"terminal"}}function x8(Z,$){if(!/^[a-z0-9][a-z0-9-]*$/.test(Z)||!/^[a-z0-9][a-z0-9-]*$/.test($))throw new T("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${Z}-${$}`}function h8(Z){return VX.connect(Z)}function g0(Z){let $=C0(Z)||".json",X=f0(Z,C0(Z));return{statePath:k8(lZ(Z),`${X}-state${$}`),tokenPath:Z}}function v8(Z){let $=Z.override?.trim();if($&&!T0($)&&!Z.cwd)throw new T("invalid-state","A relative Claustrum enrollment override needs a base directory");let X=$?T0($)?$:HX(Z.cwd,$):k8(Z.stateDir,`${Z.host}-enrollment.json`);return g0(X)}function m0(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function Q6(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0}function w0(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=1}function z3(){return new T("invalid-state","invalid Claustrum enrollment state")}function H6(Z){if(!m0(Z)||Z.version!==qX||typeof Z.proposedName!=="string"||Z.proposedName.length===0)throw z3();if(Z.phase==="pending"){if(!f8.test(String(Z.requestSecret??""))||Z.requestId!==void 0&&(typeof Z.requestId!=="string"||Z.requestId.length===0)||!Q6(Z.createdAt)||!Q6(Z.updatedAt))throw z3();return{version:1,phase:"pending",proposedName:Z.proposedName,requestSecret:Z.requestSecret,...Z.requestId!==void 0&&{requestId:Z.requestId},createdAt:Z.createdAt,updatedAt:Z.updatedAt}}if(Z.phase==="approved"){if(Z.approvedName!==void 0&&(typeof Z.approvedName!=="string"||Z.approvedName.length===0)||!w0(Z.tokenGeneration)||!Q6(Z.updatedAt))throw z3();return{version:1,phase:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration,updatedAt:Z.updatedAt}}if(Z.phase==="denied"||Z.phase==="blocked"){if(Z.errorCode!==void 0&&typeof Z.errorCode!=="string"||!Q6(Z.updatedAt))throw z3();return{version:1,phase:Z.phase,proposedName:Z.proposedName,...Z.errorCode!==void 0&&{errorCode:Z.errorCode},updatedAt:Z.updatedAt}}throw z3()}function g8(Z){if(!m0(Z)||!f8.test(String(Z.token??""))||!w0(Z.token_generation))throw new T("invalid-token","invalid Claustrum enrollment token file");return{token:Z.token,token_generation:Z.token_generation}}function DX(Z){if(!Z.isFile())throw new T("unsafe-file","Claustrum enrollment file must be a regular file");if((Z.mode&63)!==0)throw new T("unsafe-file","Claustrum enrollment file must be owner-only");let $=process.geteuid?.();if($!==void 0&&Z.uid!==$)throw new T("unsafe-file","Claustrum enrollment file must be owned by the current user")}function S0(Z){try{return JSON.parse(Z)}catch{throw new T("invalid-state","Claustrum enrollment file is not valid JSON")}}async function uZ(Z){if(RZ)try{await y8(lZ(Z));let X=await _1(Z,!0);if(Buffer.byteLength(X)>W6)throw new T("unsafe-file","Claustrum enrollment file is too large");return S0(X)}catch(X){if(X.code==="ENOENT")return;throw X}let $;try{$=await I0(Z,O0.O_RDONLY|O0.O_NOFOLLOW)}catch(X){if(X.code==="ENOENT")return;throw new T("unsafe-file","Claustrum enrollment file could not be opened safely")}try{DX(await $.stat());let X=Buffer.alloc(W6+1),{bytesRead:J}=await $.read(X,0,X.byteLength,0);if(J>W6)throw new T("unsafe-file","Claustrum enrollment file is too large");return S0(X.subarray(0,J).toString("utf8"))}finally{await $.close()}}function A0(Z,$){let X=[];for(let J of Z.split(`
88
+ `)){if(J.trim()===""||J.startsWith("#"))continue;let z=J.split(":");if(z.length!==$||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||$===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||$===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;X.push(z)}return X}async function KX(Z,$,X){try{let[J,z]=await Promise.all([b8(X.passwdPath??"/etc/passwd","utf8"),b8(X.groupPath??"/etc/group","utf8")]),G=A0(J,7),B=A0(z,4);if(!G||!B)return!1;let Q=G.filter((V)=>Number(V[2])===Z),W=B.filter((V)=>Number(V[2])===$);if(Q.length!==1||W.length!==1)return!1;let Y=Q[0]?.[0],U=W[0]?.[3]??"";return(U===""||U.split(",").every((V)=>V===Y))&&!G.some((V)=>Number(V[2])!==Z&&Number(V[3])===$)}catch{return!1}}function p0(Z){if(!Z.passwdPath&&!Z.groupPath)return;return{fs:{readFile:($)=>b8($==="/etc/passwd"?Z.passwdPath??$:$==="/etc/group"?Z.groupPath??$:$)}}}async function l0(Z,$={}){if(!RZ){let X=process.geteuid?.();if(X===void 0)return;let J=process.getegid?.(),z;try{z=await WX(Z)}catch{return}let G;for(;;){let B=await y0(z).catch(()=>{return});if(B&&(B.mode&18)!==0&&(B.mode&512)===0){if(G===void 0)G=J!==void 0&&await KX(X,J,$);if((B.mode&2)!==0||B.uid!==X||B.gid!==J||!G)throw new T("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let Q=lZ(z);if(Q===z)return;z=Q}}try{await E0(Z,p0($))}catch(X){if(!(X instanceof R0))throw X;throw new T("unsafe-file",`Claustrum enrollment parent refused: ${X.path} (${X.reason??X.code}). Use a folder that other users cannot write or replace.`)}}async function Y6(Z,$={}){if(RZ){await y8(Z,!1,p0($));return}await QX(Z,{recursive:!0,mode:448});let X=await y0(Z),J=process.geteuid?.();if(J!==void 0&&X.uid!==J)throw new T("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((X.mode&63)!==0)await BX(Z,448)}async function z1(Z,$,X={}){let J=lZ(Z);await Y6(J,X),await l0(J,X);let z=`${JSON.stringify($)}
89
+ `;if(Buffer.byteLength(z)>W6)throw new T("invalid-state","Claustrum enrollment state is too large");if(RZ)return b0(Z,z);let G=k8(J,`.${f0(Z)}.${process.pid}.${GX()}.tmp`),B,Q=!1;try{B=await I0(G,"wx",384),Q=!0,await B.writeFile(z,"utf8"),await B.chmod(384),await B.sync(),await B.close(),B=void 0,await YX(G,Z),Q=!1}finally{if(await B?.close().catch(()=>{}),Q)await k0(G).catch(()=>{})}}async function G3(Z,$){let X=await uZ(Z.tokenPath),J=X===void 0?void 0:g8(X),z=await uZ(Z.statePath),G=z===void 0?void 0:H6(z);if(J)return{state:"approved",proposedName:G?.proposedName??$,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:J.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return pZ(G)}async function m8(Z,$){let X;try{X=await G3(Z,$)}catch(J){if(!(J instanceof T)||J.kind!=="invalid-state"&&J.kind!=="invalid-token")return"unreadable";try{let z=await uZ(Z.statePath);if(z===void 0)return"unreadable";let G=H6(z);return G.phase==="approved"&&G.proposedName===$?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in X&&X.proposedName!==$)return"unreadable";if(X.state==="approved"||X.state==="blocked"&&X.code==="missing_token")return"vault";return"local"}async function G1(Z){let $=await uZ(Z);if($===void 0)throw new T("not-enrolled","Claustrum enrollment is not configured");return g8($)}function pZ(Z){if(Z.phase==="pending")return{state:"pending",proposedName:Z.proposedName,...Z.requestId!==void 0&&{requestId:Z.requestId}};if(Z.phase==="approved")return{state:"approved",proposedName:Z.proposedName,...Z.approvedName!==void 0&&{approvedName:Z.approvedName},tokenGeneration:Z.tokenGeneration};if(Z.phase==="denied")return{state:"denied",proposedName:Z.proposedName};return{state:"blocked",proposedName:Z.proposedName,code:Z.errorCode??"unknown"}}function u0(){return new T("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class U6{#Z;#$;#B;#z;#G;#Q;#X;constructor(Z){this.#X=Z.ancestorOptions??{},this.#Z=Z.client,this.#$=Z.paths,this.#B=Z.proposedName,this.#z=Z.now??Date.now,this.#G=Z.mintSecret??(()=>zX(32).toString("hex")),this.#Q=Z.writeTokenFile??jX}async status(){return G3(this.#$,this.#B)}async resetTerminal(){return d0(this.#$,this.#B)}async#W(Z,$){let X={version:1,phase:"blocked",proposedName:Z.proposedName,errorCode:$,updatedAt:this.#z()};return await z1(this.#$.statePath,X,this.#X),pZ(X)}async reconcile(){await Y6(lZ(this.#$.statePath),this.#X);let Z=await w({name:"ceremony",path:this.#$.statePath,ttlMs:x0,renew:!0});if(!Z)return{state:"busy"};try{let $=await uZ(this.#$.tokenPath),X=$===void 0?void 0:g8($),J=await uZ(this.#$.statePath),z=J===void 0?void 0:H6(J);if(z&&z.proposedName!==this.#B)throw u0();if(X){if(!z||z.phase==="pending"){let B={version:1,phase:"approved",proposedName:z?.proposedName??this.#B,tokenGeneration:X.token_generation,updatedAt:this.#z()};await z1(this.#$.statePath,B,this.#X),z=B}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:X.token_generation}}if(z?.phase==="approved"){let B={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#z()};return await z1(this.#$.statePath,B,this.#X),pZ(B)}if(z&&z.phase!=="pending")return pZ(z);if(!z){let B=this.#z();if(z={version:1,phase:"pending",proposedName:this.#B,requestSecret:this.#G(),createdAt:B,updatedAt:B},!f8.test(z.requestSecret))throw new T("invalid-state","invalid minted Claustrum enrollment secret");await z1(this.#$.statePath,z,this.#X)}if(!z.requestId)try{let B=JX("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),Q=await this.#Z.enrollPropose({name:z.proposedName,requestSecretHash:B});z={...z,requestId:Q.requestId,updatedAt:this.#z()},await z1(this.#$.statePath,z,this.#X)}catch(B){let Q=I8(B);if(!Q)throw B;if(Q.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:Q.code};return this.#W(z,Q.code)}let G=z.requestId;if(!G)return pZ(z);try{let B=await this.#Z.enrollPoll({requestId:G,requestSecret:z.requestSecret});if(B.status==="pending")return pZ(z);if(B.status==="denied"){let W={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#z()};return await z1(this.#$.statePath,W,this.#X),pZ(W)}await Y6(lZ(this.#$.tokenPath),this.#X),await l0(lZ(this.#$.tokenPath),this.#X),await this.#Q(this.#$.tokenPath,{token:B.token,token_generation:B.tokenGeneration});let Q={version:1,phase:"approved",proposedName:z.proposedName,approvedName:B.name,tokenGeneration:B.tokenGeneration,updatedAt:this.#z()};return await z1(this.#$.statePath,Q,this.#X),pZ(Q)}catch(B){let Q=I8(B);if(!Q)throw B;if(Q.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:G,retryCode:Q.code};return this.#W(z,Q.code)}}finally{await Z.release()}}}async function d0(Z,$){await Y6(lZ(Z.statePath));let X=await w({name:"ceremony",path:Z.statePath,ttlMs:x0,renew:!0});if(!X)return"busy";try{if(await uZ(Z.tokenPath)!==void 0)return"refused-approved";let J=await uZ(Z.statePath);if(J===void 0)return"idle";let z=H6(J);if(z.proposedName!==$)throw u0();if(z.phase==="pending")return"refused-pending";return await X.assertOwned(),await k0(Z.statePath),"reset"}finally{await X.release()}}var B3="claustrum-tombstone:v1:";function V6(Z){return`${B3}${Z}`}function w8(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function j6(Z){return typeof Z==="string"&&Z.startsWith(B3)}function c0(Z,$){if(!w8(Z)||Z.type!=="oauth")return!1;return Z.refresh===V6($)}function s0(Z,$){if(c0(Z,$))return"placeholder";if(w8(Z)&&Z.type==="oauth"&&typeof Z.refresh==="string"&&Z.refresh.length>0&&!j6(Z.refresh))return"login";if(w8(Z)&&Z.type==="api"&&typeof Z.key==="string"&&Z.key.length>0)return"login";return"empty"}function p8(Z){let $=s0(Z.auth,Z.provider);if(Z.mode==="custody"&&$==="login")throw new T("host-slot-login",`${Z.provider} has a host login while its accounts are vault-custodied; refusing to serve until one is removed`);if(Z.mode==="local"&&$==="placeholder")throw new T("host-slot-placeholder",`${Z.provider} host slot holds the vault placeholder; sign in to use local accounts`);return $}function i0(Z,$){return $!==void 0&&$.credentialId===Z.credentialId&&$.accountIdentity===Z.accountIdentity&&$.recordVersion!==Z.recordVersion}function NX(Z,$){if($===void 0)return"reauthorize-failed";if($.credentialId!==Z.credentialId)return"credential-changed";if($.accountIdentity!==Z.accountIdentity)return"account-changed";if($.recordVersion===Z.recordVersion)return"version-unchanged";return"rotated"}var a0=v("claustrum");function d8(Z,$,X,J=a0){let z=i0($,X);return J.debug("scoped 401 re-authorized",{site:Z,credentialId:$.credentialId,servedVersion:$.recordVersion,currentVersion:X?.recordVersion??null,retry:z,reason:NX($,X)}),z}var u8=300000;function l8(){return new T("invalid-material","Claustrum returned invalid credential material")}function MX(Z){let $=Z.trim();if($.startsWith("{")){let X;try{X=JSON.parse($)}catch{throw l8()}if(!X||typeof X!=="object")throw l8();let J=X,z=J.access_token??J.access;$=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test($)||$.startsWith(B3))throw l8();return $}function PX(Z,$){if(!Z.operations.includes("read"))return;if(!Z.categories.includes($.category))return;if(Z.credentialType==="oauth")return Z.refreshAdapter===$.refreshAdapter?"oauth":void 0;if(Z.credentialType==="api_key"&&$.apiKeys)return Z.refreshAdapter===void 0?"api_key":void 0;return}class q6{#Z;#$;#B;#z;#G;#Q;#X;#W=new WeakMap;#U=new WeakMap;#Y=!1;constructor(Z){let $=Z.tokenPath;if(Z.readToken)this.#$=Z.readToken;else if($)this.#$=()=>G1($);else throw new T("not-enrolled","Claustrum enrollment token path is required");this.#Z=Z.client,this.#z=Z.family,this.#G=Z.parseIdentity,this.#Q=Z.requireAssertion??!1,this.#B=Z.now??Date.now,this.#X=Z.logger??a0}#J(Z){if(this.#Y)throw new T("closed","Claustrum scoped custody is closed");Z?.throwIfAborted()}async#H(Z){this.#J(Z);let $=await this.#$();if(this.#J(Z),!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new T("invalid-token","Invalid Claustrum enrollment token");return $.token}async#V(Z,$){this.#J($);let X,J;try{let z=Z();X=$?await Promise.race([z,new Promise((G,B)=>{let Q=()=>B($.reason);if($.addEventListener("abort",Q,{once:!0}),J=()=>$.removeEventListener("abort",Q),$.aborted)Q()})]):await z}catch(z){if(this.#J($),z instanceof FX)throw z;throw new T("unavailable","Claustrum scoped operation unavailable")}finally{J?.()}return this.#J($),X}async discover(Z){let $=await this.#H(Z),X=await this.#V(()=>this.#Z.listScoped($),Z),J=[],z=[],G=new Map;for(let Q of X.rows){let W=PX(Q,this.#z);if(!W)continue;z.push({row:Q,type:W}),G.set(Q.id,(G.get(Q.id)??0)+1)}let B=[];for(let{row:Q,type:W}of z){let Y;if(!Q.id.trim())Y="empty credential id";else if((G.get(Q.id)??0)>1)Y="duplicate credential id";else if(Q.accountId!==void 0&&!Q.accountId.trim())Y="blank account identity";else if(!Q.state.trim())Y="empty state";if(Y){J.push({...Q.id.trim()&&{credentialId:Q.id},reason:Y});continue}B.push(Object.freeze({credentialId:Q.id,credentialType:W,...Q.accountId!==void 0&&{accountIdentity:Q.accountId},state:Q.state,...Q.email!==void 0&&{email:Q.email},...Q.orgName!==void 0&&{orgName:Q.orgName}}))}for(let Q of J)this.#X.warn("skipped malformed vault record",Q);return{view:X.view,credentials:Object.freeze(B),skipped:Object.freeze(J)}}async authorize(Z,$){if(!Z.credentialId)throw new T("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:J,accountIdentity:z}=Z;if(this.#Q&&z===void 0)throw new T("identity-unasserted","Claustrum dispatch requires a known account identity");let G=await this.#H($),B=await this.#V(()=>this.#Z.getScoped({credentialId:X,enrollmentToken:G,...J==="oauth"&&{minTtlMs:u8}}),$);if(B.credentialId!==void 0&&B.credentialId!==X)throw new T("identity-changed","Claustrum served credential identity changed");let Q=B.expiresAtMs;if(!Number.isSafeInteger(B.recordVersion)||B.recordVersion<0||Q===null&&J==="oauth"||Q!==null&&(!Number.isFinite(Q)||Q-this.#B()<u8))throw new T("insufficient-validity","Claustrum served credential has insufficient validity");let W=MX(B.material),Y=B.accountId?.trim()?B.accountId:void 0;if(this.#Q&&(B.credentialId===void 0||Y===void 0))throw new T("identity-unasserted","Claustrum served credential did not assert its identity");let U=Y===void 0?this.#G?.(W):void 0,V=Y??U;if(z!==void 0&&V!==void 0&&V!==z)throw new T("identity-changed","Claustrum served credential identity changed");let j=V??z,H=Object.freeze(Object.defineProperty({credentialId:X,credentialType:J,...j!==void 0&&{accountIdentity:j},accountIdentitySource:Y!==void 0?"asserted":U!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...B.credentialId!==void 0&&{assertedCredentialId:B.credentialId},...Y!==void 0&&{assertedAccountIdentity:Y},...B.projectId!==void 0&&{projectId:B.projectId},recordVersion:B.recordVersion,expiresAtMs:Q},"accessToken",{value:W,enumerable:!1}));return this.#W.set(H,G),H}async reportFailure(Z,$,X){if($!==401)return;this.#J();let J=this.#W.get(Z);if(!J)throw new T("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#U.get(Z);if(z)return z;let G=this.#V(()=>this.#Z.reportAuthFailureScoped({credentialId:Z.credentialId,enrollmentToken:J,providerStatus:401,recordVersion:Z.recordVersion,reporterSource:X}));this.#U.set(Z,G);try{await G,this.#X.debug("scoped 401 reported",{credentialId:Z.credentialId,recordVersion:Z.recordVersion,reporterSource:X})}catch(B){throw this.#U.delete(Z),B}}close(){if(this.#Y)return;this.#Y=!0,this.#Z.close()}}import{createHash as LX}from"node:crypto";function n0(Z,$,X){if(Z.accountIdentity!==void 0&&X!==void 0)return Z.accountIdentity===X;return Z.credentialId===$}function c8(Z,$,X){return Z.some((J)=>n0(J,$,X))}function s8(Z,$,X){let J={credentialId:$,...X!==void 0&&{accountIdentity:X}};return[...Z.filter((z)=>z.credentialId!==$||z.accountIdentity!==X),J]}function i8(Z,$,X){return Z.filter((J)=>!$.some((z)=>n0(J,z,X)))}var e0="vault:";function _X(Z){return LX("sha256").update(Z).digest("hex")}function OX(Z){let $=Z.credentialId.split(":");return($.length>=3?$.slice(2).join(":").trim():void 0)||Z.email||Z.credentialId}function CX(Z){return Z.identity!==void 0?`identity:${Z.identity}`:`credential:${Z.credential.credentialId}`}function dZ(Z){return[Z.credentialId,...Z.aliases??[]]}function Z4(Z,$,X={}){let J=X.now??Date.now(),z=X.routePrefix??e0,G=X.reservedRouteIds??new Set,B=Z?.rows??[],Q=[...Z?.declined??[]],W=$.skipped.length===0,Y=new Set($.credentials.map((F)=>F.credentialId)),U=new Set($.skipped.flatMap((F)=>F.credentialId===void 0?[]:[F.credentialId])),V=$.skipped.some((F)=>F.credentialId===void 0),j=(F)=>!Y.has(F)&&(U.has(F)||V),D=new Map;for(let F of B){if(F.accountIdentity===void 0)continue;for(let K of dZ(F))if(!D.has(K))D.set(K,F.accountIdentity)}let H=new Map;for(let F of $.credentials){let K=F.accountIdentity!==void 0?{credential:F,identity:F.accountIdentity,claimed:!0}:{credential:F,identity:D.get(F.credentialId),claimed:!1},P=CX(K),C=H.get(P)??[];C.push(K),H.set(P,C)}let q=new Set,N=new Set(G),M=[],O=(F,K)=>F.credential.credentialId.localeCompare(K.credential.credentialId),S=[...H.values()].map((F)=>F.toSorted(O)).sort((F,K)=>F[0]&&K[0]?O(F[0],K[0]):0);for(let F of S){let K=F[0]?.identity,P=F.filter((I)=>I.credential.state==="active"),C=P.length?P:F,k=C.filter((I)=>I.claimed),t=k.length?k:C,e=new Set(F.map((I)=>I.credential.credentialId)),h=B.find((I)=>!q.has(I)&&dZ(I).some((D1)=>e.has(D1))&&(I.accountIdentity===void 0||I.accountIdentity===K)),f=t.find((I)=>I.credential.credentialId===h?.credentialId)??t[0];if(!f)continue;let m=f.credential,JZ=h??(K===void 0?void 0:B.find((I)=>!q.has(I)&&I.accountIdentity===K));if(JZ)q.add(JZ);let d=JZ?.routeId;if(!d||G.has(d)){let I=`${z}${m.credentialId}${K===void 0?"":`~${_X(K).slice(0,10)}`}`;d=I;for(let D1=2;N.has(d);D1++)d=`${I}~${D1}`}N.add(d);let M2=JZ?dZ(JZ).filter(j):[],d6=[...new Set([...F.map((I)=>I.credential.credentialId),...M2])].filter((I)=>I!==m.credentialId).sort((I,D1)=>I.localeCompare(D1)),P2=X.mapAccount?.(m)??{};M.push({previousIndex:JZ?B.indexOf(JZ):1/0,row:{routeId:d,credentialId:m.credentialId,credentialType:m.credentialType,...K!==void 0&&{accountIdentity:K},...d6.length&&{aliases:d6},state:m.state,label:P2.label?.trim()||OX(m),...m.email!==void 0&&{email:m.email},...m.orgName!==void 0&&{orgName:m.orgName},enabled:![m.credentialId,...d6].some((I)=>c8(Q,I,K)),addedAt:JZ?.addedAt??J,...JZ?.quota!==void 0&&{quota:JZ.quota},...!f.claimed&&K!==void 0&&{unclaimed:!0}}})}return B.forEach((F,K)=>{if(q.has(F)||!dZ(F).some(j))return;if(N.has(F.routeId))return;let[P,...C]=dZ(F).filter((e)=>!Y.has(e));if(P===void 0)return;N.add(F.routeId);let{aliases:k,...t}=F;M.push({previousIndex:K,row:{...t,credentialId:P,...C.length&&{aliases:C},stale:!0}})}),M.sort((F,K)=>F.previousIndex===K.previousIndex?F.row.credentialId.localeCompare(K.row.credentialId):F.previousIndex-K.previousIndex),{version:1,view:$.view,complete:W,...!W&&{rejected:$.skipped.map((F)=>({...F.credentialId!==void 0&&{credentialId:F.credentialId},reason:F.reason}))},rows:M.map((F)=>F.row),declined:Q}}function a8(Z){return(Z?.rows??[]).filter(($)=>$.enabled&&$.state==="active").map(($)=>({id:$.routeId,kind:$.credentialType==="oauth"?"oauth":"api-key",...$.quota!==void 0&&{quota:$.quota}}))}function Q3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function I1(Z){return Z===void 0||typeof Z==="string"}function TX(Z){let $=Q3(Z)?o0(Z.quota):void 0;if(!Q3(Z)||typeof Z.routeId!=="string"||typeof Z.credentialId!=="string"||Z.credentialType!=="oauth"&&Z.credentialType!=="api_key"||typeof Z.state!=="string"||typeof Z.label!=="string"||typeof Z.enabled!=="boolean"||typeof Z.addedAt!=="number"||!I1(Z.accountIdentity)||!I1(Z.email)||!I1(Z.orgName)||Z.aliases!==void 0&&(!Array.isArray(Z.aliases)||!Z.aliases.every((X)=>typeof X==="string"))||Z.quota!==void 0&&$===void 0||Z.stale!==void 0&&Z.stale!==!0||Z.unclaimed!==void 0&&Z.unclaimed!==!0)return;return{...Z,...$===void 0?{}:{quota:$}}}var SX=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function r0(Z){if(!Array.isArray(Z))return;let $=[];for(let X of Z){if(!Q3(X)||!I1(X.credentialId)||typeof X.reason!=="string"||!SX.has(X.reason))return;$.push(X)}return $}function AX(Z){if(!Q3(Z)||Z.version!==1||!I1(Z.view)||!Array.isArray(Z.rows)||!Array.isArray(Z.declined)||Z.complete!==void 0&&typeof Z.complete!=="boolean"||Z.rejected!==void 0&&!r0(Z.rejected))throw new T("invalid-state","Claustrum roster file is not valid");let $=[];for(let z of Z.rows){let G=TX(z);if(!G)throw new T("invalid-state","Claustrum roster file is not valid");$.push(G)}let X=[];for(let z of Z.declined){if(!Q3(z)||typeof z.credentialId!=="string"||!I1(z.accountIdentity))throw new T("invalid-state","Claustrum roster file is not valid");X.push(z)}let J=r0(Z.rejected);return{version:1,...typeof Z.view==="string"&&{view:Z.view},complete:Z.complete!==!1,...J&&{rejected:J},rows:$,declined:X}}async function BZ(Z){let $;try{$=await _1(Z,RZ)}catch(J){if(J.code==="ENOENT")return;throw J}let X;try{X=JSON.parse($)}catch{throw new T("invalid-state","Claustrum roster file is not valid")}return AX(X)}var RX={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},EX={name:"claustrum-roster",ttlMs:30000};async function y1(Z,$,X={}){return t0(Z,RX,async(J)=>{let z=await BZ(Z),{next:G,result:B}=await $(z,{assertOwned:()=>J.assertOwned()});if(G)await J.assertOwned(),await n(Z,G,{beforeRename:async()=>{await X.beforePublish?.(),await J.assertOwned()}});return B})}function n8(Z,$){return y1(Z,(X)=>{let J=X?.rows.find((G)=>G.routeId===$);if(!X||!J)throw new T("route-unavailable","Claustrum route is not in the roster");let z=s8(X.declined,J.credentialId,J.accountIdentity);return{next:{...X,declined:z,rows:X.rows.map((G)=>G===J?{...G,enabled:!1}:G)},result:void 0}})}function r8(Z,$){return y1(Z,(X)=>{let J=X?.rows.find((z)=>z.routeId===$);if(!X||!J)throw new T("route-unavailable","Claustrum route is not in the roster");return{next:{...X,declined:i8(X.declined,dZ(J),J.accountIdentity),rows:X.rows.map((z)=>z===J?{...z,enabled:!0}:z)},result:void 0}})}function bX(Z,$){if(!dZ(Z).includes($.credentialId))return"refuse";if(Z.unclaimed&&($.accountIdentitySource==="expected"||$.accountIdentitySource==="none"))return"refuse";if(Z.accountIdentity===$.accountIdentity)return"hold";if(Z.accountIdentity===void 0&&$.expectedAccountIdentity===void 0&&$.accountIdentity!==void 0&&($.accountIdentitySource==="asserted"||$.accountIdentitySource==="parsed")&&dZ(Z).length===1)return"bind";return"refuse"}function o8(Z,$){return y1(Z,(X)=>{let J=X?.rows.find((Q)=>Q.routeId===$.routeId),z=!X||!J?"refuse":bX(J,$);if(!X||!J||z==="refuse")return{result:!1};let G=W3(J.quota,$.observation),B=z==="bind"?{accountIdentity:$.accountIdentity,unclaimed:!0}:{};return{next:{...X,rows:X.rows.map((Q)=>Q===J?{...Q,...B,quota:G}:Q)},result:!0}})}function t8(Z,$){return y1(Z,(X)=>{let J=X?.rows.find((G)=>G.routeId===$.routeId);if(!X||!J||J.accountIdentity===void 0||J.accountIdentity!==$.accountIdentity)return{result:!1};let z=W3(J.quota,$.observation);return{next:{...X,rows:X.rows.map((G)=>G===J?{...G,quota:z}:G)},result:!0}})}async function e8(Z){Z.signal?.throwIfAborted();let $=async()=>await Z.isActive?.()??!0;if(!await $())return;let X=await w({...EX,path:Z.path,renew:!0});if(!X){let J=await BZ(Z.path);if(Z.signal?.throwIfAborted(),!J?.view)throw new T("roster-busy","Claustrum account discovery is already in progress");return J}try{let J=await Z.custody.discover(Z.signal);return Z.signal?.throwIfAborted(),await y1(Z.path,async(z)=>{if(!await $())return{result:void 0};Z.signal?.throwIfAborted(),await X.assertOwned();let G=typeof Z.projection==="function"?Z.projection():Z.projection,B=Z4(z,J,G);return{...JSON.stringify(z)!==JSON.stringify(B)&&{next:B},result:B}})}finally{await X.release()}}class D6{#Z;#$=new AbortController;#B;#z;#G;#Q;#X;#W;#U=!1;#Y;constructor(Z){this.#Z=Z,this.#B=Z.logger??v("claustrum")}#J(Z){this.#$.signal.throwIfAborted(),Z?.throwIfAborted()}async#H(){return await this.#Z.isCustodyActive?.()??!0}#V(Z,$){let X=E8([this.#$.signal,...$?[$]:[]]);return new Promise((J,z)=>{let G=()=>{X.signal.removeEventListener("abort",B),X.dispose()},B=()=>{G(),z(X.signal.reason)};if(X.signal.addEventListener("abort",B,{once:!0}),Z.then((Q)=>{if(G(),X.signal.aborted)z(X.signal.reason);else J(Q)},(Q)=>{G(),z(Q)}),X.signal.aborted)B()})}async#q(){if(this.#J(),this.#z)return this.#z;if(!this.#G)this.#G=this.#Z.connect().then((Z)=>{if(this.#$.signal.aborted)Z.close(),this.#J();if(this.#z=new q6({client:Z,family:this.#Z.family,tokenPath:this.#Z.tokenPath,parseIdentity:this.#Z.parseIdentity,requireAssertion:this.#Z.requireAssertion,now:this.#Z.now,logger:this.#B}),this.#Z.insula&&Z.insula)this.#Y=_0(Z.insula,this.#Z.tokenPath);return this.#z}).finally(()=>{this.#G=void 0});return this.#V(this.#G)}snapshot(){return this.#X}routingRows(){return a8(this.#X)}refresh(){if(this.#J(),this.#Q)return this.#Q;return this.#Q=(async()=>{if(!await this.#H()){this.#X=void 0,this.#z?.close(),this.#z=void 0,this.#Y?.release(),this.#Y=void 0;return}let Z=await this.#q(),$=await e8({path:this.#Z.rosterPath,custody:Z,isActive:()=>this.#H(),signal:this.#$.signal,projection:()=>({reservedRouteIds:new Set(this.#Z.reservedRouteIds?.()??[]),routePrefix:this.#Z.routePrefix,mapAccount:this.#Z.mapAccount,now:(this.#Z.now??Date.now)()})});this.#J();let X=$?.view!==this.#X?.view;if(this.#X=$,$&&X)this.#Z.onRoster?.($);return $})().finally(()=>{this.#Q=void 0}),this.#Q}start(){if(this.#U)return;this.#J(),this.#U=!0;let Z=async()=>{try{await this.refresh(),await this.refreshInsulaQuota()}catch(X){if(!this.#$.signal.aborted)this.#Z.onError?.(X)}if(this.#$.signal.aborted)return;let $=this.#Z.pollIntervalMs??5000;if($<=0)return;this.#W=(this.#Z.setTimeoutImpl??setTimeout)(()=>{this.#W=void 0,Z()},$),this.#W.unref?.()};Z()}async refreshInsulaQuota(){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#H())return;try{await G1(this.#Z.tokenPath),await this.#q(),await this.#Y?.source.refresh((this.#Z.now??Date.now)())}catch{}}async cachedInsulaQuota(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#H())return;try{return await G1(this.#Z.tokenPath),this.#D(Z.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute(Z){if(!this.#Z.insula||this.#$.signal.aborted||!await this.#H())return;try{await G1(this.#Z.tokenPath);let X=(await BZ(this.#Z.rosterPath))?.rows.find((J)=>J.routeId===Z);return this.#D(X?.accountIdentity)}catch{return}}#D(Z){if(!this.#Z.insula||!Z)return;let $=this.#Y?.source.current(this.#Z.insula.provider,Z,(this.#Z.now??Date.now)());return $?this.#Z.insula.normalize($.entry,$.context):void 0}async authorize(Z,$){this.#J($);let X=this.#X??await this.#V(this.refresh(),$);if(!X||!await this.#H())throw new T("not-active","Claustrum scoped custody is not active");let J=await BZ(this.#Z.rosterPath);this.#J($);let z=X.rows.find((W)=>W.routeId===Z),G=J?.rows.find((W)=>W.routeId===Z);if(G&&!G.enabled)throw new T("route-declined","Claustrum route is disabled");if(!z||!G||G.state!=="active"||G.credentialId!==z.credentialId||G.accountIdentity!==z.accountIdentity)throw new T("route-unavailable","Claustrum route is disabled, removed or changed");let B=await this.#V(this.#q(),$),Q=E8([this.#$.signal,...$?[$]:[]]);try{return await B.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},Q.signal)}finally{Q.dispose()}}async reportFailure(Z,$,X){if(this.#J(),!this.#z)throw new T("no-receipt","Claustrum dispatch receipt has no active owner");await this.#z.reportFailure(Z,$,X)}async send(Z,$,X){let J=X.signal,z=await this.authorize(Z,J),G=await $(z,J);if(G.status===401&&!J?.aborted){let B;try{B=await this.authorize(Z,J)}catch{}if(d8(X.site,z,B,this.#B))await G.body?.cancel().catch(()=>{}),z=B,G=await $(B,J)}if(G.status===401)await this.reportFailure(z,401,X.reporterSource??"direct").catch((B)=>this.#Z.onError?.(B)),Promise.resolve().then(()=>this.refresh()).catch((B)=>{if(!this.#$.signal.aborted)this.#Z.onError?.(B)});return G}async decline(Z){this.#J(),await n8(this.#Z.rosterPath,Z),this.#X=await BZ(this.#Z.rosterPath)}async accept(Z){this.#J(),await r8(this.#Z.rosterPath,Z),this.#X=await BZ(this.#Z.rosterPath)}async recordQuota(Z,$,X){this.#J();let J=await o8(this.#Z.rosterPath,{routeId:Z,observation:$,credentialId:X.credentialId,accountIdentitySource:X.accountIdentitySource,...X.accountIdentity!==void 0&&{accountIdentity:X.accountIdentity},...X.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:X.expectedAccountIdentity}});if(J)this.#X=await BZ(this.#Z.rosterPath);return J}async recordAccountQuota(Z,$,X){this.#J();let J=await t8(this.#Z.rosterPath,{routeId:Z,accountIdentity:$,observation:X});if(J)this.#X=await BZ(this.#Z.rosterPath);return J}close(){if(this.#$.signal.aborted)return;if(this.#$.abort(new T("closed","Claustrum consumer is closed")),this.#W)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#W);this.#W=void 0,this.#z?.close(),this.#Y?.release(),this.#Y=void 0,this.#X=void 0}}async function $4(Z){let $=await IX.connect(Z);return Object.assign($,{insula:P0(Z)})}var X4=V6("openai");function J4(Z){return j6(Z)}function QZ(Z){if(!Z||Z.corrupt===!0)return!1;return J4(Z.refresh)}class Y3 extends Error{code="tombstone-refresh";constructor(){super("This OpenAI account was moved into the Claustrum vault by an older version of OpenAI auth and holds no local credential. Connect the vault, or sign in to the account again.");this.name="TombstoneRefreshError"}}function K6(Z){if(J4(Z))throw new Y3}var yX=v("quota"),Z$="primary",$$="secondary",kX="app_EMoamEEZ73f0CkXaXp7hrann",fX="https://auth.openai.com";async function lY(Z){K6(Z.refreshToken);let $=await Z.fetchImpl(`${fX}/oauth/token`,{method:"POST",signal:AbortSignal.timeout(15000),headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:Z.refreshToken,client_id:kX}).toString()});if(!$.ok){let z=O8($.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${$.status}`),{status:$.status,retryAfter:z,isRefreshError:!0})}let X=await $.json();if(!X||typeof X.access_token!=="string"||!X.access_token||typeof X.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});if(X.refresh_token!==void 0&&typeof X.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});let J=typeof X.refresh_token==="string"&&X.refresh_token?X.refresh_token:Z.refreshToken;return{access:X.access_token,refresh:J,expires:Z.now()+X.expires_in*1000,expiresIn:X.expires_in}}var xX="https://chatgpt.com/backend-api/wham/usage";async function H3(Z){let $=Z.logger??yX,X=Z.accountKey??"unknown",J=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:X});try{let z=await Z.fetchImpl(xX,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!z.ok){let B=O8(z.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${z.status}`),{status:z.status,retryAfter:B})}let G=N0(await z.json());return $.debug("wham usage fetch succeeded",{pid:process.pid,accountId:X,status:z.status,elapsedMs:Date.now()-J}),G}catch(z){throw $.warn("wham usage fetch failed",{pid:process.pid,accountId:X,status:typeof z?.status==="number"?z.status:"error",elapsedMs:Date.now()-J,error:WZ(z)}),z}}import{createHash as hX}from"node:crypto";var vX=globalThis.setTimeout,gX=5;function U3(Z){let $=Z?.quota?.checkIntervalMinutes??gX;return Math.max(1,$)*60000}function mX(Z){return Z?.quota?.enabled!==!1}function F6(Z,$){if(!Z?.resetsAt)return!1;let X=Date.parse(Z.resetsAt);return Number.isFinite(X)&&X<=$}function nY(Z,$,X,J,z){if(z!==void 0&&Number.isFinite(z)&&z>X)return z;let G=$===Z$?Z?.primary:$===$$?Z?.secondary:void 0,B=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(B)&&B>X)return B;return X+J}function wX(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function z4(Z,$,X){if(!mX($))return X+U3($);let J=wX($),z=[];for(let G of["primary","secondary"]){let B=Z?.[G];if(!B)continue;if(B.remainingPercent>=J[G])continue;let Q=B.resetsAt?Date.parse(B.resetsAt):Number.NaN;if(!Number.isFinite(Q)||Q<=X)return X+U3($);z.push(Q)}if(!z.length)return X+U3($);return Math.min(...z)+60000}function pX(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function lX(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function $Z(Z){return hX("sha256").update(Z).digest("hex").slice(0,16)}class cZ{main=null;mainTokenFp=null;mainQuotaAccountId=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;rateLimitedUntilMap=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;fetchQuotaFn;onMainQuotaFetched;onApiError;configPath;constructor(Z){this.storage=Z.storage,this.fetchImpl=Z.fetchImpl??fetch,this.configPath=Z.configPath,this.now=Z.now??Date.now,this.fetchQuotaFn=Z.fetchQuotaFn,this.onMainQuotaFetched=Z.onMainQuotaFetched,this.onApiError=Z.onApiError,this.seedMainFromStorage(Z.storage),this.seedMainBackoffFromStorage(Z.storage)}getMain(Z){if(Z&&this.main&&this.mainTokenFp&&this.mainTokenFp!==$Z(Z))this.main=null,this.mainTokenFp=null;return this.main}getFallback(Z,$){let X=this.fallbacks.get(Z)??null;if(!$||!X)return X;if(this.fallbackTokenFps.get(Z)!==$Z($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return X}getAllFallbacks(){return this.fallbacks}setMain(Z,$,X,J=!1){if(!J&&!G4($.quota))return;if(this.mainTokenFp=$Z(Z),X&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==X)this.clearRateLimited("main");if(X)this.mainQuotaAccountId=X;if(this.main=$,X$($.quota))this.clearRateLimited("main")}peekMainForPolicy(Z){if(Z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z)return null;return this.main}peekFallbackForPolicy(Z,$){let X=this.fallbacks.get(Z)??null;if($&&X?.accountId&&X.accountId!==$)return null;return X}setFallback(Z,$,X,J=!1,z){if(!J&&!G4($.quota))return;let G=this.fallbacks.get(Z)?.accountId;if(z&&G&&z!==G)this.clearRateLimited(Z);let B=z??G;if(this.fallbacks.set(Z,{...$,accountId:B}),X)this.fallbackTokenFps.set(Z,$Z(X));else this.fallbackTokenFps.delete(Z);if(X$($.quota))this.clearRateLimited(Z)}markRateLimited(Z,$){let X=this.rateLimitedUntilMap.get(Z);if(X!==void 0&&X>$)return;this.rateLimitedUntilMap.set(Z,$)}isRateLimited(Z){let $=this.rateLimitedUntilMap.get(Z);return $!==void 0&&this.now()<$}rateLimitedUntil(Z){return this.rateLimitedUntilMap.get(Z)}clearRateLimited(Z){this.rateLimitedUntilMap.delete(Z)}async refreshMain(Z){let $=$Z(Z);if(this.mainTokenFp&&this.mainTokenFp!==$)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===$)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=$,this.inflightMain=this._fetchMain(Z),this.inflightMain}async refreshFallback(Z,$){let X=cZ.fallbackInflightKey(Z,$),J=this.inflightFallbacks.get(X);if(J)return J;if(this.isFallbackBackedOff(Z,$)){let G=this.getFallback(Z,$);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let z=this._fetchFallback(Z,$);return this.inflightFallbacks.set(X,z),z}async refreshAllFallbacks(Z){let $=this.now();for(let X of Z){if(X.enabled===!1)continue;if(QZ(X)||!X.access)continue;let J=this.getFallback(X.id,X.access);if(J&&$<J.refreshAfter)continue;try{await this.refreshFallback(X.id,X.access)}catch{}}}refreshMainInBackground(Z){let $=$Z(Z);if(this.inflightMain&&this.inflightMainFp===$)return;if(this.isBackedOff())return;this.refreshMain(Z).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(Z,$){let X=this.getFallback(Z,$);if(!X)return!0;return this.now()>=X.refreshAfter}shouldRefreshOnRequestCount(Z){let $=lX(this.storage);if($<=0)return!1;return Z>0&&Z%$===0}needsRefresh(Z){return this.isMainStale()||this.shouldRefreshOnRequestCount(Z)}updateStorage(Z){this.storage=Z,this.seedMainFromStorage(Z),this.seedMainBackoffFromStorage(Z)}seedMainFromStorage(Z,$){let X=pX(Z);if(!X)return;let J=$?$Z($):null;if(J&&X.tokenFingerprint&&X.tokenFingerprint!==J)return;let z={quota:X.quota,refreshAfter:z4(X.quota,Z,X.checkedAt),checkedAt:X.checkedAt};if(this.main&&this.main.checkedAt>=z.checkedAt&&(!J||!this.mainTokenFp||this.mainTokenFp===J))return;if(this.main=z,this.mainTokenFp=X.tokenFingerprint??null,Z?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=Z.mainAccountId}}seedMainBackoffFromStorage(Z){let $=Z?.quota?.mainLastQuotaApiError;this.mainLastApiError=$&&A1($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=U3(this.storage);for(let X of Z){if(X.enabled===!1)continue;if(!X.quota)continue;let J=Math.max(X.quota.primary?.checkedAt??0,X.quota.secondary?.checkedAt??0);if(J<=0)continue;let z=this.getFallback(X.id,X.access);if(z&&z.checkedAt>=J)continue;this.setFallback(X.id,{quota:X.quota,refreshAfter:J+$,checkedAt:J},X.access,!1,X.accountId)}}isBackedOff(){return A1(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==$Z($))return!1}return A1(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,$Z($)])}static quotaLockName(Z){return`opencode-fallback-quota-refresh-${Z.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(Z){let $=async()=>{let J=this.now()-this.lastApiCallAt;if(J<cZ.API_CALL_GAP_MS)await new Promise((z)=>{let G=vX(z,cZ.API_CALL_GAP_MS-J);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),Z()},X=this.apiGate.then($,$);return this.apiGate=X.catch(()=>{}),X}async _fetchMain(Z){let $=$Z(Z);return this._enqueueApiFetch(async()=>{try{if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}let X=await w({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!X){let J=this.main;if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=this.now(),z=await this._fetchQuota(Z),G=this.now();if(this.mainTokenFp=$Z(Z),this.main={quota:z,refreshAfter:z4(z,this.storage,G),checkedAt:G},X$(z))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(z,G,this.mainTokenFp,J),z}catch(J){throw this._handleMainFetchError(J),J}finally{await X.release()}}finally{if(this.inflightMainFp===$)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(Z,$){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(Z,$)){let J=this.getFallback(Z,$);if(J)return J.quota;throw Error("Quota API rate-limited — try again later")}let X=await w({name:cZ.quotaLockName(Z),ttlMs:30000,path:this.configPath});if(!X){let J=this.getFallback(Z,$);if(J&&this.now()<J.refreshAfter)return J.quota;throw Error("Quota refresh is already in progress")}try{let J=await this._fetchQuota($),z=this.now();return this.setFallback(Z,{quota:J,refreshAfter:z+U3(this.storage),checkedAt:z},$,!0),this.fallbackApiErrors.delete(Z),this.fallbackErrorTokenFps.delete(Z),J}finally{await X.release()}}catch(X){throw this._handleFallbackFetchError(Z,$,X),X}finally{this.inflightFallbacks.delete(cZ.fallbackInflightKey(Z,$))}})}async _fetchQuota(Z){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:Z,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError(Z){return Z?.status===401}_handleMainFetchError(Z){if(cZ.isAuthError(Z))return;this.mainLastApiError=$3({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,X){if(cZ.isAuthError(X))return;let J=$Z($),z=this.fallbackErrorTokenFps.get(Z)===J?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,$3({error:X,now:this.now(),previous:z})),this.fallbackErrorTokenFps.set(Z,J)}}function G4(Z){return Boolean(Z.primary||Z.secondary)}function X$(Z){let{primary:$,secondary:X}=Z;if(!$&&!X)return!1;if($&&$.usedPercent>=100)return!1;if(X&&X.usedPercent>=100)return!1;return!0}import{createHash as dX,randomUUID as cX}from"node:crypto";import{setTimeout as sX}from"node:timers/promises";import{readFile as JJ}from"node:fs/promises";var B1=v("refresh"),M6=v("accounts"),iX=1e4,aX=15000,J$=50;function NZ(Z){return Z.type==="oauth"&&Z.corrupt!==!0}function nX(Z){let $=Z?.trim();if(!$)return!1;try{let X=new URL($);return(X.protocol==="http:"||X.protocol==="https:")&&!X.username&&!X.password}catch{return!1}}var k1="floors-v1";function QH(Z){return Z.costZeroing?.enabled!==!1}class P6 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var rX=[401,403,429],B4={primary:0,secondary:0},oX=!1,sZ={primary:5,secondary:10};function A(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var tX=new Set(["__proto__","constructor","prototype"]);function OZ(Z){return Z.length>0&&!tX.has(Z)}function eX(Z){return Z instanceof P6||A(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function N6(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():cX(),label:typeof Z.label==="string"?Z.label:void 0,enabled:typeof Z.enabled==="boolean"?Z.enabled:void 0,addedAt:typeof Z.addedAt==="number"?Z.addedAt:void 0,lastUsed:typeof Z.lastUsed==="number"?Z.lastUsed:void 0,accountId:typeof Z.accountId==="string"?Z.accountId:void 0}}function Q4(Z){if(!A(Z))return;if(typeof Z.message!=="string")return;let $=Number(Z.checkedAt);if(!Number.isFinite($))return;let X=Number(Z.nextRetryAt),J=Number(Z.retryCount);return{message:Z.message,checkedAt:$,nextRetryAt:Number.isFinite(X)?X:void 0,retryCount:Number.isFinite(J)?J:void 0,tokenHash:typeof Z.tokenHash==="string"?Z.tokenHash:void 0}}function ZJ(Z){if(!A(Z))return;let $={};for(let z of["primary","secondary"]){let G=Z[z];if(!A(G))continue;let B=Number(G.usedPercent),Q=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(B)||!Number.isFinite(Q)||!Number.isFinite(W))continue;let Y=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;$[z]={usedPercent:B,remainingPercent:Q,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Y)&&Y>0?{windowMinutes:Y}:{}}}for(let z of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof Z[z]==="number"?Z[z]:Number.NaN;if(Number.isFinite(G)&&G>=0)$[z]=G}let X=Z.spendControl;if(A(X)){let z=Number(X.limit),G=Number(X.used),B=Number(X.remaining),Q=Number(X.usedPercent),W=Number(X.remainingPercent);if(Number.isFinite(z)&&Number.isFinite(G)&&Number.isFinite(B)&&Number.isFinite(Q)&&Number.isFinite(W)&&typeof X.reached==="boolean")$.spendControl={limit:z,used:G,remaining:B,usedPercent:Q,remainingPercent:W,resetsAt:typeof X.resetsAt==="string"?X.resetsAt:void 0,unit:typeof X.unit==="string"?X.unit:void 0,source:typeof X.source==="string"?X.source:void 0,reached:X.reached}}let J=Z.credits;if(A(J)&&typeof J.hasCredits==="boolean"&&typeof J.unlimited==="boolean"&&typeof J.overageLimitReached==="boolean"){let z=Number(J.balance);$.credits={hasCredits:J.hasCredits,unlimited:J.unlimited,overageLimitReached:J.overageLimitReached,...Number.isFinite(z)?{balance:z}:{}}}return Object.keys($).length?$:void 0}function $J(Z){if(!A(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",X=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!nX($))return null;let J=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...N6(Z),type:"api",apiKey:X||void 0,baseURL:$,authHeader:J}}if(Z.type!=="oauth")return null;if(Z.corrupt===!0){if(typeof Z.id!=="string"||!Z.id.trim())return null;return{...N6(Z),type:"oauth",corrupt:!0}}if(typeof Z.refresh!=="string"||!Z.refresh.trim()){if(!Object.hasOwn(Z,"refresh")||typeof Z.id!=="string"||!Z.id.trim())return null;return{...N6(Z),type:"oauth",corrupt:!0}}return{...N6(Z),type:"oauth",access:typeof Z.access==="string"?Z.access:void 0,refresh:Z.refresh,expires:typeof Z.expires==="number"?Z.expires:void 0,lastRefreshedAt:typeof Z.lastRefreshedAt==="number"?Z.lastRefreshedAt:void 0,lastRefreshError:Q4(Z.lastRefreshError),lastQuotaRefreshError:Q4(Z.lastQuotaRefreshError),quota:ZJ(Z.quota)}}function XJ(Z){if(!A(Z))return;let $=Object.create(null);for(let[X,J]of Object.entries(Z)){if(!OZ(X)||!A(J))continue;let z={};if(A(J.inFlight))z.inFlight={...J.inFlight};if(A(J.lastOutcome)&&typeof J.lastOutcome.code==="string"&&J.lastOutcome.code.length>0&&typeof J.lastOutcome.at==="number"&&Number.isFinite(J.lastOutcome.at))z.lastOutcome={code:J.lastOutcome.code,at:J.lastOutcome.at,...A(J.lastOutcome.previousOutcome)&&typeof J.lastOutcome.previousOutcome.code==="string"&&J.lastOutcome.previousOutcome.code.length>0&&typeof J.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(J.lastOutcome.previousOutcome.at)?{previousOutcome:{code:J.lastOutcome.previousOutcome.code,at:J.lastOutcome.previousOutcome.at}}:{}};if(typeof J.cooldownUntil==="number"&&Number.isFinite(J.cooldownUntil))z.cooldownUntil=J.cooldownUntil;if(Object.keys(z).length>0)$[X]=z}return Object.keys($).length>0?$:void 0}var W4=new Set;function D4(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(W4.has($))return;W4.add($),M6.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function K4(Z){if(!A(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,X=$.map($J).filter((J)=>J!=null);if(X.length<$.length){let J=new Set;for(let B of $)if(A(B)&&typeof B.id==="string"&&B.id.trim())J.add(B.id.trim());let z=new Set(X.map((B)=>B.id)),G=[];for(let B of J)if(!z.has(B))G.push(B);D4(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:A(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((J)=>Number.isInteger(J)):void 0,refresh:A(Z.refresh)?Z.refresh:void 0,quota:A(Z.quota)?Z.quota:void 0,reset:XJ(Z.reset),dump:A(Z.dump)?Z.dump:void 0,costZeroing:A(Z.costZeroing)?Z.costZeroing:void 0,killswitch:A(Z.killswitch)?Z.killswitch:void 0,logging:A(Z.logging)?Z.logging:void 0,cachekeep:A(Z.cachekeep)?Z.cachekeep:void 0,cacheKeep:A(Z.cacheKeep)?Z.cacheKeep:void 0,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:X}}function F4(Z){if(!("claustrum"in Z))return Z;let{claustrum:$,...X}=Z;return X}async function iZ(Z){try{return{exists:!0,value:JSON.parse(await JJ(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function aZ(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function zJ(Z){let $;try{$=(await iZ(Z)).value}catch{return null}return H$($)}function N4(Z,$){if(!A(Z))return Z;let X=A($)?$:{},J=A(X.main)?X.main:void 0,z=A(X.accounts)?X.accounts:{},G=A(Z.quota)?Z.quota:{},B=A(Z.refresh)?Z.refresh:{},Q=J??G,W=J??B,U=B.mainRefreshLeaseId!==void 0?{id:B.mainRefreshLeaseId,until:B.mainRefreshLeaseUntil,tokenHash:B.mainRefreshLeaseTokenHash}:{id:W.refreshLeaseId,until:W.refreshLeaseUntil,tokenHash:W.refreshLeaseTokenHash},j=Array.isArray(Z.accounts)?Z.accounts.map((D)=>{if(!A(D))return D;let H=typeof D.id==="string"&&A(z[D.id])?z[D.id]:{};return{...D,...H}}):void 0;return M4({...Z,refresh:aZ({...B,mainLastRefreshError:B.mainLastRefreshError??W.lastRefreshError,mainRefreshLeaseId:U.id,mainRefreshLeaseUntil:U.until,mainRefreshLeaseTokenHash:U.tokenHash}),quota:aZ({...G,mainQuota:Q.quota,mainQuotaCheckedAt:Q.quotaCheckedAt,mainQuotaToken:Q.quotaToken,mainLastQuotaApiError:Q.lastQuotaApiError}),accounts:j})}async function K3(Z){let $=await iZ(Z.configPath);if(!$.exists)return null;let X=await iZ(Z.statePath);return K4(N4($.value,X.value))}function M4(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function GJ(Z){return aZ({id:Z.id,label:Z.label,type:Z.type,corrupt:Z.type==="oauth"&&Z.corrupt===!0?!0:void 0,enabled:Z.enabled,addedAt:Z.addedAt,accountId:Z.accountId,baseURL:Z.type==="api"?Z.baseURL:void 0,authHeader:Z.type==="api"?Z.authHeader:void 0})}function P4(Z){if(Z.type==="api")return aZ({apiKey:Z.apiKey,lastUsed:Z.lastUsed});if(Z.corrupt)return{};return aZ({access:Z.access,refresh:Z.refresh,expires:Z.expires,lastUsed:Z.lastUsed,lastRefreshedAt:Z.lastRefreshedAt,lastRefreshError:Z.lastRefreshError,lastQuotaRefreshError:Z.lastQuotaRefreshError,quota:Z.quota})}function L6(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function V3(Z,$,X){if(X in $)Z[X]=$[X];else delete Z[X]}function BJ(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function QJ(Z,$){if(!BJ(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}var WJ=300000;function Y4(Z,$){if(Z===void 0)return 0;return Z>$+WJ?0:Z}function YJ(Z,$,X){let J=Date.now(),z=Y4($.lastRefreshedAt,J),G=Y4(X.lastRefreshedAt,J),B=$.expires??0,Q=X.expires??0,W=G>z?X:z>G?$:Q>B?X:B>Q?$:QJ($,X);V3(Z,W,"access"),V3(Z,W,"refresh"),V3(Z,W,"expires"),V3(Z,W,"lastRefreshedAt"),V3(Z,W,"lastRefreshError")}function HJ(Z,$){if(!A(Z))return $;let X=Z,J=L6(X.quota),z=L6($.quota),G=J>z,B=G?{...X,...$,quota:X.quota,lastQuotaRefreshError:X.lastQuotaRefreshError}:{...X,...$};if(!G&&!("lastQuotaRefreshError"in $))delete B.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete B.lastRefreshError;if(typeof X.lastUsed==="number"&&(typeof $.lastUsed!=="number"||X.lastUsed>$.lastUsed))B.lastUsed=X.lastUsed;return YJ(B,X,$),B}function L4(Z){let $=Z.refresh?aZ({enabled:Z.refresh.enabled,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,X=Z.quota?aZ({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota}):void 0;return M4({version:1,main:Z.main,routing:Z.routing,fallbackOn:Z.fallbackOn,refresh:$,quota:X,reset:Z.reset,dump:Z.dump,costZeroing:Z.costZeroing,killswitch:Z.killswitch,logging:Z.logging,cachekeep:Z.cachekeep,cacheKeep:Z.cacheKeep,mainAccountId:Z.mainAccountId,accounts:Z.accounts.map(GJ)})}async function q3(Z,$=!1){let X=Date.now(),J=X+aX,z=0;while(Date.now()<=J){z++;let Q=await w({name:"save",ttlMs:iX,path:Z,renew:$});if(Q)return Q;let W=J-Date.now();if(W<=0)break;await sX(Math.min(J$+T4(J$),W))}let G=Date.now()-X,B=Math.round(G/Math.max(1,z));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${Z} (${z} attempts, ~${B}ms apart; retry interval is ${J$}ms). A gap near the retry interval means lock contention; a much larger one means this process's event loop was saturated and the wait expired without getting scheduled.`)}function _4(Z){let $=Object.fromEntries(Z.accounts.map((X)=>[X.id,P4(X)]));return{version:1,main:aZ({quota:Z.quota?.mainQuota,quotaCheckedAt:Z.quota?.mainQuotaCheckedAt,quotaToken:Z.quota?.mainQuotaToken,lastQuotaApiError:Z.quota?.mainLastQuotaApiError,lastRefreshError:Z.refresh?.mainLastRefreshError,refreshLeaseId:Z.refresh?.mainRefreshLeaseId,refreshLeaseUntil:Z.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:Z.refresh?.mainRefreshLeaseTokenHash}),accounts:$}}function H$(Z){if(!A(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let X of Z.accounts){if(!A(X))continue;if(typeof X.id!=="string")continue;let J=X.id.trim();if(!J)continue;$.add(J)}return $}function UJ(Z,$,X,J){if(!A(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let z=[],G=[];for(let B of $){if(X.has(B))continue;if(J.has(B))continue;let Q=Z.accounts.find((W)=>A(W)&&typeof W.id==="string"&&W.id.trim()===B);if(!Q)continue;z.push(Q),G.push(B)}return{preservedRawEntries:z,preservedIds:G}}function VJ(Z){if(!Array.isArray(Z))return[];let $=[];for(let X of Z){if(!A(X))continue;if(typeof X.id!=="string")continue;$.push(X.id)}return $}function jJ(Z,$,X){let J=H$(Z);if(J===null)return[];let{preservedRawEntries:z,preservedIds:G}=UJ(Z,J,$,X);return D4(G),z}async function YH(Z,$,X={}){let{configPath:J,statePath:z}=$,G=await q3(J);try{let B=await q3(z);try{let Q=await iZ(J),W=await iZ(z),Y=(Q.exists?K4(N4(Q.value,W.value)):null)??qJ(),U=new Set(Y.accounts.map((F)=>F.id)),V=H$(Q.value)??new Set,j=Z(Y,{rawRosterIds:[...V],loadedRosterIds:[...U]})??Y,D=new Set(X.allowDrop??[]),H=jJ(Q.value,U,D),q=L4(j),N=new Set((Array.isArray(q.accounts)?q.accounts:[]).map((F)=>A(F)&&typeof F.id==="string"?F.id.trim():"").filter(Boolean)),M=H.filter((F)=>{if(!A(F))return!1;if(typeof F.id!=="string")return!1;return!N.has(F.id.trim())}),O=A(Q.value)?Q.value:{},S={...F4(O),...q,accounts:[...Array.isArray(q.accounts)?q.accounts:[],...M]};if(X.canWrite&&!X.canWrite())return Y;if(await n(J,S),X.canWrite&&!X.canWrite())return Y;return await n(z,_4(j)),M6.debug("account config written",{accountCount:S.accounts.length,accountIds:VJ(S.accounts)}),j}finally{await B.release()}}finally{await G.release()}}function qJ(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function DJ(Z,$){Z.main=Z.main??{};let X=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:L6(Z.main.quota),J=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:L6($.quota?.mainQuota);if(X>J)return;Z.main.quota=$.quota?.mainQuota,Z.main.quotaCheckedAt=$.quota?.mainQuotaCheckedAt,Z.main.quotaToken=$.quota?.mainQuotaToken,Z.main.lastQuotaApiError=$.quota?.mainLastQuotaApiError}function KJ(Z,$){Z.main=Z.main??{},Z.main.lastRefreshError=$.refresh?.mainLastRefreshError,Z.main.refreshLeaseId=$.refresh?.mainRefreshLeaseId,Z.main.refreshLeaseUntil=$.refresh?.mainRefreshLeaseUntil,Z.main.refreshLeaseTokenHash=$.refresh?.mainRefreshLeaseTokenHash}function G$(Z){if(Array.isArray(Z))return Z.map(G$);if(!A(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,X])=>[$,G$(X)]))}async function U$(Z,$,X={mainQuota:!0,mainRefresh:!0,accounts:!0},J){let z=$.statePath,G=await q3(z);try{let B=(await iZ(z)).value,Q=A(B)?{...B,version:1}:{version:1};if(X.mainQuota)DJ(Q,Z);if(X.mainRefresh)KJ(Q,Z);if(X.accounts){let W=X.accounts===!0?null:new Set(X.accounts),Y=await zJ($.configPath);Q.accounts={...A(Q.accounts)?Q.accounts:{}};for(let U of Z.accounts){if(W&&!W.has(U.id))continue;if(Y&&!Y.has(U.id))continue;Q.accounts[U.id]=HJ(Q.accounts[U.id],P4(U))}if(W){for(let U of W)if(!Z.accounts.some((V)=>V.id===U))delete Q.accounts[U]}if(Y){for(let U of Object.keys(Q.accounts))if(!Y.has(U))delete Q.accounts[U]}}if(J&&!J())return;await n(z,G$(Q))}finally{await G.release()}}function FJ(Z){return Z?.fallbackOn?.length?Z.fallbackOn:rX}function HH(Z,$){return FJ($).includes(Z)}function NJ(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??B4.primary,secondary:$.secondary??$["1w"]??B4.secondary}}function B$(Z){return Z?.quota?.enabled!==!1}function D3(Z){return Z?.quota?.failClosedOnUnknownQuota??oX}function O4(Z,$,X=Date.now()){if(!B$($))return!0;if(!Z)return!D3($);let J=NJ($),z=D3($);for(let G of["primary","secondary"]){let B=Z[G];if(!B)continue;if(F6(B,X)){if(z)return!1;continue}if(B.remainingPercent<J[G])return!1}return!0}function C4(Z){return Z?.killswitch?.enabled===!0}function H4(Z){return{primary:Z?.primary??Z?.["5h"]??sZ.primary,secondary:Z?.secondary??Z?.["1w"]??sZ.secondary}}function UH(Z){return Z?.cacheKeep??Z?.cachekeep}function U4(Z){return typeof Z==="number"&&Number.isFinite(Z)?Z:0}function Y1(Z,$){if(!Z?.killswitch)return sZ;if(Z.killswitch.schema===k1){let{accounts:X,defaults:J}=Z.killswitch,z=$??"main",G=A(X)&&Object.hasOwn(X,z)&&A(X[z])?X[z]:A(J)?J:void 0;return{primary:U4(G?.primary),secondary:U4(G?.secondary)}}if($&&Z.killswitch.accounts?.[$])return H4(Z.killswitch.accounts[$]);return H4(Z.killswitch.main)}function VH(Z,$,X,J=Date.now()){if(!C4($))return!0;if(!Z)return!D3($);let z=Y1($,X),G=D3($);for(let B of["primary","secondary"]){let Q=Z[B];if(!Q)continue;if(F6(Q,J)){if(G)return!1;continue}if(Q.remainingPercent<z[B])return!1}return!0}function jH(Z,$,X,J){if(!C4(J))return 300;let z=[],G=[{accountId:void 0,quota:Z},...$];for(let{accountId:Q,quota:W}of G){if(!W)continue;let Y=Y1(J,Q),U=[],V=!1;for(let j of["primary","secondary"]){let D=W[j];if(!D||F6(D,X))continue;if(D.remainingPercent>=Y[j])continue;let H=D.resetsAt?Date.parse(D.resetsAt):NaN;if(!Number.isFinite(H)||H<=X){V=!0;break}U.push(H)}if(V||U.length===0)continue;z.push(Math.max(...U))}if(z.length===0)return 300;let B=Math.min(...z);return Math.max(1,Math.ceil((B-X)/1000))}function V4(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function qH(Z,$){let{configPath:X,statePath:J}=$;if(!Z)return;try{let G=await iZ(X);if(G.exists&&A(G.value)&&V4(G.value))return}catch{}let z=await q3(X);try{let G=await q3(J);try{let B=await iZ(X);if(B.exists&&A(B.value)){if(V4(B.value))return}if(!Z)return;let Q={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let U=X6({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(U)Q.mainAccountId=U}let W=B.exists&&A(B.value)?B.value:{},Y={...F4(W),...L4(Q)};await n(X,Y),await n(J,_4(Q))}finally{await G.release()}}finally{await z.release()}}function MJ(Z){return Z?.refresh?.enabled!==!1}function PJ(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function T4(Z){return Math.floor(Math.random()*(Z+1))}function Q1(Z,$,X){return!Z.access||!Z.expires||Z.expires-X<=PJ($)}function LJ(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function W1(Z,$){return Boolean(Z?.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}class S4 extends Error{constructor(Z){super(`Refusing to refresh account ${Z}: it holds the main account's credential while the main slot is live`);this.name="ShieldedMainRowRefreshError"}}var _J="common-auth-placeholder:v1:openai",A4="main";function R4(Z){return A(Z)&&Z.type==="oauth"&&(Z.refresh===_J||Z.refresh===X4)}function E4(Z){return Z?.accounts.find(($)=>$.id===A4&&$.enabled!==!1&&NZ($))}function DH(Z){if(!Z)return Z;return{...Z,accounts:Z.accounts.filter(($)=>$.id!==A4)}}function XZ(Z,$){let X=Z.accounts.findIndex((J)=>J.id===$.id);if(X!==-1)Z.accounts[X]=$}function j3(Z){return Z instanceof Error?Z.message:String(Z)}function Q$(Z,$,X){if($ instanceof Y3)return;Z.lastRefreshError=Z6({error:$,now:X,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function z$(Z,$,X){if($ instanceof Y3)return;if(Z.lastQuotaRefreshError=$3({error:$,now:X,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)Q$(Z,$,X)}function j4(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let X=Date.parse(Z.resetsAt);return Number.isFinite(X)?X>$:!0}function OJ(Z,$){if(!Z)return!1;return j4(Z.primary,$)||j4(Z.secondary,$)}function CJ(Z,$,X){if(!Z)return!1;let J=$?.quota?.checkIntervalMinutes??5,z=Math.max(1,J)*60000,G=Math.max(Z.primary?.checkedAt??0,Z.secondary?.checkedAt??0);return X-G<z}function q4(Z,$,X){return!CJ(Z.quota,$,X)}function TJ(Z,$,X,J){return _8(X)&&O4(Z.quota,$,J)&&OJ(Z.quota,J)}function SJ(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var AJ=60000,RJ=60000,V$=600000;function j$(Z){return`fallback-oauth-refresh-${dX("sha256").update(Z).digest("base64url").slice(0,16)}`}var EJ=1e4,bJ=100;class IJ{now;fetchImpl;paths;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;options;constructor(Z){this.options=Z,this.now=Z.now??Date.now,this.fetchImpl=Z.fetchImpl??fetch,this.paths=Z.paths,this.quotaManager=Z.quotaManager??null,this.onFallbackStorageChanged=Z.onFallbackStorageChanged}assertNotTombstoned(Z){if(Z)K6(Z.refresh)}seedFallbackQuota(Z,$){if(!this.quotaManager)return;if(!Z.quota)return;let X=Math.max(Z.quota.primary?.checkedAt??0,Z.quota.secondary?.checkedAt??0);if(X<=0)return;let J=this.quotaManager.getFallback(Z.id,Z.access);if(J&&J.checkedAt>=X)return;this.quotaManager.setFallback(Z.id,{quota:Z.quota,refreshAfter:X+SJ($),checkedAt:X},Z.access,!1,Z.accountId)}async load(){return K3(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(Z,$){await U$(Z,this.paths,{accounts:$??!0},this.options.canWrite)}startBackgroundRefresh(){let Z=async()=>{if(await this.options.backgroundRefreshPaused?.())return;if(await this.refreshDueAccounts(),this.options.fetchQuotaFn)await this.refreshQuotaForDueAccounts()};if(Z().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{Z().catch(()=>{})},AJ+T4(RJ)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(Z){let $=Z!==void 0?Z:await this.load();if(!$)return[];let X=[],J=!1;for(let z of $.accounts){if(z.enabled===!1||!NZ(z))continue;if(W1($,z))continue;if(QZ(z))continue;let G=!1,B=z;try{if(Q1(B,$,this.now())){let Q=B.lastRefreshError;if(Q&&yZ(Q,B.refresh,this.now()))throw G=!0,Error(S1(Q,this.now()));try{B=await this.refreshAccount(B,$),J=!0}catch(W){if(eX(W))continue;G=!0;let Y=$.accounts.find((U)=>U.id===z.id&&NZ(U));if(Y&&!yZ(Y.lastRefreshError,Y.refresh,this.now()))Q$(Y,W,this.now()),XZ($,Y),J=!0;throw W}}if(this.seedFallbackQuota(B,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(B),$))X.push(B)}catch(Q){let W=LJ(B,this.now());if(G){if(!W)continue}else if(!W)continue;if(TJ(B,$,Q,this.now()))B1.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:B.id,error:j3(Q)}),X.push(B);else if(!D3($))X.push(B)}}if(J){let z=structuredClone($);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(z)).catch((G)=>{M6.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:j3(G)})})}return X}async markUsed(Z){try{let $=await this.load();if(!$)return;let X=$.accounts.find((J)=>J.id===Z.id);if(!X)return;X.lastUsed=this.now(),await this.save($,[X.id])}catch($){M6.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:j3($)})}}accountPassesQuotaPolicy(Z,$){return O4(Z.quota,$,this.now())}quotaPolicyAccount(Z){if(!this.quotaManager)return Z;let $=this.quotaManager.getFallback(Z.id,Z.access)?.quota;return $?{...Z,quota:$}:Z}async refreshDueAccounts(){let Z=await this.load();if(!Z||!MJ(Z))return;let $=!1;for(let X of Z.accounts){if(X.enabled===!1||!NZ(X))continue;if(W1(Z,X))continue;if(QZ(X))continue;if(!Q1(X,Z,this.now()))continue;if(yZ(X.lastRefreshError,X.refresh,this.now()))continue;try{B1.debug("fallback oauth background due",{pid:process.pid,accountId:X.id,expiresInMs:X.expires?X.expires-this.now():void 0}),await this.refreshAccount(X,Z),$=!0}catch(J){B1.warn("fallback oauth background failed",{pid:process.pid,accountId:X.id,error:j3(J)}),Q$(X,J,this.now()),XZ(Z,X),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!B$(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let X of Z.accounts){if(X.enabled===!1||!NZ(X))continue;if(W1(Z,X))continue;if(QZ(X))continue;let J=X;try{if(Q1(J,Z,this.now())){if(yZ(J.lastRefreshError,J.refresh,this.now()))continue;J=await this.refreshAccount(J,Z),$=!0}if(A1(J.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(J,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(J.id,J.access):q4(J,Z,this.now())))continue;await this.refreshAccountQuota(J,Z),$=!0}catch(z){z$(X,z,this.now()),XZ(Z,X),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),X=[];if(!$||!B$($))return{storage:$,errors:X};if(!this.options.fetchQuotaFn)return{storage:$,errors:X};let J=Z.force??!1,z=!1;for(let G of $.accounts){if(G.enabled===!1||!NZ(G))continue;if(W1($,G))continue;if(QZ(G))continue;let B=G;try{if(Q1(B,$,this.now())){let Q=B.lastRefreshError;if(Q&&yZ(Q,B.refresh,this.now()))throw Error(S1(Q,this.now()));B=await this.refreshAccount(B,$),z=!0}if(!J&&!q4(B,$,this.now())){if(B.lastQuotaRefreshError)B.lastQuotaRefreshError=void 0,XZ($,B),z=!0;continue}await this.refreshAccountQuota(B,$),z=!0}catch(Q){z$(G,Q,this.now()),XZ($,G),z=!0,X.push({accountId:G.id,message:j3(Q)})}}if(z)await this.save($);return{storage:$,errors:X}}async refreshAccount(Z,$,X={}){let J=this.refreshPromises.get(Z.id);if(J){let B=await J;return XZ($,B),B}let z=this.refreshAccountNow(Z,$,X).finally(()=>{this.refreshPromises.delete(Z.id)});this.refreshPromises.set(Z.id,z);let G=await z;return XZ($,G),G}async waitForConcurrentFallbackRefresh(Z,$,X,J){let z=Date.now()+EJ;while(Date.now()<z){await new Promise((Y)=>setTimeout(Y,bJ));let G=await this.load(),B=G?.accounts.find((Y)=>Y.id===Z.id&&NZ(Y));if(!B)continue;if(this.assertNotTombstoned(B),(B.access!==X.access||B.refresh!==X.refresh||(B.expires??0)>(X.expires??0)+60000)&&(J.force||!Q1(B,G,this.now())))return XZ($,B),B1.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:B.id,expiresInMs:B.expires?B.expires-this.now():void 0}),B;let W=B.lastRefreshError;if(W&&yZ(W,B.refresh,this.now()))throw XZ($,B),Error(S1(W,this.now()))}return null}assertNotShieldedMainRow(Z,$,X){if(X.asPoolMain||!$)return;if(W1(Z,$))throw new S4($.id)}async refreshAccountNow(Z,$,X){let J=await this.load(),z=J?.accounts.find((Q)=>Q.id===Z.id&&NZ(Q));if(this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!Q1(z,J,this.now()))return XZ($,z),z;let G=z??Z,B=await w({name:j$(G.id),ttlMs:V$,path:this.paths.configPath,now:this.now,renew:!0});if(!B){B1.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let Q=await this.waitForConcurrentFallbackRefresh(Z,$,G,X);if(Q)return Q;throw Error("Fallback OAuth refresh is already in progress")}try{if(J=await this.load(),z=J?.accounts.find((U)=>U.id===Z.id&&NZ(U)),this.assertNotTombstoned(z),this.assertNotShieldedMainRow(J,z,X),z&&!X.force&&!Q1(z,J,this.now()))return XZ($,z),z;if(!z)throw new P6(Z.id);G=z;let Q=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});B1.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:X.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let W=await Q({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=W.access,G.refresh=W.refresh,G.expires=W.expires,G.lastRefreshedAt=W.expires-W.expiresIn*1000,G.lastRefreshError=void 0,XZ($,G),await this.save($),!(await this.load())?.accounts.some((U)=>U.id===Z.id))throw new P6(Z.id);return B1.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await B.release()}}async refreshAccountQuota(Z,$){let X=Z;if(this.assertNotTombstoned(X),!X.access)throw Error(`Fallback account ${Z.id} has no access token`);if(!this.options.fetchQuotaFn)throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled");let J=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),z=(G)=>this.quotaManager?this.quotaManager.refreshFallback(X.id,G):J({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!X.access)throw Error(`Fallback account ${Z.id} has no access token`);let G=await z(X.access);X.quota=G,X.lastQuotaRefreshError=void 0,XZ($,X),await this.save($)}catch(G){throw z$(Z,G,this.now()),XZ($,Z),G}}}function u(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}var b4=["primary","secondary"];function q$(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function F3(Z){return typeof Z==="number"&&Number.isFinite(Z)}function yJ(Z,$){if(!q$($))return;let X=$.usedPercent;if(!F3(X)||X<0||X>100)return;return{label:Z,usedPercent:X,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...F3($.windowMinutes)&&$.windowMinutes>0?{windowMinutes:$.windowMinutes}:{}}}function kJ(Z){let $=Z.spendControl;if(q$($)&&typeof $.reached==="boolean"){let X=(J)=>F3($[J])?{[J]:$[J]}:{};return{kind:"reading",reached:$.reached,...X("remainingPercent"),...X("usedPercent"),...X("limit"),...X("used"),...X("remaining"),...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...typeof $.unit==="string"?{unit:$.unit}:{}}}if(Z.spendControlCleared===!0)return{kind:"cleared"};return}function _6(Z,$,X){if(!q$(Z)||!F3($))return;let J=[],z=[];for(let W of b4){let Y=yJ(W,Z[W]);if(Y)J.push(Y);else if(X)z.push({label:W})}let G=kJ(Z),B=Z.resetCreditsAvailable,Q=typeof B==="number"&&Number.isSafeInteger(B)&&B>=0?{resetCredits:{value:B,checkedAt:$}}:void 0;if(J.length===0&&z.length===0&&!G&&!Q)return;return{checkedAt:$,...J.length>0?{readings:J}:{},...z.length>0?{coverage:z}:{},...G?{budget:G}:{},...Q?{counters:Q}:{}}}function MH(Z){if(!wZ(Z))return;let $=c(Z),X={};for(let J of b4){let z=$.limits.find((B)=>B.label===J&&B.kind==="reading");if(!z||!F3(z.usedPercent))continue;let G={usedPercent:z.usedPercent,remainingPercent:100-z.usedPercent,checkedAt:z.checkedAt,...z.resetsAt!==void 0?{resetsAt:z.resetsAt}:{},...z.windowMinutes!==void 0?{windowMinutes:z.windowMinutes}:{}};X[J]=G}return X.primary||X.secondary?X:void 0}import{statSync as xJ}from"node:fs";import{rm as f4}from"node:fs/promises";import{dirname as hJ,join as x4}from"node:path";import{resolveClaustrumConnectionPath as vJ}from"@cortexkit/claustrum-client";function I4(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 y4(Z){if(!u(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 fJ(Z){let $=y4(Z.total),X=y4(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},...u(Z.total)&&typeof Z.total.unit==="string"&&{unit:Z.total.unit}}}function k4(Z,$){let X=I4(Z.usage?.primary,$.fetchedAt);if(!X||!Number.isFinite($.fetchedAt))return;let J=I4(Z.usage?.secondary,$.fetchedAt),z=Array.isArray(Z.spend)?Z.spend.find((Q)=>u(Q)&&Q.id==="individual_limit"):void 0,G=u(z)?fJ(z):void 0,B=u(Z.savedResets)?Z.savedResets.availableCount:void 0;return{primary:X,...J&&{secondary:J},...typeof B==="number"&&Number.isFinite(B)&&B>=0&&{resetCreditsAvailable:B},...G&&{spendControl:G},...!z&&{spendControlCleared:!0}}}var fZ=v("vault"),gJ="openai-auth",h4={refreshAdapter:"openai",category:"openai-native",apiKeys:!1},mJ={opencode:"OpenCode",pi:"Pi"};function wJ(Z){return x8(gJ,Z)}function hH(Z){return x4(hJ(Z),"openai-auth-vault")}function pJ(Z,$){return{...v8({stateDir:Z,host:$}),rosterPath:x4(Z,`${$}-roster.json`)}}var v4=2000,vH={"vault-unreachable":"Request refused locally: this host is connected to the credential vault, which could not be reached, and local accounts are not used while it is connected. Start the vault and connect accounts in it, or disconnect this host from the vault.","vault-empty":"Request refused locally: this host is connected to the credential vault, which serves it no usable OpenAI account, and local accounts are not used while it is connected. Connect accounts in the vault, or disconnect this host from the vault.","vault-refused":"Request refused locally: the credential vault did not authorize an account, and local accounts are not used while this host is connected to it. Check the accounts in the vault, or disconnect this host from the vault."};function gH(Z){return Z.snapshot()===void 0?"vault-unreachable":"vault-empty"}function lJ(Z){let $=R1(Z);return $?E1($):void 0}class uJ{host;name;paths;#Z;#$;#B=new Map;#z=new Map;#G;#Q;#X;#W=!1;#U=!1;#Y=Promise.withResolvers();#J;#H="unknown";#V;constructor(Z){this.#Z=Z,this.host=Z.host,this.name=wJ(Z.host),this.paths=pJ(Z.stateDir,Z.host),this.#$=new D6({rosterPath:this.paths.rosterPath,tokenPath:this.paths.tokenPath,family:h4,connect:()=>this.#N(),isCustodyActive:()=>this.enrolled(),...Z.reservedRouteIds?{reservedRouteIds:Z.reservedRouteIds}:{},parseIdentity:lJ,insula:{provider:"codex",normalize:k4},...Z.now?{now:Z.now}:{},onRoster:()=>{this.#G=void 0},onError:($)=>this.#j("vault roster refresh failed",$),logger:fZ})}#q(){return(this.#Z.connectionFile??vJ)()}#D(){return{connectionFile:this.#q(),projectRoot:this.#Z.projectRoot??process.cwd(),storagePath:this.paths.tokenPath,logger:(Z)=>fZ.debug("vault transport error",{errorClass:Z})}}#N(){return this.#Z.connectScoped?.()??$4(this.#D())}#M(){return this.#Z.connectEnrollment?.()??h8(this.#D())}#j(Z,$){this.#G=WZ($),fZ.warn(Z,{host:this.host,error:this.#G})}#K(){return[this.paths.tokenPath,this.paths.statePath].map((Z)=>{try{let $=xJ(Z);return`${$.ino}:${$.size}:${$.mtimeMs}:${$.ctimeMs}`}catch{return"?"}}).join("|")}async authority(){let Z=this.#K(),$=await m8(this.paths,this.name);if(Z===this.#K())return this.#H=$,this.#V=Z,$;return"unreadable"}enrolled(){return this.#V!==this.#K()||this.#H!=="local"}start(){if(this.#W||this.#U)return;this.#W=!0;let Z=async()=>{try{await this.authority(),await this.#F(),await this.#$.refreshInsulaQuota()}catch(X){if(!this.#U)this.#j("vault roster refresh failed",X)}if(this.#U)return;let $=this.#Z.pollIntervalMs??5000;if($<=0)return;this.#J=setTimeout(()=>{this.#J=void 0,Z()},$),this.#J.unref?.()};Z()}#F(){return this.#X??=this.#$.refresh().finally(()=>{this.#X=void 0,this.#Y.resolve()}),this.#X}firstRoster(){return this.#Y.promise}async awaitRequestRoster(){if(this.snapshot())return;if(await this.authority()!=="vault")return;let Z=this.#X;if(Z)await Z.catch(()=>{return});if(this.snapshot()||await this.authority()!=="vault")return;await(this.#X??this.#F()).catch((X)=>{this.#j("vault roster refresh failed",X)})}async refresh(){try{await this.authority();let Z=this.#X;if(Z)await Z.catch(()=>{return});let $=await this.#F();return this.#G=void 0,$}catch(Z){return this.#j("vault roster refresh failed",Z),this.#$.snapshot()}}snapshot(){return this.#$.snapshot()}serves(){return this.enrolled()&&(this.snapshot()?.rows.length??0)>0}identities(){if(!this.enrolled())return new Set;return new Set((this.snapshot()?.rows??[]).flatMap((Z)=>Z.accountIdentity!==void 0?[Z.accountIdentity]:[]))}routes(){if(!this.enrolled())return[];let Z=new Map((this.snapshot()?.rows??[]).map(($)=>[$.routeId,$]));return this.#$.routingRows().map(($)=>{let X=Z.get($.id)?.accountIdentity;return{id:$.id,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.#$.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.#$.authorize(Z,$.signal)}catch(X){this.#j("vault refused to serve an account",X);return}}async reportFailure(Z,$){if($!==401)return;try{await this.#$.reportFailure(Z,401,"direct")}catch(X){this.#j("vault failure report failed",X)}await this.refresh()}recordSnapshot(Z,$,X,J){let z=_6($,(this.#Z.now??Date.now)(),X);if(!z)return Promise.resolve();return this.#$.recordQuota(Z,z,J).then(()=>{},(G)=>this.#j("vault quota write failed",G))}pollQuota(Z,$=!0){let X=this.#z.get(Z);if(X)return X;let J=this.#P(Z,$).finally(()=>{this.#z.delete(Z)});return this.#z.set(Z,J),J}async#P(Z,$){if($){await this.authority(),await this.#$.refreshInsulaQuota();let G=(await BZ(this.paths.rosterPath))?.rows.find((Q)=>Q.routeId===Z),B=await this.#$.cachedInsulaQuotaForRoute(Z);if(B!==void 0&&G?.accountIdentity){let Q=_6(B,B.primary.checkedAt,!0);if(!Q)return{ok:!1,error:"unusable insula reading"};return await this.#$.recordAccountQuota(Z,G.accountIdentity,Q)?{ok:!0}:{ok:!1,error:"vault account changed"}}}let X,J=this.#Z.fetchImpl?.()??globalThis.fetch,z=await this.send(Z,async(G,B)=>{try{let Q=$?void 0:await this.#$.cachedInsulaQuota(B);if(Q!==void 0){let Y=_6(Q,Q.primary.checkedAt,!0);if(!Y)throw Error("unusable insula reading");return await this.#$.recordQuota(Z,Y,B),new Response(null,{status:200})}let W=await H3({accessToken:G,fetchImpl:J,now:this.#Z.now??Date.now,...B.accountIdentity?{accountId:B.accountIdentity}:{},accountKey:Z,logger:fZ});return await this.recordSnapshot(Z,W,!0,B),X=void 0,new Response(null,{status:200})}catch(Q){X=WZ(Q);let W=Q?.status;if(typeof W==="number")return new Response(null,{status:W});throw Q}},{site:"quota"}).catch((G)=>{X=WZ(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)=>{fZ.warn("vault quota poll failed",{routeId:Z,error:WZ(J)})}).finally(()=>{this.#B.delete(Z)});return this.#B.set(Z,X),X}async pollStale(Z){let $=(this.#Z.now??Date.now)(),X=[];for(let J of this.routes()){let z=dJ(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.#$.decline(Z),fZ.info("vault account declined",{routeId:Z})}async accept(Z){await this.#$.accept(Z),fZ.info("vault account accepted",{routeId:Z})}async status(){await this.authority();let Z;try{Z=await G3(this.paths,this.name)}catch($){this.#j("vault enrollment state unreadable",$),Z={state:"blocked",proposedName:this.name,code:$ instanceof T?$.kind:"unreadable-state"}}return{host:this.host,name:this.name,enrollment:Z,accounts:this.enrolled()?this.snapshot()?.rows??[]:[],...this.#G?{lastError:this.#G}:{}}}async connectStep(){let Z=await this.#M().catch(($)=>{throw new GZ("vault-unreachable",`Could not reach the Claustrum vault (${this.#q()}): ${WZ($)}. Is the vault running?`)});try{let $=new U6({client:Z,paths:this.paths,proposedName:this.name,...this.#Z.now?{now:this.#Z.now}:{}}),X=await $.status();if(X.state==="denied"||X.state==="blocked")await $.resetTerminal();let J=await $.reconcile();if(fZ.info("vault enrollment step",{host:this.host,state:J.state}),J.state==="approved")this.#G=void 0,await this.refresh();return J}finally{Z.close()}}waitForApproval(Z={}){return this.#Q??=(async()=>{let $=Z.sleep??((G)=>new Promise((B)=>setTimeout(B,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.#Q=void 0}),this.#Q}async disconnect(){await f4(this.paths.tokenPath,{force:!0}),await f4(this.paths.statePath,{force:!0}),await this.authority(),this.#G=void 0,fZ.info("vault enrollment forgotten",{host:this.host})}assertHostSlot(Z){if(this.serves())p8({mode:"custody",auth:Z,provider:"openai"})}close(){if(this.#U=!0,this.#Y.resolve(),this.#J)clearTimeout(this.#J);this.#J=void 0,this.#$.close()}}function dJ(Z){if(!Z)return;let $=c(Z).limits.map((X)=>X.checkedAt);return $.length>0?Math.max(...$):void 0}function O6(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 ${h4.category} --operation read`]}function g4(Z,$,X){let J=`${mJ[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 D$(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?" (grant it the openai-native category with `ck auth grant` to add some)":""}.`}}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:[...O6(Z.name,$),"Still waiting. The request stays open: run Connect again after approving it."].join(`
90
+ `)};default:return{ok:!1,text:`Enrollment is ${$.state}.`}}}var K$="/backend-api/wham/rate-limit-reset-credits",cJ=`https://chatgpt.com${K$}`,d4=`${K$}/consume`,sJ=`https://chatgpt.com${d4}`,iJ=300000,aJ=60000,nJ=15000,rJ=60000;function f1(Z){return{configPath:Z.configPath,statePath:Z.statePath}}class YZ extends Error{kind;cooldownUntil;constructor(Z,$,X){super($);this.name="ResetRedemptionError",this.kind=Z,this.cooldownUntil=X}}class H1 extends Error{kind;status;constructor(Z,$,X){super($);this.name="ResetCreditError",this.kind=Z,this.status=X}}function c4(Z,$,X){return{authorization:`Bearer ${Z}`,...X?{"chatgpt-account-id":X}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":$}}function T6(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function s4(Z){if(!Z)return;return{...Z.inFlight?{inFlight:{...Z.inFlight}}:{},...Z.lastOutcome?{lastOutcome:{...Z.lastOutcome}}:{},...Z.cooldownUntil!==void 0?{cooldownUntil:Z.cooldownUntil}:{}}}function S6(Z){if(!T6(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}:{},...i4(Z.rejectedStatus)?{rejectedStatus:Z.rejectedStatus}:{},...typeof Z.unknownAnswers==="number"&&Number.isSafeInteger(Z.unknownAnswers)&&Z.unknownAnswers>0?{unknownAnswers:Z.unknownAnswers}:{}}}function i4(Z){return typeof Z==="number"&&Z>=400&&Z<500&&Z!==408&&Z!==409&&Z!==425&&Z!==429}function C6(Z){return Z.kind==="http_error"&&i4(Z.status)}function a4(Z,$){return Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$||Z.rejectedStatus!==void 0}function oJ(Z,$){if(Z.chatgptAccountId!==void 0&&Z.chatgptAccountId!==$)throw new YZ("pair_identity_mismatch","the saved reset redemption was started under a different ChatGPT account")}function n4(Z){return Boolean(Z&&Object.hasOwn(Z,"inFlight"))}function r4(Z,$){return $-Z.startedAt<iJ}function x1(Z,$){if(!OZ($))return;return Z.reset?.[$]}function o4(Z){if(!Z.reset)Z.reset=Object.create(null);return Z.reset}function t4(Z,$,X){if(!OZ($))return;let J=o4(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 e4(Z,$){let X=s4(Z),J=S6(Z?.inFlight);if(n4(Z)&&!J)return{kind:"corrupt",beforeState:X};if(Z?.cooldownUntil!==void 0&&Z.cooldownUntil>$)return{kind:"cooldown",beforeState:X,cooldownUntil:Z.cooldownUntil};if(J&&r4(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 tJ(Z,$){if(!OZ($))return{kind:"fresh",beforeState:void 0};let X=await Z.loadAccountsFn(f1(Z));return e4(X?x1(X,$):void 0,Z.now())}async function eJ(Z,$){let X;if(await Z.mutateAccountsFn((J)=>{let z=Z.now(),G=x1(J,$);if(X=e4(G,z),X.kind==="corrupt")t4(J,$,z);return J},f1(Z)),!X)throw Error("corrupt reset state mutation did not run");return X}async function Zz(Z,$,X,J){if(!OZ($))return{kind:"fresh",beforeState:void 0};let z;if(await Z.mutateAccountsFn((G)=>{let B=Z.now(),Q=x1(G,$),W=s4(Q),Y=S6(Q?.inFlight);if(n4(Q)&&!Y)return t4(G,$,B),z={kind:"corrupt",beforeState:W},G;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>B)return z={kind:"cooldown",beforeState:W,cooldownUntil:Q.cooldownUntil},G;if(Y&&r4(Y,B))return z={kind:"claim",beforeState:W,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;if(Y&&!a4(Y,J))return z={kind:"expired_unreconciled",beforeState:W,claim:{inFlight:Y,selectedCredit:{id:Y.creditId}}},G;let U=A6(X);if(!U)return z={kind:"fresh",beforeState:W},G;let V={redeemRequestId:Z.randomUUID(),creditId:U.id,startedAt:B,...J===void 0?{}:{chatgptAccountId:J}},j=o4(G);return j[$]={...Q,inFlight:V},z={kind:"claim",beforeState:W,claim:{inFlight:V,selectedCredit:U}},G},f1(Z)),!z)throw Error("reset claim mutation did not run");return z}async function $z(Z,$,X,J,z){if(!OZ($))return;if(!M$(J.kind))return Xz(Z,$,X,J,z);await Z.mutateAccountsFn((G)=>{let B=x1(G,$),Q=S6(B?.inFlight);if(!B||!Q||Q.redeemRequestId!==X.redeemRequestId||Q.creditId!==X.creditId)return G;let W=Z.now();if(delete B.inFlight,B.lastOutcome={code:J.kind,at:W},J.kind==="reset"||J.kind==="already_redeemed")B.cooldownUntil=W+rJ;else delete B.cooldownUntil;return G},f1(Z));return}function m4(Z,$){let X=S6(Z?.inFlight);return X&&X.redeemRequestId===$.redeemRequestId&&X.creditId===$.creditId?X:void 0}async function Xz(Z,$,X,J,z){let G=C6(J)?J.status:void 0;if(!(X.chatgptAccountId===void 0&&z!==void 0)&&G!==void 0&&G===X.rejectedStatus){let W=await Z.loadAccountsFn(f1(Z));return m4(W?x1(W,$):void 0,X)}let Q;return await Z.mutateAccountsFn((W)=>{Q=void 0;let Y=x1(W,$),U=m4(Y,X);if(!Y||!U)return W;let V={...U};if(V.chatgptAccountId===void 0&&z!==void 0)V.chatgptAccountId=z;if(G===void 0)delete V.rejectedStatus,V.unknownAnswers=(U.unknownAnswers??0)+1;else if((U.unknownAnswers??0)===(X.unknownAnswers??0))V.rejectedStatus=G;return Y.inFlight=V,Q=V,W},f1(Z)),Q}function N3(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 F$(Z,$,X){if(!($||N3(Z.primary,X)||N3(Z.secondary,X)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function w4(Z,$){let X=Z[$];if(X===void 0||X===null)return;return typeof X==="string"?X:null}function Jz(Z){if(!T6(Z))return;let $=w4(Z,"granted_at"),X=w4(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 N$(Z,$,X){let J;try{J=await Z(cJ,{method:"GET",headers:c4($,K$,X),signal:AbortSignal.timeout(nJ)})}catch{throw new H1("http_error","reset credit list request failed")}if(!J.ok)throw new H1("http_error",`reset credit list request failed: ${J.status}`,J.status);let z;try{z=await J.json()}catch{throw new H1("invalid_response","reset credit list response was not valid JSON",J.status)}if(!T6(z))throw new H1("invalid_response","reset credit list response was not an object",J.status);return{credits:(Array.isArray(z.credits)?z.credits:[]).flatMap((B)=>{let Q=Jz(B);return Q===void 0?[]:[Q]}),availableCount:typeof z.available_count==="number"&&Number.isFinite(z.available_count)?z.available_count:void 0}}function A6(Z){return[...Z].filter(Z7).sort(($,X)=>Date.parse($.expiresAt)-Date.parse(X.expiresAt))[0]}function Z7(Z){return Z.status==="available"&&Z.isSupportedByPlan&&Z.resetType==="codex_rate_limits"}function $7(Z){return Z.filter(Z7).length}function M$(Z){return Z==="reset"||Z==="already_redeemed"||Z==="nothing_to_reset"||Z==="no_credit"}async function zz(Z,$,X,J,z){let G;try{G=await Z(sJ,{method:"POST",headers:{...c4($,d4,X),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:z,credit_id:J}),signal:AbortSignal.timeout(aJ)})}catch(Y){return{kind:"ambiguous",raw:Y}}let B;try{B=await G.text()}catch(Y){return G.ok?{kind:"ambiguous",raw:Y}:{kind:"http_error",raw:Y,status:G.status}}let Q=B,W=!1;try{Q=JSON.parse(B),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Q,status:G.status};if(!W||!T6(Q)||!M$(Q.code))return{kind:"ambiguous",raw:Q};return{kind:Q.code,raw:Q}}function p4(Z){if(Z.kind==="cooldown")throw new YZ("cooldown_active","reset credit redemption is cooling down",Z.cooldownUntil);throw Error(`unexpected reset state decision: ${Z.kind}`)}function l4(){throw new YZ("expired_unreconciled","the previous reset attempt outcome is unknown")}function u4(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 Gz(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(C6(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 Bz(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 X7(Z,$){if(!OZ($.accountKey))throw new YZ("invalid_account_key","the reset account key is reserved");let X=await Z.resolveTarget($.accountKey);if(X.chatgptAccountId!==$.expectedChatgptAccountId)throw new YZ("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let J=X.chatgptAccountId,z=X.accountKey==="main"?void 0:J,G=await tJ(Z,$.accountKey);if(G.kind==="corrupt"){if(G=await eJ(Z,$.accountKey),G.kind==="corrupt")return u4(X,G.beforeState)}if(G.kind==="cooldown")p4(G);let B;if(G.kind==="claim")B=G.claim;else if(G.kind==="expired_unreconciled"&&($.retry||!a4(G.claim.inFlight,J))){if(!$.retry)l4();B=G.claim}else{if($.retry)throw new YZ("retry_without_inflight","there is no active reset credit redemption to retry");let[j,D]=await Promise.all([Z.fetchUsage(X),N$(Z.fetchImpl,X.accessToken,z)]),H=F$(j,Z.hasActiveRateLimitMark($.accountKey),Z.now());if(!H.ok)throw new YZ("not_exhausted",H.reason);if(!A6(D.credits))throw new YZ("no_eligible_credit","no eligible reset credit was returned");let q=await Zz(Z,$.accountKey,D.credits,J);if(q.kind==="corrupt")return u4(X,q.beforeState);if(q.kind==="cooldown")p4(q);if(q.kind==="expired_unreconciled")l4();if(q.kind!=="claim")throw new YZ("no_eligible_credit","no eligible reset credit was available while claiming");B=q.claim}oJ(B.inFlight,J);let Q=await zz(Z.fetchImpl,X.accessToken,z,B.inFlight.creditId,B.inFlight.redeemRequestId),W,Y=!1;try{W=await $z(Z,$.accountKey,B.inFlight,Q,J)}catch{Y=!0}let U=Y&&M$(Q.kind),V=C6(Q)&&!Y&&W?.rejectedStatus!==void 0;return{target:X,selectedCredit:B.selectedCredit,beforeState:G.beforeState,outcome:Q,retrySafety:U?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":C6(Q)&&!V?Bz(Y,W):Gz(Q),...V?{refused:!0}:{},...U?{finalizeStateWriteFailed:!0}:{}}}async function J7(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 z7(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 G7(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 P$(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 J7(Z.checks);for(let B of z7($,J))X.print(B);let z=J.findings.filter((B)=>B.repair);if(z.length===0){if(J.findings.length>0)X.print("No repairs are available.");return}let G=await G7(X,J);X.print(`Applied ${G.applied.length} of ${z.length} repair(s).`)}}}import{execFileSync as Qz,spawn as Wz}from"node:child_process";function Q7(Z,$=process.platform,X=Qz,J=Wz){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 B7(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 R6(Z,$){let X=new AbortController,J=await Z.begin({headless:!1,signal:X.signal});J.completion.catch(()=>{}),B7($,J);let z=!1;try{z=await(Z.openBrowser??Q7)(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}),B7($,J);return J.completion}var R={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 L$(Z){let $=Z.toString(),X=[];for(let J=0;J<$.length;){let z=$[J];if(z==="\x1B"){let G=$.slice(J,J+3),B=G[1]==="["||G[1]==="O"?G[2]:void 0;if(B&&"ABCD".includes(B)){let W={A:"up",B:"down",C:"right",D:"left"}[B];if(W)X.push(W);J+=3}else if(J+1===$.length){if(J===0)X.push("escape-start");J+=1}else if(($[J+1]==="["||$[J+1]==="O")&&J+2>=$.length)break;else J+=1;continue}if(z==="\r"||z===`
91
+ `)X.push("enter");else if(z==="\x03")X.push("escape");else if(z&&z>=" ")X.push("char");J+=1}return X}var W7=`${String.fromCharCode(27)}\\[[0-9;]*m`,Yz=new RegExp(W7,"g"),Hz=new RegExp(`^${W7}`);function Y7(Z){return Z.replace(Yz,"")}function U1(Z,$){if($<=0)return"";if(Y7(Z).length<=$)return Z;let X=$>=3?"...":".".repeat($),J=Math.max(0,$-X.length),z="",G=0,B=0;while(G<Z.length&&B<J){if(Z[G]==="\x1B"){let Q=Z.slice(G).match(Hz);if(Q){z+=Q[0],G+=Q[0].length;continue}}z+=Z[G],G+=1,B+=1}return z.includes("\x1B[")?`${z}${R.reset}${X}`:z+X}function _$(){return{input:process.stdin,output:process.stdout,signals:process}}function V1(Z){return Z.input.isTTY===!0}function O$(Z,$=""){Z.output.write(`${$}
92
+ `)}var Uz=50;function Vz(Z){if(Z==="red")return R.red;if(Z==="cyan")return R.cyan;return""}async function h1(Z,$,X){if(!V1(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,B=0,Q=null,W=!1,Y=0,U=()=>{let V=z.columns??80,j=z.rows??24,D=Y;if(X.clearScreen)z.write(R.clearScreen+R.moveTo(1,1));else if(D>0)z.write(R.up(D));let H=0,q=(P)=>{z.write(`${R.clearLine}${P}
93
+ `),H+=1},N=X.lines??[],M=1+(X.subtitle?3:0)+N.length+(N.length?1:0),O=Math.max(1,Math.min($.length,j-M-2-1)),S=Math.max(0,Math.min(B-Math.floor(O/2),Math.max(0,$.length-O))),F=$.slice(S,S+O);if(q(`${R.dim}┌ ${R.reset}${U1(X.message,Math.max(1,V-4))}`),X.subtitle)q(`${R.dim}│${R.reset}`),q(`${R.cyan}◆${R.reset} ${U1(X.subtitle,Math.max(1,V-4))}`),q("");for(let P of N)q(`${R.cyan}│${R.reset} ${U1(P,Math.max(1,V-4))}`);if(N.length)q(`${R.cyan}│${R.reset}`);for(let P=0;P<F.length;P++){let C=F[P];if(!C)continue;let k=S+P===B,t=Vz(C.color),e=t?`${k?"":R.dim}${t}${C.label}${R.reset}`:k?C.label:`${R.dim}${C.label}${R.reset}`;if(C.hint)e+=` ${R.dim}${C.hint}${R.reset}`;e=U1(e,Math.max(1,V-8)),q(k?`${R.cyan}│${R.reset} ${R.green}●${R.reset} ${e}`:`${R.cyan}│${R.reset} ${R.dim}○${R.reset} ${e}`)}let K=F.length<$.length?` (${S+1}-${S+F.length}/${$.length})`:"";q(`${R.cyan}│${R.reset} ${R.dim}${U1(`Up/Down to select | Enter: confirm | Esc: back${K}`,Math.max(1,V-6))}${R.reset}`),q(`${R.cyan}└${R.reset}`);for(let P=H;P<D;P++)q("");Y=H};return new Promise((V)=>{let j=J.isRaw??!1,D=()=>{if(W)return;if(W=!0,Q)clearTimeout(Q);J.removeListener("data",N);try{J.setRawMode(j),J.pause(),z.write(R.show)}catch{}G?.removeListener("SIGINT",q),G?.removeListener("SIGTERM",q)},H=(M)=>{D(),V(M)},q=()=>H(null),N=(M)=>{for(let O of L$(M)){if(W)break;if(Q)clearTimeout(Q),Q=null;switch(O){case"up":B=(B-1+$.length)%$.length,U();break;case"down":B=(B+1)%$.length,U();break;case"enter":H($[B]?.value??null);break;case"escape":H(null);break;case"escape-start":Q=setTimeout(()=>H(null),Uz);break;default:break}}};G?.once("SIGINT",q),G?.once("SIGTERM",q);try{J.setRawMode(!0)}catch{D(),V(null);return}J.resume(),z.write(R.hide),U(),J.on("data",N)})}async function C$(Z,$,X=!1){if(!V1(Z))return!1;return await h1(Z,X?[{label:"Yes",value:!0},{label:"No",value:!1}]:[{label:"No",value:!1},{label:"Yes",value:!0}],{message:$})??!1}function H7(Z){let $=V1(Z);return{terminal:Z,interactive:$,print:(X)=>O$(Z,X),confirm:(X,J)=>C$(Z,X,J),select:async(X,J)=>$&&X.length>0?h1(Z,X,J):null}}function jz(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 M3(Z){let $=Z.terminal??_$(),X=H7($);if(!X.interactive)return jz(X,Z);if(Z.actions.length===0)return X.print("No actions are available."),{status:"cancelled"};let J=await h1($,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 V7="disabled from the auth menu",U7=8;async function CZ(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 qz(Z){let{rows:$}=await CZ(Z);return $.some((X)=>X.credential!==void 0)}function A$(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 Dz(Z){if(Z.problem)return[Z.problem];if(Z.rows.length===0)return["No accounts yet."];let $=Z.rows.slice(0,U7).map((J)=>`${J.id}: ${A$(J)}`),X=Z.rows.length-U7;if(X>0)$.push(`... and ${X} more`);return $}function Kz(Z){return Z instanceof Error?Z.message:String(Z)}async function R$(Z,$,X){if($.length===0)return Z.print("There are no accounts."),null;return Z.select($.map((J)=>({label:J.id,value:J,hint:A$(J)})),{message:X})}function Fz(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 j7(Z,$=Date.now()){let X=wZ(Z.quota)?c(Z.quota):void 0,J=E6(X,{now:$,form:"full"});return(J.length>0?J:[_Z(X,{now:$})]).map((z)=>` ${z}`)}function q7(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 R6(X,$),{rows:z}=await CZ(Z.store),G=(Z.newAccountId??Fz)(J,z),B=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(B.outcome==="rotated")$.print(`That sign-in is already account ${B.id}; its credential was updated.`);else if(B.outcome==="added-disabled")$.print(`Added account ${B.id}, disabled: another enabled account is the same provider account.`);else if(B.outcome==="completed")$.print(`Finished adding account ${B.id}.`);else $.print(`Added account ${B.id}.`)}}}function D7(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 CZ(Z.store),z=await R$($,J,"Re-authenticate which account?");if(!z)return;let G=await R6(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 B=G.identity??z.identity;await Z.store.replace(z.id,G.credential,B!==void 0?{identity:B}:{},Z.extraLocks?{extraLocks:Z.extraLocks}:{}),$.print(`Updated the sign-in of account ${z.id}.`)}}}function K7(Z){return{...Z.protect?{protect:Z.protect}:{},...Z.extraLocks?{extraLocks:Z.extraLocks}:{}}}function F7(Z){return Z instanceof E&&Z.kind==="row-protected"?Z.message:void 0}function N7(Z){return{id:"remove-account",label:"Remove account",hint:"delete one account",async run($){let{rows:X}=await CZ(Z.store),J=await R$($,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,K7(Z))}catch(z){let G=F7(z);if(G===void 0)throw z;$.print(`Account ${J.id} was kept: ${G}`);return}$.print(`Removed account ${J.id}.`)}}}function T$(Z){return{id:"toggle-account",label:"Enable or disable account",hint:"stop or resume using an account",async run($){let{rows:X}=await CZ(Z.store),J=await R$($,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??V7,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 M7(Z){return{id:"list-accounts",label:"List accounts",hint:"show every account",async run($){let X=await CZ(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}: ${A$(J)}`)}}}function S$(Z){return{id:"check-quotas",label:"Check quotas",hint:"poll and show the windows of each account",async run($){let X=await CZ(Z.store);if(X.problem){$.print(X.problem);return}let J=new Map,z=Z.pollQuota;if(z)for(let B of X.rows){if(B.invalid||!B.credential||B.credentialEpoch===void 0){J.set(B.id,"no usable credential");continue}try{let Q=await z(B);await Z.store.recordQuota(B.id,{credentialEpoch:B.credentialEpoch,...B.identity!==void 0?{identity:B.identity}:{}},Q)}catch(Q){J.set(B.id,Kz(Q))}}let G=await CZ(Z.store);if(G.rows.length===0)$.print("No accounts yet.");for(let B of G.rows){$.print(`${B.id}:`);let Q=J.get(B.id);if(Q)$.print(` quota check failed: ${Q}`);for(let W of j7(B,(Z.now??Date.now)()))$.print(W)}}}}function P7(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 CZ(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,K7(Z)),J.push(G.id)}catch(B){let Q=F7(B);if(Q===void 0)throw B;z.push(`${G.id} (${Q})`)}if($.print(`Deleted ${J.length} account(s).`),z.length>0)$.print(`Kept: ${z.join(", ")}.`)}}}async function E$(Z){return L7(Z,await Z.custody?.()===!0)}function L7(Z,$){let X=Z.doctor?.length?[P$({checks:Z.doctor})]:[],J=[...Z.extraActions??[]];if($)return[M7(Z),T$(Z),S$(Z),...X,...J];return[...Z.login?[q7(Z),D7(Z)]:[],N7(Z),T$(Z),S$(Z),...X,...J,P7(Z)]}async function Nz(Z){let $=await Z.custody?.()===!0,X=L7(Z,$),[J,z]=await Promise.all([CZ(Z.store),Z.status?.()??[]]);return M3({title:Z.title,subtitle:$?"Accounts come from the vault; select an action":"Select an account action",status:[...z,...Dz(J)],actions:X,...Z.terminal?{terminal:Z.terminal}:{}})}function _7(){return{url:"",instructions:"",method:"auto",callback:async()=>({type:"failed"})}}function O7(Z){return Z!==void 0}function Mz(Z){return async($)=>{if(!O7($))return Z.login();if(!await Z.hasCredential())return Z.login($);return await Z.openMenu($),_7()}}function TZ(Z){return Z.authority!=="local"}async function HZ(Z){return{authority:await Z.authority(),status:await Z.status(),identities:Z.identities(),routes:new Set(Z.routes().map(($)=>$.id))}}async function b6(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."),v4)})])}finally{clearTimeout($)}}function SZ(Z){return Z.email||Z.label||Z.routeId}function C7(Z,$){let X=c(wZ(Z.quota)?Z.quota:void 0),J=E6(X,{now:$});return(J.length>0?J:[_Z(X,{now:$})]).map((z)=>` ${z}`)}var P3="Accounts are managed in the vault with ck. Disconnect to use local accounts.",I6="Nothing was changed: accounts are managed in the vault with ck. Disconnect to use local accounts.";function T7(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 Pz(Z,$){let X=await b6($),J=await HZ($),{status:z}=J,G=TZ(J)?void 0:await Z.store.read(),B=await E$(Z),Q=new Set(["check-quotas",...(Z.extraActions??[]).map((U)=>U.id)]),W=B.filter((U)=>!TZ(J)||Q.has(U.id)).map((U)=>({...U,run:async(V)=>{if(!Q.has(U.id)&&TZ(await HZ($))){V.print(I6);return}await $.authority(),await U.run(V)}})),Y=W.find((U)=>U.id==="check-quotas");if(Y)Y.run=async(U)=>{await b6($);let V=await HZ($),j=TZ(V)?void 0:await Z.store.read();if(!j)U.print(P3);else if(j.status!=="ready")U.print("The local account store could not be read.");else for(let q of j.rows){U.print(T7(q));try{if(Z.pollQuota&&q.credentialEpoch!==void 0){let O=await Z.pollQuota(q);await Z.store.recordQuota(q.id,{credentialEpoch:q.credentialEpoch,...q.identity!==void 0?{identity:q.identity}:{}},O)}}catch(O){U.print(` quota check failed: ${O instanceof Error?O.message:String(O)}`)}let N=await Z.store.read(),M=N.status==="ready"?N.rows.find((O)=>O.id===q.id):void 0;for(let O of C7(M??q,(Z.now??Date.now)()))U.print(O)}let D=V.routes;for(let q of $.snapshot()?.rows??[]){if(U.print(`Vault ${SZ(q)}: ${q.enabled?q.state:"declined"}`),!D.has(q.routeId)){U.print(" quota check skipped: account is not enabled and active");continue}let N=await $.pollQuota(q.routeId);if(!N.ok)U.print(` quota check failed: ${N.error??"vault unavailable"}`);let M=$.snapshot()?.rows.find((O)=>O.routeId===q.routeId);for(let O of C7({quota:M?.quota},(Z.now??Date.now)()))U.print(O)}let H=await $.status();if(H.lastError)U.print(`Claustrum vault unreachable: ${H.lastError}`)};return M3({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((U)=>`Vault ${SZ(U)}: ${U.enabled?`enabled (${U.state})`:"declined"}`),...!G?[P3]:G.status==="ready"?G.rows.map((U)=>T7(U)):["The local account store could not be read."]],actions:W,...Z.terminal?{terminal:Z.terminal}:{}})}function S7(Z){return u(Z)?{...Z}:{}}function y6(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:B})=>{let Q=await Z.apply({command:Z.command,sectionId:$,...J?{itemId:J}:{},actionId:X.id,values:G,confirmed:!0},B);return{ok:Q.ok,text:Q.text,...Q.code?{code:Q.code}:{}}}}}function b$(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 B={...G,rows:G.rows.map((Y)=>({...Y,label:Y.label??Y.id}))};if(!$)return B;let Q=await HZ($);if(!TZ(Q))return B;let W=[...Q.status.accounts.map((Y)=>({id:Y.routeId,label:SZ(Y),type:"oauth",enabled:Y.enabled,identity:Y.accountIdentity,quota:Y.quota,hasEntry:!1,needsFirstReading:!1,candidate:!1}))];return{...G,rows:W}};if(J==="readSettings")return async()=>{let G=await X.readSettings();if(G.status==="error"||!$)return G;let B=await HZ($),Q=S7(G.settings.killswitch);if(!TZ(B)||!G.settings.killswitch)return G;let W=S7(Q.accounts);for(let Y of B.status.accounts)W[Y.routeId]=Y1({version:1,accounts:[],...G.settings},Y.routeId);return{...G,settings:{...G.settings,killswitch:{...Q,accounts:W}}}};let z=Reflect.get(X,J);return typeof z==="function"?z.bind(X):z}})}function A7(Z,$){let X=tZ(Z),J=tZ({command:Z.command,title:Z.title,store:b$(Z.store,$),accounts:Z.accounts,quota:Z.quota,limits:Z.limits,routing:Z.routing,...Z.extraLocks?{extraLocks:Z.extraLocks}:{},...Z.now?{now:Z.now}:{}}),z=async(W,Y)=>{let U=await HZ($),V=TZ(U),j=V?J:X,H=(await j.open(Y)).menu.sections.find((F)=>F.id===W);if(!H)throw new GZ("unavailable","The account menu is unavailable.");if(!V)return{lines:H.lines,items:H.items.map((F)=>({...F,actions:F.actions.map((K)=>y6(j,W,K,F.id))})),actions:H.actions.map((F)=>y6(j,W,F))};let q=new Map(U.status.accounts.map((F)=>[F.routeId,F])),N=(Z.now??Date.now)(),M=(F)=>({id:"check",label:F?"Check this account":"Check now",group:"Actions",run:async()=>{let P=[...(await HZ($)).routes].filter((C)=>!F||C===F);if(F&&P.length===0)throw new GZ("unavailable","This vault account cannot be checked right now.");for(let C of P){let k=await $.pollQuota(C);if(!k.ok)throw new GZ("quota-check-failed",`${C}: ${k.error??"vault unavailable"}`)}return`Checked quota for ${P.length} account${P.length===1?"":"s"}.`}});if(W==="quota"){let F=(K,P)=>_Z(c(K.quota,Z.quota?.scope),{now:N,form:P});return{lines:U.status.accounts.filter((K)=>!U.routes.has(K.routeId)).map((K)=>`${SZ(K)} (${K.enabled?K.state:"disabled"}): ${F(K,"compact")}`),items:U.status.accounts.filter((K)=>U.routes.has(K.routeId)).map((K)=>({id:K.routeId,label:SZ(K),group:"Accounts",status:F(K,"compact"),detail:F(K,"full"),actions:[M(K.routeId)]})),actions:U.routes.size>0?[M()]:[]}}let O=H.items.map((F)=>{let K=q.get(F.id),P=K&&W==="accounts"?`Vault · ${K.credentialType==="oauth"?"login":"API key"} · ${K.state} · ${K.enabled?"enabled":"declined"}`:F.detail;return{id:F.id,label:F.label,detail:P,group:F.group,status:K&&W==="accounts"?K.enabled?K.state:"disabled":F.status,...F.facts?{facts:F.facts}:{},actions:K&&W!=="limits"?[]:F.actions.map((C)=>y6(j,W,C,F.id))}}),S=H.actions.filter((F)=>W==="limits"||W==="routing"&&F.id==="mode").map((F)=>y6(j,W,F));return{lines:W==="accounts"?[`${U.status.accounts.length} vault account${U.status.accounts.length===1?"":"s"}`,`${U.routes.size} can route`,P3]:H.lines,items:O,actions:S}},G=tZ({...Z,accounts:void 0,quota:void 0,routing:void 0,limits:void 0,replace:{accounts:{title:"Accounts",build:(W)=>z("accounts",W)},quota:{title:"Quota",build:(W)=>z("quota",W)},routing:{title:"Routing",build:(W)=>z("routing",W)},limits:{title:"Limits",build:(W)=>z("limits",W)}},extras:Z.extras?.map((W)=>W.id!=="reset"?W:{...W,build:async(Y)=>{let U=await HZ($);if(TZ(U))return{lines:[P3]};return W.build(Y)}})}),B=async()=>{if(!TZ(await HZ($)))return{menu:X,error:void 0};let W=await b6($);return{menu:G,error:W}},Q=async(W,Y)=>{let U=await W.menu.open(Y);if(W.error)U.menu.sections.find((j)=>j.id==="vault")?.lines.push(`Last error: ${W.error}`);return U};return{command:Z.command,open:async(W)=>Q(await B(),W),apply:async(W,Y)=>{let U=await B(),{menu:V}=U;if(V===G&&(W.sectionId==="accounts"||W.sectionId==="routing"&&W.actionId==="order"||W.sectionId==="reset"||W.sectionId==="quota"&&(await HZ($)).routes.size===0||W.sectionId==="limits"&&W.itemId!==void 0&&!(await HZ($)).status.accounts.some((j)=>j.routeId===W.itemId)))return{...await Q(U,Y),ok:!1,code:"vault-local-action",text:I6};return V.apply(W,Y)}}}var L3="openai",y7="OpenAI accounts",j1="main",k7="that account is already your main account, so it was not added again",VZ=v("commands"),f7=new Set(["__proto__","constructor","prototype"]);function Lz(Z,$){let X={version:1,accounts:[],killswitch:Z},J=u(Z.accounts)?Object.keys(Z.accounts):[],z={};for(let Q of new Set([j1,...$,...J])){if(f7.has(Q))continue;let W=Y1(X,Q===j1?void 0:Q);z[Q]={primary:W.primary,secondary:W.secondary}}let G=Y1(X,void 0),B={...Z};return delete B.main,B.accounts=z,B.defaults={primary:G.primary,secondary:G.secondary},B.schema=k1,B}function _z(Z,$){let X=u(Z.accounts)?{...Z.accounts}:{};for(let z of new Set([j1,...$])){if(f7.has(z)||Object.hasOwn(X,z))continue;X[z]={primary:sZ.primary,secondary:sZ.secondary}}let J=u(Z.defaults)?Z.defaults:{primary:sZ.primary,secondary:sZ.secondary};return{...Z,accounts:X,defaults:J,schema:k1}}function R7(Z,$){let X=!1;if(u(Z.cachekeep))Z.cacheKeep={...Z.cachekeep,...u(Z.cacheKeep)?Z.cacheKeep:{}},delete Z.cachekeep,X=!0;let J=Z.killswitch;if(u(J)&&J.schema!==k1)Z.killswitch=Lz(J,$),X=!0;return X}async function E7(Z){let $=await Z.read();return $.status==="ready"?$.rows.map((X)=>X.id):[]}function y$(Z){let $=async()=>{let J=await Z.readSettings();if(J.status==="error")return J;let z=structuredClone(J.settings);return R7(z,await E7(Z)),{...J,settings:z}},X=async(J,z)=>{let G=await E7(Z);return Z.updateSettings(async(B)=>{R7(B,G);let Q=await J(B)??B;if(u(Q.killswitch)&&Q.killswitch.schema!==k1)Q.killswitch=_z(Q.killswitch,G);return Q},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 Oz(Z,$){let X=(W,Y)=>$.rowLocks?$.rowLocks(W):Y,J=(W,Y)=>{let U=X(W,Y?.extraLocks);return{...Y??{},...U?{extraLocks:U}:{}}},z=(W,Y,U,V)=>Z.replace(W,Y,U,J(W,V)),Q={add:async(W,Y)=>{let U=await Z.read(),j=(U.status==="ready"?U.rows:[]).filter((N)=>N.type==="oauth"&&!N.invalid),D=W.identity?j.find((N)=>N.identity===W.identity):void 0;if(D?.id===j1)throw new GZ("main-account",k7);let H=D??j.find((N)=>N.id===W.id&&N.id!==j1);if(!H||W.credential.type!=="oauth")return Z.add(W,Y);let q=await z(H.id,W.credential,W.identity!==void 0?{identity:W.identity}:{},Y?.extraLocks?{extraLocks:Y.extraLocks}:void 0);return VZ.info("account signed in again",{id:H.id}),{id:q.id,outcome:"rotated",credential:q.credential,credentialEpoch:q.credentialEpoch}},replace:z,enable:(W,Y)=>Z.enable(W,J(W,Y)),disable:(W,Y,U)=>Z.disable(W,Y,J(W,U)),remove:(W,Y)=>Z.remove(W,J(W,Y))};return new Proxy(Z,{get(W,Y){if(Object.hasOwn(Q,Y))return Q[Y];let U=Reflect.get(W,Y,W);return typeof U==="function"?U.bind(W):U}})}async function pU(Z,$,X){await y$(Z).updateSettings((J)=>{X(J);return},$?{extraLocks:$}:{})}var Cz=["version","accounts","commonAuthPool"];function lU(Z,$){return async(X)=>{let J;if(await y$(Z).updateSettings((z)=>{let G={...z,version:1,accounts:[]},B=X(G)??G;J=B;let Q={...B};for(let W of Cz)delete Q[W];return Q},$?{extraLocks:$}:{}),!J)throw Error("the settings write did not run");return J}}var Tz="migration";function b7(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:L3,title:y7,sections:[{id:Tz,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 Rz(X)}var Sz=new Set(["access","refresh","apikey","authheader","password","credential","credentials"]);function Az(Z){let $=Z.toLowerCase().replace(/[-_]/g,"");if(Sz.has($))return!0;return $.endsWith("token")||$.endsWith("key")||$.endsWith("secret")}function I$(Z,$,X){if(Array.isArray(Z))return Z.map((z,G)=>I$(z,`${$}[${G}]`,X));if(!u(Z))return Z;let J={};for(let[z,G]of Object.entries(Z)){if(Az(z)){X.push(`${$}.${z}`);continue}J[z]=I$(G,`${$}.${z}`,X)}return J}function Rz(Z){let $=[],X=I$(Z,"menu",$);if($.length>0)VZ.warn("credential-shaped field stripped before RPC",{fields:$});return X}function Ez(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 bz(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($)=>{let X=typeof $.label==="string"&&$.label.trim().length>0?$.label.trim():void 0,J=$.headless===!0,z=await Z.begin({...X!==void 0?{label:X}:{},headless:J}),G=J?`Open this verification URL:
94
+
95
+ ${z.url}
96
+
97
+ Then enter the code: ${z.instructions.match(/Enter code: (.+)/)?.[1]??z.instructions}
98
+
99
+ The account is added when you finish.`:`Open this URL and complete sign-in:
100
+
101
+ ${z.url}
102
+
103
+ ${z.instructions}
104
+
105
+ The account is added when you finish.`,B=z.completion.then(async(Q)=>{let W=await Z.mainIdentity?.();if(Q.accountId&&W&&Q.accountId===W)throw VZ.warn("account add rejected (main identity)",{id:Q.id}),new GZ("main-account",k7);return VZ.info("account added",{id:Q.id}),Ez(Q)});return{status:"pending",message:G,completion:B}}}}function uU(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),VZ.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 dU(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}`,g4(X.host,X.name,X.enrollment),...O6(X.name,X.enrollment),...J?[X.accounts.length===0?"The vault serves no OpenAI account to this host yet.":`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:SZ(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?.(),`${SZ(G)} is disabled on this host.`}}:{id:"enable",label:"Enable on this host",run:async()=>{return await $.accept(G.routeId),await Z.changed?.(),`${SZ(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 B=await $.connectStep();if(B.state!=="pending"&&B.state!=="busy")return await Z.changed?.(),D$($,B);return $.waitForApproval(Z.wait).then(async(Q)=>{await Z.changed?.();let W=D$($,Q);G.notify(W.text,W.ok?"info":"warning")}).catch((Q)=>{G.notify(`Connecting to the vault failed: ${Q instanceof Error?Q.message:String(Q)}`,"error")}),{ok:!0,text:[...O6($.name,B),"Waiting for the approval; you are told here when it lands."].join(`
106
+ `)}}}]}}}}async function I7(Z,$,X){if(!OZ($))return UZ($,"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 B=await h7($,Z);if(!B.eligible)return UZ($,"not_eligible",v7(B));J=B.chatgptAccountId}if(!J)return UZ($,"not_eligible","Cannot reset: stable ChatGPT account identity unavailable.");VZ.info("reset redemption decision",{accountKey:$,retry:X});let G=await X7({configPath:Z.configPath,statePath:Z.statePath,mutateAccountsFn:Z.mutateAccounts,loadAccountsFn:Z.loadAccounts,now:Z.now,randomUUID:Z.randomUUID,fetchImpl:Z.fetchImpl,resolveTarget:Z.resolveResetTarget,fetchUsage:(B)=>H3({accessToken:B.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:$,expectedChatgptAccountId:J,retry:X});return VZ.info("reset redemption outcome",{accountKey:$,code:G.outcome.kind}),g7(G,Z,J)}catch(z){let G=hz($,z,J);return VZ.info("reset redemption outcome",{accountKey:$,code:G.code}),G}}function cU(Z){return{id:"reset",title:"Reset credits",build:async()=>({lines:["Restore exhausted quota"],items:(await Z.accountKeys()).map(($)=>({id:$,group:"Accounts",label:$===j1?"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 h7($,Z);return{ok:X.eligible,text:`${xz(X)}
107
+
108
+ ${v7(X)}`}}},{id:"spend",label:"Spend a reset credit",irreversible:!0,confirm:"Spend one reset credit on this account? Its eligibility is checked again first, and nothing is spent when it is not eligible.",run:async()=>{let{ok:X,text:J}=await I7(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 I7(Z,$,!0);return{ok:X,text:J}}}]}))})}}var Iz=[{value:"main-first",label:"Main first"},{value:"fallback-first",label:"Fallback first"}],yz=["primary","secondary"];function sU(Z){let $={command:L3,title:y7,store:b$(y$(Oz(Z.store,{...Z.rowLocks?{rowLocks:Z.rowLocks}:{}}))),...Z.extraLocks?{extraLocks:Z.extraLocks}:{},accounts:{...Z.login?{login:bz(Z.login)}:{},...Z.protect?{protect:Z.protect}:{},...Z.describeIdentity?{describeIdentity:Z.describeIdentity}:{}},quota:Z.quotaCheck?{check:Z.quotaCheck}:{},routing:{orderedVariants:Iz,formerMainId:j1},limits:{labels:yz},...Z.cache?{cache:Z.cache}:{},...Z.diagnostics?{diagnostics:Z.diagnostics}:{},...Z.extras?{extras:Z.extras}:{},...Z.logger?{logger:Z.logger}:{},...Z.now?{now:Z.now}:{}},X=Z.vault?A7($,Z.vault):tZ($),J=(z)=>{let{sessionId:G}=z,B=z.notify.bind(z);return{...G!==void 0?{sessionId:G}:{},notify:B}};return{command:L3,async open(z){let G=J(z),B=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(B&&!B.migrated)return{command:L3,menu:b7(B.blockers)};return X.open(G)},async apply(z,G){let B=J(G),Q=Z.vault&&await Z.vault.authority()!=="local"?void 0:await Z.migration?.();if(Q&&!Q.migrated)return{command:L3,ok:!1,text:"Nothing was changed: the accounts have not moved to the new layout yet.",menu:b7(Q.blockers)};let W=await X.apply(z,B);if(W.ok)await Z.afterApply?.();return W}}}function x7(Z){let $=[Z.primary?.usedPercent,Z.secondary?.usedPercent].filter((X)=>X!==void 0);return $.length>0?Math.max(...$):void 0}function kz(Z,$){let X=[Z.primary,Z.secondary].filter((z)=>z!==void 0),J=X.filter((z)=>N3(z,$));return(J.length>0?J:X).sort((z,G)=>G.usedPercent-z.usedPercent)[0]?.resetsAt}function fz(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)=>!N3(J,$))}async function h7(Z,$){let X;try{X=await $.resolveResetTarget(Z);let J=X.accountKey==="main"?void 0:X.chatgptAccountId,[z,G]=await Promise.all([H3({accessToken:X.accessToken,fetchImpl:$.fetchImpl,now:$.now,accountId:X.chatgptAccountId}),N$($.fetchImpl,X.accessToken,J)]),B=A6(G.credits),Q=$7(G.credits),W=G.availableCount??z.resetCreditsAvailable??(Q>0?Q:void 0),Y=z.resetCreditsApplicable,U=F$(z,$.quotaManager.isRateLimited(Z),$.now()),V;if(!X.chatgptAccountId)V="stable ChatGPT account identity unavailable";else if(!U.ok)V=U.reason;else if(!B)V="no eligible credit";return{accountKey:X.accountKey,label:X.label,chatgptAccountId:X.chatgptAccountId,usedPercent:x7(z),resetTime:kz(z,$.now()),availableCount:W,applicableAvailableCount:Y,eligible:V===void 0,reason:V,selectedCreditId:B?.id,selectedCreditExpiresAt:B?.expiresAt}}catch(J){if(J?.status===401)await X?.onAuthFailure?.(401);return VZ.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 xz(Z){let $=Z.usedPercent===void 0?"quota unavailable":`${Z.usedPercent}% used`,X=Z.availableCount===void 0?"credits unavailable":`${Z.applicableAvailableCount===void 0?"?":Z.applicableAvailableCount}/${Z.availableCount} applicable/available`,J=Z.eligible?`eligible · credit ${Z.selectedCreditId} expires ${Z.selectedCreditExpiresAt}`:Z.reason;return`${$}; ${X}; ${J}`}function v7(Z){let $=["## Confirm reset credit","",`Account: **${Z.label}** (\`${Z.accountKey}\`)`,`Current quota: **${Z.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${Z.availableCount??"unknown"}**`,`Credit expires: **${Z.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${Z.resetTime??"unavailable"}**`,""];if((Z.availableCount??0)>0&&Z.applicableAvailableCount===0)$.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),$.push("");if(Z.eligible&&Z.chatgptAccountId)$.push('Eligible: choose "Spend a reset credit" to redeem one.');else $.push(`Cannot reset: **${Z.reason??"not eligible"}**`);return $.join(`
109
+ `)}function UZ(Z,$,X,J={}){if(Object.keys(J).length>0)VZ.debug("reset step details",{accountKey:Z,code:$,...J});return{ok:$==="reset"||$==="already_redeemed",code:$,text:X}}function hz(Z,$,X){if($ instanceof YZ){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 UZ(Z,$.kind,`## Reset credit
110
+
111
+ ${z[$.kind]}
112
+
113
+ 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 UZ(Z,J,`## Reset credit
114
+
115
+ ${{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]}
116
+
117
+ Code: \`${J}\``);if($ instanceof H1)return UZ(Z,$.kind,`## Reset credit
118
+
119
+ No redemption was attempted: reset credit availability could not be loaded.
120
+
121
+ Code: \`${$.kind}\``);return VZ.warn("reset command failed before a known result",{accountKey:Z,error:$?.message??String($)}),UZ(Z,"error",`## Reset credit
122
+
123
+ The reset request failed before a known result: internal command failure — see plugin log.`)}async function g7(Z,$,X){let{accountKey:J}=Z.target,z=Z.outcome.kind;if(Z.finalizeStateWriteFailed)return UZ(J,z,`## Reset credit result
124
+
125
+ Account: **${Z.target.label}** (\`${J}\`)
126
+
127
+ 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 B={account:J,ok:!1,error:"targeted quota refresh did not complete"};try{B=await $.refreshResetTargetQuota(J)}catch(D){B.error=D?.message??String(D)}let Q=!B.ok&&B.error!==void 0;if(Q)VZ.warn("reset quota re-check failed",{accountKey:J,error:B.error});let W=J==="main"?$.quotaManager.getMain():$.quotaManager.getFallback(J),Y=B.ok&&fz(W?.quota,$.now()),U=W?.quota.resetCreditsApplicable,V=Y?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${z}\`).`,j=Q?`
128
+
129
+ quota re-check failed — see log.`:"";return UZ(J,z,`## Reset credit result
130
+
131
+ Account: **${Z.target.label}** (\`${J}\`)
132
+
133
+ Code: \`${z}\`
134
+
135
+ ${V}${j}${U===void 0?"":`
136
+
137
+ Remaining applicable credits: **${U}**`}`,{verifiedFresh:Y,afterUsedPercent:x7(W?.quota??{}),remainingCredits:U})}if(z==="ambiguous_local")return UZ(J,z,`## Reset credit result
138
+
139
+ Account: **${Z.target.label}** (\`${J}\`)
140
+
141
+ Code: \`${z}\`
142
+
143
+ ${Z.retrySafety}`,{retryGuidance:Z.retrySafety});if(z==="ambiguous"||z==="http_error"){let B=Z.refused?' The server refused the request; five minutes after the redemption started, "Spend a reset credit" starts a new one instead.':"";return UZ(J,z,`## Reset credit result
144
+
145
+ Account: **${Z.target.label}** (\`${J}\`)
146
+
147
+ The redemption outcome is unknown (\`${z}\`).
148
+
149
+ Retry with "Retry the last redemption" on this account. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.${B}`,{retryGuidance:Z.retrySafety,chatgptAccountId:X})}let 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 UZ(J,z,`## Reset credit result
150
+
151
+ Account: **${Z.target.label}** (\`${J}\`)
152
+
153
+ Code: \`${z}\`
154
+
155
+ ${G[z]??"The server returned a no-op result. No reset was confirmed."}`)}var k$=v("quota"),m7="the account holds a tombstone from the removed vault custody, not a credential";function vz(Z){return Z?.status===401}async function eU(Z,$={}){let X=Z.whamFn;if(!X)throw Error("whamFn is required for refreshAllQuota");let J=[],z=Z.logger??k$,G=(H)=>{J.push(H);let q={pid:process.pid,accountId:H.account,status:H.ok?"ok":"error",...H.error?{error:H.error}:{}};if(H.ok)z.debug("quota refresh succeeded",q);else z.warn("quota refresh failed",q)},B=Z.skipFresherThanMs,Q=!1,W;if(B!==void 0)try{W=await Z.readSidebarState()}catch{}let Y=new Map(W?.fallbacks.map((H)=>[H.id,H])??[]),U=(...H)=>B!==void 0&&H.some((q)=>typeof q==="number"&&Number.isFinite(q)&&q<=Z.now()&&Z.now()-q<B),V=await Z.loadAccounts(Z.paths).catch(()=>{return}),j=V?.mainAccountId??Z.storageMainAccountId,D;if(!$.accountKey||$.accountKey==="main")try{let H=await Z.getAuth();if(R4(H)){if(D=E4(V),!D)G({account:"main",ok:!1,error:QZ(H)?m7:"main account row is missing from the account pool"})}else if(H.type==="oauth"){let q=W&&j!==void 0&&W.main.mainAccountId===j?W.main.quota:void 0;if(U(Z.quotaManager.peekMainForPolicy(j)?.checkedAt,q?.primary?.checkedAt,q?.secondary?.checkedAt,q?.checkedAt))G({account:"main",ok:!0});else{if(!H.access||(H.expires??0)<Z.now()){let M=await Z.refreshMainWithLease();H={...H,access:M.access,expires:M.expires}}if(H.access)if(Z.respectBackoff&&Z.quotaManager.isBackedOff())G({account:"main",ok:!0});else{let M=await X({accessToken:H.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:j,accountKey:"main"});Z.quotaManager.setMain(H.access,{quota:M,refreshAfter:Z.now()+300000,checkedAt:Z.now()},j,!0),Q=!0,G({account:"main",ok:!0})}else if(!J.some((M)=>M.account==="main"))G({account:"main",ok:!1,error:"no access token"})}}else G({account:"main",ok:!1,error:"auth type is not oauth"})}catch(H){G({account:"main",ok:!1,error:WZ(H)})}if(V)for(let H of V.accounts){let q=D!==void 0&&H===D;if(!q&&$.accountKey&&($.accountKey==="main"||H.id!==$.accountKey))continue;if(!q&&Z.isOAuthAccountFn(H)&&W1(V,H)){if($.accountKey)G({account:H.id,ok:!1,error:"account holds the main credential while the main slot is live"});continue}let N=q?H.accountId??j:void 0,M=(O,S,F)=>{if(q)Z.quotaManager.setMain(S,O,N,!0);else Z.quotaManager.setFallback(H.id,O,S,!0,F)};if(H.enabled===!1||!Z.isOAuthAccountFn(H)){if($.accountKey)G({account:H.id,ok:!1,error:"account is not an enabled OAuth fallback"});continue}try{let O=Y.get(H.id),S=H.accountId,F=q?W&&N!==void 0&&W.main.mainAccountId===N?W.main.quota:void 0:O&&S!==void 0&&O.accountId===S?O.quota:void 0;if(U(q?Z.quotaManager.peekMainForPolicy(N)?.checkedAt:Z.quotaManager.peekFallbackForPolicy(H.id,S)?.checkedAt,F?.primary?.checkedAt,F?.secondary?.checkedAt,F?.checkedAt)){G({account:H.id,ok:!0});continue}if(Z.respectBackoff&&(q?Z.quotaManager.isBackedOff():Z.quotaManager.isFallbackBackedOff(H.id,H.access))){G({account:H.id,ok:!0});continue}let K=H.lastRefreshError;if(yZ(K,H.refresh,Z.now())){G({account:H.id,ok:!1,error:S1(K,Z.now()),permanent:!0});continue}if(QZ(H)){G({account:H.id,ok:!1,error:m7});continue}let P;try{P=q?await Z.fallbackManager.refreshAccount(H,V,{asPoolMain:!0}):await Z.fallbackManager.refreshAccount(H,V)}catch(k){k$.warn("fallback token refresh failed during quota poll",{pid:process.pid,accountId:H.id,error:WZ(k)}),P=H}if(!P.access||(P.expires??0)<Z.now()){G({account:H.id,ok:!1,error:"no usable access token"});continue}let C;try{C=await X({accessToken:P.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:P.accountId,accountKey:H.id})}catch(k){if(!vz(k))throw k;if(k$.warn("quota endpoint rejected the token; forcing a refresh",{pid:process.pid,accountId:H.id}),P=await Z.fallbackManager.refreshAccount(H,V,q?{force:!0,asPoolMain:!0}:{force:!0}),!P.access){G({account:H.id,ok:!1,error:"no usable access token after forced refresh"});continue}C=await X({accessToken:P.access,fetchImpl:Z.fetchImpl,now:Z.now,accountId:P.accountId,accountKey:H.id})}M({quota:C,refreshAfter:Z.now()+300000,checkedAt:Z.now()},P.access,P.accountId),Q=!0,G({account:H.id,ok:!0})}catch(O){G({account:H.id,ok:!1,error:WZ(O)})}}if($.accountKey&&$.accountKey!=="main"&&!J.some((H)=>H.account===$.accountKey))J.push({account:$.accountKey,ok:!1,error:"account not found"});if(B===void 0||Q){let H=await Z.loadAccounts(Z.paths);await Z.writeSidebarState(Z.quotaManager,H)}return J}import{types as gz}from"node:util";var mz=/"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"\s*:/i,wz=/"(?:t|\\u0074)(?:y|\\u0079)(?:p|\\u0070)(?:e|\\u0065)"\s*:\s*"(?:e|\\u0065)(?:r|\\u0072){2}(?:o|\\u006f)(?:r|\\u0072)"/i;function d7(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:`
156
+ `,r:"\r",t:"\t"}[J]??J??$})}function pz(Z,$){if(!$)return Z;let X=Z.split($).join("[credential]"),J=$.replace(/\s/g,"");if(!J)return X;let z=X.replace(/\s/g,"");if(!z.includes(J))return X;let G=[];for(let W=0;W<X.length;W++){let Y=X[W]??"";if(!/\s/.test(Y))G.push(W)}let B=[],Q=0;for(let W=z.indexOf(J);W>=0;W=z.indexOf(J,W+J.length)){let Y=G[W]??Q,U=(G[W+J.length-1]??Y)+1;B.push(X.slice(Q,Y),"[credential]"),Q=U}return B.length?B.join("")+X.slice(Q):X}function w7(Z,$){let X=pz(Z,$);return u7(X).replaceAll("***REDACTED***","[credential]")}function v1(Z,$){let X=w7(Z,$),J=d7(X),z=w7(J,$);return z===J?X:z}function p7(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 B=$[4]??"0",Q=B.startsWith("-")||B.startsWith("+")?1:0;while(B[Q]==="0")Q++;let W=B.slice(Q)||"0";if(W.length>16)return;let Y=BigInt((B.startsWith("-")?"-":"")+W)-BigInt(X.length)+BigInt(J.length-G);return`${$[1]}${J.slice(z,G)}e${Y}`}function c7(Z,$){let X=$?p7($):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&&p7(J)===X||($==="Infinity"||$==="-Infinity")&&/^[-\d]/.test(J)&&String(Number(J))===$)?'"[credential]"':J;let z=d7(J.slice(1,-1)),G=v1(z,$);return G===z?J:JSON.stringify(G)})}function x$(Z,$){let X=c7(Z,$);try{return JSON.parse(Z),X}catch{return v1(X,$)}}var lz=16384,uz=65536,dz=[/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 cz(Z){try{let $=p(JSON.parse(Z),"request_id");if(typeof $==="string")return $;if(typeof $!=="number")return;let X=0,J,z=!0,G=!1,B;for(let Q of Z.matchAll(/"(?:\\.|[^"\\])*"|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?|[{}[\]:,]/g)){let W=Q[0];if(W==="{"||W==="["){X++;continue}if(W==="}"||W==="]"){X--;continue}if(X!==1)continue;if(W===","){z=!0,G=!1,J=void 0;continue}if(W===":"){G=!0;continue}if(z&&W.startsWith('"')){J=JSON.parse(W),z=!1;continue}if(G&&J==="request_id"&&!W.startsWith('"'))B=W;G=!1}return B}catch{return}}function sz(Z,$){let X=x$(Z,$);if(Buffer.byteLength(X,"utf8")<=uz)return X;let J=dz.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(p(G,"type")==="error")z.type="error";let B=p(G,"error"),Q={};for(let Y of["code","type"]){let U=p(B,Y);if(typeof U==="string")Q[Y]=U.slice(0,256)}if(Object.keys(Q).length)z.error=Q;let W={};for(let Y of["workspace","limitName"]){let U=p(p(G,"metadata"),Y);if(typeof U==="string")W[Y]=U.slice(0,256)}if(Object.keys(W).length)z.metadata=W}catch{}return JSON.stringify(z)}function k6(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;for(let X=0;$&&X<16;X++){if(gz.isProxy($))return!1;$=Object.getPrototypeOf($)}return $===null}function p(Z,$){if(!k6(Z))return;let X=Object.getOwnPropertyDescriptor(Z,$);return X&&"value"in X?X.value:void 0}function _3(Z,$){return v1(Z,$).slice(0,lz)}function g1(Z,$){let X=Object.getOwnPropertyDescriptor(Z,$)?.get;if(!X)throw Error(`Missing native ${$} accessor`);return X}var iz=g1(DOMException.prototype,"message"),az=g1(DOMException.prototype,"name");function f$(Z,$){let X=p(Z,"message"),J=p(Z,"name");if(k6(Z)&&Z instanceof DOMException)try{X=iz.call(Z),J=az.call(Z)}catch{}let z=Error(_3(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"?_3(J,$):"Error",configurable:!0,writable:!0});let G=(V,j,D)=>{let H=p(V,D);if(typeof H==="string"||typeof H==="number"&&Number.isFinite(H)||typeof H==="boolean")Object.defineProperty(j,D,{value:typeof H==="string"?_3(H,$):H,enumerable:!0,configurable:!0,writable:!0})};for(let V of["status","statusCode","status_code","resets_at","resets_in_seconds"]){let j=p(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=p(Z,V),D=Object.create(null);for(let q of["type","code","message","resets_at","resets_in_seconds"])G(j,D,q);let H=p(j,"error");if(k6(H)){let q=Object.create(null);for(let N of["type","code","message","resets_at","resets_in_seconds"])G(H,q,N);D.error=q}if(Object.keys(D).length)Object.defineProperty(z,V,{value:D,enumerable:!0})}let B=p(Z,"responseHeaders");if(B&&typeof B==="object"){let V={};for(let j of["retry-after-ms","retry-after"]){let D=p(B,j);if(typeof D==="string")V[j]=_3(D,$)}Object.defineProperty(z,"responseHeaders",{value:V,enumerable:!0})}let Q=p(Z,"responseBody");if(typeof Q==="string")Object.defineProperty(z,"responseBody",{value:sz(Q,$),enumerable:!0});let W=p(Z,"request_id"),Y=p(B,"x-request-id"),U=typeof W==="string"?W:typeof Y==="string"?Y:typeof Q==="string"?cz(x$(Q,$)):void 0;if(typeof U==="string")Object.defineProperty(z,"request_id",{value:_3(U,$),enumerable:!0});for(let V of["vercel.ai.error","vercel.ai.error.AI_APICallError"]){let j=Symbol.for(V);if(p(Z,j)===!0)Object.defineProperty(z,j,{value:!0})}return z}function nz(Z,$){if(!Z.includes("error")&&(!Z.includes("\\u00")||!mz.test(Z)&&!wz.test(Z)))return Z;let X;try{X=JSON.parse(Z)}catch{return Z}if(X?.type==="error"||X?.error||X?.response?.error)return c7(Z,$);return Z}var rz=g1(Response.prototype,"status"),oz=g1(Response.prototype,"statusText"),tz=g1(Response.prototype,"headers"),ez=g1(Response.prototype,"body"),ZG=Response.prototype.text,l7=Headers.prototype.entries;async function JV(Z,$,X="http"){try{let D=function(H){let q=j&&H.startsWith("\uFEFF")?"\uFEFF":"";return j=!1,q+H.slice(q.length).replace(/^data: ?([^\r\n]*)/gm,(N,M)=>N.slice(0,N.length-M.length)+nz(M,$))};if(!k6(Z))throw Error("Invalid provider response");let J=rz.call(Z),z=tz.call(Z),G=ez.call(Z),B=new Headers;for(let[H,q]of l7.call(z))B.append(H,q);let Q={status:J,statusText:v1(oz.call(Z),$),headers:B};if(J<200||J>299){for(let[q,N]of l7.call(z)){if(v1(q,$?.toLowerCase())!==q){Q.headers.delete(q);continue}try{Q.headers.set(q,v1(N,$))}catch{Q.headers.delete(q)}}Q.headers.delete("content-length");let H=await ZG.call(Z);return new Response(x$(H,$),Q)}if(!G||X==="http")return Z;Q.headers.delete("content-length");let W=ReadableStream.prototype.getReader.call(G),Y=new TextDecoder("utf-8",{ignoreBOM:!0}),U=new TextEncoder,V="",j=!0;return new Response(new ReadableStream({async pull(H){try{for(;;){let q=await W.read();V+=Y.decode(q.value,{stream:!q.done});let N=!1;for(;;){let M=/\r?\n\r?\n/.exec(V);if(!M)break;let O=M.index+M[0].length;H.enqueue(U.encode(D(V.slice(0,O)))),V=V.slice(O),N=!0}if(q.done){if(V)H.enqueue(U.encode(D(V)));H.close();return}if(N)return}}catch(q){H.error(f$(q,$))}},async cancel(H){try{await W.cancel(H)}catch(q){throw f$(q,$)}finally{W.releaseLock()}}}),Q)}catch(J){throw f$(J,$)}}function BV(Z,$,X){let J=Z.get($.sessionId),z=new Set($.validPinnedAccountIds);if(J&&!$.excludeAccountIds.includes(J.accountId)&&u1(J,z,$.wireAccountIdByAccount[J.accountId])){if($.persist){let W=$.quotaCheckedAtByAccount[J.accountId];X($.sessionId,{accountId:J.accountId,inputBytes:$.requestBytes,...J.wireIdentity!==void 0?{wireIdentity:J.wireIdentity}:{},...W!==void 0?{quotaCheckedAt:W}:{}})}return{accountId:J.accountId}}let G=new Map(Object.entries($.quotaCheckedAtByAccount)),B=i6(Z,G,$.sessionId),Q=$.select(B);if(!Q)return;if($.persist){let W=$.wireAccountIdByAccount[Q.accountId];X($.sessionId,{accountId:Q.accountId,inputBytes:$.requestBytes,...W!==void 0?{wireIdentity:W}:{},...Q.quotaCheckedAt!==void 0?{quotaCheckedAt:Q.quotaCheckedAt}:{}})}return{accountId:Q.accountId}}import{statSync as $G}from"node:fs";var s7=30000,XG=8,JG=1800000;function i7(Z){return Z.identity?`identity:${Z.identity}`:`row:${Z.id}`}function UV(Z){try{let $=$G(Z);return`${$.ino}:${$.size}:${$.mtimeMs}`}catch{return"-"}}function VV(Z){let $=Z.credential;if($?.type!=="oauth")return;return{access:$.access??"",expires:$.expires,refresh:$.refresh}}function zG(Z,$){try{return W3(Z,$)}catch{return Z}}function jV(Z,$,X){let J=i7($);Z.set(J,[...Z.get(J)??[],{credentialEpoch:$.credentialEpoch,identity:$.identity,observation:X}].slice(-XG))}function qV(Z,$,X){let J=Z;for(let z of $.get(i7(Z))??[]){if(!(X-z.observation.checkedAt<=JG)||z.credentialEpoch!==Z.credentialEpoch||z.identity!==Z.identity)continue;J={...J,quota:zG(J.quota,z.observation)}}return J}function DV(Z,$,X,J){let z=eZ(Z);if(typeof $?.status==="number"||L8($)){let B=Z6({error:$,now:X,refreshToken:Z,...J?{previous:{message:"",checkedAt:X,nextRetryAt:J.nextRetryAt,retryCount:J.retryCount,tokenHash:J.tokenHash}}:{}});return{nextRetryAt:B.nextRetryAt,tokenHash:z,retryCount:B.retryCount}}return{nextRetryAt:X+s7,tokenHash:z,retryCount:J?.tokenHash===z?J.retryCount:0}}function KV(Z,$,X,J){let z=new Map;for(let G of Z){if(J(G,X))continue;let B=$.get(G.id);z.set(G.id,B&&B.nextRetryAt>X?B.nextRetryAt:X+s7)}return z}import{realpathSync as a7}from"node:fs";import{homedir as GG}from"node:os";import{basename as BG,dirname as QG,join as x6,resolve as r7}from"node:path";function WG(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return x6(process.env.XDG_CONFIG_HOME||x6(GG(),".config"),"opencode")}function o7(){return process.env.OPENCODE_OPENAI_AUTH_FILE?.trim()||x6(WG(),W$)}function f6(Z,$){let X=r7(Z);return $==="win32"||$==="darwin"?X.toLowerCase():X}function n7(Z){try{return a7.native(Z)}catch{try{return x6(a7.native(QG(Z)),BG(Z))}catch{return}}}function YG(Z,$,X=process.platform){if(f6(Z,X)===f6($,X))return!0;let J=n7(Z),z=n7($);return J!==void 0&&z!==void 0&&f6(J,X)===f6(z,X)}function HG(Z=o7()){let $=process.env.OPENCODE_OPENAI_AUTH_STATE_FILE?.trim();if($){if(YG(Z,$))throw Error(`OPENCODE_OPENAI_AUTH_STATE_FILE resolves to the config path (${r7(Z)}). Set OPENCODE_OPENAI_AUTH_STATE_FILE to a different file.`);return $}return Y$(Z)}function sV(Z=o7()){return{configPath:Z,statePath:HG(Z)}}import{createHash as NG}from"node:crypto";import{readFileSync as MG}from"node:fs";import{readFile as PG}from"node:fs/promises";import{resolve as LG}from"node:path";import{createHash as UG}from"node:crypto";import{readFile as VG}from"node:fs/promises";import{homedir as jG}from"node:os";import{join as t7,resolve as qG}from"node:path";var DG="openai",e7=250,C3="main-refresh";function v$(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 UG("sha256").update(J($)).update($).update(J(X)).update(X).digest("hex")}function G2(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 B2(Z){let $=G2(Z);if(typeof $?.access!=="string"||typeof $.refresh!=="string")return;return{access:$.access,refresh:$.refresh,...typeof $.expires==="number"?{expires:$.expires}:{}}}function Z2(Z){if(q1(Z)&&Z.type==="api"&&typeof Z.key==="string")return{kind:"api"};let $=G2(Z);if(!$)return{kind:"indeterminate"};return QZ($)?{kind:"tombstone",oauth:$}:{kind:"real",oauth:$}}async function $2(Z){return Z.auth.get({path:{id:DG}})}async function X2(Z){return Object.keys(await Z.auth.all()).length>0}async function Q2(Z){let $=await $2(Z.client);if($!==void 0)return Z2($);let X=await X2(Z.client),J=Z.now();if(await Z.sleep(e7),Z.now()-J<e7)return{kind:"indeterminate"};let z=await $2(Z.client);if(z!==void 0)return Z2(z);let G=await X2(Z.client);return X&&G?{kind:"slot-absent"}:{kind:"indeterminate"}}function h6(Z=process.env,$=jG()){let X=Z.XDG_DATA_HOME||t7($,".local","share");return t7(X,"opencode","auth.json")}function q1(Z){return!!Z&&typeof Z==="object"&&!Array.isArray(Z)}var J2=(Z)=>Z===void 0||typeof Z==="string";function KG(Z){if(!q1(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&&J2(Z.accountId)&&J2(Z.enterpriseUrl);case"api":return typeof Z.key==="string"&&(Z.metadata===void 0||q1(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 h$(Z,$=process.env){let X=$.OPENCODE_AUTH_CONTENT;if(X)try{let z=JSON.parse(X);return q1(z)?z:{}}catch{}let J;try{J=JSON.parse(await VG(Z,"utf8"))}catch{return{}}if(!q1(J))return{};return Object.fromEntries(Object.entries(J).filter(([,z])=>KG(z)))}function z2(Z){if(!Z.OPENCODE_AUTH_CONTENT)return!1;try{return JSON.parse(Z.OPENCODE_AUTH_CONTENT),!0}catch{return!1}}class v6 extends Error{constructor(){super("OpenCode openai login changed after the account-pool migration read it; nothing was written");this.name="HostSlotChangedError"}}function FG(Z){let $=Z.env??process.env,X=Z.path??h6($),J=new Map;return{path:qG(X),migrationDisabledReason:()=>z2($)?"OPENCODE_AUTH_CONTENT supplies the login; the environment-backed slot is read-only":void 0,async get(z){let G=(await h$(X,$))[z.path.id];return J.set(z.path.id,JSON.stringify(G)),G},async all(){return h$(X,$)},async set(z){if(z2($))throw Error("OPENCODE_AUTH_CONTENT supplies a read-only login slot");let G=(await h$(X,$))[z.path.id];if(O3(z.body)&&(!J.has(z.path.id)||J.get(z.path.id)!==JSON.stringify(G)))throw new v6;let B=await Z.set(z);if(q1(B)&&"error"in B&&B.error!==void 0)throw Error(`OpenCode refused the write of its ${z.path.id} login: ${JSON.stringify(B.error)}`);return B}}}function Zj(Z,$={}){let X=q1(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:FG({...$,set:(z)=>J.call(X,z)})}}var m1="openai",_G="common-auth-placeholder:v1:openai",T3=Object.freeze({type:"oauth",access:"",refresh:_G,expires:0});function O3(Z){if(!jZ(Z))return!1;return Z.type===T3.type&&Z.access===T3.access&&Z.refresh===T3.refresh&&Z.expires===T3.expires}var g6="openaiAuthPool",OG=120000,U2="pool-migration",CG="slot-transfer-origin-unknown",TG="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.",l6=Object.freeze({mainRefreshTtlMs:OG,fallbackTtlMs:V$,saveTtlMs:1e4,renew:!0,timeoutMs:15000,retryMs:50});function m6(Z,$,X){return Z.kind==="placeholder"&&!$&&!X.pending}class S3 extends Error{constructor(Z){super(`timed out waiting for the legacy ${Z} lock`);this.name="LegacyLockContention"}}function jZ(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function SG(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??v("pool-migration"),...Z.vaultServes?{vaultServes:Z.vaultServes}:{},locks:{...l6,...Z.legacyLocks},leaseWait:Z.leaseWait??{timeoutMs:4000,pollMs:50},store:t1({provider:m1,configPath:Z.paths.configPath,statePath:Z.paths.statePath,quota:p6,now:$,...Z.store}),onStep:async(X)=>{await Z.onStep?.(X)}}}async function p1(Z){let $;try{$=await PG(Z,"utf8")}catch(J){if(J.code==="ENOENT")return{};throw J}let X=JSON.parse($);if(!jZ(X))throw Error("config root is not an object");return X}async function A3(Z,$,X,J){let z=performance.now();for(;;){let G=await w({name:$,path:X,ttlMs:J,now:Z.now,renew:Z.locks.renew,...Z.locks.renewIntervalMs!==void 0?{renewIntervalMs:Z.locks.renewIntervalMs}:{}});if(G)return G;if(performance.now()-z>=Z.locks.timeoutMs)throw new S3($);await Z.sleep(Z.locks.retryMs)}}async function Vj(Z,$,X={}){let J={...l6,...X},z=performance.now();for(;;){let G=await w({name:C3,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 S3(C3);await new Promise((B)=>setTimeout(B,J.retryMs))}}async function R3(Z,$){let X=Z.locks.saveTtlMs,J=await A3(Z,"save",Z.paths.configPath,X);try{let z=await A3(Z,"save",Z.paths.statePath,X);try{let G=await p1(Z.paths.configPath);if(!await $(G))return;await n(Z.paths.configPath,G,{beforeRename:async()=>{await J.assertOwned(),await z.assertOwned()}})}finally{await z.release().catch(()=>{})}}finally{await J.release().catch(()=>{})}}function AG(Z){if(!jZ(Z))return;let{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:z}=Z,{credentialFingerprint:G,carryLegacyMain:B,recordedAt:Q,identity:W}=Z;if(typeof $!=="string"||!$)return;if(X!=="add"&&X!=="rotate"&&X!=="replace")return;if(J!==null&&typeof J!=="string")return;if(typeof z!=="string")return;if(typeof G!=="string")return;return{rowId:$,operation:X,rowFingerprint:J,slotFingerprint:z,credentialFingerprint:G,...typeof W==="string"&&W?{identity:W}:{},carryLegacyMain:B===!0,recordedAt:typeof Q==="number"?Q:0}}function V2(Z,$){if(!jZ(Z)||!$)return!1;return MZ(Z).pending?.credentialFingerprint===DZ({type:"oauth",refresh:$})}function jj(Z,$){let X;try{X=JSON.parse(MG(Z,"utf8"))}catch{return!1}return V2(X,$)}class RG extends Error{constructor(){super("the account-pool migration is moving this token; not refreshing it");this.name="PoolTransferPendingError"}}var EG=600000;async function qj(Z,$,X={}){let J=X.now??Date.now,z=(W)=>{let Y=MZ(W).pending;return Y&&V2(W,$)&&J()-Y.recordedAt>=EG?Y:void 0},G=z(await p1(Z.configPath));if(!G)return!1;let B={...l6,...X.legacyLocks},Q=await w({name:U2,path:Z.configPath,ttlMs:B.mainRefreshTtlMs,now:J});if(!Q)return!1;try{let W=await p1(Z.configPath),Y=MZ(W).migratedAt!==void 0,U=await t1({provider:m1,configPath:Z.configPath,statePath:Z.statePath,quota:p6,now:J}).read();if(Y&&U.status!=="ready")return!1;let V;if(U.status==="ready"){let D=U.rows.find((q)=>q.id===G.rowId&&!q.invalid),H=D?.fingerprint??null;if(Y&&D&&H===G.credentialFingerprint)return!1;if(D&&H!==G.credentialFingerprint&&H!==G.rowFingerprint)V=X.slotAccess!==void 0?v$({type:"oauth",access:X.slotAccess,refresh:$}):G.slotFingerprint}let j=!1;if(await R3({paths:Z,now:J,locks:B,sleep:(D)=>new Promise((H)=>setTimeout(H,D))},(D)=>{let H=MZ(D),q=z(D);if(!q||q.recordedAt!==G.recordedAt)return!1;let{pending:N,...M}=H;return u6(D,V!==void 0?{...M,declinedSlotFingerprint:V}:M),j=!0,!0}),j)(X.log??v("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 Q.release().catch(()=>{})}}function MZ(Z){let $=Z[g6];if(!jZ($))return{};let X=AG($.pending);return{...typeof $.migratedAt==="number"?{migratedAt:$.migratedAt}:{},...X?{pending:X}:{},...typeof $.declinedSlotFingerprint==="string"?{declinedSlotFingerprint:$.declinedSlotFingerprint}:{}}}function u6(Z,$){let J={...jZ(Z[g6])?Z[g6]:{}};for(let z of["migratedAt","pending","declinedSlotFingerprint"])delete J[z];Object.assign(J,$),Z[g6]=J}function bG(Z){let $=Z?R1(Z):void 0;return $?E1($):void 0}function IG(Z){let $=v$({type:"oauth",...Z}),X=bG(Z.access);return{kind:"real",credential:Z,fingerprint:$,credentialFingerprint:DZ({type:"oauth",refresh:Z.refresh}),...X?{identity:X}:{}}}function j2(Z){if(O3(Z))return{kind:"placeholder",...jZ(Z)&&typeof Z.accountId==="string"?{origin:Z.accountId}:{}};let $=B2(Z);if(!$?.refresh.trim())return{kind:"empty"};return IG($)}async function E3(Z){let $=await Q2({client:{auth:{get:(X)=>Z.slot.get(X),all:()=>Z.slot.all()}},now:Z.now,sleep:Z.sleep});if($.kind==="real")return j2($.oauth);return $.kind==="slot-absent"||$.kind==="indeterminate"?{kind:$.kind}:{kind:$.kind}}async function Dj(Z,$){if(!O3($))return!1;let X=await p1(Z.configPath),J=await t1({provider:m1,configPath:Z.configPath,statePath:Z.statePath,quota:p6}).read();if(J.status==="error")return!1;let z=J.status==="ready"?J.rows.some((G)=>G.id==="main"):J.roster.some((G)=>jZ(G)&&G.id==="main");return m6({kind:"placeholder"},z,MZ(X))}async function yG(Z){let $=Z.now()+Z.leaseWait.timeoutMs;for(;;){let X=await E3(Z);if(X.kind!=="real")return X;if(!await q2(Z,X.credential.refresh))return X;if(Z.now()>=$)return{kind:"retry"};await Z.sleep(Z.leaseWait.pollMs)}}async function q2(Z,$){let X=await K3(Z.paths),J=X?.refresh?.mainRefreshLeaseUntil;return Boolean(J&&J>Z.now()&&X?.refresh?.mainRefreshLeaseTokenHash===eZ($))}function kG(Z){return Z.length>0&&Z.trim()===Z&&!["__proto__","constructor","prototype","main"].includes(Z)}function fG(Z,$,X,J,z){let G=X.identity?{identity:X.identity}:{},B=$.find((U)=>!U.invalid&&U.fingerprint===X.credentialFingerprint);if(B)return{rowId:B.id,operation:"rotate",rowFingerprint:B.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&B.id==="main"};let Q=$.find((U)=>U.id==="main");if(!Q||!Q.invalid&&!Q.credential)return{rowId:"main",operation:"add",rowFingerprint:null,...G,carryLegacyMain:Z==="migrate"};if(X.identity){let U=$.find((V)=>!V.invalid&&V.type==="oauth"&&V.enabled&&V.identity===X.identity);if(U)return{rowId:U.id,operation:"replace",rowFingerprint:U.fingerprint??null,...G,carryLegacyMain:Z==="migrate"&&U.id==="main"}}let W=new Set($.map((U)=>U.id));return{rowId:J??(X.identity&&kG(X.identity)&&!W.has(X.identity)?X.identity:z()),operation:"add",rowFingerprint:null,...G,carryLegacyMain:!1}}function xG(Z,$,X,J,z,G,B){let Q=$.pending;if(Q){let W=X.find((V)=>V.id===Q.rowId&&!V.invalid),Y=W?.fingerprint??null,U=J.kind==="real"&&J.fingerprint===Q.slotFingerprint;if(W&&Y===Q.credentialFingerprint)return{kind:"finish",record:Q};if((W||Q.rowFingerprint===null)&&Y===Q.rowFingerprint)return U&&J.kind==="real"?{kind:"transfer",record:Q,credential:J.credential,fresh:!1}:{kind:"drop-record"};if(!W)return{kind:"drop-record"};return U?{kind:"ambiguous",record:Q}:{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:{...fG(Z,X,J,z,B),slotFingerprint:J.fingerprint,credentialFingerprint:J.credentialFingerprint,recordedAt:G},credential:J.credential,fresh:!0}}async function hG(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:w6(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 B=await Z.store.read(),Q=B.status==="ready"?B.rows.find((W)=>W.id===$.rowId):void 0;await Z.store.rotate($.rowId,J,Q?.identity===void 0?z:{},G)}}async function vG(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 gG(Z,$){let X=[],J=[["primary",Z.primary],["secondary",Z.secondary]],z=0;for(let[Q,W]of J){if(!W||!Number.isFinite(W.checkedAt)||!Number.isFinite(W.usedPercent))continue;z=Math.max(z,W.checkedAt),X.push({checkedAt:W.checkedAt,readings:[{label:Q,usedPercent:W.usedPercent,...typeof W.resetsAt==="string"?{resetsAt:W.resetsAt}:{},...Number.isFinite(W.windowMinutes)?{windowMinutes:W.windowMinutes}:{}}]})}let G=$??(z||void 0),B=Z.spendControl;if(G!==void 0&&B)X.push({checkedAt:G,budget:{kind:"reading",reached:B.reached,remainingPercent:B.remainingPercent,usedPercent:B.usedPercent,limit:B.limit,used:B.used,remaining:B.remaining,...B.resetsAt!==void 0?{resetsAt:B.resetsAt}:{},...B.unit!==void 0?{unit:B.unit}:{}}});else if(G!==void 0&&Z.spendControlCleared)X.push({checkedAt:G,budget:{kind:"cleared"}});return X.sort((Q,W)=>Q.checkedAt-W.checkedAt)}async function mG(Z,$){let X=await K3(Z.paths);if(!X)return;let J=X.quota?.mainQuotaToken,z=$.credential?.type==="oauth"?$.credential.access:void 0,B=!J||z!==void 0&&J===$Z(z)?X.quota?.mainQuota:void 0;if(B&&$.credentialEpoch!==void 0){let U={credentialEpoch:$.credentialEpoch,...$.identity!==void 0?{identity:$.identity}:{}};for(let V of gG(B,X.quota?.mainQuotaCheckedAt))try{await Z.store.recordQuota($.id,U,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 Q=X.refresh?.mainLastRefreshError,W=X.accounts.find((U)=>U.id===$.id);if(!W||!NZ(W)||W.corrupt)return;if(!Q&&!B)return;let Y={...X,accounts:[{...W,...W.lastRefreshError||!Q?{}:{lastRefreshError:Q},...W.quota||!B?{}:{quota:B}}]};try{await U$(Y,Z.paths,{accounts:[$.id]})}catch(U){Z.log.warn("legacy main backoff not carried to the pool row",{rowId:$.id,error:U instanceof Error?U.message:String(U)})}}async function w1(Z,$,X={}){await R3(Z,(J)=>{let z=MZ(J);if(delete J.mainAccountId,$==="migrate"&&z.migratedAt===void 0)wG(J);return u6(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 wG(Z){let $=Z.routing;if($===void 0)Z.routing={mode:"main-first"};else if(jZ($)&&$.mode===void 0)Z.routing={...$,mode:"main-first"}}async function m$(Z){await R3(Z,($)=>{let X=MZ($);if(!X.pending)return!1;let{pending:J,...z}=X;return u6($,z),!0})}async function pG(Z,$){await R3(Z,(X)=>{let J=MZ(X);if($.identity)X.mainAccountId=$.identity;return u6(X,{...J,pending:$}),!0})}async function lG(Z,$,X,J){let z=await A3(Z,C3,Z.paths.configPath,Z.locks.mainRefreshTtlMs);try{return await uG(Z,$,X,J)}finally{await z.release().catch(()=>{})}}async function uG(Z,$,X,J){let z=(Y)=>({status:"completed",rowId:X.rowId,operation:J,placeholder:Y}),G=await E3(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!==g$(Z))return{status:"foreign-placeholder"};return await w1(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 m$(Z),await Z.onStep("after-record-clear"),{status:"restart"};if(G.kind!=="real"||G.fingerprint!==X.slotFingerprint)return await w1(Z,$),await Z.onStep("after-record-clear"),z("slot-moved-on");await Z.onStep("before-placeholder-write");let B=await Z.slot.get({path:{id:m1}}),Q=B===void 0||B===null?void 0:j2(B);if(Q?.kind!=="real"||Q.fingerprint!==X.slotFingerprint)return{status:"retry",reason:"slot-changed"};try{await Z.slot.set({path:{id:m1},body:{...T3,accountId:g$(Z)}})}catch(Y){if(Y instanceof v6)return{status:"retry",reason:"slot-changed"};throw Y}await Z.onStep("after-placeholder-write");let W=await Z.slot.get({path:{id:m1}});if(!O3(W))return{status:"retry",reason:"placeholder-overwritten"};if(jZ(W)&&W.accountId===void 0)return{status:"untagged-placeholder"};if(jZ(W)&&W.accountId!==g$(Z))return{status:"foreign-placeholder"};return await w1(Z,$),await Z.onStep("after-record-clear"),z("written")}async function dG(Z,$,X){let{record:J}=X;if(X.fresh)await pG(Z,J),await Z.onStep("after-record-write");if(await q2(Z,X.credential.refresh))return{status:"restart"};let z=await E3(Z);if(z.kind!=="real"||z.fingerprint!==J.slotFingerprint)return{status:"restart"};return await hG(Z,J,X.credential),await Z.onStep("after-row-write"),D2(Z,$,J,X.fresh?J.operation:"resumed")}async function D2(Z,$,X,J){let z=await vG(Z,X);if(!z)return{status:"retry",reason:"verify-failed"};if(await Z.onStep("after-verify"),X.carryLegacyMain)await mG(Z,z),await Z.onStep("after-carry-over");let G=await lG(Z,$,X,J);if(G.status==="untagged-placeholder"){await Z.store.disable(X.rowId,CG,{extraLocks:w6(Z.paths,X.rowId,Z.locks),attribution:{credentialEpoch:z.credentialEpoch,...z.identity!==void 0?{identity:z.identity}:{}}}),await w1(Z,$);let B=`${Z.paths.configPath}\x00${X.rowId}`;if(!H2.has(B))H2.add(B),Z.log.warn(`Interrupted account transfer has an untagged placeholder; its credential was preserved disabled. ${TG}`,{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:w6(Z.paths,X.rowId,Z.locks),protect:(B,Q)=>Q.row?.fingerprint!==X.credentialFingerprint?"the transfer row changed before rollback":void 0}),await m$(Z),await w$(Z),{status:"refused",reason:"placeholder-without-main"}}var W2=new Set,Y2=new Set,H2=new Set;function g$(Z){return`openai-auth-pool:${NG("sha256").update(LG(Z.paths.configPath)).digest("hex")}`}async function cG(Z){try{let $=await Z();return $.open?[]:$.blockers}catch($){return[{pid:"unknown",version:"unknown",detail:$ instanceof Error?$.message:String($)}]}}async function K2(Z,$,X){let J=SG(Z),z=J.slot.migrationDisabledReason?.();if(z){let Y=J.slot.path??h6();if(!Y2.has(Y))Y2.add(Y),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 p1(J.paths.configPath)}catch(Y){return{status:"error",reason:Y instanceof Error?Y.message:String(Y)}}let B=await F2(J,$,G);if(B){if(B.status==="already-migrated"&&"mainAccountId"in G)await w$(J);return B}if(X){let Y=await cG(X);if(Y.length>0){let U=`${J.paths.configPath}\x00${Y.map((V)=>`${V.pid}@${V.version}`).join(",")}`;if(!W2.has(U))W2.add(U),J.log.info("account pool migration deferred: an older openai-auth version is running",{blockers:Y});return{status:"deferred",reason:"older-version-running",blockers:Y}}}let Q,W;try{W=await A3(J,"pool-slot-transfer",J.slot.path??h6(),J.locks.mainRefreshTtlMs),Q=await A3(J,U2,J.paths.configPath,J.locks.mainRefreshTtlMs)}catch(Y){if(await W?.release().catch(()=>{}),Y instanceof S3)return{status:"retry",reason:"lock-contention"};throw Y}try{return await sG(J,$)}catch(Y){if(Y instanceof S3)return{status:"retry",reason:"lock-contention"};if(Y instanceof E)return{status:"retry",reason:Y.kind==="lock-contention"?"lock-contention":`store-${Y.kind}`};throw Y}finally{await Q?.release().catch(()=>{}),await W?.release().catch(()=>{})}}async function F2(Z,$,X){let J=MZ(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&&m6(await E3(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 sG(Z,$){let X;for(let J=0;J<4;J++){let z=await p1(Z.paths.configPath),G=await F2(Z,$,z);if(G){if(G.status==="already-migrated")await w$(Z);return G}let B=await Z.store.read(),Q=MZ(z);if(B.status==="pending-migration"){if(m6(await E3(Z),B.roster.some((V)=>jZ(V)&&V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};await Z.store.initialize(),await Z.onStep("after-pool-key-write"),B=await Z.store.read()}if(B.status!=="ready")return{status:"error",reason:B.status==="error"?`${B.file}: ${B.reason}`:"pool still pending migration"};let W=await yG(Z);if(W.kind==="retry")return{status:"retry",reason:"legacy-refresh-in-progress"};if(W.kind==="indeterminate")return{status:"retry",reason:"host-slot-indeterminate"};if(m6(W,B.rows.some((V)=>V.id==="main"),Q))return{status:"refused",reason:"placeholder-without-main"};let Y=xG($,Q,B.rows,W,X,Z.now(),Z.newId);if(Y.kind==="nothing"){if($==="migrate")await w1(Z,$),await Z.onStep("after-marker-write");return{status:"nothing-to-import",slot:Y.slot}}if(Y.kind==="drop-record"){await m$(Z),await Z.onStep("after-record-clear");continue}if(Y.kind==="ambiguous")return await w1(Z,$,{declinedSlotFingerprint:Y.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:Y.record.rowId}),{status:"ambiguous",rowId:Y.record.rowId};if(Y.kind==="transfer"&&Y.fresh)X=Y.record.rowId;let U=Y.kind==="finish"?await D2(Z,$,Y.record,"resumed"):await dG(Z,$,Y);if(U.status!=="restart")return U}return{status:"retry",reason:"unsettled"}}async function w$(Z){await R3(Z,($)=>{if(!("mainAccountId"in $))return!1;if(MZ($).pending)return!1;return delete $.mainAccountId,!0})}function Kj(Z){return K2(Z,"migrate",Z.fence)}function Fj(Z){return K2(Z,"adopt")}class N2 extends Error{constructor(){super("an older build holds a refresh lease on this token; not refreshing it here");this.name="LegacyMainRefreshInFlightError"}}function w6(Z,$,X={}){let J={...l6,...X},z={renew:J.renew,timeoutMs:J.timeoutMs,retryMs:J.retryMs,...J.renewIntervalMs!==void 0?{renewIntervalMs:J.renewIntervalMs}:{}};return[{name:C3,path:Z.configPath,ttlMs:J.mainRefreshTtlMs,...z},{name:j$($),path:Z.configPath,ttlMs:J.fallbackTtlMs,...z}]}async function Nj(Z,$,X,J={}){let z=Z.now??Date.now,G=Z.sleep??((W)=>new Promise((Y)=>setTimeout(Y,W))),B=Z.leaseWait??{timeoutMs:4000,pollMs:50},Q=async(W,Y)=>{let U=eZ(W.refresh),V=async()=>{let j=await K3(Z.paths),D=j?.refresh?.mainRefreshLeaseUntil;return Boolean(D&&D>z()&&j?.refresh?.mainRefreshLeaseTokenHash===U)};if(await V()){let j=z()+B.timeoutMs;while(z()<j&&await V())await G(B.pollMs);throw new N2}return X(W,Y)};return Z.store.refresh($,Q,{...J,extraLocks:w6(Z.paths,$,Z.legacyLocks)})}
157
+ export{l1 as ba,y3 as ca,_2 as da,O2 as ea,C2 as fa,S2 as ga,t1 as ha,GZ as ia,y5 as ja,f5 as ka,eZ as la,Z6 as ma,yZ as na,S1 as oa,W0 as pa,H0 as qa,d5 as ra,R1 as sa,E1 as ta,X6 as ua,s5 as va,J1 as wa,r5 as xa,o5 as ya,t5 as za,e5 as Aa,RW as Ba,bW as Ca,IW as Da,yW as Ea,E8 as Fa,h8 as Ga,v8 as Ha,m8 as Ia,U6 as Ja,QZ as Ka,Y3 as La,lY as Ma,H3 as Na,nY as Oa,cZ as Pa,NZ as Qa,QH as Ra,zJ as Sa,K3 as Ta,YH as Ua,FJ as Va,HH as Wa,O4 as Xa,C4 as Ya,UH as Za,Y1 as _a,VH as $a,jH as ab,qH as bb,PJ as cb,W1 as db,A4 as eb,R4 as fb,E4 as gb,DH as hb,IJ as ib,u as jb,_6 as kb,MH as lb,h4 as mb,wJ as nb,hH as ob,vH as pb,gH as qb,uJ as rb,O6 as sb,g4 as tb,D$ as ub,P$ as vb,_$ as wb,V1 as xb,O$ as yb,h1 as zb,C$ as Ab,M3 as Bb,qz as Cb,Nz as Db,Mz as Eb,I6 as Fb,Pz as Gb,L3 as Hb,Oz as Ib,pU as Jb,lU as Kb,uU as Lb,dU as Mb,cU as Nb,sU as Ob,BV as Pb,i7 as Qb,UV as Rb,VV as Sb,zG as Tb,jV as Ub,qV as Vb,DV as Wb,KV as Xb,eU as Yb,v1 as Zb,f$ as _b,nz as $b,JV as ac,HG as bc,sV as cc,_G as dc,T3 as ec,CG as fc,TG as gc,Vj as hc,jj as ic,RG as jc,qj as kc,MZ as lc,Dj as mc,Kj as nc,Fj as oc,w6 as pc,Nj as qc,C3 as rc,Z2 as sc,h6 as tc,z2 as uc,v6 as vc,Zj as wc};