@cortexkit/opencode-openai-auth 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/bin.js +8 -8
  2. package/dist/{codex-request-CjXETpTA.d.ts → codex-request-hw0XcldE.d.ts} +146 -29
  3. package/dist/index-1eq2s1cp.js +2 -0
  4. package/dist/{index-qp5hdpw8.js → index-1tdnrt68.js} +1 -1
  5. package/dist/index-5230x6s8.js +2 -0
  6. package/dist/{index-qxbchh2d.js → index-ag04nyv7.js} +7 -7
  7. package/dist/index-brbqqer5.js +90 -0
  8. package/dist/{index-xwvze96g.js → index-d98f1xdp.js} +1 -1
  9. package/dist/index-jcyrm58f.js +65 -0
  10. package/dist/{index-htvcmtcx.js → index-rsvnabbe.js} +2 -2
  11. package/dist/{index-ftkhhr6d.js → index-s88n2bjn.js} +1 -1
  12. package/dist/{index-bc89akak.js → index-t5m0dhmq.js} +1 -1
  13. package/dist/index-vy729a0b.js +69 -0
  14. package/dist/index-wgwze391.js +2 -0
  15. package/dist/{index-ffg0sgg5.js → index-yhw3hnsh.js} +2 -2
  16. package/dist/index.d.ts +11 -3
  17. package/dist/index.js +1 -1
  18. package/dist/{model-CQcw10oW.d.ts → model-DphbMQce.d.ts} +1 -1
  19. package/dist/{port-file-BDJnzgHH.d.ts → port-file-Cx-wwe5Q.d.ts} +1 -1
  20. package/dist/{protocol-C-kagE6O.d.ts → protocol-CDqdjh74.d.ts} +1 -1
  21. package/dist/rpc/port-file.d.ts +1 -1
  22. package/dist/rpc/port-file.js +1 -1
  23. package/dist/rpc/protocol.d.ts +1 -1
  24. package/dist/rpc/protocol.js +1 -1
  25. package/dist/rpc/rpc-client.d.ts +3 -3
  26. package/dist/rpc/rpc-client.js +1 -1
  27. package/dist/rpc/rpc-dir.js +1 -1
  28. package/dist/{sidebar-state-BfQ4mpZO.d.ts → sidebar-state-pTd9gg9W.d.ts} +71 -7
  29. package/dist/sidebar-state.d.ts +2 -2
  30. package/dist/sidebar-state.js +1 -1
  31. package/dist/{token-z6qq7a1d.js → token-0z5g59p8.js} +1 -1
  32. package/dist/token-util-jf9g6stk.js +1 -0
  33. package/dist/tui-preferences.js +1 -1
  34. package/dist/tui.d.ts +30 -3
  35. package/dist/v2/server.d.ts +2 -2
  36. package/dist/v2/server.js +2 -2
  37. package/package.json +6 -6
  38. package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +119 -6
  39. package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +294 -16
  40. package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +178 -26
  41. package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
  42. package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +100 -43
  43. package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +10 -2
  44. package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
  45. package/src/tui-compiled/raw/shared/42ae93ab554fcec2-open-url.js +7 -9
  46. package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -0
  47. package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +17 -3
  48. package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +253 -0
  49. package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +31 -6
  50. package/src/tui-compiled/raw/shared/94f53cfd572ba4bb-availability.js +106 -0
  51. package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +116 -12
  52. package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
  53. package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +348 -21
  54. package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +2 -2
  55. package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +5 -4
  56. package/src/tui-compiled/raw/shared/dc9290c2a7552ba6-watch.js +254 -0
  57. package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +5 -1
  58. package/src/tui-compiled/raw/sidebar-state.js +32 -3
  59. package/src/tui-compiled/raw/tui/v2-dialog.js +2 -1
  60. package/src/tui-compiled/raw/tui.tsx +170 -26
  61. package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +119 -6
  62. package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +294 -16
  63. package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +178 -26
  64. package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
  65. package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +100 -43
  66. package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +10 -2
  67. package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
  68. package/src/tui-compiled/runtime/shared/42ae93ab554fcec2-open-url.js +7 -9
  69. package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -0
  70. package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +17 -3
  71. package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +253 -0
  72. package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +31 -6
  73. package/src/tui-compiled/runtime/shared/94f53cfd572ba4bb-availability.js +106 -0
  74. package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +116 -12
  75. package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
  76. package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +348 -21
  77. package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +2 -2
  78. package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +5 -4
  79. package/src/tui-compiled/runtime/shared/dc9290c2a7552ba6-watch.js +254 -0
  80. package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +5 -1
  81. package/src/tui-compiled/runtime/sidebar-state.js +32 -3
  82. package/src/tui-compiled/runtime/tui/v2-dialog.js +2 -1
  83. package/src/tui-compiled/runtime/tui.js +350 -219
  84. package/dist/index-03em8hv1.js +0 -69
  85. package/dist/index-6n4pnfkg.js +0 -2
  86. package/dist/index-ehjj89rx.js +0 -2
  87. package/dist/index-f21addzm.js +0 -90
  88. package/dist/index-r2s51ac1.js +0 -2
  89. package/dist/index-rwbrhkse.js +0 -65
  90. package/dist/token-util-cf0nyh7n.js +0 -1
@@ -0,0 +1,2 @@
1
+ import{Ac as NZ,Bc as PZ,Dc as g,Ec as WZ,Fc as HZ,Ic as d,be as _Z,ee as TZ,ge as RZ}from"./index-brbqqer5.js";import{oe as XZ,se as VZ,te as YZ,ue as y,ve as x}from"./index-ag04nyv7.js";import{Me as OZ}from"./index-wgwze391.js";import{Ue as b,Ve as $Z,Ze as A,_e as JZ}from"./index-5230x6s8.js";import{createHash as cZ}from"node:crypto";import{constants as oZ,copyFileSync as aZ,mkdirSync as iZ,statSync as sZ}from"node:fs";import{readFile as nZ}from"node:fs/promises";import{homedir as eZ,tmpdir as tZ}from"node:os";import{dirname as Z0,join as h}from"node:path";import{chmod as dZ,mkdir as lZ}from"node:fs/promises";import{dirname as ZZ}from"node:path";function k(Z){let{path:$,defaultValue:V,normalize:J}=Z,X=Promise.resolve(),Y=(B)=>{if(B==="")return V;try{return J(JSON.parse(B))}catch{return V}},G=async()=>{try{if(b)await A(ZZ($),Z.secureDir??!0);return await JZ($,b)}catch(B){if(B.code==="ENOENT")return"";throw B}},z=async()=>{try{return Y(await G())}catch(B){if(B instanceof $Z)throw B;return V}},U=(B,D)=>{let N=X.then(B).then((P)=>D?.onResult?.(P));return X=N.catch(()=>{}),N},L={...x.sidebar,name:Z.lockName??x.sidebar.name,timeoutMs:Z.timeoutMs??x.sidebar.timeoutMs},j=async(B,D,N)=>{await XZ($,D,{serialize:JSON.stringify,beforeRename:async()=>{await N?.beforeCommit?.(),await B.assertOwned()}}),await N?.afterRename?.();try{return await B.assertOwned(),!0}catch(P){if(P instanceof YZ)return!1;throw P}},Q=async(B,D,N)=>{Z.logger?.warn("sidebar lock lost after rename; repairing write",{path:$});try{let P=await y($,L,async(W)=>{let H=B(await z(),D);if(H===void 0)return"skipped";return await j(W,H,N)?"written":"lost-again"});if(P==="lost-again")Z.logger?.warn("sidebar repair lost its lock after rename",{path:$});return{status:"lost-after-rename",repair:P}}catch(P){if(!(P instanceof VZ))throw P;return Z.logger?.warn("sidebar repair lock unavailable; repair skipped",{path:$}),{status:"lost-after-rename",repair:"lock-unavailable"}}},K=async(B,D)=>{let N=D,P=ZZ($),W=Z.secureDir??!0;if(b)await A(P,W);else if(await lZ(P,{recursive:!0,mode:448}),W)await dZ(P,448).catch((F)=>{Z.logger?.warn("sidebar directory permission remediation failed",{error:F instanceof Error?F.message:String(F)})});let H=await y($,L,async(F)=>{let s=async(C)=>({value:C,held:await j(F,C,N)});for(let C=0;C<3;C+=1){let e=await G(),t=B(Y(e));if(t===void 0)return;if(C===0)await N?.beforeRecheck?.();if(await G()!==e)continue;return await s(t)}let n=B(await z());return n===void 0?void 0:await s(n)});if(H===void 0)return{status:"skipped"};if(H.held)return{status:"written"};let i=D?.repair??Z.repair;if(!i)return Z.logger?.warn("sidebar lock lost after rename; write not repaired",{path:$}),{status:"lost-after-rename",repair:"none"};return await Q(i,H.value,N)};return{read:z,write:(B,D)=>U(()=>K(()=>B,D),D),update:(B,D)=>U(()=>K(B,D),D)}}function v0(Z){let $=Z?.credits;if($===null||typeof $!=="object")return;let{hasCredits:V,unlimited:J,balance:X}=$;if(typeof V!=="boolean"||typeof J!=="boolean")return;return WZ({hasCredits:V,unlimited:J,...typeof X==="number"?{balance:X}:{}})}function S0(Z,$=Date.now()){if(!xZ(Z,$))return!1;if(bZ(Z,$))return!1;return RZ(Z?.credits,$)}var l=["primary","secondary"],uZ={primary:300,secondary:10080};function rZ(Z,$){return NZ({scope:"all",label:$,windowMinutes:Z})}function f0(Z){if(!Z)return[];let $=[];for(let V of l){let J=Z[V];if(!J)continue;let X=J.windowMinutes,Y=X!==void 0&&Number.isFinite(X)&&X>0?X:uZ[V];$.push({key:V,label:rZ(X,V),window:J,windowMs:Y*60000})}return $}var M=OZ("sidebar"),$0="OPENCODE_OPENAI_AUTH_SIDEBAR_STATE_FILE";function CZ(){let Z=process.env.XDG_STATE_HOME||h(eZ(),".local","state");return h(Z,"cortexkit","openai-auth","sidebar-state.json")}var FZ=h(tZ(),"opencode-openai-auth","sidebar-state.json");function g0(Z){FZ=Z,m.clear()}var J0=/^[a-f0-9]{64}$/,u=604800000,MZ=256,EZ=3600000;function T(Z){return cZ("sha256").update(Z).digest("hex")}function X0(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function qZ(Z){let $=X0(Z);return $!==void 0?{resetCredits:$}:{}}function V0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.activeId!=="string"||typeof X.route!=="string"||typeof X.updatedAt!=="number"||!Number.isFinite(X.updatedAt))continue;$[V]={activeId:X.activeId,route:X.route,updatedAt:X.updatedAt}}return Object.keys($).length>0?$:void 0}function Y0(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return;let $={};for(let[V,J]of Object.entries(Z)){if(!J0.test(V)||J===null||typeof J!=="object"||Array.isArray(J))continue;let X=J;if(typeof X.accountId!=="string"||X.accountId.length===0||typeof X.assignedAt!=="number"||!Number.isFinite(X.assignedAt)||X.assignedAt<0||typeof X.lastSeenAt!=="number"||!Number.isFinite(X.lastSeenAt)||X.lastSeenAt<0||typeof X.inputBytes!=="number"||!Number.isFinite(X.inputBytes)||X.inputBytes<0)continue;let Y=X.quotaCheckedAt;if(Y!==void 0&&(typeof Y!=="number"||!Number.isFinite(Y)||Y<0))continue;let G=X.wireAccountId;$[V]={accountId:X.accountId,assignedAt:X.assignedAt,lastSeenAt:X.lastSeenAt,inputBytes:X.inputBytes,...Y===void 0?{}:{quotaCheckedAt:Y},...typeof G==="string"?{wireAccountId:G}:{}}}return Object.keys($).length>0?$:void 0}function O(){let Z=process.env[$0];if(Z)return Z;let $=CZ();if(!m.has($))m.add($),z0($,FZ);return $}var m=new Set;function z0(Z,$){try{iZ(Z0(Z),{recursive:!0,mode:448}),aZ($,Z,oZ.COPYFILE_EXCL)}catch{}}var q={main:{quota:null,killed:!1},fallbacks:[],activeId:void 0,route:"main",lastUpdated:0};function f(Z){if(Z===null||typeof Z!=="object"||Array.isArray(Z))return q;let $=Z,V=$.main,J;if(V!==null&&typeof V==="object"&&!Array.isArray(V)){let K=V;J={quota:"quota"in K?K.quota:null,killed:typeof K.killed==="boolean"?K.killed:!1,...typeof K.mainAccountId==="string"?{mainAccountId:K.mainAccountId}:{},...typeof K.quotaBackedOff==="boolean"?{quotaBackedOff:K.quotaBackedOff}:{},...typeof K.quotaBackoffUntil==="number"?{quotaBackoffUntil:K.quotaBackoffUntil}:{},...typeof K.refreshBackedOff==="boolean"?{refreshBackedOff:K.refreshBackedOff}:{},...typeof K.refreshBackoffUntil==="number"?{refreshBackoffUntil:K.refreshBackoffUntil}:{},...qZ(K.resetCredits)}}else J={quota:null,killed:!1};let X=zZ($.fallbacks),Y=Array.isArray($.vaultAccounts)?zZ($.vaultAccounts):void 0,G=typeof $.activeId==="string"?$.activeId:void 0,z=typeof $.route==="string"?$.route:q.route,U=typeof $.lastUpdated==="number"?$.lastUpdated:0,L=typeof $.planType==="string"?$.planType:void 0,j=V0($.activeRouting),Q=Y0($.stickyAssignments);return{main:J,fallbacks:X,activeId:G,route:z,lastUpdated:U,...j!==void 0?{activeRouting:j}:{},...Q!==void 0?{stickyAssignments:Q}:{},...L!==void 0?{planType:L}:{},...$.accountPool===!0?{accountPool:!0}:{},...Y!==void 0?{vaultAccounts:Y}:{}}}function zZ(Z){if(!Array.isArray(Z))return[];return Z.filter(($)=>$!==null&&typeof $==="object"&&!Array.isArray($)&&typeof $.id==="string").map(($)=>({id:$.id,...typeof $.credentialId==="string"?{credentialId:$.credentialId}:{},label:typeof $.label==="string"?$.label:void 0,...typeof $.accountId==="string"?{accountId:$.accountId}:{},quota:"quota"in $?$.quota:null,killed:typeof $.killed==="boolean"?$.killed:!1,enabled:typeof $.enabled==="boolean"?$.enabled:!0,...typeof $.routable==="boolean"?{routable:$.routable}:{},...["needs sign-in","turned off in vault","unavailable"].includes($.vaultState)?{vaultState:$.vaultState}:{},...qZ($.resetCredits)}))}function r(Z){return[...Z.fallbacks,...Z.vaultAccounts??[]]}async function G0(Z=O()){try{let $=await nZ(Z,"utf8");return f(JSON.parse($))}catch{return q}}var K0=3600000,GZ=128;function IZ(Z,$,V=Date.now()){if(!(Z.updatedAt>=V-K0&&Z.updatedAt<=V))return!1;if($===void 0)return!0;return Z.activeId==="main"||$.some((X)=>X.enabled!==!1&&X.routable!==!1&&X.killed!==!0&&X.id===Z.activeId)}function bZ(Z,$=Date.now()){let V=Z?.spendControl;if(V?.reached!==!0||typeof V.resetsAt!=="string")return;let J=Date.parse(V.resetsAt);if(!Number.isFinite(J)||J<=$)return;return{resetsAt:V.resetsAt,resetAtMs:J}}function xZ(Z,$=Date.now()){let V;for(let X of l){let Y=Z?.[X];if(typeof Y?.resetsAt!=="string"||!Number.isFinite(Y.usedPercent)||Y.usedPercent<100)continue;let G=Date.parse(Y.resetsAt);if(!Number.isFinite(G)||G<=$)continue;if(!V||G<V.resetAtMs)V={resetsAt:Y.resetsAt,resetAtMs:G}}let J=bZ(Z,$);if(J&&(!V||J.resetAtMs<V.resetAtMs))V=J;return V}function E(Z,$=Date.now()){return xZ(Z,$)!==void 0}function j0(Z,$,V=Date.now()){if(!$||Z.route!=="sticky-balanced")return;let J=Z.stickyAssignments?.[T($)];if(!J||J.lastSeenAt<V-u)return;if(J.accountId==="main"&&Z.vaultAccounts===void 0)return Z.main?.killed||E(Z.main?.quota,V)?void 0:"main";let X=r(Z).find((Y)=>Y.id===J.accountId);if(!X||X.enabled===!1||X.routable===!1||X.killed===!0||E(X.quota,V))return;return X.id}function d0(Z,$,V=Date.now()){if(!$){if(Z.vaultAccounts===void 0)return{activeId:Z.activeId??"main",route:Z.route};let j=Z.vaultAccounts.find((Q)=>Q.id===Z.activeId&&Q.enabled&&Q.routable!==!1&&!Q.killed);if(j&&!E(j.quota,V))return{activeId:j.id,route:Z.route}}let J=$?Z.activeRouting?.[$]:void 0,X=r(Z),Y=J?.activeId==="main"?Z.main.quota:X.find((j)=>j.id===J?.activeId)?.quota;if(J&&(Z.vaultAccounts===void 0||J.activeId.startsWith("vault:"))&&IZ(J,X,V)&&!E(Y,V))return{activeId:J.activeId,route:J.route};let G=j0(Z,$,V);if(G)return{activeId:G,route:Z.route};let z=Z.vaultAccounts!==void 0,U=(z?c(Z):Z.fallbacks).filter((j)=>j.enabled&&j.routable!==!1&&!j.killed),L=U.find((j)=>!E(j.quota,V))??U[0];return{activeId:z?L?.id??"vault":Z.route==="fallback-first"&&L?L.id:"main",route:Z.route}}function c(Z){let $=Z.vaultAccounts??[],V=new Map($.map((J)=>[J.id,J]));return d($.map((J)=>J.id),gZ(Z),_Z($)??"").flatMap((J)=>{let X=V.get(J);return X?[X]:[]})}function vZ(Z,$,V=Date.now(),J){if(!Z)return;let X=Object.entries(Z).filter(([G,z])=>G!==J&&IZ(z,$,V)),Y=X.length<=GZ?X:X.sort((G,z)=>z[1].updatedAt-G[1].updatedAt).slice(0,GZ);return Y.length>0?Object.fromEntries(Y):void 0}function I(Z,$,V=Date.now(),J){if(!Z)return;let X=0,Y=0,G=0,z=[];for(let[L,j]of Object.entries(Z)){if(L===J){G+=1;continue}if(j.lastSeenAt<V-u){Y+=1;continue}if($!==void 0&&!$.has(j.accountId)){X+=1;continue}z.push([L,j])}let U=X+Y+G;if(U>0)M.debug("pruned sticky assignments",{pid:process.pid,removed:U,reasons:{"account-not-in-roster":X,expired:Y,"explicit-removal":G}});return z.length>0?Object.fromEntries(z):void 0}function SZ(Z,$){let V=Object.keys(Z).length-MZ;if(V<=0)return Z;let J=new Set(Object.entries(Z).filter(([X])=>X!==$).sort(([X,Y],[G,z])=>Y.lastSeenAt-z.lastSeenAt||X.localeCompare(G)).slice(0,V).map(([X])=>X));return Object.fromEntries(Object.entries(Z).filter(([X])=>!J.has(X)))}function fZ(Z,$){if(Z===$)return!0;if(!Z||!$)return!1;let V=Object.entries(Z);if(V.length!==Object.keys($).length)return!1;return V.every(([J,X])=>Object.is($[J],X))}function AZ(Z,$,V,J){return Z!==void 0&&$.has(Z.accountId)&&!V.has(Z.accountId)&&Z.lastSeenAt>=J-u}function yZ(Z,$,V,J){return $>Z.inputBytes||V-Z.lastSeenAt>=EZ||Z.wireAccountId===void 0&&J!==void 0}function kZ(Z,$){return typeof Z.wireAccountId==="string"&&typeof $==="string"&&Z.wireAccountId!==$}function L0(Z){let $=new Map(Z),V={get size(){return $.size},has:(J)=>$.has(J),get:(J)=>$.get(J),entries:()=>$.entries(),keys:()=>$.keys(),values:()=>$.values(),forEach:(J,X)=>{$.forEach((Y,G)=>{J.call(X,Y,G,V)})},[Symbol.iterator]:()=>$[Symbol.iterator]()};return Object.freeze(V)}function B0(Z,$,V){let J=new Map;for(let[X,Y]of Object.entries(Z??{})){if(X===V)continue;if(Y.quotaCheckedAt!==$[Y.accountId])continue;J.set(Y.accountId,(J.get(Y.accountId)??0)+Y.inputBytes)}return L0(J)}function o(Z){if(Z===void 0)return;return new Set(["main",...Z.filter(($)=>$.enabled!==!1&&$.killed!==!0).map(($)=>$.id)])}var p=Promise.resolve();function _(Z){let $=p.then(Z);return p=$.catch(()=>{}),$}var KZ=new Map;function a(Z){let $=KZ.get(Z);if(!$)$=k({path:Z,defaultValue:q,normalize:f,secureDir:Z===CZ(),logger:M}),KZ.set(Z,$);return $}var w=new Set;async function wZ(Z,$){try{await $}catch(V){let J={pid:process.pid,error:V instanceof Error?V.message:String(V)};if(w.has(Z))M.debug("sidebar write failed again",J);else w.add(Z),M.warn("sidebar write failed",J);throw V}if(w.delete(Z))M.info("sidebar write recovered",{pid:process.pid})}function l0(Z,$=O()){return _(()=>wZ($,a($).write(f(Z))))}function U0(Z){return a(Z).read()}function R(Z,$,V){let J=Symbol("sidebar authority changed");return wZ(Z,a(Z).update((X)=>{if(V?.canWrite&&!V.canWrite())return;let Y=$(X);if(Y===void 0)return;if(Y.vaultAccounts!==void 0)Y.activeId=Y.activeId?.startsWith("vault:")?Y.activeId:void 0,Y.activeRouting=Object.fromEntries(Object.entries(Y.activeRouting??{}).filter(([,G])=>G.activeId.startsWith("vault:"))),Y.stickyAssignments=Object.fromEntries(Object.entries(Y.stickyAssignments??{}).filter(([,G])=>G.accountId.startsWith("vault:")&&!Y.vaultAccounts?.some((z)=>z.id===G.accountId&&z.killed)));return f(Y)},{beforeRecheck:async(...X)=>{if(await V?.beforeRecheck?.(...X),V?.canWrite&&!V.canWrite())throw J}}).catch((X)=>{if(X!==J)throw X}))}function v(Z){let $;for(let V of[Z?.primary?.checkedAt,Z?.secondary?.checkedAt,Z?.checkedAt])if(typeof V==="number"&&Number.isFinite(V))$=$===void 0?V:Math.max($,V);return $}function jZ(Z,$){let V=v(Z),J=v($);if(J!==void 0&&(V===void 0||J>V))return $;return Z}function LZ(Z,$){return Z!==void 0&&$!==void 0&&Z===$}function S(Z,$){let V=Z?.checkedAt;if(typeof V==="number"&&Number.isFinite(V))return V;if(typeof $==="number"&&Number.isFinite($))return $;return}function BZ(Z,$,V,J,X){if(Z&&$){let Y=S(Z,J),G=S($,X);if(G!==void 0&&(Y===void 0||G>Y))return $;return Z}return V?$:Z}function UZ(Z,$){if(Z.spendControl!==void 0)return Z.spendControl;if(Z.spendControlCleared===!0)return;return $.spendControl}function Q0(Z,$){if(!Z||!$)return Z??$;let V=(J)=>typeof J.checkedAt==="number"&&Number.isFinite(J.checkedAt)?J.checkedAt:Number.NEGATIVE_INFINITY;return V($)>V(Z)?$:Z}function QZ(Z,$){if(!Z)return $;if(!$)return Z;let V=v(Z),J=v($),X=J!==void 0&&(V===void 0||J>V),Y=BZ(Z.primary,$.primary,X,Z.checkedAt,$.checkedAt),G=BZ(Z.secondary,$.secondary,X,Z.checkedAt,$.checkedAt),z=X?UZ($,Z):UZ(Z,$),U=z===void 0&&(Z.spendControlCleared===!0||$.spendControlCleared===!0),L=Q0(Z.credits,$.credits),j;for(let N of[S(Y),S(G)])if(N!==void 0)j=j===void 0?N:Math.max(j,N);let{spendControl:Q,spendControlCleared:K,credits:B,...D}=Z;return{...D,primary:Y,secondary:G,...z!==void 0?{spendControl:z}:{},...U?{spendControlCleared:!0}:{},...L!==void 0?{credits:L}:{},checkedAt:j??Z.checkedAt}}function u0(Z,$=O(),V){return _(async()=>{await R($,(J)=>{let X=new Map(J.fallbacks.map((j)=>[j.id,j])),Y=Z.vaultAccounts!==void 0,G=LZ(Z.main.mainAccountId,J.main.mainAccountId),z=G?QZ(Z.main.quota,J.main.quota):jZ(Z.main.quota,J.main.quota),U=Date.now(),L=I(J.stickyAssignments,Y?void 0:o(r(Z)),U);return{...J,...Z,main:Y?Z.main:{...Z.main,quota:z,mainAccountId:G?Z.main.mainAccountId:z===J.main.quota&&z!==Z.main.quota?J.main.mainAccountId:Z.main.mainAccountId},fallbacks:Y?Z.fallbacks:Z.fallbacks.map((j)=>{let Q=X.get(j.id),K=LZ(j.accountId,Q?.accountId),B=K?QZ(j.quota,Q?.quota??null):jZ(j.quota,Q?.quota??null);return{...j,quota:B,accountId:K?j.accountId:B===Q?.quota&&B!==j.quota?Q?.accountId:j.accountId}}),activeId:J.activeId,activeRouting:J.activeRouting,stickyAssignments:L,lastUpdated:Math.max(U,J.lastUpdated+1),accountPool:Z.accountPool===!0?!0:void 0,vaultAccounts:Z.vaultAccounts}},V)})}function r0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=vZ({...X.activeRouting,[Z.sessionId]:{activeId:Z.activeId,route:Z.route,updatedAt:Z.updatedAt}},$,Date.now()),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Date.now());return{...X,activeId:Z.activeId,route:Z.route,activeRouting:Y,stickyAssignments:G,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function c0(Z,$=O(),V){return _(async()=>{await R($,(J)=>({...J,activeId:Z.activeId,route:Z.route,lastUpdated:Math.max(Date.now(),J.lastUpdated+1)}),V)})}function o0(Z,$,V=O(),J){return _(async()=>{await R(V,(X)=>{let Y=Date.now(),G=vZ(X.activeRouting,$,Y,Z),z=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:o($),Y,T(Z));return{...X,activeRouting:G,stickyAssignments:z,lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}},J)})}function hZ(Z,$){return AZ(Z,new Set($.validPinnedAccountIds),new Set($.excludeAccountIds),$.now)&&!kZ(Z,$.wireAccountIdByAccount?.[Z.accountId])&&!yZ(Z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[Z.accountId])}function mZ(Z,$){let V=T($.sessionId),J=new Set($.validPinnedAccountIds),X=new Set($.excludeAccountIds),Y=I(Z.stickyAssignments,J,$.now),G=!fZ(Z.stickyAssignments,Y),z=Y?.[V],U=z!==void 0&&kZ(z,$.wireAccountIdByAccount?.[z.accountId]);if(AZ(z,J,X,$.now)&&!U){let Q=yZ(z,$.requestBytes,$.now,$.wireAccountIdByAccount?.[z.accountId]),K=Q?{...z,inputBytes:Math.max(z.inputBytes,$.requestBytes),...z.wireAccountId===void 0&&$.wireAccountIdByAccount?.[z.accountId]!==void 0?{wireAccountId:$.wireAccountIdByAccount?.[z.accountId]}:{},...$.now-z.lastSeenAt>=EZ?{lastSeenAt:$.now}:{}}:z;if(!G&&!Q)return{assignment:K,next:void 0};return{assignment:K,next:{...Z,stickyAssignments:{...Y,[V]:K},lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let L=$.choose(B0(Y,$.quotaCheckedAtByAccount,U?V:void 0));if(!L){if(!G)return{assignment:void 0,next:void 0};return{assignment:void 0,next:{...Z,stickyAssignments:Y,lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}let j={accountId:L.accountId,assignedAt:$.now,lastSeenAt:$.now,inputBytes:$.requestBytes,...L.quotaCheckedAt===void 0?{}:{quotaCheckedAt:L.quotaCheckedAt},...$.wireAccountIdByAccount?.[L.accountId]===void 0?{}:{wireAccountId:$.wireAccountIdByAccount?.[L.accountId]}};return{assignment:j,next:{...Z,stickyAssignments:SZ({...Y,[V]:j},V),lastUpdated:Math.max($.now,Z.lastUpdated+1)}}}async function a0(Z,$=O(),V){let J=T(Z.sessionId),X=(await U0($)).stickyAssignments?.[J];if(hZ(X,Z))return X;let Y;return await _(async()=>{await R($,(G)=>{let z=mZ(G,Z);return Y=z.assignment,z.next},V)}),Y}function i0(Z,$){let V=Z.stickyAssignments?.[T($.sessionId)];if(hZ(V,$))return{assignment:V,next:void 0};return mZ(Z,$)}function s0(Z,$=O()){let V=T(Z.sessionId),J=new Set(Z.validPinnedAccountIds);return _(async()=>{await R($,(X)=>{let Y=Date.now(),G=I(X.stickyAssignments,X.vaultAccounts!==void 0?void 0:J,Y),z=G?.[V];if(z&&z.assignedAt>Z.assignment.assignedAt){if(fZ(X.stickyAssignments,G))return;return{...X,stickyAssignments:G,lastUpdated:Math.max(Y,X.lastUpdated+1)}}let L=z!==void 0&&z.accountId===Z.assignment.accountId&&z.assignedAt===Z.assignment.assignedAt?{...Z.assignment,inputBytes:Math.max(z.inputBytes,Z.assignment.inputBytes),lastSeenAt:Math.max(z.lastSeenAt,Z.assignment.lastSeenAt)}:Z.assignment;return{...X,stickyAssignments:SZ({...G,[V]:L},V),lastUpdated:Math.max(Y,X.lastUpdated+1)}})})}async function n0(Z,$=O()){let V=T(Z),J=!1;return await _(async()=>{await R($,(X)=>{let Y=X.stickyAssignments;if(Y?.[V]===void 0){J=!1;return}J=!0;let{[V]:G,...z}=Y;return{...X,...Object.keys(z).length>0?{stickyAssignments:z}:{stickyAssignments:void 0},lastUpdated:Math.max(Date.now(),X.lastUpdated+1)}})}),J}function e0(){return p}var D0=500;function N0(Z,$,V){return new Promise((J,X)=>{let Y=setTimeout(()=>J(V()),$);Y.unref?.(),Z.then((G)=>{clearTimeout(Y),J(G)},(G)=>{clearTimeout(Y),X(G)})})}function t0(Z,$={}){let V=$.readBudgetMs??D0,J,X,Y=()=>{try{let z=sZ(Z);return`${z.ino}:${z.size}:${z.mtimeMs}`}catch{return}},G=(z)=>{if(X&&X.key===z)return X.promise;let U=Date.now(),L=G0(Z).then((K)=>{if(!J||J.readAt<=U)J={state:K,readAt:U,key:z};return{state:K,readAt:U}}),j={key:z,promise:L};X=j;let Q=()=>{if(X===j)X=void 0};return L.then(Q,Q),L};return{get(){let z=Y();if(J&&J.key===z)return Promise.resolve({state:J.state,readAt:J.readAt});return N0(G(z),V,()=>J?{state:J.state,readAt:J.readAt}:{state:q,readAt:0})},read(){return G(Y())},refreshInBackground(){let z=Y();if(J?.key===z)return;G(z)}}}function Z1(Z,$,V){let J={assignment:V};Z.delete($),Z.set($,J);while(Z.size>MZ){let X=Z.keys().next().value;if(X===void 0)break;Z.delete(X)}return J}function $1(Z,$){if($.size===0)return Z.state;let V={...Z.state.stickyAssignments},J=!1;for(let[X,Y]of $){if(Y.persistedAt!==void 0&&Z.readAt>Y.persistedAt){$.delete(X);continue}V[X]=Y.assignment,J=!0}if(!J)return Z.state;return{...Z.state,stickyAssignments:V}}function J1(Z){let $=Z.retryDelayMs??500,V=Z.maxRetryDelayMs??30000,J=new Map,X=new Map,Y=new Set,G=0,z=$,U,L=!1,j=()=>{if(U||L||X.size===0)return;U=setTimeout(()=>{U=void 0;let K=[...X];X.clear(),z=Math.min(z*2,V);for(let[B,D]of K){let N=J.get(B);if(N!==void 0)Q(B,D.label,D.write,N)}},z),U.unref?.()},Q=(K,B,D,N)=>{let P;try{P=D()}catch(W){P=Promise.reject(W)}P.then(()=>{if(J.get(K)!==N)return;if(J.delete(K),Y.delete(K))Z.logger.info("sidebar bookkeeping write recovered",{pid:process.pid,write:B});if(Y.size===0)z=$;Z.onWritten?.()},(W)=>{if(J.get(K)!==N)return;let H={pid:process.pid,write:B,error:W instanceof Error?W.message:String(W)};if(L){J.delete(K),Z.logger.debug("sidebar bookkeeping write dropped",H);return}if(Y.has(K))Z.logger.debug("sidebar bookkeeping write failed again",H);else Y.add(K),Z.logger.warn("sidebar bookkeeping write failed; retrying in the background",H);X.set(K,{label:B,write:D}),j()})};return{enqueue(K,B,D){G+=1,J.set(K,G),X.delete(K),Q(K,B,D,G)},cancel(K){J.delete(K),X.delete(K),Y.delete(K)},stop(){if(L=!0,U)clearTimeout(U);U=void 0,X.clear()}}}function P0(Z){let $=Z.activeId;if(Z.vaultAccounts!==void 0){let V=c(Z).filter((X)=>X.enabled&&X.routable!==!1),J=V.find((X)=>X.id===$)??V[0];return J?{id:J.id,name:J.label??J.id,quota:J.quota,killed:J.killed}:{id:"vault",name:"vault",quota:null,killed:!1}}if($&&$!=="main"){let V=Z.fallbacks.find((J)=>J.enabled&&J.id===$);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,killed:V.killed}}return{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed}}function pZ(Z,$=Date.now()){if(!Z)return;return HZ({limits:l.flatMap((V)=>{let J=Z[V];return J?[{kind:"reading",scope:"all",label:V,usedPercent:J.usedPercent,checkedAt:J.checkedAt??Z.checkedAt??$,windowMinutes:J.windowMinutes,resetsAt:J.resetsAt}]:[]}),...Z.spendControl?{budget:{...Z.spendControl,kind:"reading",checkedAt:Z.checkedAt??$}}:{}})}function X1(Z,$=Date.now()){let V=Z?.primary?.usedPercent??null,J=Z?.secondary?.usedPercent??null,X=pZ(Z,$);return{primaryUsedPercent:V,secondaryUsedPercent:J,text:!X||X.limits.length===0&&!X.budget?null:g(X,{now:$,form:"compact"})}}function gZ(Z){return Z.route==="sticky-balanced"?"roster":TZ(Z.route)}function V1(Z,$={}){let V=$.now??Date.now(),J=P0(Z).id;return(Z.vaultAccounts!==void 0?c(Z).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed})):W0(Z,J,$.showFallbacks??!0)).map((Y)=>{let G=pZ(Y.quota,V),z=G&&(G.limits.length>0||G.budget)?G:void 0;return{id:Y.id,name:Y.name,killed:Y.killed,active:Y.id===J,stale:z?PZ(z,{now:V}):!1,text:z?g(z,{now:V,form:"narrow"}):null}})}function W0(Z,$,V){let J=[{id:"main",name:"main",quota:Z.main.quota,killed:Z.main.killed},...Z.fallbacks.filter((Y)=>Y.enabled&&(V||Y.id===$)).map((Y)=>({id:Y.id,name:Y.label??Y.id,quota:Y.quota,killed:Y.killed}))],X=new Map(J.map((Y)=>[Y.id,Y]));return d(J.map((Y)=>Y.id),gZ(Z),"main").flatMap((Y)=>{let G=X.get(Y);return G?[G]:[]})}function DZ(Z){let $=globalThis.Bun;return $?.stringWidth?$.stringWidth(Z):Array.from(Z).length}function Y1(Z,$){if(DZ(Z)<=$)return Z;if($<1)return"";let V="",J=0;for(let X of Z){let Y=DZ(X);if(J+Y>$-1)break;V+=X,J+=Y}return`${V}…`}var H0=300000,O0=0.01,_0=1;function z1(Z,$,V){if(!Z.resetsAt)return null;let J=new Date(Z.resetsAt).getTime();if(!Number.isFinite(J))return null;let X=J-$,Y=V-X;if(Y<H0)return null;if(Y<$*O0)return null;if(Y>=$)return null;let G=Z.usedPercent,z=Math.min(Math.max(Y/$*100,0),100),U=G-z,L=Math.abs(U)<_0?"on-pace":U>0?"deficit":"reserve",j=null;if(G>0){let Q=Y*100/G,K=X+Q;if(K<J)j=new Date(K).toISOString()}return{pacePercent:z,deltaPercent:U,state:L,runsOutAt:j}}
2
+ export{v0 as Fb,S0 as Gb,rZ as Hb,f0 as Ib,g0 as Jb,u as Kb,MZ as Lb,T as Mb,O as Nb,q as Ob,f as Pb,G0 as Qb,K0 as Rb,GZ as Sb,IZ as Tb,bZ as Ub,xZ as Vb,E as Wb,j0 as Xb,d0 as Yb,vZ as Zb,I as _b,l0 as $b,u0 as ac,r0 as bc,c0 as cc,o0 as dc,mZ as ec,a0 as fc,i0 as gc,s0 as hc,n0 as ic,e0 as jc,D0 as kc,N0 as lc,t0 as mc,Z1 as nc,$1 as oc,J1 as pc,P0 as qc,pZ as rc,X1 as sc,V1 as tc,DZ as uc,Y1 as vc,z1 as wc};
@@ -1,3 +1,3 @@
1
- import{Bb as X,Db as V}from"./index-03em8hv1.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
1
+ import{Bb as X,Db as V}from"./index-vy729a0b.js";import{randomUUID as Z}from"node:crypto";import{chmod as $,mkdir as G,readFile as H,rename as L,rm as T,stat as f,writeFile as g}from"node:fs/promises";import{dirname as k,resolve as w}from"node:path";var x="(no OpenCode 1 logins on this machine)";function C(b=process.env){return X(b)}async function Q(b){let z;try{z=await H(b,"utf8")}catch(q){if(q.code==="ENOENT")return;throw q}let j=JSON.parse(z);if(!j||typeof j!=="object"||Array.isArray(j))throw Error(`${b} does not hold a JSON object`);return j}function R(b){return b===void 0?void 0:JSON.stringify(b)}async function D(b){try{return(await f(b)).mode&511}catch(z){if(z.code==="ENOENT")return;throw z}}function _(b=C()){let z=new Map;return{path:w(b),async get(j){let q=(await Q(b))?.[j.path.id];return z.set(j.path.id,R(q)),q},async set(j){let q=j.path.id,W=await D(b),J=await Q(b)??{};if(!z.has(q)||z.get(q)!==R(J[q]))throw new V;J[q]=j.body,await G(k(b),{recursive:!0});let B=`${b}.${Z()}.tmp`;try{await g(B,`${JSON.stringify(J,null,2)}
2
2
  `,{mode:W??384}),await $(B,W??384),await L(B,b)}catch(Y){throw await T(B,{force:!0}).catch(()=>{}),Y}return z.set(q,R(j.body)),!0},async all(){let j=await Q(b);if(!j||Object.keys(j).length===0)return{[x]:!0};return j}}}
3
3
  export{_ as c};
@@ -0,0 +1,2 @@
1
+ import{jf as E}from"./index-d98f1xdp.js";import{randomUUID as k}from"node:crypto";import{lstat as S,readFile as O,rename as F,unlink as C}from"node:fs/promises";import{dirname as V,resolve as M}from"node:path";var b=process.platform==="win32",N=new Set;function T(j){if(j?.reason==="io-error"){if(j.win32Code===2||j.win32Code===3)return"ENOENT";if(j.win32Code===80||j.win32Code===183)return"EEXIST"}return j?.code??"ERR_PRIVATE_FILE"}var B;function $(){return B??=import("@cortexkit/private-files"),B}class R extends Error{path;stage;code;win32Code;reason;published=!1;durabilityConfirmed=!1;fileDurable=!1;attempts=0;elapsedMs=0;orphanPath;constructor(j,G,A){let z=A;super(`Private file refused at ${G}: ${j} (${z?.reason??z?.code??"io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`,{cause:A});this.path=j,this.stage=G,this.name="PrivateFileError",this.code=T(z),this.win32Code=z?.win32Code,this.reason=z?.reason}}async function q(j,G,A){try{return await A()}catch(z){if(z instanceof R)throw z;throw new R(j,G,z)}}var g;async function Z(j,G){j=M(j),G??=g,await q(j,"safe-parent",async()=>{let A=await(await $()).verifySafeParent(j,G);if(A.ok===!1){if(A.reason==="io-error"||A.reason==="wrong-kind")await S(j);throw new R(A.level??A.path,"safe-parent",{...A,code:"ERR_PRIVATE_FILES_SECURITY"})}})}async function U(j,G,A=!1){if(j=M(j),G==="directory")return Z(j);await q(j,"verify",async()=>{let z=await $(),K=await z.verifyOwnerOnly(j),H=!1;if(!K.ok){let{reason:L}=K.refusal;if(L==="io-error")await z.verifyPrivatePath(j,G);if(A&&[z.EXTRA_ACE,z.NOT_PROTECTED,z.NULL_DACL,z.EMPTY_DACL].includes(L))await Z(V(j)),await z.securePrivatePath(j,G),H=!0;else throw Object.assign(Error("Owner-only verification refused"),{reason:L,code:"ERR_PRIVATE_FILES_SECURITY"})}if(await z.verifyPrivatePath(j,G),H&&!N.has(j))N.add(j),process.emitWarning(`Private permissions tightened: ${j}. This object may have been readable before; rotate credentials if needed.`,"PrivateFileMigration")})}async function w(j,G=!1,A){j=M(j),await q(j,"directory",async()=>{let z=await $();try{return await S(j),await Z(j,A)}catch(H){if(T(H)!=="ENOENT")throw H}let K=V(j);if(K===j)throw Object.assign(Error("Missing root"),{code:"ENOENT"});await w(K,!1,A);try{await z.createOwnerOnly(j,{kind:"dir"})}catch(H){if(T(H)!=="EEXIST")throw H}await Z(j,A)})}async function d(j,G=!1){if(!b)return O(j,"utf8");return(await P(j,G)).toString("utf8")}async function P(j,G=!1){if(!b)return O(j);if(j=M(j),G)await Z(V(j)),await U(j,"file",!0);return q(j,"read",async()=>(await $()).readOwnerOnly(j))}async function f(j,G){await Z(V(M(j))),await q(j,"create",async()=>{await(await $()).createPrivateFile(M(j),G)})}async function l(j){await Z(V(M(j))),await q(j,"directory-create",async()=>{await(await $()).createOwnerOnly(M(j),{kind:"dir"})})}async function y(j,G,A={}){j=M(j),G=M(G);let z=A.now??(()=>performance.now()),K=z(),H=A.deadline??1/0,L,_=[0,10,20,40,80,100],x,J=0;for(let W of _){let I=Math.min(L??1/0,H);if(z()>=I)break;if(W)await(A.sleep??((X)=>new Promise((Y)=>setTimeout(Y,X))))(Math.min(W,Math.max(0,I-z())));if(z()>=I)break;let D=z();if(await A.beforeRename?.(),L!==void 0)L+=z()-D;if(z()>=H)break;J++;try{return await(A.rename??F)(j,G),{attempts:J,elapsedMs:z()-K}}catch(X){x??=X;let Y=X;if(!(Y.win32Code!==void 0?Y.win32Code===32||Y.win32Code===33:["EBUSY","EPERM","EACCES"].includes(Y.code??"")&&!Y.reason))break;L??=z()+500}}let Q=new R(G,"rename",x??Object.assign(Error("Publication deadline expired"),{code:"ETIMEDOUT"}));throw Q.attempts=J,Q.elapsedMs=z()-K,Q}async function n(j,G,A={}){j=M(j),await w(V(j));try{await U(j,"file",!0)}catch(J){if(J.code!=="ENOENT")throw J}let z=M(A.stagePath??`${j}.${k()}.tmp`);if(V(z)!==V(j))throw new R(j,"stage-directory",{code:"EXDEV"});let K=!1,H=!1,L={attempts:0,elapsedMs:0},_="stage-create",x=(J)=>{try{A.onOutcome?.({path:j,stage:J?.stage??"published",published:H,fileDurable:H,durabilityConfirmed:!1,attempts:J?.attempts??L.attempts,elapsedMs:J?.elapsedMs??L.elapsedMs,...J&&{code:J.code,win32Code:J.win32Code}})}catch{}};try{if(await f(z,G),K=!0,_="before-rename",L=await y(z,j,A),K=!1,H=!0,_="published-callback",A.onRenamed?.(),_="published-verify",await U(j,"file"),A.durable&&A.durability!=="file-only-on-windows")throw new R(j,"directory-sync-unsupported",{code:"ENOTSUP"});x()}catch(J){let Q=J instanceof R?J:new R(j,_,J);if(Q.published=H,Q.fileDurable=H,H)Object.assign(Q,L);if(K){try{await C(z)}catch{Q.orphanPath=z}K=!1}throw x(Q),Q}finally{if(K)await C(z).catch(()=>{})}}
2
+ export{b as Ue,R as Ve,q as We,Z as Xe,U as Ye,w as Ze,d as _e,f as $e,l as af,y as bf,n as cf};
@@ -1,8 +1,8 @@
1
- import{Pe as H,Qe as q,Re as V0,Te as x,Ue as h,Ve as S,We as v,Xe as _0,Ze as b}from"./index-r2s51ac1.js";import{randomUUID as I}from"node:crypto";import{mkdir as H0,open as B0,readFile as Q0,rename as W0,rm as L,stat as Y0}from"node:fs/promises";import{dirname as P,join as Z0}from"node:path";function N0($,G){return`${$}.${G}.lock`}class G0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class R extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function A0($,G,Q){let Y=performance.now();for(;;){let Z=await K0({path:$,name:G.name,ttlMs:G.ttlMs,renew:G.renew??!1,...G.onStep?{onStep:G.onStep}:{},...G.onRenewalTimer?{onRenewalTimer:G.onRenewalTimer}:{}});if(Z)try{return await Q(Z)}finally{await Z.release()}let J=G.timeoutMs-(performance.now()-Y);if(J<=0)throw new G0({target:$,name:G.name,timeoutMs:G.timeoutMs});await new Promise((_)=>setTimeout(_,Math.min(25,Math.ceil(J))))}}async function J0($,G){let Q=await B0($,"wx",384);try{await Q.writeFile(G,"utf8")}finally{await Q.close()}}var D0=globalThis.setTimeout.bind(globalThis),U0=globalThis.clearTimeout.bind(globalThis);function q0($){let G=$?.code;return G==="ENOENT"||!H&&(G==="EINVAL"||G==="ENOTDIR")}function K0($){return x0({...$,now:Date.now})}async function x0($){let G=N0($.path,$.name),Q=Z0(G,"owner.json"),Y=I(),Z=$.now??Date.now,J=null,_=!1,D=!1,B,l,j0=new Promise((z)=>{l=z});function p(z){try{let K=$.onRenewalTimer?.(z);if(K&&(typeof K==="object"||typeof K==="function")&&"then"in K&&typeof K.then==="function")Promise.resolve(K).catch(()=>{})}catch{}}function d(){if(!J)return;U0(J),J=null,p("cancelled")}function C(z,K){if(B||_)return;B=Object.freeze({reason:z,expectedOwnerId:Y,...typeof K?.ownerId==="string"?{observedOwnerId:K.ownerId}:{},...typeof K?.expiresAt==="number"?{observedExpiresAt:K.expiresAt}:{}}),d(),l(B)}let E,M=null,g=`${G}.evicting`,f=Z0(g,"owner.json"),a=I(),C0=5000,y=8;async function j(){if(H)try{return JSON.parse(await S(G,!0))}catch(z){if(z.code!=="EISDIR"&&z.reason!=="wrong-kind")throw z;return await x(G,"directory",!0),JSON.parse(await S(Q,!0))}try{return JSON.parse(await Q0(G,"utf8"))}catch(z){if(z.code!=="EISDIR")throw z;return JSON.parse(await Q0(Q,"utf8"))}}async function g0(){if(H){let W=await j(),V=Number(W?.expiresAt)-Z();await b(G,`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
2
- `,{deadline:performance.now()+Math.max(0,V),beforeRename:async()=>{let T=await j();if(T?.ownerId!==Y||!(Number(T?.expiresAt)>Z())||!await X())throw new R({target:$.path,name:$.name})}});return}let z=`${G}.${I()}.tmp`,K,N=!1;try{K=await B0(z,"wx",384),N=!0,await K.writeFile(`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
3
- `,"utf8"),await K.chmod(384),await K.close(),K=void 0;let W=await j();if(W?.ownerId!==Y||!(Number(W?.expiresAt)>Z())||!await X())throw new R({target:$.path,name:$.name});await W0(z,G),N=!1}finally{if(await K?.close().catch(()=>{}),N)await L(z,{force:!0}).catch(()=>{})}}async function s(){let z=`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
4
- `;if(H)await v(G,z);else await J0(G,z)}async function n(z){let K=z.code;if(K==="EEXIST"){if(H)await j();return!0}if(K==="EISDIR"){if(H)await x(G,"directory",!0),await S(Q,!0);return!0}return!1}async function k(){if(H)await h(P(G));try{return await s(),!0}catch(z){let K=z.code;if(await n(z))return!1;if(K==="ENOENT"){if(H)await h(P(G));else await H0(P(G),{recursive:!0});try{return await s(),!0}catch(N){if(await n(N))return!1;throw N}}throw z}}async function O(){await new Promise((z)=>setTimeout(z,Math.floor(Math.random()*4)))}async function m(z=!0){if(z&&$.onStep)await $.onStep("lock-read-ready");let K;try{K=await j()}catch(W){if(H&&W.code!=="ENOENT")throw W}let N=Number(K?.expiresAt);if(Number.isFinite(N)&&N>Z())return{status:"live"};if(typeof K?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:K.ownerId,expiresAt:N}};try{let W=await Y0(G),V=Number.isFinite(N)?N:W.mtimeMs+$.ttlMs;if(V>Z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:W.dev,ino:W.ino,mtimeMs:W.mtimeMs,expiresAt:V}}}catch(W){if(W.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw W}}function i(z,K){if(K.status!=="stale")return!1;let N=K.identity;if(z.kind==="owner"&&N.kind==="owner")return z.ownerId===N.ownerId&&z.expiresAt===N.expiresAt;return z.kind==="stat"&&N.kind==="stat"&&z.dev===N.dev&&z.ino===N.ino&&z.mtimeMs===N.mtimeMs&&z.expiresAt===N.expiresAt}async function X(){try{return JSON.parse(await S(f,H))?.ownerId===a}catch(z){if(H&&z.code!=="ENOENT")throw z;return!1}}async function A(z){if(H)await V0(z,"remove",()=>L(z,{recursive:!0,force:!0}));else await L(z,{recursive:!0,force:!0}).catch(()=>{})}async function u(){if(await X())await A(g)}async function t(){if(H)await _0(g);else await H0(g);try{let z=`${JSON.stringify({ownerId:a,createdAt:Z()})}
5
- `;if(H)await v(f,z);else await J0(f,z)}catch(z){if(q0(z))return!1;throw await u(),z}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function r(){let z;try{z=await Y0(g)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(H)await x(g,"directory",!0);if(z.mtimeMs+C0>Z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let K=`${g}.${I()}`;try{await W0(g,K)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if($.onStep)await $.onStep("stale-marker-claimed");return await A(K),"recovered"}async function o(z){try{if(!await t())return!1}catch(K){if(K.code==="EEXIST"){if(H){await x(g,"directory",!0);try{await S(f,!0)}catch(N){if(N.code!=="ENOENT")throw N}}return!1}throw K}try{await z()}finally{await u()}return!0}async function e(){for(let z=0;z<y;z++){if($.onStep)await $.onStep("relinquish-read");let K;try{K=await j()}catch(N){if(H)throw N;return}if(K?.ownerId!==Y)return;try{await L(G,{recursive:!0,force:!0});return}catch(N){if(H)throw N;await O()}}}function $0(){if(!$.renew||_||B)return;let z=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(J=D0(()=>{J=null;let K=(async()=>{let N=!_;try{if(!await o(async()=>{let V=await j(),T=Z();if(_||B){N=!1;return}if(V?.ownerId!==Y){C("taken-over",V),N=!1;return}if(!(Number(V?.expiresAt)>T)){C("expired",V),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-fenced");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-ready");if(_||B){N=!1;return}if(await g0(),$.onStep)await $.onStep("renewal-write-finished");if(!await X()){C("marker-lost"),N=!1,await e();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(W){if(H&&W instanceof q)E=W,C("renewal-failed"),N=!1;try{let V=await j();if(V?.ownerId!==Y)C("taken-over",V);else if(!(Number(V?.expiresAt)>Z()))C("expired",V)}catch{C("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!_&&!B)$0()}})();M=K,K.finally(()=>{if(M===K)M=null})},z),"unref"in J)J.unref();p("scheduled")}function z0(){try{let z=$.onContended?.();if(z&&(typeof z==="object"||typeof z==="function")&&"then"in z&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}return null}let U=await k();if(!U)for(let z=0;z<y;z++){if(U=await k(),U)break;let K=await m();if(K.status==="live")return z0();if(K.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await t()){await O();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await r()==="fresh")return null;await O();continue}try{let N=await m();if(N.status==="live")return z0();if(!i(K.identity,N))continue;if(!await X())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await X())return null;let W=await m(!1);if(!i(K.identity,W))continue;if(await A(G),!await X())return null;if($.onStep)await $.onStep("stale-lock-removed");if(U=await k(),!U)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await X())return await e(),U=!1,null;break}finally{await u()}}if(!U)return null;return $0(),{ownerId:Y,whenLost:()=>j0,hasLost:()=>B!==void 0,assertOwned:async()=>{if(E)throw E;let z;try{let K=await j();if(z=K,!_&&!B&&K?.ownerId===Y&&Number(K?.expiresAt)>Z())return;C(K?.ownerId!==Y?"taken-over":"expired",K)}catch(K){if(C("unreadable"),H&&K instanceof q)throw K}throw new R({target:$.path,name:$.name,expectedOwnerId:Y,...typeof z?.ownerId==="string"?{observedOwnerId:z.ownerId}:{},...typeof z?.expiresAt==="number"?{observedExpiresAt:z.expiresAt}:{}})},release:async()=>{if(H&&D)return;_=!0,d(),await M;for(let z=0;z<y;z++){try{let K=!1;if(await o(async()=>{let W;try{W=await j()}catch(V){if(H&&V.code==="ENOENT"){K=!0;return}throw V}if(W?.ownerId!==Y){K=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await X())return;await A(G),K=!0})){if(H&&!K)throw new q(G,"release-not-confirmed",{code:"EIO"});D=K;return}await r()}catch(K){if(H)throw K;return}await O()}if(H)throw new q(G,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as X0}from"node:crypto";import{mkdir as S0,open as F,rename as R0,rm as M0}from"node:fs/promises";import{dirname as w}from"node:path";class c extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function h0($,G,Q={}){await f0($,G,Q)}async function f0($,G,Q,Y){if(H)return b($,Q.serialize?Q.serialize(G):`${JSON.stringify(G,null,2)}
1
+ import{$e as v,Ue as H,Ve as q,We as V0,Ye as x,Ze as h,_e as S,af as _0,cf as b}from"./index-5230x6s8.js";import{randomUUID as T}from"node:crypto";import{mkdir as H0,open as B0,readFile as Q0,rename as W0,rm as L,stat as Y0}from"node:fs/promises";import{dirname as P,join as Z0}from"node:path";function N0($,G){return`${$}.${G}.lock`}class G0 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class f extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function A0($,G,Q){let Y=performance.now();for(;;){G.signal?.throwIfAborted();let Z=await K0({path:$,name:G.name,ttlMs:G.ttlMs,renew:G.renew??!1,...G.onStep?{onStep:G.onStep}:{},...G.onRenewalTimer?{onRenewalTimer:G.onRenewalTimer}:{}});if(Z)try{return G.signal?.throwIfAborted(),await Q(Z)}finally{await Z.release()}let J=G.timeoutMs-(performance.now()-Y);if(J<=0)throw new G0({target:$,name:G.name,timeoutMs:G.timeoutMs});await new Promise((_)=>setTimeout(_,Math.min(25,Math.ceil(J))))}}async function J0($,G){let Q=await B0($,"wx",384);try{await Q.writeFile(G,"utf8")}finally{await Q.close()}}var D0=globalThis.setTimeout.bind(globalThis),U0=globalThis.clearTimeout.bind(globalThis);function q0($){let G=$?.code;return G==="ENOENT"||!H&&(G==="EINVAL"||G==="ENOTDIR")}function K0($){return x0({...$,now:Date.now})}async function x0($){let G=N0($.path,$.name),Q=Z0(G,"owner.json"),Y=T(),Z=$.now??Date.now,J=null,_=!1,D=!1,B,l,j0=new Promise((z)=>{l=z});function p(z){try{let K=$.onRenewalTimer?.(z);if(K&&(typeof K==="object"||typeof K==="function")&&"then"in K&&typeof K.then==="function")Promise.resolve(K).catch(()=>{})}catch{}}function d(){if(!J)return;U0(J),J=null,p("cancelled")}function g(z,K){if(B||_)return;B=Object.freeze({reason:z,expectedOwnerId:Y,...typeof K?.ownerId==="string"?{observedOwnerId:K.ownerId}:{},...typeof K?.expiresAt==="number"?{observedExpiresAt:K.expiresAt}:{}}),d(),l(B)}let E,R=null,C=`${G}.evicting`,M=Z0(C,"owner.json"),a=T(),g0=5000,y=8;async function j(){if(H)try{return JSON.parse(await S(G,!0))}catch(z){if(z.code!=="EISDIR"&&z.reason!=="wrong-kind")throw z;return await x(G,"directory",!0),JSON.parse(await S(Q,!0))}try{return JSON.parse(await Q0(G,"utf8"))}catch(z){if(z.code!=="EISDIR")throw z;return JSON.parse(await Q0(Q,"utf8"))}}async function C0(){if(H){let W=await j(),V=Number(W?.expiresAt)-Z();await b(G,`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
2
+ `,{deadline:performance.now()+Math.max(0,V),beforeRename:async()=>{let I=await j();if(I?.ownerId!==Y||!(Number(I?.expiresAt)>Z())||!await X())throw new f({target:$.path,name:$.name})}});return}let z=`${G}.${T()}.tmp`,K,N=!1;try{K=await B0(z,"wx",384),N=!0,await K.writeFile(`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
3
+ `,"utf8"),await K.chmod(384),await K.close(),K=void 0;let W=await j();if(W?.ownerId!==Y||!(Number(W?.expiresAt)>Z())||!await X())throw new f({target:$.path,name:$.name});await W0(z,G),N=!1}finally{if(await K?.close().catch(()=>{}),N)await L(z,{force:!0}).catch(()=>{})}}async function s(){let z=`${JSON.stringify({ownerId:Y,expiresAt:Z()+$.ttlMs})}
4
+ `;if(H)await v(G,z);else await J0(G,z)}async function n(z){let K=z.code;if(K==="EEXIST"){if(H)await j();return!0}if(K==="EISDIR"){if(H)await x(G,"directory",!0),await S(Q,!0);return!0}return!1}async function k(){if(H)await h(P(G));try{return await s(),!0}catch(z){let K=z.code;if(await n(z))return!1;if(K==="ENOENT"){if(H)await h(P(G));else await H0(P(G),{recursive:!0});try{return await s(),!0}catch(N){if(await n(N))return!1;throw N}}throw z}}async function O(){await new Promise((z)=>setTimeout(z,Math.floor(Math.random()*4)))}async function m(z=!0){if(z&&$.onStep)await $.onStep("lock-read-ready");let K;try{K=await j()}catch(W){if(H&&W.code!=="ENOENT")throw W}let N=Number(K?.expiresAt);if(Number.isFinite(N)&&N>Z())return{status:"live"};if(typeof K?.ownerId==="string"&&Number.isFinite(N))return{status:"stale",identity:{kind:"owner",ownerId:K.ownerId,expiresAt:N}};try{let W=await Y0(G),V=Number.isFinite(N)?N:W.mtimeMs+$.ttlMs;if(V>Z())return{status:"live"};return{status:"stale",identity:{kind:"stat",dev:W.dev,ino:W.ino,mtimeMs:W.mtimeMs,expiresAt:V}}}catch(W){if(W.code==="ENOENT"){if($.onStep)await $.onStep("lock-missing");return{status:"missing"}}throw W}}function i(z,K){if(K.status!=="stale")return!1;let N=K.identity;if(z.kind==="owner"&&N.kind==="owner")return z.ownerId===N.ownerId&&z.expiresAt===N.expiresAt;return z.kind==="stat"&&N.kind==="stat"&&z.dev===N.dev&&z.ino===N.ino&&z.mtimeMs===N.mtimeMs&&z.expiresAt===N.expiresAt}async function X(){try{return JSON.parse(await S(M,H))?.ownerId===a}catch(z){if(H&&z.code!=="ENOENT")throw z;return!1}}async function A(z){if(H)await V0(z,"remove",()=>L(z,{recursive:!0,force:!0}));else await L(z,{recursive:!0,force:!0}).catch(()=>{})}async function u(){if(await X())await A(C)}async function t(){if(H)await _0(C);else await H0(C);try{let z=`${JSON.stringify({ownerId:a,createdAt:Z()})}
5
+ `;if(H)await v(M,z);else await J0(M,z)}catch(z){if(q0(z))return!1;throw await u(),z}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function r(){let z;try{z=await Y0(C)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if(H)await x(C,"directory",!0);if(z.mtimeMs+g0>Z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let K=`${C}.${T()}`;try{await W0(C,K)}catch(N){if(N.code==="ENOENT")return"missing";throw N}if($.onStep)await $.onStep("stale-marker-claimed");return await A(K),"recovered"}async function o(z){try{if(!await t())return!1}catch(K){if(K.code==="EEXIST"){if(H){await x(C,"directory",!0);try{await S(M,!0)}catch(N){if(N.code!=="ENOENT")throw N}}return!1}throw K}try{await z()}finally{await u()}return!0}async function e(){for(let z=0;z<y;z++){if($.onStep)await $.onStep("relinquish-read");let K;try{K=await j()}catch(N){if(H)throw N;return}if(K?.ownerId!==Y)return;try{await L(G,{recursive:!0,force:!0});return}catch(N){if(H)throw N;await O()}}}function $0(){if(!$.renew||_||B)return;let z=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(J=D0(()=>{J=null;let K=(async()=>{let N=!_;try{if(!await o(async()=>{let V=await j(),I=Z();if(_||B){N=!1;return}if(V?.ownerId!==Y){g("taken-over",V),N=!1;return}if(!(Number(V?.expiresAt)>I)){g("expired",V),N=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-fenced");if(_||B){N=!1;return}if(!await X())return;if($.onStep)await $.onStep("renewal-write-ready");if(_||B){N=!1;return}if(await C0(),$.onStep)await $.onStep("renewal-write-finished");if(!await X()){g("marker-lost"),N=!1,await e();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch(W){if(H&&W instanceof q)E=W,g("renewal-failed"),N=!1;try{let V=await j();if(V?.ownerId!==Y)g("taken-over",V);else if(!(Number(V?.expiresAt)>Z()))g("expired",V)}catch{g("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(N&&!_&&!B)$0()}})();R=K,K.finally(()=>{if(R===K)R=null})},z),"unref"in J)J.unref();p("scheduled")}function z0(){try{let z=$.onContended?.();if(z&&(typeof z==="object"||typeof z==="function")&&"then"in z&&typeof z.then==="function")Promise.resolve(z).catch(()=>{})}catch{}return null}let U=await k();if(!U)for(let z=0;z<y;z++){if(U=await k(),U)break;let K=await m();if(K.status==="live")return z0();if(K.status==="missing")continue;if($.onStep)await $.onStep("stale-lock-observed");try{if(!await t()){await O();continue}}catch(N){if(N.code!=="EEXIST")throw N;if(await r()==="fresh")return null;await O();continue}try{let N=await m();if(N.status==="live")return z0();if(!i(K.identity,N))continue;if(!await X())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await X())return null;let W=await m(!1);if(!i(K.identity,W))continue;if(await A(G),!await X())return null;if($.onStep)await $.onStep("stale-lock-removed");if(U=await k(),!U)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await X())return await e(),U=!1,null;break}finally{await u()}}if(!U)return null;return $0(),{ownerId:Y,whenLost:()=>j0,hasLost:()=>B!==void 0,assertOwned:async()=>{if(E)throw E;let z;try{let K=await j();if(z=K,!_&&!B&&K?.ownerId===Y&&Number(K?.expiresAt)>Z())return;g(K?.ownerId!==Y?"taken-over":"expired",K)}catch(K){if(g("unreadable"),H&&K instanceof q)throw K}throw new f({target:$.path,name:$.name,expectedOwnerId:Y,...typeof z?.ownerId==="string"?{observedOwnerId:z.ownerId}:{},...typeof z?.expiresAt==="number"?{observedExpiresAt:z.expiresAt}:{}})},release:async()=>{if(H&&D)return;_=!0,d(),await R;for(let z=0;z<y;z++){try{let K=!1;if(await o(async()=>{let W;try{W=await j()}catch(V){if(H&&V.code==="ENOENT"){K=!0;return}throw V}if(W?.ownerId!==Y){K=!0;return}if($.onStep)await $.onStep("release-owner-confirmed");if(!await X())return;await A(G),K=!0})){if(H&&!K)throw new q(G,"release-not-confirmed",{code:"EIO"});D=K;return}await r()}catch(K){if(H)throw K;return}await O()}if(H)throw new q(G,"release-not-confirmed",{code:"ETIMEDOUT"})}}}import{randomUUID as X0}from"node:crypto";import{mkdir as S0,open as F,rename as f0,rm as R0}from"node:fs/promises";import{dirname as w}from"node:path";class c extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function h0($,G,Q={}){await M0($,G,Q)}async function M0($,G,Q,Y){if(H)return b($,Q.serialize?Q.serialize(G):`${JSON.stringify(G,null,2)}
6
6
  `,{beforeRename:Q.beforeRename,stagePath:`${$}.${(Q.stageName??X0)()}.tmp`,onRenamed:Y,durable:Q.durable,durability:Q.durability,onOutcome:Q.onOutcome});await S0(w($),{recursive:!0});let Z=`${$}.${(Q.stageName??X0)()}.tmp`,J,_=!1;try{if(J=await F(Z,"wx",384),_=!0,await J.writeFile(Q.serialize?Q.serialize(G):`${JSON.stringify(G,null,2)}
7
- `,"utf8"),await J.chmod(384),Q.durable)try{await J.sync()}catch(D){throw new c(D)}if(await J.close(),J=void 0,await Q.beforeRename?.(),await R0(Z,$),_=!1,Y?.(),Q.durable){let D=await F(w($),"r");try{await D.sync()}catch(B){throw new c(B)}finally{await D.close()}}}finally{if(await J?.close().catch(()=>{}),_)await M0(Z,{force:!0}).catch(()=>{})}}async function v0($){if(H){await x($,"file");let Y=new q($,"directory-sync-unsupported",{code:"ENOTSUP"});throw Y.published=!0,Y}let G=await F($,"r");try{await G.sync()}finally{await G.close()}let Q=await F(w($),"r");try{await Q.sync()}finally{await Q.close()}}var c0=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
8
- export{c as ie,h0 as je,f0 as ke,v0 as le,K0 as me,G0 as ne,R as oe,A0 as pe,c0 as qe};
7
+ `,"utf8"),await J.chmod(384),Q.durable)try{await J.sync()}catch(D){throw new c(D)}if(await J.close(),J=void 0,await Q.beforeRename?.(),await f0(Z,$),_=!1,Y?.(),Q.durable){let D=await F(w($),"r");try{await D.sync()}catch(B){throw new c(B)}finally{await D.close()}}}finally{if(await J?.close().catch(()=>{}),_)await R0(Z,{force:!0}).catch(()=>{})}}async function v0($){if(H){await x($,"file");let Y=new q($,"directory-sync-unsupported",{code:"ENOTSUP"});throw Y.published=!0,Y}let G=await F($,"r");try{await G.sync()}finally{await G.close()}let Q=await F(w($),"r");try{await Q.sync()}finally{await Q.close()}}var c0=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});
8
+ export{c as ne,h0 as oe,M0 as pe,v0 as qe,K0 as re,G0 as se,f as te,A0 as ue,c0 as ve};
@@ -0,0 +1,90 @@
1
+ import{oe as w,re as A,se as s0,ue as n0}from"./index-ag04nyv7.js";import{Le as T0,Me as I,Oe as X8,Re as L6}from"./index-wgwze391.js";import{Ue as DZ,Ve as i0,Xe as g4,Ze as H3,_e as Q0,cf as v4}from"./index-5230x6s8.js";var P="all",f0=Object.freeze(["primary"]);function l3(Z){return Z.kind==="retired"?Z.retiredAt:Z.checkedAt}function qZ(Z,$){return JSON.stringify([Z,$])}function c(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function R(Z){return typeof Z==="number"&&Number.isFinite(Z)}function p3(Z){return typeof Z==="string"&&Z.length>0}function S(Z,$,z){return Z[$]===void 0||z(Z[$])}function J8(Z){return R(Z)&&Z>0}function b0(Z){return typeof Z==="string"}function B8(Z){if(!c(Z)||!p3(Z.scope)||!p3(Z.label))return!1;switch(Z.kind){case"reading":return R(Z.checkedAt)&&R(Z.usedPercent)&&S(Z,"resetsAt",b0)&&S(Z,"windowMinutes",J8);case"retired":return R(Z.retiredAt);case"absent":return R(Z.checkedAt);default:return!1}}function H8(Z){if(!c(Z)||!R(Z.checkedAt))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&S(Z,"remainingPercent",R)&&S(Z,"usedPercent",R)&&S(Z,"resetsAt",b0)&&S(Z,"limit",R)&&S(Z,"used",R)&&S(Z,"remaining",R)&&S(Z,"unit",b0)}function d3(Z){return c(Z)&&R(Z.value)&&Number.isInteger(Z.value)&&Z.value>=0&&R(Z.checkedAt)}function k0(Z){return c(Z)&&Object.values(Z).every(d3)}function K8(Z){return typeof Z==="boolean"}function h(Z){return c(Z)&&typeof Z.hasCredits==="boolean"&&typeof Z.unlimited==="boolean"&&S(Z,"balance",R)&&S(Z,"overageLimitReached",K8)&&R(Z.checkedAt)}function y0(Z){if(!c(Z))return;let $=Object.entries(Z).filter(([,z])=>d3(z));return $.length===0?void 0:Object.fromEntries($)}function YZ(Z){if(XZ(Z))return Z;if(!c(Z))return;let{counters:$,credits:z,...X}=Z;if(!XZ(X))return;let Y=y0($),G=h(z)?z:void 0;return{...X,...Y===void 0?{}:{counters:Y},...G===void 0?{}:{credits:G}}}function XZ(Z){if(!c(Z)||!Array.isArray(Z.limits))return!1;let $=new Set;for(let z of Z.limits){if(!B8(z))return!1;let X=qZ(z.scope,z.label);if($.has(X))return!1;$.add(X)}return S(Z,"budget",H8)&&S(Z,"counters",k0)&&S(Z,"credits",h)}var s3=900000,n3="no quota reading yet",a3="no limits reported";function o3(Z){let $=Math.max(1,Math.floor(Z/60000));if($<60)return`${$}m`;if($<1440){let Y=Math.floor($/60),G=$%60;return G===0?`${Y}h`:`${Y}h${G}m`}let z=Math.floor($/1440),X=Math.floor($%1440/60);return X===0?`${z}d`:`${z}d${X}h`}function r3(Z){if(Z%1440===0)return`${Z/1440}d`;if(Z%60===0)return`${Z/60}h`;return`${Z}m`}function t3(Z){if(Z.scope!==P||Z.windowMinutes===void 0)return Z.label;return r3(Z.windowMinutes)}function h0(Z){return Math.min(100,Math.max(0,Z))}function cZ(Z){return Math.round(h0(Z))}function c3(Z){return`${cZ(Z)}% left`}function u3(Z,$,z){let X=Z===void 0?Number.NaN:Date.parse(Z);return{...Number.isFinite(X)&&X>z?{resetIn:o3(X-z)}:{},resetSinceReading:Number.isFinite(X)&&X>$&&X<=z}}function W8(Z,$){let z=Z.windowMinutes,X=$.windowMinutes;if(z!==void 0&&X!==void 0&&z!==X)return z-X;if(z===void 0!==(X===void 0))return z===void 0?1:-1;if(Z.scope!==$.scope){if(Z.scope===P)return-1;if($.scope===P)return 1;return Z.scope<$.scope?-1:1}return Z.label<$.label?-1:Z.label>$.label?1:0}function e3(Z,$){let{windows:z,age:X}=w0(Z,$),Y=z.map(({part:G})=>G);return X===void 0?{windows:Y}:{windows:Y,age:X}}function Q8(Z){let $=Z4(Z.filter(({part:z,scope:X})=>z.kind==="window"&&X!==P).map(({scope:z})=>z));for(let z of Z)z.part.short=z.part.kind==="budget"?"cr":z.scope===P?z.part.name:$.get(z.scope)??z.scope;return Z}function w0(Z,$){if(!Z)return{windows:[]};let{now:z}=$,Y=Z.limits.filter((J)=>J.kind==="reading"&&J.remainingPercent!==void 0).sort(W8).map((J)=>{let B=h0(J.remainingPercent??0);return{scope:J.scope,...J.windowMinutes===void 0?{}:{windowMinutes:J.windowMinutes},part:{kind:"window",name:t3(J),short:"",figure:c3(J.remainingPercent??0),remainingPercent:B,checkedAt:J.checkedAt,...u3(J.resetsAt,J.checkedAt,z)}}}),G=Z.budget;if(G){let J=G.remainingPercent,B=G.reached?"credits spent":J!==void 0?`credits ${c3(J)}`:"credits available";Y.push({scope:P,spent:G.reached,part:{kind:"budget",name:"credits",short:"",figure:B,...J===void 0?{}:{remainingPercent:h0(J)},checkedAt:G.checkedAt,...u3(G.resetsAt,G.checkedAt,z)}})}if(Q8(Y),Y.length>0){let J=z-Math.min(...Y.map(({part:B})=>B.checkedAt));if(J>($.staleAfterMs??s3))return{windows:Y,age:`checked ${o3(J)} ago`}}return{windows:Y}}function U8(Z,$){return w0(Z,$).age!==void 0}function i3(Z){let $=Z.slice(Z.indexOf(":")+1);return $.charAt(0).toUpperCase()+$.slice(1)}function Z4(Z){let $=[...new Set(Z.map(i3))],z=new Map($.map((Y)=>[Y,2])),X=(Y)=>Y.slice(0,z.get(Y));for(;;){let Y=new Map;for(let J of $)Y.set(X(J),[...Y.get(X(J))??[],J]);let G=!1;for(let J of Y.values()){if(J.length<2)continue;for(let B of J){let H=z.get(B)??2;if(H<B.length)z.set(B,H+1),G=!0}}if(!G)break}return new Map(Z.map((Y)=>[Y,X(i3(Y))]))}var D8=2;function V8(Z){let $=Z.map((X)=>X.label.trim()||X.scope),z=Z4($);return $.map((X)=>z.get(X)??X)}function F8(Z,$){if(!Z||Z.length===0)return;let z=$.filter(({part:B})=>B.kind==="window");if(z.some(({scope:B})=>B===P))return;let X=Z.flatMap((B,H)=>{let K=z.filter(({scope:W})=>W===B.scope).reduce((W,U)=>W===void 0||(U.part.remainingPercent??0)<(W.part.remainingPercent??0)?U:W,void 0);return K?[{group:B,listed:H,window:K}]:[]});if(X.length===0)return;let Y=V8(Z),G=(B)=>B.window.part.remainingPercent??0,J=[...X].sort((B,H)=>G(B)-G(H)||B.listed-H.listed).slice(0,D8).sort((B,H)=>B.listed-H.listed);return J.map((B,H)=>{let{windowMinutes:Q}=B.window,K=[Y[B.listed]??B.group.scope,...Q===void 0?[]:[r3(Q)],`${cZ(G(B))}%`].join(" ");return H===J.length-1?`${K} left`:K})}function N8(Z,$){let{windows:z}=w0(Z,$),X=F8(Z?.groups,z);if(X)return X;let Y=z.filter(({part:W,scope:U})=>W.kind==="window"&&U===P),G=z.filter(({part:W,scope:U})=>W.kind==="window"&&U!==P),J=z.find(({part:W})=>W.kind==="budget"),B=J?.spent?0:J?.part.remainingPercent,Q=[...G.map(({part:W})=>({label:W.short,remaining:W.remainingPercent??0})),...B===void 0||J===void 0?[]:[{label:J.part.short,remaining:B}]].reduce((W,U)=>W===void 0||U.remaining<W.remaining?U:W,void 0),K=Y.map(({part:W})=>`${W.name} ${cZ(W.remainingPercent??0)}%`);if(Q)K.push(`${Q.label} ${cZ(Q.remaining)}%`);if(K.length===0)return z.map(({part:W})=>W.figure);return K.map((W,U)=>U===K.length-1?`${W} left`:W)}function $4(Z,$){if($.form==="narrow")return N8(Z,$);let z=e3(Z,$),X=($.form??"full")==="full",Y=z.windows.map((G)=>{let J=X&&G.resetIn?`, resets ${G.resetIn}`:"";return`${G.kind==="budget"?"":`${G.name} `}${G.figure}${J}`});return z.age===void 0?Y:[...Y,z.age]}function j8(Z,$){let z=$4(Z,$);if(z.length>0)return z.join(" · ");return Z&&Z.limits.length>0?a3:n3}function q8(Z){if(Z===void 0)return;if(Z.unlimited)return"Unlimited";if(!Z.hasCredits)return;let{balance:$}=Z;return typeof $==="number"&&Number.isFinite($)&&$>0?`${Math.round($)} credits`:"Available"}function O8(Z){if(Z.kind==="retired")return{scope:Z.scope,label:Z.label,kind:"retired",checkedAt:Z.retiredAt};if(Z.kind==="absent")return{scope:Z.scope,label:Z.label,kind:"absent",checkedAt:Z.checkedAt};return{scope:Z.scope,label:Z.label,kind:"reading",checkedAt:Z.checkedAt,usedPercent:Z.usedPercent,remainingPercent:100-Z.usedPercent,...Z.windowMinutes===void 0?{}:{windowMinutes:Z.windowMinutes},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function M8(Z,$){let z=Z.windowMinutes!==void 0,X=$.windowMinutes!==void 0;if(z!==X)return z?-1:1;if(z&&X&&Z.windowMinutes!==$.windowMinutes)return($.windowMinutes??0)-(Z.windowMinutes??0);if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function _8(Z){return{checkedAt:Z.checkedAt,reached:Z.reached,...Z.remainingPercent===void 0?{}:{remainingPercent:Z.remainingPercent},...Z.resetsAt===void 0?{}:{resetsAt:Z.resetsAt}}}function C(Z,$=P){let z=new Map;for(let K of Z?.limits??[]){if(K.scope!==$&&K.scope!==P)continue;let W=z.get(K.label);if(W===void 0){z.set(K.label,K);continue}let U=K.scope===P?W:K,j=K.scope===P?K:W;z.set(K.label,U.kind==="reading"?U:j)}let X=[...z.values()].map(O8).sort(M8),Y=X.filter((K)=>K.kind==="reading"),G=Y.length>0?Y:X,J=G.length>0?Math.min(...G.map((K)=>K.checkedAt)):void 0,B=Z?.budget?.kind==="reading"?_8(Z.budget):void 0,H=y0(Z?.counters),Q=h(Z?.credits)?Z.credits:void 0;return{scope:$,limits:X,...J===void 0?{}:{checkedAt:J},...B===void 0?{}:{budget:B},...H===void 0?{}:{counters:H},...Q===void 0?{}:{credits:Q}}}function GZ(Z,$){let z=Z?.budget;if(z?.reached!==!0||typeof z.resetsAt!=="string")return;let X=Date.parse(z.resetsAt);if(!Number.isFinite(X)||X<=$)return;return{resetsAt:z.resetsAt,resetAtMs:X}}function m0(Z){return Z.kind==="reading"&&typeof Z.usedPercent==="number"&&Number.isFinite(Z.usedPercent)&&Z.usedPercent>=100}function uZ(Z,$){if(typeof Z.resetsAt!=="string")return;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z>$?z:void 0}class iZ extends TypeError{constructor(Z){super(Z);this.name="QuotaCodecError"}}function nZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function sZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function z4(Z){return Z===void 0||typeof Z==="string"&&Z!==""}function X4(Z){return typeof Z==="string"&&Z!==""}function SZ(Z,$){return Z[$]===void 0||sZ(Z[$])}function g0(Z,$){return Z[$]===void 0||typeof Z[$]==="string"}function P8(Z){return nZ(Z)&&z4(Z.scope)&&X4(Z.label)&&sZ(Z.usedPercent)&&g0(Z,"resetsAt")&&(Z.windowMinutes===void 0||sZ(Z.windowMinutes)&&Z.windowMinutes>0)}function L8(Z){return nZ(Z)&&z4(Z.scope)&&X4(Z.label)}function R8(Z){if(!nZ(Z))return!1;if(Z.kind==="cleared")return!0;return Z.kind==="reading"&&typeof Z.reached==="boolean"&&SZ(Z,"remainingPercent")&&SZ(Z,"usedPercent")&&g0(Z,"resetsAt")&&SZ(Z,"limit")&&SZ(Z,"used")&&SZ(Z,"remaining")&&g0(Z,"unit")}function OZ(Z){if(!nZ(Z)||!sZ(Z.checkedAt))return!1;let $=Z.readings??[],z=Z.coverage??[];if(!Array.isArray($)||!Array.isArray(z))return!1;let X=new Set;for(let Y of $){if(!P8(Y))return!1;let G=qZ(Y.scope??P,Y.label);if(X.has(G))return!1;X.add(G)}if(!z.every(L8))return!1;return(Z.budget===void 0||R8(Z.budget))&&(Z.counters===void 0||k0(Z.counters))&&(Z.credits===void 0||h(Z.credits))}function S8(Z,$){if(Z.scope!==$.scope)return Z.scope<$.scope?-1:1;if(Z.label!==$.label)return Z.label<$.label?-1:1;return 0}function x8(Z,$,z){if($===void 0)return Z;if(Z!==void 0&&z<Z.checkedAt)return Z;return{...$,checkedAt:z}}function T8(Z,$){let z=new Map(Object.entries(Z??{}));for(let[X,Y]of Object.entries($??{})){let G=z.get(X);if(G===void 0||Y.checkedAt>=G.checkedAt)z.set(X,Y)}return z.size===0?void 0:Object.fromEntries(z)}function E8(Z,$){if($===void 0)return Z;if(Z!==void 0&&$.checkedAt<Z.checkedAt)return Z;return{...$}}function xZ(Z,$){let z=Z===void 0?void 0:YZ(Z);if(Z!==void 0&&z===void 0)throw new iZ("stored quota map is malformed");if(!OZ($))throw new iZ("quota observation is malformed");let X=z??{limits:[]},Y=$.checkedAt,G=new Map;for(let q of X.limits)G.set(qZ(q.scope,q.label),q);let J=(q)=>{let L=G.get(q);return L===void 0||Y>=l3(L)},B=new Set;for(let q of $.readings??[]){let L=q.scope??P,T=qZ(L,q.label);if(B.add(T),!J(T))continue;G.set(T,{scope:L,label:q.label,kind:"reading",checkedAt:Y,usedPercent:q.usedPercent,...q.resetsAt===void 0?{}:{resetsAt:q.resetsAt},...q.windowMinutes===void 0?{}:{windowMinutes:q.windowMinutes}})}for(let q of $.coverage??[]){let L=q.scope??P,T=qZ(L,q.label);if(B.has(T)||!J(T))continue;let p=G.get(T);G.set(T,p===void 0||p.kind==="absent"?{scope:L,label:q.label,kind:"absent",checkedAt:Y}:{scope:L,label:q.label,kind:"retired",retiredAt:Y})}let{limits:H,budget:Q,counters:K,credits:W,...U}=X,j=x8(X.budget,$.budget,Y),D=T8(X.counters,$.counters),O=E8(X.credits,$.credits);return{...U,limits:[...G.values()].sort(S8),...j===void 0?{}:{budget:j},...D===void 0?{}:{counters:D},...O===void 0?{}:{credits:O}}}var C8=Object.freeze({validate:XZ,decode:YZ,merge:xZ});function Y4(Z,$,z){let X=$.rateLimitMarks?.get(Z);if(X!==void 0&&z<X)return{id:Z,reason:"rate-limited",until:X};let Y=$.refreshBackoff?.get(Z);if(Y!==void 0&&z<Y)return{id:Z,reason:"refresh-backoff",until:Y};return}function A8(Z,$,z,X){if($.limits.length===0)return{id:Z,stage:1,gate:2,reason:"needs-first-reading",pullRequested:!0};for(let G of z)if(!$.limits.some((J)=>J.label===G))return{id:Z,stage:1,gate:3,reason:"unknown-window",window:{scope:$.scope,label:G},pullRequested:!0};let Y=$.limits.filter(m0);for(let G of Y)if(uZ(G,X)===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 Y){let J=uZ(G,X);if(J!==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:J}}return}function y(Z){let $=Z.scope??P,z=Z.requiredLabels??f0,X=[],Y=[],G=[];for(let U of Z.rows){let j=Y4(U.id,Z,Z.now);if(j){X.push(j);continue}if(U.kind==="api-key"){G.push({id:U.id,kind:U.kind});continue}let D=C(U.quota,$),O=A8(U.id,D,z,Z.now);if(O){Y.push(O);continue}G.push({id:U.id,kind:U.kind,projection:D})}let J=new Map(G.flatMap((U)=>{let j=GZ(U.projection,Z.now);return j?[[U.id,j]]:[]})),B=J.size>0&&J.size===G.length,H=[];for(let U of G){let j=J.get(U.id);if(j===void 0)H.push(U);else if(B)H.push({...U,lastPath:!0});else Y.push({id:U.id,stage:2,reason:"budget-spent",...j})}let Q=new Map(Z.rows.map((U,j)=>[U.id,j])),K=(U,j)=>(Q.get(U.id)??0)-(Q.get(j.id)??0);Y.sort(K);let W=Y.filter((U)=>("pullRequested"in U)).map((U)=>U.id);for(let U of W)Z.requestPull?.(U);return{admitted:H,refused:Y,excluded:X,pulls:W}}var G4="main";function I8(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 aZ(Z,$,z=G4){if($==="roster"||!Z.includes(z))return[...Z];let X=Z.filter((Y)=>Y!==z);return $==="main-first"?[z,...X]:[...X,z]}function v0(Z){let $=y(Z),z=new Set($.admitted.map((Y)=>Y.id));return{order:aZ(Z.rows.map((Y)=>Y.id),Z.placement??"roster",Z.formerMainId).filter((Y)=>z.has(Y)&&Z.killswitch?.get(Y)!==!1),admission:$}}function b8(Z,$,z){let X=$.at(-1);if(X!==void 0){if(X.status===void 0||!z.includes(X.status))return}let Y=new Set($.map((G)=>G.id));return Z.find((G)=>!Y.has(G))}function p0(Z,$,z){if(!$.has(Z.accountId))return!1;return!(typeof Z.wireIdentity==="string"&&typeof z==="string"&&Z.wireIdentity!==z)}function f8(Z,$,z){let X=new Map;for(let[Y,G]of Z){if(Y===z)continue;if(G.quotaCheckedAt!==$.get(G.accountId))continue;X.set(G.accountId,(X.get(G.accountId)??0)+(G.inputBytes??0))}return X}var TZ=900000,B4=0.016666666666666666,l0=0.000001;function oZ(Z,$){for(let z of[Z?.checkedAt,$])if(typeof z==="number"&&Number.isFinite(z))return z;return}function H4(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 K4(Z){return Z.limits.filter(($)=>$.kind==="reading").sort(($,z)=>{let X=$.windowMinutes!==void 0,Y=z.windowMinutes!==void 0;if(X!==Y)return X?-1:1;if(X&&Y)return(z.windowMinutes??0)-($.windowMinutes??0);return 0})}function c0(Z){let $=(Z.classifyStatus??H4)(Z.status);if($==="permanent")return{action:"migrate",reason:"permanent"};if(!Z.quota)return{action:"retain",reason:"unknown"};let z=oZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||!Number.isFinite(z)||Z.now-z>TZ)return{action:"retain",reason:"stale"};if(Z.killswitchPasses===!1)return{action:"migrate",reason:"killswitch"};for(let Y of K4(Z.quota)){let G=Y.remainingPercent;if(typeof G==="number"&&Number.isFinite(G)&&G<=0)return{action:"migrate",reason:"exhausted",window:{scope:Y.scope,label:Y.label},...typeof Y.resetsAt==="string"?{resetsAt:Y.resetsAt}:{}}}let X=GZ(Z.quota,Z.now);if(X)return{action:"migrate",reason:"exhausted",resetsAt:X.resetsAt};return{action:"retain",reason:$}}function d0(Z,$,z){let X=Math.max(0,Z.remainingPercent-$);if(X<=0)return 0;if(!Z.resetsAt)return X;let Y=Date.parse(Z.resetsAt);if(!Number.isFinite(Y)||Y<=z)return X;let G=Math.max((Y-z)/3600000,B4);return X/G}function J4(Z,$){if(Z<$)return-1;if(Z>$)return 1;return 0}function k8(Z,$){if(!Z.quota)return;let z=oZ(Z.quota,Z.quotaCheckedAt);if(z===void 0||$-z>TZ)return;let X=K4(Z.quota).map((J)=>d0({remainingPercent:J.remainingPercent??Number.NaN,...J.resetsAt===void 0?{}:{resetsAt:J.resetsAt}},Z.reservePercent[J.label]??0,$)),Y=Z.quota.budget;if(Y&&typeof Y.remainingPercent==="number"&&Number.isFinite(Y.remainingPercent))X.push(d0({remainingPercent:Y.remainingPercent,...Y.resetsAt===void 0?{}:{resetsAt:Y.resetsAt}},0,$));let G=X.length>0?Math.min(...X):0;return G>0?{candidate:Z,quotaCheckedAt:z,weight:G}:void 0}function W4(Z){let $=Z.candidates.filter((Y)=>Y.killswitchPasses!==!1);if(Z.candidates.length===0)throw Error("Cannot select a sticky candidate: input.candidates is empty");if($.length===0)return;let z=$.map((Y)=>k8(Y,Z.now)).filter((Y)=>Y!==void 0);if(z.length>0){z.sort((G,J)=>{let B=((Z.pendingBytes.get(G.candidate.accountId)??0)+Z.requestBytes)/Math.max(G.weight,l0),H=((Z.pendingBytes.get(J.candidate.accountId)??0)+Z.requestBytes)/Math.max(J.weight,l0);return B-H||G.candidate.configuredOrder-J.candidate.configuredOrder||J4(G.candidate.accountId,J.candidate.accountId)});let Y=z[0];if(Y)return{accountId:Y.candidate.accountId,quotaCheckedAt:Y.quotaCheckedAt,source:"weighted"}}Z.onEmptyWeightedSet?.();let X=[...$].sort((Y,G)=>{let J=(Y.resetCreditsApplicable??0)>0?1:0;return((G.resetCreditsApplicable??0)>0?1:0)-J||Y.configuredOrder-G.configuredOrder||J4(Y.accountId,G.accountId)})[0];if(!X)throw Error("Cannot select a sticky candidate: input.candidates is empty");return{accountId:X.accountId,quotaCheckedAt:oZ(X.quota,X.quotaCheckedAt),source:"mode-fallback"}}function u0(Z){let $=y(Z),z=new Map($.admitted.map((D)=>[D.id,D])),X=new Map($.refused.map((D)=>[D.id,D])),Y=new Set($.excluded.map((D)=>D.id)),G=new Set(Z.rows.map((D)=>D.id)),J=Z.pin!==void 0&&p0(Z.pin,G,Z.identities?.get(Z.pin.accountId));if(J&&Z.pin){let D=z.get(Z.pin.accountId);if(D&&Z.killswitch?.get(D.id)!==!1)return{outcome:"dispatch",accountId:D.id,source:"pin",...D.projection?.checkedAt===void 0?{}:{quotaCheckedAt:D.projection.checkedAt},pin:{action:"retain"},refusedSelections:[],admission:$}}let B=Z.pin?X.get(Z.pin.accountId):void 0,H=J&&Z.pin!==void 0&&Z.refusedPinPolicy==="move-on-confirmed-exhaustion"&&(Z.killswitch?.get(Z.pin.accountId)===!1||B?.reason==="exhausted"||B?.reason==="budget-spent"),Q=(D)=>{return(typeof Z.rowReservePercent==="function"?Z.rowReservePercent(D):Z.rowReservePercent?.get(D.id))??Z.reservePercent??{}},K=Z.scope,W=Z.rows.map((D,O)=>({row:D,configuredOrder:O})).filter(({row:D})=>!Y.has(D.id)).map(({row:D,configuredOrder:O})=>{let q=Z.killswitch?.get(D.id),L=Z.resetCreditsApplicable?.get(D.id);return{accountId:D.id,quota:D.kind==="api-key"?void 0:z.get(D.id)?.projection??C(D.quota,K),reservePercent:Q(D),configuredOrder:O,...L===void 0?{}:{resetCreditsApplicable:L},...q===void 0?{}:{killswitchPasses:q}}}),U=[],j=J?{action:"retain"}:Z.pin?{action:"clear"}:{action:"none"};while(W.length>0){let D=W4({candidates:W,pendingBytes:Z.pendingBytes??new Map,requestBytes:Z.requestBytes,now:Z.now,...Z.onEmptyWeightedSet?{onEmptyWeightedSet:Z.onEmptyWeightedSet}:{}});if(!D)break;let O=X.get(D.accountId);if(O){U.push(O),W=W.filter((L)=>L.accountId!==D.accountId);continue}let q=Z.identities?.get(D.accountId);return{outcome:"dispatch",accountId:D.accountId,source:D.source,...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt},pin:J&&!H?{action:"retain"}:{action:"assign",pin:{accountId:D.accountId,inputBytes:Z.requestBytes,...q===void 0?{}:{wireIdentity:q},...D.quotaCheckedAt===void 0?{}:{quotaCheckedAt:D.quotaCheckedAt}}},refusedSelections:U,admission:$}}return{outcome:"no-admissible-account",pin:j,refusedSelections:U,admission:$}}import{createHash as y8}from"node:crypto";var h8=86400000,w8=300000,m8=3600000,g8=60000,v8=900000,p8=300000;function a0(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 o0(Z){let $=a0(Z),z=Z?.status;if(typeof z==="number")return z===429||z>=500;if(!(Z instanceof Error))return!1;let X=Z.code;return Z.name==="AbortError"||Z.name==="TimeoutError"||$.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function Q4(Z){return y8("sha256").update(Z).digest("hex")}function U4(Z){let $=Q4(Z.refreshToken),X=(Z.previous?.tokenHash===$?Z.previous.retryCount??0:0)+1,Y,G=Z.error?.retryAfter;if(typeof G==="number"&&G>0)Y=G*1000;else if(l8(Z.error))Y=Math.min(m8,w8*2**Math.min(X-1,6));else Y=h8;return{message:a0(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+Y,retryCount:X,tokenHash:$}}function JZ(Z,$,z){if(!Z?.nextRetryAt||Z.nextRetryAt<=z)return!1;if(!$)return!0;return Z.tokenHash===Q4($)}function rZ(Z,$){return`Codex OAuth refresh is backed off for ${Math.max(1,Math.ceil(((Z.nextRetryAt??$)-$)/1000))}s after: ${Z.message}`}function EZ(Z){let z=(Z.previous?.retryCount??0)+1,X,Y=Z.error?.retryAfter;if(typeof Y==="number"&&Y>0)X=Y*1000;else if(o0(Z.error))X=Math.min(v8,g8*2**Math.min(z-1,6));else X=p8;return{message:a0(Z.error),checkedAt:Z.now,nextRetryAt:Z.now+X,retryCount:z}}function MZ(Z,$){if(!Z?.nextRetryAt||Z.nextRetryAt<=$)return!1;return!0}function r0(Z){if(!Z)return;let $=Number(Z);if(Number.isFinite($)&&$>0)return Math.ceil($);let z=Date.parse(Z);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{createServer as D4}from"node:http";import{setTimeout as d8}from"node:timers/promises";var $0="app_EMoamEEZ73f0CkXaXp7hrann",KZ="https://auth.openai.com",AZ=1455,c8=3000,u8="cortexkit-opencode-openai-auth";function j4(Z){return`${u8}/${Z}`}var q4="main",i8=`"${q4}" is a reserved account id; choose a different label.`;function O4(Z){let $=new Uint8Array(Z),z=String.fromCharCode(...$);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function s8(){let $=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=O4(await crypto.subtle.digest("SHA-256",new TextEncoder().encode($)));return{verifier:$,challenge:z}}function V4(Z){if(Z.length>16384)return;let $=Z.split(".");if($.length!==3)return;let z=$[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function F4(Z){let $=Z.chatgpt_account_id;if(typeof $==="string"&&$.length>0)return $;let z=Z["https://api.openai.com/auth"];if(z&&typeof z==="object"&&!Array.isArray(z)&&typeof z.chatgpt_account_id==="string"&&z.chatgpt_account_id.length>0)return z.chatgpt_account_id;let X=Z.organizations;if(Array.isArray(X)){let Y=X[0];if(Y&&typeof Y==="object"&&!Array.isArray(Y)&&typeof Y.id==="string"&&Y.id.length>0)return Y.id}return}function eZ(Z){if(Z.id_token){let $=V4(Z.id_token),z=$&&F4($);if(z)return z}if(Z.access_token){let $=V4(Z.access_token);return $?F4($):void 0}return}function n8(Z){return typeof Z==="string"&&Z.toLowerCase()===q4}function t0(Z){if(n8(Z))throw Error(i8);return Z}function a8(Z,$,z){let X=new URLSearchParams({response_type:"code",client_id:$0,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:z,originator:"opencode"});return`${KZ}/oauth/authorize?${X.toString()}`}async function o8(Z,$,z){let X=await fetch(`${KZ}/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:$0,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function r8(Z){return Z.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}var t8=`<!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>`,tZ=(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">${r8(Z)}</div>
85
+ </div>
86
+ </body>
87
+ </html>`,Z0=[],CZ,m=new Map;function N4(Z,$){return new Promise((z,X)=>{let Y=(J)=>{Z.off("listening",G),X(J)},G=()=>{Z.off("error",Y),z()};Z.once("error",Y),Z.once("listening",G),Z.listen(AZ,$)})}function M4(Z){Z.close(()=>{}),Z.closeIdleConnections?.(),setTimeout(()=>{Z.closeAllConnections?.()},25).unref?.()}function BZ(){return m.size}function WZ(Z){if(m.delete(Z),BZ()===0)HZ()}async function e8(){let Z=`http://localhost:${AZ}/auth/callback`;if(Z0.length>0)return{port:AZ,redirectUri:Z};if(CZ)return CZ;CZ=(async()=>{let $=(G,J)=>{let B=new URL(G.url||"/",`http://127.0.0.1:${AZ}`);if(B.pathname==="/auth/callback"){let H=B.searchParams.get("code"),Q=B.searchParams.get("state"),K=B.searchParams.get("error"),W=B.searchParams.get("error_description");if(K){let j=W||K;if(Q){let D=m.get(Q);if(D)D.reject(Error(j)),WZ(Q);else if(BZ()===0)HZ()}else if(BZ()===0)HZ();J.writeHead(200,{"Content-Type":"text/html"}),J.end(tZ(j));return}if(!Q){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Missing state parameter"));return}if(!H){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Missing authorization code"));return}let U=m.get(Q);if(!U){if(BZ()===0)HZ();J.writeHead(400,{"Content-Type":"text/html"}),J.end(tZ("Unknown state — authorization may have expired"));return}WZ(Q),o8(H,Z,U.pkce).then((j)=>U.resolve(j)).catch((j)=>U.reject(j)),J.writeHead(200,{"Content-Type":"text/html"}),J.end(t8);return}if(B.pathname==="/cancel"){let H=B.searchParams.get("state"),Q=H?[H]:[...m.keys()];J.writeHead(200),J.end("Login cancelled");for(let K of Q){let W=m.get(K);if(!W)continue;W.reject(Error("Login cancelled")),WZ(K)}if(BZ()===0)HZ();return}J.writeHead(404),J.end("Not found")},z=D4($);await N4(z,"127.0.0.1");let X=[z],Y=D4($);try{await N4(Y,"::1"),X.push(Y)}catch(G){let J=G.code;if(J!=="EADDRNOTAVAIL"&&J!=="EAFNOSUPPORT")throw M4(z),G}return Z0=X,{port:AZ,redirectUri:Z}})();try{return await CZ}finally{CZ=void 0}}function HZ(){let Z=Z0;Z0=[];for(let $ of Z)M4($)}function Z9(Z,$,z=300000,X){return new Promise((Y,G)=>{if(X?.aborted){WZ($),G(Error("Login cancelled"));return}let J=setTimeout(()=>{if(m.get($))WZ($),G(Error("OAuth callback timeout — authorization took too long"))},z),B=()=>{if(clearTimeout(J),m.get($))WZ($),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",B);m.set($,{pkce:Z,state:$,resolve:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);Y(H)},reject:(H)=>{if(clearTimeout(J),X)X.removeEventListener("abort",B);G(H)}})})}async function $9(Z){let $=await fetch(`${KZ}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":j4(Z)},body:JSON.stringify({client_id:$0})});if(!$.ok)throw Error("Failed to initiate device authorization");let z=await $.json();return{deviceData:z,url:`${KZ}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function z9(Z,$,z){let X=Math.max(parseInt(Z.interval,10)||5,1)*1000,Y=typeof Z.expires_in==="number"?Z.expires_in:parseInt(Z.expires_in||"",10),G=!Number.isNaN(Y)&&Y>0?Y*1000:900000,J=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-J>G)throw Error("Device authorization expired");let B=await fetch(`${KZ}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":j4($)},body:JSON.stringify({device_auth_id:Z.device_auth_id,user_code:Z.user_code})});if(B.ok){let K=await B.json(),W=await fetch(`${KZ}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:K.authorization_code,redirect_uri:`${KZ}/deviceauth/callback`,client_id:$0,code_verifier:K.code_verifier}).toString()});if(!W.ok)throw Error(`Token exchange failed: ${W.status}`);return await W.json()}if(B.status!==403&&B.status!==404)throw Error(`Device authorization failed: ${B.status}`);let H=G-(Date.now()-J);if(H<=0)throw Error("Device authorization expired");let Q=Math.min(X+c8,H);try{await d8(Q,void 0,{signal:z})}catch(K){if(K instanceof Error&&K.name==="AbortError")throw Error("Device authorization cancelled");throw K}}}async function z2(Z){let{label:$,headless:z=!1,signal:X,version:Y}=Z;if(t0($),z){let{deviceData:K,url:W,instructions:U}=await $9(Y),j=(async()=>{let D=await z9(K,Y,X),O=Date.now(),q=eZ(D);return{id:t0($||q||crypto.randomUUID()),label:$||void 0,type:"oauth",access:D.access_token,refresh:D.refresh_token,expires:O+(D.expires_in??3600)*1000,enabled:!0,addedAt:O,lastUsed:O,lastRefreshedAt:O,accountId:q}})();return{url:W,instructions:U,completion:j}}let{redirectUri:G}=await e8(),J=await s8(),B=O4(crypto.getRandomValues(new Uint8Array(32)).buffer),H=a8(G,J,B),Q=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let K=await Z9(J,B,void 0,X),W=Date.now(),U=eZ(K);return{id:t0($||U||crypto.randomUUID()),label:$||void 0,type:"oauth",access:K.access_token,refresh:K.refresh_token,expires:W+(K.expires_in??3600)*1000,enabled:!0,addedAt:W,lastUsed:W,lastRefreshedAt:W,accountId:U}}finally{WZ(B)}})();return{url:H,instructions:"Complete authorization in your browser. This window will close automatically.",completion:Q}}function z0(Z){if(Z==null||Z==="")return;let $=typeof Z==="number"?Z:Number(Z);if(Number.isFinite($)){let X=$<100000000000?$*1000:$,Y=new Date(X);return Number.isNaN(Y.getTime())?void 0:Y.toISOString()}let z=new Date(Z);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function e0(Z){let $=Number(Z);return Number.isFinite($)&&$>0?$:void 0}function _4(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>=0?Z:void 0}function P4(Z,$){let z=Z.get($);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let Y=$.slice(0,-13),G=e0(Z.get(`${Y}-window-minutes`)),J=z0(Z.get(`${Y}-reset-at`)??void 0);if(X===0&&Z.get(`${Y}-window-minutes`)==="0"&&!J)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:J,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}var x4=["x-codex-primary-used-percent","x-codex-secondary-used-percent"];function T4(Z,$){let z=Z.get($);if(z===null)return"absent";if(z.trim()==="")return"invalid";let X=Number(z);return Number.isFinite(X)&&X>=0&&X<=100?"valid":"invalid"}function Y2(Z){if(x4.some((G)=>T4(Z,G)==="invalid"))return{};let $={},z=P4(Z,"x-codex-primary-used-percent");if(z)$.primary=z;let X=P4(Z,"x-codex-secondary-used-percent");if(X)$.secondary=X;let Y=X9(Z);if(Y)$.credits=Y;return $}function L4(Z,$){let z=Z.get($)?.trim();if(z===void 0)return;if(z.toLowerCase()==="true"||z==="1")return!0;if(z.toLowerCase()==="false"||z==="0")return!1;return}function X9(Z){let $=L4(Z,"x-codex-credits-has-credits"),z=L4(Z,"x-codex-credits-unlimited");if($===void 0||z===void 0)return;let X=u(Z.get("x-codex-credits-balance")?.trim());return{hasCredits:$,unlimited:z,...X!==void 0?{balance:X}:{},checkedAt:Date.now()}}function G2(Z){let $=x4.map((z)=>T4(Z,z));return $.includes("valid")&&!$.includes("invalid")}function R4(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=e0(Z.window_minutes),z=z0(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$}:{}}}function J2(Z){let $={},z=R4(Z.rate_limits?.primary);if(z)$.primary=z;let X=R4(Z.rate_limits?.secondary);if(X)$.secondary=X;let Y=Y9(Z.credits);if(Y)$.credits=Y;return $}function Y9(Z){if(Z===null||typeof Z!=="object")return;let $=Z;if(typeof $.has_credits!=="boolean"||typeof $.unlimited!=="boolean")return;let z=u(typeof $.balance==="string"?$.balance.trim():$.balance);return{hasCredits:$.has_credits,unlimited:$.unlimited,...z!==void 0?{balance:z}:{},...typeof $.overage_limit_reached==="boolean"?{overageLimitReached:$.overage_limit_reached}:{},checkedAt:Date.now()}}function u(Z){if(Z==null||Z==="")return;let $=Number(Z);return Number.isFinite($)&&$>=0?$:void 0}function S4(Z){if(!Z)return;if(!Number.isFinite(Z.used_percent)||Z.used_percent<0||Z.used_percent>100)return;let $=e0(Z.limit_window_seconds),z=z0(Z.reset_at);if(Z.used_percent===0&&$===void 0&&!z)return;return{usedPercent:Z.used_percent,remainingPercent:100-Z.used_percent,resetsAt:z,checkedAt:Date.now(),...$!==void 0?{windowMinutes:$/60}:{}}}function E4(Z){let $={},z=S4(Z.rate_limit?.primary_window);if(z)$.primary=z;let X=S4(Z.rate_limit?.secondary_window);if(X)$.secondary=X;let Y=_4(Z.rate_limit_reset_credits?.available_count);if(Y!==void 0)$.resetCreditsAvailable=Y;let G=_4(Z.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)$.resetCreditsApplicable=G;let J=Z.spend_control?.individual_limit;if(Z.spend_control===null||J===null)$.spendControlCleared=!0;if(J&&typeof Z.spend_control?.reached==="boolean"){let H=u(J.limit),Q=u(J.used),K=u(J.remaining),W=u(J.used_percent),U=u(J.remaining_percent);if(H!==void 0&&Q!==void 0&&K!==void 0&&W!==void 0&&U!==void 0)$.spendControl={limit:H,used:Q,remaining:K,usedPercent:W,remainingPercent:U,resetsAt:z0(J.reset_at),unit:J.unit,source:J.source,reached:Z.spend_control.reached}}let B=Z.credits;if(B&&typeof B.has_credits==="boolean"&&typeof B.unlimited==="boolean"&&typeof B.overage_limit_reached==="boolean"){let H=u(B.balance);$.credits={hasCredits:B.has_credits,unlimited:B.unlimited,overageLimitReached:B.overage_limit_reached,...H!==void 0?{balance:H}:{},checkedAt:Date.now()}}return $}import{ClaustrumClient as n9}from"@cortexkit/claustrum-client";import{resolve as C4}from"node:path";import{storeIdentity as K9}from"@cortexkit/claustrum-client";import{SubcClient as A4}from"@cortexkit/subc-client";import{ClaustrumCredentialError as G9}from"@cortexkit/claustrum-client";import{SocketClosedError as J9,SocketTimeoutError as B9,SubcCallError as H9}from"@cortexkit/subc-client";class F extends Error{kind;constructor(Z,$){super($);this.name="ClaustrumConsumerError",this.kind=Z}}var Z3=Object.freeze({ECONNREFUSED:"unreachable",ENOENT:"unreachable",ECONNRESET:"unreachable",EPIPE:"unreachable",ETIMEDOUT:"unreachable",transport_error:"unreachable",unavailable:"unreachable",timeout:"unreachable",route_closed:"unreachable",daemon_draining:"unreachable",connection_closed:"unreachable",connection_dropped:"unreachable",request_deadline:"unreachable",deadline_exceeded_no_drop_observed:"unreachable",module_reloading:"unreachable",module_warming:"unreachable",target_unavailable:"unreachable",module_timeout:"unreachable",invalid_response:"answered",invalid_record_version:"answered",invalid_expiry:"answered",invalid_status:"answered",invalid_params:"answered",ttl_unsatisfiable:"answered",not_found:"answered",enrollment_revoked:"answered",enrollment_invalid:"answered",grant_denied:"answered",credential_unavailable:"answered",needs_reauth:"answered",declined:"answered",disabled:"answered",identity_changed:"answered",closed:"answered",client_closed:"answered",pending_exists:"answered",pending_queue_full:"answered",already_consumed:"answered",superseded:"answered",stale_generation:"answered",missing_identity:"answered",invalid_control_body:"answered",unknown_module:"answered",module_removed:"answered",capability_denied:"answered",unknown_channel:"unreachable",stale_route_epoch:"unreachable",capability_forbidden:"answered",capability_unprovided:"answered",capability_ambiguous:"answered",invalid_capability_identifier:"answered",binary_body_required:"answered",binary_call_requires_call_binary:"answered",corr_exhausted:"answered",late_route_cleanup_failed:"answered",reverse_request_capability_not_declared:"answered",stale_route_handle:"answered",reverse_request_unhandled:"answered",handler_error:"answered",health_error:"answered",duplicate_module_id:"answered",route_rejected:"answered",lock_busy:"answered",owner_invalid:"answered",renewal_failed:"answered",unsupported_platform:"answered",EACCES:"answered",EPERM:"answered",ERR_PRIVATE_FILES_SECURITY:"answered"});class QZ extends F{constructor(){super("unavailable","Claustrum scoped operation unavailable");this.name="ClaustrumUnreachableError"}}function i(Z){if(Z instanceof QZ||Z instanceof J9||Z instanceof B9)return"unreachable";let $=Z instanceof G9||Z instanceof H9?Z.code:Z instanceof Error&&("code"in Z)?Z.code:void 0;if(typeof $!=="string"||!Object.hasOwn(Z3,$))return"answered";return Z3[$]}var $3=300000,X0=300000,z3=1000;class IZ{#Z;#z=0;restart(){this.#z=0}continuous(Z){let $=Z.kind==="changed"&&Z.seq===this.#z+1&&(this.#Z===void 0||Z.epoch===this.#Z);return this.#Z=Z.epoch,this.#z=Z.seq,$}}class Y0{#Z;#z;#Y;#X=!1;constructor(Z,$){this.#Z=Z,this.#z=$}get running(){return this.#Y}request(){if(this.#Y)return this.#X=!0,this.#Y;return this.#Y=(async()=>{do{this.#X=!1;try{await this.#Z()}catch(Z){this.#z(Z)}}while(this.#X)})().finally(()=>{this.#Y=void 0}),this.#Y}}class G0{#Z;#z=new IZ;#Y;#X="polling";#H;#J;#$=!1;#K;#Q=!1;#B=0;constructor(Z){this.#Z=Z,this.#Y=new Y0(async()=>{let $=this.#Q;if(this.#Q=!1,$||this.#K!==this.#Z.view())await this.#Z.discover(this.#K??"")},($)=>{if(!this.#$)this.#Z.onError?.($)})}get mode(){return this.#X}start(){if(this.#$||this.#H||this.#J)return;if(typeof this.#Z.client.watchScoped!=="function"){this.#G("fallback","client-without-watch");return}this.#V(!1)}stop(){if(this.#$)return;if(this.#$=!0,this.#J)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#J);this.#J=void 0;let Z=this.#H;this.#H=void 0,Z?.handle.stop()}#G(Z,$){if(this.#X===Z)return;this.#X=Z,this.#Z.logger?.debug("claustrum vault watch",{mode:Z,reason:$}),this.#Z.onMode?.(Z)}#U(Z,$){this.#J=(this.#Z.setTimeoutImpl??setTimeout)(()=>{if(this.#J=void 0,!this.#$)$()},Z),this.#J.unref?.()}async#V(Z){let $;try{$=await this.#Z.enrollmentToken()}catch(J){if(this.#$)return;this.#Z.onError?.(J),this.#N("token-unreadable");return}let z=this.#Z.client.watchScoped;if(this.#$||this.#H||!z)return;this.#z.restart(),this.#Q=Z;let X,Y;try{Y=z.call(this.#Z.client,(J)=>{if(this.#$||!X||this.#H!==X)return;if(X.notices++,X.notices===1)this.#Z.onReachable?.(),X.acceptedAt=(this.#Z.now??Date.now)(),this.#G("watching","accepted");if(!this.#z.continuous(J))this.#Q=!0;this.#K=J.view,this.#Y.request()},{enrollmentToken:$})}catch(J){this.#Z.onError?.(J),this.#N("watch-failed");return}X={handle:Y,notices:0},this.#H=X,this.#G("polling",Z?"resubscribing":"opening");let G=X;Y.closed.then((J)=>this.#D(G,J),(J)=>this.#D(G,{kind:"transport_lost",error:J}))}#D(Z,$){if(this.#$||this.#H!==Z)return;if(this.#H=void 0,$.kind==="stopped")return;if($.kind==="transport_lost")this.#Z.onTransportLost?.();if($.kind==="unsupported"){this.#G("fallback","vault-without-watch");return}if($.kind==="refused"){this.#N("refused");try{this.#Z.onRefused($.error)}catch(z){this.#Z.onError?.(z)}return}if(Z.notices>0){let z=(this.#Z.now??Date.now)();if(Z.acceptedAt!==void 0&&z-Z.acceptedAt>=300000)this.#B=0;let X=Math.min(1000*2**Math.min(this.#B,16),300000);this.#B++,this.#G("polling","resubscribing"),this.#U(X,()=>void this.#V(!0));return}this.#N($.kind)}#N(Z){this.#G("fallback",Z),this.#U(300000,()=>void this.#V(!1))}}function b4(Z){let $=Z.identity??K9(Z.projectRoot??process.cwd(),Z.storagePath??process.cwd());return{connectionFile:Z.connectionFile,async getUsage(){let z,X=!1,Y,G=new Promise((B,H)=>{Y=setTimeout(()=>H(Error("insula usage timeout")),3000),Y.unref?.()}),J=(async()=>{if(z=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}):await A4.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:Math.min(Z.handshakeTimeoutMs??3000,3000)}),X)throw z.close(),Error("insula usage timeout");let B=await z.routeOpen({kind:"management_surface",module_id:"insula"},$);return await z.request(B,{method:"usage.get",params:{}})})();try{return await Promise.race([J,G])}finally{X=!0,clearTimeout(Y),z?.close()}},watchUsage(z){let X,Y,G=!1,J=(async()=>{let B,H=new Promise((K,W)=>{B=setTimeout(()=>W(Object.assign(Error("insula watch timeout"),{code:"timeout"})),3000),B.unref?.()}),Q=(async()=>{let K=Math.min(Z.handshakeTimeoutMs??3000,3000),W=Z.connector?await Z.connector({connectionFile:Z.connectionFile,handshakeTimeoutMs:K}):await A4.connect({connectionFile:Z.connectionFile,handshakeTimeoutMs:K});if(X=W,G){W.close();return}let U=await W.routeOpen({kind:"management_surface",module_id:"insula"},$);if(G){W.close();return}Y=W.subscribe(U,{method:"usage.watch"},z)})();try{await Promise.race([Q,H])}catch(K){throw G=!0,K}finally{clearTimeout(B)}if(Y)await Y.closed})().finally(()=>{G=!0,X?.close()});return{stop(){if(G)return;G=!0,Y?.unsubscribe(),X?.close()},closed:J}}}}var B0=60000,I4=4*B0,W9=2*B0,X3=new Map,J0=new Map;function bZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function Q9(Z){let $;try{$=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Z))}catch{return}if(!bZ($)||typeof $.kind!=="string"||typeof $.epoch!=="string"||$.epoch.length===0||typeof $.seq!=="number"||!Number.isSafeInteger($.seq)||$.seq<1||$.provider!==void 0&&typeof $.provider!=="string")return;return{kind:$.kind,epoch:$.epoch,seq:$.seq,...typeof $.provider==="string"&&{provider:$.provider}}}function U9(Z){return Z instanceof Error&&"code"in Z&&typeof Z.code==="string"?Z.code:void 0}class f4{transport;key;#Z=[];#z=!1;#Y=new Set;#X=new Map;#H=new Y0(async()=>{try{let Z=await this.transport.getUsage();if(!bZ(Z)||!Array.isArray(Z.result)||Z.error!==void 0)throw Error("unavailable insula usage");this.#Z=Z.result.filter(($)=>bZ($)&&typeof $.provider==="string"),this.#z=this.#Z.length===Z.result.length&&(Z.completeProviders===void 0||Array.isArray(Z.completeProviders)&&Z.completeProviders.every(($)=>typeof $==="string")),this.#Y=new Set(this.#z&&Array.isArray(Z.completeProviders)?Z.completeProviders:[]);for(let $ of this.#Y)this.#X.delete($)}catch{this.#Z=[],this.#z=!1,this.#Y.clear()}},()=>{});#J=new IZ;#$="polling";#K=0;#Q=0;#B=new Map;#G;#U;#V={};#D=0;constructor(Z,$){this.transport=Z,this.key=$}refresh(Z){if(this.#H.running)return this.#H.running;if(this.#$==="watching")return Promise.resolve();for(let[z,X]of J0)if(Z-X>=B0)J0.delete(z);let $=J0.get(this.key);if($!==void 0&&Z-$<B0)return Promise.resolve();return J0.set(this.key,Z),this.#H.request()}watchMode(){return this.#$}watch(Z={}){this.#K++;let $=Z.provider;if($===void 0)this.#Q++;else this.#B.set($,(this.#B.get($)??0)+1);if(this.#K===1)this.#V=Z,this.#W();let z=!1;return()=>{if(z)return;if(z=!0,$===void 0)this.#Q--;else{let X=(this.#B.get($)??1)-1;if(X>0)this.#B.set($,X);else this.#B.delete($)}if(--this.#K===0)this.#N()}}#N(){if(this.#U)(this.#V.clearTimeoutImpl??clearTimeout)(this.#U);this.#U=void 0;let Z=this.#G;this.#G=void 0,Z?.handle?.stop(),this.#$="polling"}#F(Z){this.#U=(this.#V.setTimeoutImpl??setTimeout)(()=>{if(this.#U=void 0,this.#K>0&&!this.#G)this.#W()},Z),this.#U.unref?.()}#W(){let Z=this.transport.watchUsage;if(!Z){this.#$="fallback";return}this.#$="polling",this.#J.restart();let $={notices:0};this.#G=$;let z;try{z=Z.call(this.transport,(X)=>this.#j($,X))}catch(X){this.#q($,X);return}$.handle=z,z.closed.then(()=>this.#q($,void 0),(X)=>this.#q($,X))}#j(Z,$){if(this.#G!==Z)return;if(Z.notices++,Z.notices===1)this.#$="watching";if(Z.notices===2)this.#D=0;let z=Q9($);if(!z)this.#J.restart();if(!(z?this.#J.continuous(z):!1)||z?.provider===void 0||this.#Q>0||this.#B.has(z.provider))this.#H.request()}#q(Z,$){if(this.#G!==Z)return;this.#G=void 0;let z=U9($);if(z==="unknown_method"||z==="usage_watch_limit"){this.#$="fallback";return}if(Z.notices>0){let X=Math.min(z3*2**Math.min(this.#D,16),X0);this.#D++,this.#$="polling",this.#F(X);return}if(this.#$="fallback",this.#H.request(),$===void 0||i($)==="unreachable")this.#F(X0)}current(Z,$,z){for(let X of this.#Z){if(X.provider!==Z||typeof X.account!=="string"||X.account.trim()!==$)continue;if(X.stale!==void 0||X.errorClass!==void 0||!bZ(X.usage))continue;let Y=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!Number.isFinite(Y)||z-Y>=I4)continue;return{entry:X,context:{fetchedAt:Y,...typeof X.source==="string"&&{source:X.source}}}}return}lookup(Z,$,z){if(!this.#z)return{miss:"unreachable"};let X=this.#Z.find((J)=>J.provider===Z&&typeof J.account==="string"&&J.account.trim()===$),Y=(X??this.#Z.find((J)=>J.provider===Z&&J.account===void 0&&J.errorClass!==void 0))?.errorClass;if(Y==="upstream_failed")return{miss:"upstream-failed"};if(Y==="credential_absent"||Y==="credential_unusable"||Y==="credential_rejected")return{miss:"credential"};if(Y!==void 0)return{miss:"unreachable"};if(X){let J=typeof X.fetchedAt==="string"?Date.parse(X.fetchedAt):Number.NaN;if(!bZ(X.usage)||!Number.isFinite(J))return{miss:"unreachable"};let B={entry:X,context:{fetchedAt:J,...typeof X.source==="string"&&{source:X.source}}};return z>=J+I4||X.stale!==void 0?{miss:"stale",reading:B}:{reading:B}}if(this.#Y.has(Z))return{miss:"absent"};let G=this.#X.get(Z)??z;return this.#X.set(Z,G),{miss:z-G>=W9?"unreachable":"cold"}}}function Y3(Z,$){let z=JSON.stringify([C4(Z.connectionFile),C4($)]),X=X3.get(z);if(!X)X={source:new f4(Z,z),refs:0},X3.set(z,X);X.refs++;let Y=!1;return{source:X.source,release(){if(Y)return;if(Y=!0,--X.refs===0)X3.delete(z)}}}import{ClaustrumCredentialError as _7}from"@cortexkit/claustrum-client";function G3(Z){let $=new AbortController,z=[],X=!1,Y=()=>{if(X)return;X=!0;for(let{source:B,listener:H}of z)B.removeEventListener("abort",H);z.length=0},G=(B)=>{if(X||$.signal.aborted)return;$.abort(B),Y()},J=Z.find((B)=>B.aborted);if(J)return $.abort(J.reason),{signal:$.signal,dispose:Y};for(let B of Z){if($.signal.aborted)break;let H=()=>G(B.reason);if(z.push({source:B,listener:H}),B.addEventListener("abort",H,{once:!0}),B.aborted)G(B.reason)}return{signal:$.signal,dispose:Y}}import{ClaustrumCredentialError as Y6}from"@cortexkit/claustrum-client";import{createHash as D9,randomBytes as V9,randomUUID as F9}from"node:crypto";import{constants as k4}from"node:fs";import{chmod as N9,mkdir as j9,open as p4,readFile as J3,realpath as q9,rename as O9,stat as l4,unlink as d4}from"node:fs/promises";import{basename as c4,dirname as n,extname as y4,isAbsolute as h4,join as K3,resolve as M9}from"node:path";import{ClaustrumCredentialError as _9,ClaustrumClient as P9,writeEnrollmentTokenFile as L9}from"@cortexkit/claustrum-client";var R9=1,K0=16384,u4=30000,W3=/^[0-9a-f]{64}$/,i4=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),s4=new Set(["pending_queue_full"]);function B3(Z){if(!(Z instanceof _9))return;if(i4.has(Z.code))return{code:Z.code,disposition:"terminal"};if(s4.has(Z.code))return{code:Z.code,disposition:"retry"};return{code:Z.code,disposition:Z.action==="retry"?"retry":"terminal"}}function S9(Z,$){if(!/^[a-z0-9][a-z0-9-]*$/.test(Z)||!/^[a-z0-9][a-z0-9-]*$/.test($))throw new F("invalid-state","Claustrum enrollment names use lowercase letters, digits and dashes");return`${Z}-${$}`}function x9(Z){return P9.connect(Z)}function n4(Z){let $=y4(Z)||".json",z=c4(Z,y4(Z));return{statePath:K3(n(Z),`${z}-state${$}`),tokenPath:Z}}function T9(Z){let $=Z.override?.trim();if($&&!h4($)&&!Z.cwd)throw new F("invalid-state","A relative Claustrum enrollment override needs a base directory");let z=$?h4($)?$:M9(Z.cwd,$):K3(Z.stateDir,`${Z.host}-enrollment.json`);return n4(z)}function a4(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function H0(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0}function o4(Z){return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=1}function fZ(){return new F("invalid-state","invalid Claustrum enrollment state")}function U0(Z){if(!a4(Z)||Z.version!==R9||typeof Z.proposedName!=="string"||Z.proposedName.length===0)throw fZ();if(Z.phase==="pending"){if(!W3.test(String(Z.requestSecret??""))||Z.requestId!==void 0&&(typeof Z.requestId!=="string"||Z.requestId.length===0)||!H0(Z.createdAt)||!H0(Z.updatedAt))throw fZ();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)||!o4(Z.tokenGeneration)||!H0(Z.updatedAt))throw fZ();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"||!H0(Z.updatedAt))throw fZ();return{version:1,phase:Z.phase,proposedName:Z.proposedName,...Z.errorCode!==void 0&&{errorCode:Z.errorCode},updatedAt:Z.updatedAt}}throw fZ()}function Q3(Z){if(!a4(Z)||!W3.test(String(Z.token??""))||!o4(Z.token_generation))throw new F("invalid-token","invalid Claustrum enrollment token file");return{token:Z.token,token_generation:Z.token_generation}}function E9(Z){if(!Z.isFile())throw new F("unsafe-file","Claustrum enrollment file must be a regular file");if((Z.mode&63)!==0)throw new F("unsafe-file","Claustrum enrollment file must be owner-only");let $=process.geteuid?.();if($!==void 0&&Z.uid!==$)throw new F("unsafe-file","Claustrum enrollment file must be owned by the current user")}function w4(Z){try{return JSON.parse(Z)}catch{throw new F("invalid-state","Claustrum enrollment file is not valid JSON")}}async function a(Z){if(DZ)try{await H3(n(Z));let z=await Q0(Z,!0);if(Buffer.byteLength(z)>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return w4(z)}catch(z){if(z.code==="ENOENT")return;throw z}let $;try{$=await p4(Z,k4.O_RDONLY|k4.O_NOFOLLOW)}catch(z){if(z.code==="ENOENT")return;throw new F("unsafe-file","Claustrum enrollment file could not be opened safely")}try{E9(await $.stat());let z=Buffer.alloc(K0+1),{bytesRead:X}=await $.read(z,0,z.byteLength,0);if(X>K0)throw new F("unsafe-file","Claustrum enrollment file is too large");return w4(z.subarray(0,X).toString("utf8"))}finally{await $.close()}}function m4(Z,$){let z=[];for(let X of Z.split(`
88
+ `)){if(X.trim()===""||X.startsWith("#"))continue;let Y=X.split(":");if(Y.length!==$||!/^[^\s:,]+$/.test(Y[0]??"")||!/^\d+$/.test(Y[2]??"")||!Number.isSafeInteger(Number(Y[2]))||$===7&&(!/^\d+$/.test(Y[3]??"")||!Number.isSafeInteger(Number(Y[3])))||$===4&&Y[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(Y[3]??""))return;z.push(Y)}return z}async function C9(Z,$,z){try{let[X,Y]=await Promise.all([J3(z.passwdPath??"/etc/passwd","utf8"),J3(z.groupPath??"/etc/group","utf8")]),G=m4(X,7),J=m4(Y,4);if(!G||!J)return!1;let B=G.filter((W)=>Number(W[2])===Z),H=J.filter((W)=>Number(W[2])===$);if(B.length!==1||H.length!==1)return!1;let Q=B[0]?.[0],K=H[0]?.[3]??"";return(K===""||K.split(",").every((W)=>W===Q))&&!G.some((W)=>Number(W[2])!==Z&&Number(W[3])===$)}catch{return!1}}function r4(Z){if(!Z.passwdPath&&!Z.groupPath)return;return{fs:{readFile:($)=>J3($==="/etc/passwd"?Z.passwdPath??$:$==="/etc/group"?Z.groupPath??$:$)}}}async function t4(Z,$={}){if(!DZ){let z=process.geteuid?.();if(z===void 0)return;let X=process.getegid?.(),Y;try{Y=await q9(Z)}catch{return}let G;for(;;){let J=await l4(Y).catch(()=>{return});if(J&&(J.mode&18)!==0&&(J.mode&512)===0){if(G===void 0)G=X!==void 0&&await C9(z,X,$);if((J.mode&2)!==0||J.uid!==z||J.gid!==X||!G)throw new F("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${Y}. Another user could replace it. Run: chmod g-w,o-w ${Y}`)}let B=n(Y);if(B===Y)return;Y=B}}try{await g4(Z,r4($))}catch(z){if(!(z instanceof i0))throw z;throw new F("unsafe-file",`Claustrum enrollment parent refused: ${z.path} (${z.reason??z.code}). Use a folder that other users cannot write or replace.`)}}async function W0(Z,$={}){if(DZ){await H3(Z,!1,r4($));return}await j9(Z,{recursive:!0,mode:448});let z=await l4(Z),X=process.geteuid?.();if(X!==void 0&&z.uid!==X)throw new F("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((z.mode&63)!==0)await N9(Z,448)}async function UZ(Z,$,z={}){let X=n(Z);await W0(X,z),await t4(X,z);let Y=`${JSON.stringify($)}
89
+ `;if(Buffer.byteLength(Y)>K0)throw new F("invalid-state","Claustrum enrollment state is too large");if(DZ)return v4(Z,Y);let G=K3(X,`.${c4(Z)}.${process.pid}.${F9()}.tmp`),J,B=!1;try{J=await p4(G,"wx",384),B=!0,await J.writeFile(Y,"utf8"),await J.chmod(384),await J.sync(),await J.close(),J=void 0,await O9(G,Z),B=!1}finally{if(await J?.close().catch(()=>{}),B)await d4(G).catch(()=>{})}}async function U3(Z,$){let z=await a(Z.tokenPath),X=z===void 0?void 0:Q3(z),Y=await a(Z.statePath),G=Y===void 0?void 0:U0(Y);if(X)return{state:"approved",proposedName:G?.proposedName??$,...G?.phase==="approved"&&G.approvedName!==void 0&&{approvedName:G.approvedName},tokenGeneration:X.token_generation};if(!G)return{state:"idle"};if(G.phase==="approved")return{state:"blocked",proposedName:G.proposedName,code:"missing_token"};return s(G)}async function A9(Z,$){let z;try{z=await U3(Z,$)}catch(X){if(!(X instanceof F)||X.kind!=="invalid-state"&&X.kind!=="invalid-token")return"unreadable";try{let Y=await a(Z.statePath);if(Y===void 0)return"unreadable";let G=U0(Y);return G.phase==="approved"&&G.proposedName===$?"vault":"unreadable"}catch{return"unreadable"}}if("proposedName"in z&&z.proposedName!==$)return"unreadable";if(z.state==="approved"||z.state==="blocked"&&z.code==="missing_token")return"vault";return"local"}async function o(Z){let $=await a(Z);if($===void 0)throw new F("not-enrolled","Claustrum enrollment is not configured");return Q3($)}function s(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 e4(){return new F("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class Z6{#Z;#z;#Y;#X;#H;#J;#$;constructor(Z){this.#$=Z.ancestorOptions??{},this.#Z=Z.client,this.#z=Z.paths,this.#Y=Z.proposedName,this.#X=Z.now??Date.now,this.#H=Z.mintSecret??(()=>V9(32).toString("hex")),this.#J=Z.writeTokenFile??L9}async status(){return U3(this.#z,this.#Y)}async resetTerminal(){return $6(this.#z,this.#Y)}async#K(Z,$){let z={version:1,phase:"blocked",proposedName:Z.proposedName,errorCode:$,updatedAt:this.#X()};return await UZ(this.#z.statePath,z,this.#$),s(z)}async reconcile(){await W0(n(this.#z.statePath),this.#$);let Z=await A({name:"ceremony",path:this.#z.statePath,ttlMs:u4,renew:!0});if(!Z)return{state:"busy"};try{let $=await a(this.#z.tokenPath),z=$===void 0?void 0:Q3($),X=await a(this.#z.statePath),Y=X===void 0?void 0:U0(X);if(Y&&Y.proposedName!==this.#Y)throw e4();if(z){if(!Y||Y.phase==="pending"){let J={version:1,phase:"approved",proposedName:Y?.proposedName??this.#Y,tokenGeneration:z.token_generation,updatedAt:this.#X()};await UZ(this.#z.statePath,J,this.#$),Y=J}return{state:"approved",proposedName:Y.proposedName,...Y.phase==="approved"&&Y.approvedName!==void 0&&{approvedName:Y.approvedName},tokenGeneration:z.token_generation}}if(Y?.phase==="approved"){let J={version:1,phase:"blocked",proposedName:Y.proposedName,errorCode:"missing_token",updatedAt:this.#X()};return await UZ(this.#z.statePath,J,this.#$),s(J)}if(Y&&Y.phase!=="pending")return s(Y);if(!Y){let J=this.#X();if(Y={version:1,phase:"pending",proposedName:this.#Y,requestSecret:this.#H(),createdAt:J,updatedAt:J},!W3.test(Y.requestSecret))throw new F("invalid-state","invalid minted Claustrum enrollment secret");await UZ(this.#z.statePath,Y,this.#$)}if(!Y.requestId)try{let J=D9("sha256").update(Buffer.from(Y.requestSecret,"hex")).digest("hex"),B=await this.#Z.enrollPropose({name:Y.proposedName,requestSecretHash:J});Y={...Y,requestId:B.requestId,updatedAt:this.#X()},await UZ(this.#z.statePath,Y,this.#$)}catch(J){let B=B3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,retryCode:B.code};return this.#K(Y,B.code)}let G=Y.requestId;if(!G)return s(Y);try{let J=await this.#Z.enrollPoll({requestId:G,requestSecret:Y.requestSecret});if(J.status==="pending")return s(Y);if(J.status==="denied"){let H={version:1,phase:"denied",proposedName:Y.proposedName,updatedAt:this.#X()};return await UZ(this.#z.statePath,H,this.#$),s(H)}await W0(n(this.#z.tokenPath),this.#$),await t4(n(this.#z.tokenPath),this.#$),await this.#J(this.#z.tokenPath,{token:J.token,token_generation:J.tokenGeneration});let B={version:1,phase:"approved",proposedName:Y.proposedName,approvedName:J.name,tokenGeneration:J.tokenGeneration,updatedAt:this.#X()};return await UZ(this.#z.statePath,B,this.#$),s(B)}catch(J){let B=B3(J);if(!B)throw J;if(B.disposition==="retry")return{state:"pending",proposedName:Y.proposedName,requestId:G,retryCode:B.code};return this.#K(Y,B.code)}}finally{await Z.release()}}}async function $6(Z,$){await W0(n(Z.statePath));let z=await A({name:"ceremony",path:Z.statePath,ttlMs:u4,renew:!0});if(!z)return"busy";try{if(await a(Z.tokenPath)!==void 0)return"refused-approved";let X=await a(Z.statePath);if(X===void 0)return"idle";let Y=U0(X);if(Y.proposedName!==$)throw e4();if(Y.phase==="pending")return"refused-pending";return await z.assertOwned(),await d4(Z.statePath),"reset"}finally{await z.release()}}var kZ="claustrum-tombstone:v1:";function D0(Z){return`${kZ}${Z}`}function D3(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function V0(Z){return typeof Z==="string"&&Z.startsWith(kZ)}function z6(Z,$){if(!D3(Z)||Z.type!=="oauth")return!1;return Z.refresh===D0($)}function X6(Z,$){if(z6(Z,$))return"placeholder";if(D3(Z)&&Z.type==="oauth"&&typeof Z.refresh==="string"&&Z.refresh.length>0&&!V0(Z.refresh))return"login";if(D3(Z)&&Z.type==="api"&&typeof Z.key==="string"&&Z.key.length>0)return"login";return"empty"}function I9(Z){let $=X6(Z.auth,Z.provider);if(Z.mode==="custody"&&$==="login")throw new F("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 F("host-slot-placeholder",`${Z.provider} host slot holds the vault placeholder; sign in to use local accounts`);return $}function G6(Z,$){return $!==void 0&&!$.fromKeptReceipt&&!Z.fromKeptReceipt&&$.credentialId===Z.credentialId&&$.accountIdentity===Z.accountIdentity&&$.recordVersion!==Z.recordVersion}function b9(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 F3=I("claustrum");function j3(Z,$,z,X=F3){let Y=G6($,z);return X.debug("scoped 401 re-authorized",{site:Z,credentialId:$.credentialId,servedVersion:$.recordVersion,currentVersion:z?.recordVersion??null,retry:Y,reason:b9($,z)}),Y}var N3=300000,J6=60000;function V3(){return new F("invalid-material","Claustrum returned invalid credential material")}function f9(Z){let $=Z.trim();if($.startsWith("{")){let z;try{z=JSON.parse($)}catch{throw V3()}if(!z||typeof z!=="object")throw V3();let X=z,Y=X.access_token??X.access;$=typeof Y==="string"?Y:""}if(!/^[\x21-\x7e]+$/.test($)||$.startsWith(kZ))throw V3();return $}function k9(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}function y9(Z){let{grants:$,grantTuples:z}=Z;if($===void 0||z===void 0)return;return Object.freeze({grants:$,tuples:Object.freeze(z.map(({selectorKind:X,selector:Y,operation:G})=>Object.freeze({selectorKind:X,selector:Y,operation:G})))})}class F0{#Z;#z;#Y;#X;#H;#J;#$;#K=new WeakMap;#Q=new WeakMap;#B=new Map;#G=new WeakMap;#U;#V;#D=!1;#N=new QZ;#F;#W=!1;#j=-1/0;#q=2000;#O=!1;#_;#P=new Set;constructor(Z){let $=Z.tokenPath;if(Z.readToken)this.#z=Z.readToken;else if($)this.#z=()=>o($);else throw new F("not-enrolled","Claustrum enrollment token path is required");this.#Z=Z.client,this.#X=Z.family,this.#H=Z.parseIdentity,this.#J=Z.requireAssertion??!1,this.#Y=Z.now??Date.now,this.#$=Z.logger??F3,this.#U=Z.setTimeoutImpl??setTimeout,this.#V=Z.clearTimeoutImpl??clearTimeout}transportLost(Z){if(this.#O||this.#D)return;this.#D=!0,this.#N=Z instanceof Y6?Z:new QZ,this.#$.warn("serving kept vault receipt",{reason:"unreachable"}),this.#L()}reachable(){if(this.#O||!this.#D)return;if(this.#D=!1,this.#F)this.#V(this.#F);this.#F=void 0,this.#q=2000;for(let Z of this.#B.values())Z.since=null;(this.#$.info??F3.info)("vault receipt serving resumed",{reason:"reachable"})}#L(){if(this.#O||!this.#D||this.#F||this.#W)return;this.#F=this.#U(()=>{this.#F=void 0,this.#R(!0)},this.#q),this.#F.unref?.()}#R(Z=!1){if(this.#O||!this.#D||this.#W)return;if(this.#Y()-this.#j<1000){this.#L();return}this.#j=this.#Y(),this.#W=!0,this.#T().catch(()=>{if(Z&&this.#D)this.#q=Math.min(this.#q*2,30000)}).finally(()=>{this.#W=!1,this.#L()})}#M(Z){if(this.#O)throw new F("closed","Claustrum scoped custody is closed");Z?.throwIfAborted()}async#S(Z){this.#M(Z);let $=await this.#z();if(this.#M(Z),!/^[0-9a-f]{64}$/.test($.token)||!Number.isSafeInteger($.token_generation)||$.token_generation<1)throw new F("invalid-token","Invalid Claustrum enrollment token");return $.token}async#x(Z,$){this.#M($);let z,X;try{let Y=Z();z=$?await Promise.race([Y,new Promise((G,J)=>{let B=()=>J($.reason);if($.addEventListener("abort",B,{once:!0}),X=()=>$.removeEventListener("abort",B),$.aborted)B()})]):await Y}catch(Y){if(this.#M($),i(Y)==="unreachable")this.transportLost(Y);else this.reachable();if(Y instanceof Y6)throw Y;if(i(Y)==="unreachable")throw new QZ;throw new F("unavailable","Claustrum scoped operation unavailable")}finally{X?.()}return this.#M($),this.reachable(),z}async discover(Z){let $=await this.#T(Z);return this.#_=$.view,$}async#T(Z){let $,z;try{z=await this.#S(Z)}catch(H){throw this.#B.clear(),H}try{$=await this.#x(()=>this.#Z.listScoped(z),Z)}catch(H){throw this.listFailed(H),H}let X=[],Y=[],G=new Map;for(let H of $.rows){let Q=k9(H,this.#X);if(!Q)continue;Y.push({row:H,type:Q}),G.set(H.id,(G.get(H.id)??0)+1)}let J=[];for(let{row:H,type:Q}of Y){let K;if(!H.id.trim())K="empty credential id";else if((G.get(H.id)??0)>1)K="duplicate credential id";else if(H.accountId!==void 0&&!H.accountId.trim())K="blank account identity";else if(!H.state.trim())K="empty state";if(K){X.push({...H.id.trim()&&{credentialId:H.id},reason:K});continue}J.push(Object.freeze({credentialId:H.id,credentialType:Q,...H.accountId!==void 0&&{accountIdentity:H.accountId},state:H.state,...H.email!==void 0&&{email:H.email},...H.orgName!==void 0&&{orgName:H.orgName}}))}for(let H of X)this.#$.warn("skipped malformed vault record",H);let B=y9($);return{view:$.view,credentials:Object.freeze(J),skipped:Object.freeze(X),...B&&{grantReach:B}}}listFailed(Z){if(i(Z)==="unreachable")this.transportLost(Z);else this.reachable(),this.#B.clear()}forget(Z){this.#B.delete(Z)}retain(Z){let $=new Map(Z.map((z)=>[z.credentialId,z]));for(let[z,X]of this.#B){let Y=$.get(z);if(!Y?.enabled||Y.state!=="active"||Y.credentialType!==X.attempt.credentialType||Y.accountIdentity!==X.attempt.expectedAccountIdentity)this.forget(z)}}keptReceiptState(){let Z=null;for(let[$,z]of this.#B){if(!this.#E(z.attempt)){this.forget($);continue}if(z.since!==null)Z=Math.min(Z??z.since,z.since)}return Object.freeze({active:Z!==null,since:Z})}#E(Z){return Z.expiresAtMs===null?Z.credentialType==="api_key":Z.expiresAtMs-this.#Y()>J6}async authorize(Z,$,z="vault"){this.#M($);let{credentialId:X,credentialType:Y,accountIdentity:G}=Z,J=this.#B.get(X);if(J&&(J.attempt.credentialType!==Y||J.attempt.expectedAccountIdentity!==G))this.forget(X),J=void 0;let B;try{B=await this.#S($)}catch(H){throw this.#B.clear(),H}if(this.#D&&J)return this.#R(),this.#C(X,J,B,z);try{let H=await this.#A({credentialId:X,credentialType:Y,accountIdentity:G},B,$);return this.#B.set(X,{attempt:H,routeId:z,since:null}),H}catch(H){if(this.#M($),i(H)!=="unreachable")throw this.forget(X),H;return this.#C(X,J,B,z,H)}}#C(Z,$,z,X,Y=this.#N){if(!$||this.#B.get(Z)!==$||!this.#E($.attempt))throw this.forget(Z),Y;if($.since===null)$.since=this.#Y();let G=Object.freeze(Object.defineProperty({...$.attempt,fromKeptReceipt:!0},"accessToken",{value:$.attempt.accessToken,enumerable:!1}));return this.#K.set(G,z),this.#G.set(G,X),G}async#A(Z,$,z){if(!Z.credentialId)throw new F("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:X,credentialType:Y,accountIdentity:G}=Z;if(this.#J&&G===void 0)throw new F("identity-unasserted","Claustrum dispatch requires a known account identity");let J=await this.#x(()=>this.#Z.getScoped({credentialId:X,enrollmentToken:$,...Y==="oauth"&&{minTtlMs:N3}}),z);if(J.credentialId!==void 0&&J.credentialId!==X)throw new F("identity-changed","Claustrum served credential identity changed");let B=J.expiresAtMs;if(!Number.isSafeInteger(J.recordVersion)||J.recordVersion<0||B===null&&Y==="oauth"||B!==null&&(!Number.isFinite(B)||B-this.#Y()<N3))throw new F("insufficient-validity","Claustrum served credential has insufficient validity");let H=f9(J.material),Q=J.accountId?.trim()?J.accountId:void 0;if(this.#J&&(J.credentialId===void 0||Q===void 0))throw new F("identity-unasserted","Claustrum served credential did not assert its identity");let K=Q===void 0?this.#H?.(H):void 0,W=Q??K;if(G!==void 0&&W!==void 0&&W!==G)throw new F("identity-changed","Claustrum served credential identity changed");let U=W??G,D=Object.freeze(Object.defineProperty({credentialId:X,credentialType:Y,...U!==void 0&&{accountIdentity:U},accountIdentitySource:Q!==void 0?"asserted":K!==void 0?"parsed":G!==void 0?"expected":"none",...G!==void 0&&{expectedAccountIdentity:G},...J.credentialId!==void 0&&{assertedCredentialId:J.credentialId},...Q!==void 0&&{assertedAccountIdentity:Q},...J.projectId!==void 0&&{projectId:J.projectId},recordVersion:J.recordVersion,expiresAtMs:B},"accessToken",{value:H,enumerable:!1}));return this.#K.set(D,$),D}async reportFailure(Z,$,z){if($!==401)return;this.#M();let X=this.#K.get(Z);if(!X)throw new F("no-receipt","Claustrum failure report requires an original dispatch receipt");let Y=this.#G.get(Z);if(Y!==void 0){this.forget(Z.credentialId),this.#$.debug("scoped 401 not reported",{routeId:Y,reason:"kept-receipt"});return}let G=this.#B.get(Z.credentialId);if(G&&G.attempt.recordVersion===Z.recordVersion)this.forget(Z.credentialId);let J=this.#Q.get(Z);if(J)return J;let B=this.#x(()=>this.#Z.reportAuthFailureScoped({credentialId:Z.credentialId,enrollmentToken:X,providerStatus:401,recordVersion:Z.recordVersion,reporterSource:z}));this.#Q.set(Z,B);try{await B,this.#$.debug("scoped 401 reported",{credentialId:Z.credentialId,recordVersion:Z.recordVersion,reporterSource:z})}catch(H){throw this.#Q.delete(Z),H}}watchRoster(Z){this.#M();let $=new G0({client:this.#Z,enrollmentToken:()=>this.#S(),view:Z.view??(()=>this.#_),discover:async(z)=>{await Z.onView(z)},onRefused:(z)=>{this.listFailed(z),Z.onRefused?.(z)},onTransportLost:()=>this.transportLost(),onReachable:()=>this.reachable(),onError:Z.onError,onMode:Z.onMode,logger:this.#$,now:this.#Y,setTimeoutImpl:this.#U,clearTimeoutImpl:this.#V});return this.#P.add($),$.start(),{get mode(){return $.mode},close:()=>{this.#P.delete($),$.stop()}}}close(){if(this.#O)return;if(this.#O=!0,this.#F)this.#V(this.#F);this.#F=void 0;for(let Z of this.#P)Z.stop();this.#P.clear(),this.#B.clear(),this.#Z.close()}}import{resolve as C3}from"node:path";import{createHash as h9}from"node:crypto";import{resolve as K6}from"node:path";function B6(Z,$,z){if(Z.accountIdentity!==void 0&&z!==void 0)return Z.accountIdentity===z;return Z.credentialId===$}function q3(Z,$,z){return Z.some((X)=>B6(X,$,z))}function O3(Z,$,z){let X={credentialId:$,...z!==void 0&&{accountIdentity:z}};return[...Z.filter((Y)=>Y.credentialId!==$||Y.accountIdentity!==z),X]}function M3(Z,$,z){return Z.filter((X)=>!$.some((Y)=>B6(X,Y,z)))}var W6="vault:";function w9(Z){return h9("sha256").update(Z).digest("hex")}function m9(Z){let $=Z.credentialId.split(":");return($.length>=3?$.slice(2).join(":").trim():void 0)||Z.email||Z.credentialId}function g9(Z){return Z.identity!==void 0?`identity:${Z.identity}`:`credential:${Z.credential.credentialId}`}function r(Z){return[Z.credentialId,...Z.aliases??[]]}function Q6(Z,$,z={}){let X=z.now??Date.now(),Y=z.routePrefix??W6,G=z.reservedRouteIds??new Set,J=Z?.rows??[],B=[...Z?.declined??[]],H=$.skipped.length===0,Q=new Set($.credentials.map((V)=>V.credentialId)),K=new Set($.skipped.flatMap((V)=>V.credentialId===void 0?[]:[V.credentialId])),W=$.skipped.some((V)=>V.credentialId===void 0),U=(V)=>!Q.has(V)&&(K.has(V)||W),j=new Map;for(let V of J){if(V.accountIdentity===void 0)continue;for(let M of r(V))if(!j.has(M))j.set(M,V.accountIdentity)}let D=new Map;for(let V of $.credentials){let M=V.accountIdentity!==void 0?{credential:V,identity:V.accountIdentity,claimed:!0}:{credential:V,identity:j.get(V.credentialId),claimed:!1},l=g9(M),d=D.get(l)??[];d.push(M),D.set(l,d)}let O=new Set,q=new Set(G),L=[],T=(V,M)=>V.credential.credentialId.localeCompare(M.credential.credentialId),p=[...D.values()].map((V)=>V.toSorted(T)).sort((V,M)=>V[0]&&M[0]?T(V[0],M[0]):0);for(let V of p){let M=V[0]?.identity,l=V.filter((_)=>_.credential.state==="active"),d=l.length?l:V,E0=d.filter((_)=>_.claimed),dZ=E0.length?E0:d,C0=new Set(V.map((_)=>_.credential.credentialId)),v3=J.find((_)=>!O.has(_)&&r(_).some((jZ)=>C0.has(jZ))&&(_.accountIdentity===void 0||_.accountIdentity===M)),A0=dZ.find((_)=>_.credential.credentialId===v3?.credentialId)??dZ[0];if(!A0)continue;let E=A0.credential,k=v3??(M===void 0?void 0:J.find((_)=>!O.has(_)&&_.accountIdentity===M));if(k)O.add(k);let zZ=k?.routeId;if(!zZ||G.has(zZ)){let _=`${Y}${E.credentialId}${M===void 0?"":`~${w9(M).slice(0,10)}`}`;zZ=_;for(let jZ=2;q.has(zZ);jZ++)zZ=`${_}~${jZ}`}q.add(zZ);let Y8=k?r(k).filter(U):[],I0=[...new Set([...V.map((_)=>_.credential.credentialId),...Y8])].filter((_)=>_!==E.credentialId).sort((_,jZ)=>_.localeCompare(jZ)),G8=z.mapAccount?.(E)??{};L.push({previousIndex:k?J.indexOf(k):1/0,row:{routeId:zZ,credentialId:E.credentialId,credentialType:E.credentialType,...M!==void 0&&{accountIdentity:M},...I0.length&&{aliases:I0},state:E.state,label:G8.label?.trim()||m9(E),...E.email!==void 0&&{email:E.email},...E.orgName!==void 0&&{orgName:E.orgName},enabled:![E.credentialId,...I0].some((_)=>q3(B,_,M)),addedAt:k?.addedAt??X,...k?.quota!==void 0&&{quota:k.quota},...!A0.claimed&&M!==void 0&&{unclaimed:!0}}})}return J.forEach((V,M)=>{if(O.has(V)||!r(V).some(U))return;if(q.has(V.routeId))return;let[l,...d]=r(V).filter((C0)=>!Q.has(C0));if(l===void 0)return;q.add(V.routeId);let{aliases:E0,...dZ}=V;L.push({previousIndex:M,row:{...dZ,credentialId:l,...d.length&&{aliases:d},stale:!0}})}),L.sort((V,M)=>V.previousIndex===M.previousIndex?V.row.credentialId.localeCompare(M.row.credentialId):V.previousIndex-M.previousIndex),{version:1,view:$.view,complete:H,...!H&&{rejected:$.skipped.map((V)=>({...V.credentialId!==void 0&&{credentialId:V.credentialId},reason:V.reason}))},rows:L.map((V)=>V.row),declined:B}}function _3(Z){return(Z?.rows??[]).filter(($)=>$.enabled&&$.state==="active").map(($)=>({id:$.routeId,kind:$.credentialType==="oauth"?"oauth":"api-key",...$.quota!==void 0&&{quota:$.quota}}))}function yZ(Z){return typeof Z==="object"&&Z!==null&&!Array.isArray(Z)}function _Z(Z){return Z===void 0||typeof Z==="string"}function v9(Z){let $=yZ(Z)?YZ(Z.quota):void 0;if(!yZ(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"||!_Z(Z.accountIdentity)||!_Z(Z.email)||!_Z(Z.orgName)||Z.aliases!==void 0&&(!Array.isArray(Z.aliases)||!Z.aliases.every((z)=>typeof z==="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 p9=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function H6(Z){if(!Array.isArray(Z))return;let $=[];for(let z of Z){if(!yZ(z)||!_Z(z.credentialId)||typeof z.reason!=="string"||!p9.has(z.reason))return;$.push(z)}return $}function l9(Z){if(!yZ(Z)||Z.version!==1||!_Z(Z.view)||!Array.isArray(Z.rows)||!Array.isArray(Z.declined)||Z.complete!==void 0&&typeof Z.complete!=="boolean"||Z.rejected!==void 0&&!H6(Z.rejected))throw new F("invalid-state","Claustrum roster file is not valid");let $=[];for(let Y of Z.rows){let G=v9(Y);if(!G)throw new F("invalid-state","Claustrum roster file is not valid");$.push(G)}let z=[];for(let Y of Z.declined){if(!yZ(Y)||typeof Y.credentialId!=="string"||!_Z(Y.accountIdentity))throw new F("invalid-state","Claustrum roster file is not valid");z.push(Y)}let X=H6(Z.rejected);return{version:1,...typeof Z.view==="string"&&{view:Z.view},complete:Z.complete!==!1,...X&&{rejected:X},rows:$,declined:z}}async function f(Z){let $;try{$=await Q0(Z,DZ)}catch(X){if(X.code==="ENOENT")return;throw X}let z;try{z=JSON.parse($)}catch{throw new F("invalid-state","Claustrum roster file is not valid")}return l9(z)}var d9={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000,renew:!0},c9={name:"claustrum-roster",ttlMs:30000};async function PZ(Z,$,z={}){return n0(Z,{...d9,signal:z.signal},async(X)=>{let Y=await f(Z),{next:G,result:J}=await $(Y,{assertOwned:()=>X.assertOwned()});if(G)await X.assertOwned(),await w(Z,G,{beforeRename:async()=>{await z.beforePublish?.(),z.signal?.throwIfAborted(),await X.assertOwned()}});return J})}function P3(Z,$){return PZ(Z,(z)=>{let X=z?.rows.find((G)=>G.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");let Y=O3(z.declined,X.credentialId,X.accountIdentity);return{next:{...z,declined:Y,rows:z.rows.map((G)=>G===X?{...G,enabled:!1}:G)},result:void 0}})}function L3(Z,$){return PZ(Z,(z)=>{let X=z?.rows.find((Y)=>Y.routeId===$);if(!z||!X)throw new F("route-unavailable","Claustrum route is not in the roster");return{next:{...z,declined:M3(z.declined,r(X),X.accountIdentity),rows:z.rows.map((Y)=>Y===X?{...Y,enabled:!0}:Y)},result:void 0}})}function u9(Z,$){if(!r(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")&&r(Z).length===1)return"bind";return"refuse"}async function R3(Z,$){let{routeId:z,observation:X,...Y}=$;return U6(Z,{routeId:z,observation:X,accountIdentity:Y.accountIdentity,receipt:Y})}async function U6(Z,$){if(!OZ($.observation))return!1;let z=g(Z,await f(Z));if(!t(z,$).kept)return!1;return D6(Z,$)}function S3(Z,$){return U6(Z,$)}function t(Z,$){let z=Z?.rows.find((J)=>J.routeId===$.routeId),X=!z?"refuse":$.receipt?u9(z,$.receipt):z.accountIdentity!==void 0&&z.accountIdentity===$.accountIdentity?"hold":"refuse";if(!Z||!z||X==="refuse")return{roster:Z,kept:!1};let Y=xZ(z.quota,$.observation),G=X==="bind"?{accountIdentity:$.accountIdentity,unclaimed:!0}:{};return{roster:{...Z,rows:Z.rows.map((J)=>J===z?{...J,...G,quota:Y}:J)},kept:!0}}var N0=new Map;function x3(Z){N0.delete(K6(Z))}async function T3(Z){Z.signal?.throwIfAborted();let $=async()=>await Z.isActive?.()??!0;if(!await $()){x3(Z.path);return}let z=await A({...c9,path:Z.path,renew:!0});if(!z){let G=await f(Z.path);if(Z.signal?.throwIfAborted(),!G?.view)throw new F("roster-busy","Claustrum account discovery is already in progress");return G}let X=K6(Z.path),Y;try{let G=await f(Z.path),J=N0.get(X);Y=J&&(J.previousView===G?.view||J.inventory.view===G?.view)?J:{inventory:await Z.custody.discover(Z.signal),previousView:G?.view},N0.delete(X);let{inventory:B}=Y;return Z.onInventory?.(B),Z.signal?.throwIfAborted(),await PZ(Z.path,async(H)=>{if(!await $())return{result:void 0};Z.signal?.throwIfAborted(),await z.assertOwned();let Q=typeof Z.projection==="function"?Z.projection():Z.projection,K=Q6(H,B,Q);return{...JSON.stringify(H)!==JSON.stringify(K)&&{next:K},result:K}},{beforePublish:async()=>{Z.signal?.throwIfAborted(),await z.assertOwned()}})}catch(G){if(G instanceof s0&&Y&&!Z.signal?.aborted&&await $())N0.set(X,Y);throw G}finally{await z.release()}}var LZ=new Map,i9=I("claustrum"),V6=100;function F6(Z){let $=C3(Z),z=LZ.get($);if(!z)z={path:$,pending:new Map,listeners:new Set,wake:new Set,abort:new AbortController,failures:0,draining:!1,order:0},LZ.set($,z);return z}function N6(Z,$){let z=F6(Z);z.listeners.add($);let X;return()=>X??=(()=>{return z.listeners.delete($),z.listeners.size?Promise.resolve():E3(Z)})()}function s9(Z){let $=new Map,{observation:z}=Z,X=JSON.stringify([Z.routeId,Z.receipt?.credentialId,Z.receipt?.accountIdentitySource,Z.receipt?.expectedAccountIdentity]),Y=(B,H,Q)=>$.set(`${X}:${B}`,{at:H,order:0,publication:{...Z,observation:Q}}),G=(B,H)=>JSON.stringify([B??"all",H]),J=new Set;for(let B of z.readings??[]){let H=G(B.scope,B.label);J.add(H),Y(H,z.checkedAt,{checkedAt:z.checkedAt,readings:[{...B}]})}for(let B of z.coverage??[]){let H=G(B.scope,B.label);if(!J.has(H))Y(H,z.checkedAt,{checkedAt:z.checkedAt,coverage:[{...B}]})}if(z.budget)Y("budget",z.checkedAt,{checkedAt:z.checkedAt,budget:{...z.budget}});for(let[B,H]of Object.entries(z.counters??{}))Y(`counter:${B}`,H.checkedAt,{checkedAt:z.checkedAt,counters:{[B]:{...H}}});if(z.credits)Y("credits",z.credits.checkedAt,{checkedAt:z.checkedAt,credits:{...z.credits}});if(!$.size)Y("empty",z.checkedAt,{checkedAt:z.checkedAt});return $}function D6(Z,$){if(!OZ($.observation))return Promise.resolve(!1);let z=F6(Z),X=JSON.stringify([$.accountIdentity??null,$.accountIdentity===void 0?$.routeId:null]),Y=z.pending.get(X)??new Map;for(let[G,J]of s9($)){let B=Y.get(G);if(!B||J.at>=B.at){if(J.order=++z.order,J.publication.observation.coverage)J.priorReading=B?.publication.observation.readings?B.publication:B?.priorReading;Y.set(G,J)}}if(Y.size)z.pending.set(X,Y);for(let G of z.listeners)G($);return q6(z,V6),Promise.resolve(!0)}function j6(Z){return[...Z.values()].flatMap(($)=>[...$.values()]).sort(($,z)=>$.order-z.order)}function g(Z,$){let z=LZ.get(C3(Z));if(z)for(let X of j6(z.pending)){if(X.priorReading)$=t($,X.priorReading).roster;$=t($,X.publication).roster}return $}function q6(Z,$){if(Z.running||Z.timer||!Z.pending.size||Z.abort.signal.aborted)return;if(Z.timer=setTimeout(()=>{Z.timer=void 0,O6(Z)},$),!Z.draining)Z.timer.unref?.()}function O6(Z){if(Z.running||Z.abort.signal.aborted)return;let $=new Map([...Z.pending].map(([z,X])=>[z,new Map(X)]));Z.running=(async()=>{try{await PZ(Z.path,(z)=>{let X=z;for(let Y of j6($)){if(Y.priorReading)X=t(X,Y.priorReading).roster;X=t(X,Y.publication).roster}return{...X!==z&&{next:X},result:void 0}},{signal:Z.abort.signal});for(let[z,X]of $){let Y=Z.pending.get(z);for(let[G,J]of X)if(Y?.get(G)===J)Y.delete(G);if(!Y?.size)Z.pending.delete(z)}Z.failures=0}catch(z){if(!Z.abort.signal.aborted&&Z.failures++===0)i9.warn("vault quota publication delayed; retrying",{error:z instanceof Error?z.message:String(z)})}finally{Z.running=void 0;for(let X of Z.wake)X();let z=Z.failures?Math.min(5000,100*2**Math.min(Z.failures,6))*(0.5+Math.random()):V6;q6(Z,z)}})()}async function E3(Z,$=1000){let z=C3(Z),X=LZ.get(z);if(!X)return;X.draining=!0,clearTimeout(X.timer),X.timer=void 0;let Y,G,J=new Promise((B)=>{G=()=>{if(!X.pending.size||X.abort.signal.aborted)B()},X.wake.add(G),G()});try{if(X.pending.size)O6(X);await Promise.race([J,new Promise((B)=>{Y=setTimeout(B,Math.max(0,$))})])}finally{if(clearTimeout(Y),G)X.wake.delete(G);if(X.draining=!1,!X.listeners.size){if(X.abort.abort(),clearTimeout(X.timer),X.pending.clear(),LZ.get(z)===X)LZ.delete(z)}}}class M6{#Z;#z=new AbortController;#Y;#X;#H;#J;#$;#K;#Q;#B=!1;#G;#U;#V;#D=new Map;#N;#F;constructor(Z){this.#Z=Z,this.#Y=Z.logger??I("claustrum"),this.#F=N6(Z.rosterPath,($)=>{this.#$=t(this.#$,$).roster})}#W(Z){this.#z.signal.throwIfAborted(),Z?.throwIfAborted()}async#j(){return await this.#Z.isCustodyActive?.()??!0}#q(Z,$){let z=G3([this.#z.signal,...$?[$]:[]]);return new Promise((X,Y)=>{let G=()=>{z.signal.removeEventListener("abort",J),z.dispose()},J=()=>{G(),Y(z.signal.reason)};if(z.signal.addEventListener("abort",J,{once:!0}),Z.then((B)=>{if(G(),z.signal.aborted)Y(z.signal.reason);else X(B)},(B)=>{G(),Y(B)}),z.signal.aborted)J()})}async#O(){if(this.#W(),this.#X)return this.#X;if(!this.#H)this.#H=this.#Z.connect().then((Z)=>{if(this.#z.signal.aborted)Z.close(),this.#W();if(this.#X=new F0({client:Z,family:this.#Z.family,tokenPath:this.#Z.tokenPath,parseIdentity:this.#Z.parseIdentity,requireAssertion:this.#Z.requireAssertion,now:this.#Z.now,logger:this.#Y,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl}),this.#Z.insula&&Z.insula)this.#G=Y3(Z.insula,this.#Z.tokenPath);return this.#X}).finally(()=>{this.#H=void 0});return this.#q(this.#H)}snapshot(){return this.#$}grantReach(){let Z=this.#K;return Z&&this.#$?.view===Z.view?Z.reach:void 0}watchState(){return Object.freeze({vault:this.#U?.mode??"polling",...this.#Z.insula&&{insula:this.#G?.source.watchMode()??"polling"}})}#_(){this.#U?.close(),this.#U=void 0,this.#V?.(),this.#V=void 0}keptReceiptState(){return this.#X?.keptReceiptState()??Object.freeze({active:!1,since:null})}routingRows(){return _3(this.#$)}refresh(){if(this.#W(),this.#J)return this.#J;return this.#J=(async()=>{if(!await this.#j()){this.#$=void 0,this.#K=void 0,this.#_(),this.#X?.close(),this.#X=void 0,this.#G?.release(),this.#G=void 0;return}let Z=await this.#O(),$,z=await T3({path:this.#Z.rosterPath,custody:Z,onInventory:(Y)=>{$=Y},isActive:()=>this.#j(),signal:this.#z.signal,projection:()=>({reservedRouteIds:new Set(this.#Z.reservedRouteIds?.()??[]),routePrefix:this.#Z.routePrefix,mapAccount:this.#Z.mapAccount,now:(this.#Z.now??Date.now)()})});this.#W();let X=z?.view!==this.#$?.view;if(this.#$=g(this.#Z.rosterPath,z),Z.retain(z?.rows??[]),$&&z?.view!==void 0)this.#K=$.grantReach?{view:z.view,reach:$.grantReach}:void 0;if(z&&X)this.#Z.onRoster?.(z);return this.#N=(this.#Z.now??Date.now)(),z})().finally(()=>{this.#J=void 0}),this.#J}start(){if(this.#B)return;this.#W(),this.#B=!0;let Z=async()=>{try{if(await this.#P())await this.refresh();await this.refreshInsulaQuota(),this.#L()}catch(z){if(!this.#z.signal.aborted)this.#Z.onError?.(z)}if(this.#z.signal.aborted)return;let $=this.#Z.pollIntervalMs??5000;if($<=0)return;this.#Q=(this.#Z.setTimeoutImpl??setTimeout)(()=>{this.#Q=void 0,Z()},$),this.#Q.unref?.()};Z()}async#P(){if(this.#U?.mode!=="watching")return!0;let Z=(this.#Z.now??Date.now)();if(this.#N===void 0||Z-this.#N>=$3)return!0;return!await this.#j()}#L(){let Z=this.#X;if(this.#z.signal.aborted||!Z)return;if(this.#U??=Z.watchRoster({view:()=>this.#$?.view,onView:async()=>{while(this.#J)await this.#J.catch(()=>{});await this.refresh()},onRefused:($)=>this.#Z.onError?.($),onError:($)=>{if(!this.#z.signal.aborted)this.#Z.onError?.($)}}),this.#Z.insula&&this.#G&&!this.#V)this.#V=this.#G.source.watch({provider:this.#Z.insula.provider,setTimeoutImpl:this.#Z.setTimeoutImpl,clearTimeoutImpl:this.#Z.clearTimeoutImpl})}async refreshInsulaQuota(){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#j())return;try{await o(this.#Z.tokenPath),await this.#O(),await this.#G?.source.refresh((this.#Z.now??Date.now)())}catch{}}async cachedInsulaQuota(Z){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#j())return;try{return await o(this.#Z.tokenPath),this.#R(Z.assertedAccountIdentity)}catch{return}}async cachedInsulaQuotaForRoute(Z){if(!this.#Z.insula||this.#z.signal.aborted||!await this.#j())return;try{await o(this.#Z.tokenPath);let z=g(this.#Z.rosterPath,await f(this.#Z.rosterPath))?.rows.find((X)=>X.routeId===Z);return this.#R(z?.accountIdentity)}catch{return}}async lookupInsulaQuotaForRoute(Z){let $=this.#Z.insula;if(!$||this.#z.signal.aborted||!await this.#j())return{miss:"unreachable"};try{await o(this.#Z.tokenPath);let X=g(this.#Z.rosterPath,await f(this.#Z.rosterPath))?.rows.find((J)=>J.routeId===Z)?.accountIdentity;if(!X||!this.#G)return{miss:"unreachable"};let Y=this.#G.source.lookup($.provider,X,(this.#Z.now??Date.now)()),G=Y.reading&&$.normalize(Y.reading.entry,Y.reading.context);if(Y.miss)return{miss:Y.miss,...G!==void 0&&{reading:G}};return G===void 0?{miss:"unreachable"}:{reading:G}}catch{return{miss:"unreachable"}}}async pollInsulaQuotaForRoute(Z,$){let z=await this.lookupInsulaQuotaForRoute(Z);if(z.miss==="cold"||z.miss==="upstream-failed"){if(this.#D.get(Z)!==z.miss)this.#D.set(Z,z.miss),this.#Y.warn("skipped insula provider poll",{reason:z.miss});return}return this.#D.delete(Z),z.miss?$():z.reading}#R(Z){if(!this.#Z.insula||!Z)return;let $=this.#G?.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.#W($);let z=this.#$??await this.#q(this.refresh(),$);if(!z||!await this.#j())throw this.#X?.close(),this.#X=void 0,this.#_(),this.#G?.release(),this.#G=void 0,new F("not-active","Claustrum scoped custody is not active");let X=g(this.#Z.rosterPath,await f(this.#Z.rosterPath));this.#W($);let Y=z.rows.find((H)=>H.routeId===Z),G=X?.rows.find((H)=>H.routeId===Z);if(G&&!G.enabled){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-declined","Claustrum route is disabled")}if(!Y||!G||G.state!=="active"||G.credentialId!==Y.credentialId||G.accountIdentity!==Y.accountIdentity||G.credentialType!==Y.credentialType){if(Y)this.#X?.forget(Y.credentialId);throw new F("route-unavailable","Claustrum route is disabled, removed or changed")}let J=await this.#q(this.#O(),$),B=G3([this.#z.signal,...$?[$]:[]]);try{return await J.authorize({credentialId:G.credentialId,credentialType:G.credentialType,...G.accountIdentity!==void 0&&{accountIdentity:G.accountIdentity}},B.signal,Z)}finally{B.dispose()}}async reportFailure(Z,$,z){if(this.#W(),!this.#X)throw new F("no-receipt","Claustrum dispatch receipt has no active owner");await this.#X.reportFailure(Z,$,z)}async send(Z,$,z){let X=z.signal,Y=await this.authorize(Z,X),G=await $(Y,X);if(G.status===401&&Y.fromKeptReceipt)return await this.reportFailure(Y,401,z.reporterSource??"direct"),G;if(G.status===401&&!X?.aborted){let J;try{J=await this.authorize(Z,X)}catch{}if(j3(z.site,Y,J,this.#Y))await G.body?.cancel().catch(()=>{}),Y=J,G=await $(J,X)}if(G.status===401)await this.reportFailure(Y,401,z.reporterSource??"direct").catch((J)=>this.#Z.onError?.(J)),Promise.resolve().then(()=>this.refresh()).catch((J)=>{if(!this.#z.signal.aborted)this.#Z.onError?.(J)});return G}async decline(Z){this.#W(),await P3(this.#Z.rosterPath,Z),this.#$=g(this.#Z.rosterPath,await f(this.#Z.rosterPath)),this.#X?.retain(this.#$?.rows??[])}async accept(Z){this.#W(),await L3(this.#Z.rosterPath,Z),this.#$=g(this.#Z.rosterPath,await f(this.#Z.rosterPath))}async recordQuota(Z,$,z){return this.#W(),R3(this.#Z.rosterPath,{routeId:Z,observation:$,credentialId:z.credentialId,accountIdentitySource:z.accountIdentitySource,...z.accountIdentity!==void 0&&{accountIdentity:z.accountIdentity},...z.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:z.expectedAccountIdentity}})}async recordAccountQuota(Z,$,z){return this.#W(),S3(this.#Z.rosterPath,{routeId:Z,accountIdentity:$,observation:z})}close(){if(this.#z.signal.aborted)return;if(this.#z.abort(new F("closed","Claustrum consumer is closed")),this.#Q)(this.#Z.clearTimeoutImpl??clearTimeout)(this.#Q);this.#Q=void 0,this.#_(),this.#X?.close(),this.#G?.release(),this.#G=void 0,this.#$=void 0,this.#K=void 0,this.#F(),x3(this.#Z.rosterPath)}async dispose(){this.close(),await this.#F()}}async function q7(Z){let $=await n9.connect(Z);return Object.assign($,{insula:b4(Z)})}var _6=D0("openai");function P6(Z){return V0(Z)}function VZ(Z){if(!Z||Z.corrupt===!0)return!1;return P6(Z.refresh)}class hZ 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 j0(Z){if(P6(Z))throw new hZ}var a9=I("quota"),A3="primary",I3="secondary",o9="app_EMoamEEZ73f0CkXaXp7hrann",r9="https://auth.openai.com";async function v7(Z){j0(Z.refreshToken);let $=await Z.fetchImpl(`${r9}/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:o9}).toString()});if(!$.ok){let Y=r0($.headers.get("retry-after"));throw Object.assign(Error(`Token refresh failed: ${$.status}`),{status:$.status,retryAfter:Y,isRefreshError:!0})}let z=await $.json();if(!z||typeof z.access_token!=="string"||!z.access_token||typeof z.expires_in!=="number")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});if(z.refresh_token!==void 0&&typeof z.refresh_token!=="string")throw Object.assign(Error("Token refresh failed: malformed response"),{status:$.status,isRefreshError:!0});let X=typeof z.refresh_token==="string"&&z.refresh_token?z.refresh_token:Z.refreshToken;return{access:z.access_token,refresh:X,expires:Z.now()+z.expires_in*1000,expiresIn:z.expires_in}}var t9="https://chatgpt.com/backend-api/wham/usage";async function p7(Z){let $=Z.logger??a9,z=Z.accountKey??"unknown",X=Date.now();$.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let Y=await Z.fetchImpl(t9,{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(!Y.ok){let J=r0(Y.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${Y.status}`),{status:Y.status,retryAfter:J})}let G=E4(await Y.json());return $.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:Y.status,elapsedMs:Date.now()-X}),G}catch(Y){throw $.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof Y?.status==="number"?Y.status:"error",elapsedMs:Date.now()-X,error:L6(Y)}),Y}}import{createHash as e9}from"node:crypto";var Z$=globalThis.setTimeout,$$=5;function wZ(Z){let $=Z?.quota?.checkIntervalMinutes??$$;return Math.max(1,$)*60000}function z$(Z){return Z?.quota?.enabled!==!1}function q0(Z,$){if(!Z?.resetsAt)return!1;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)&&z<=$}function n7(Z,$,z,X,Y){if(Y!==void 0&&Number.isFinite(Y)&&Y>z)return Y;let G=$===A3?Z?.primary:$===I3?Z?.secondary:void 0,J=G?.resetsAt?Date.parse(G.resetsAt):NaN;if(Number.isFinite(J)&&J>z)return J;return z+X}function X$(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??15,secondary:$.secondary??$["1w"]??10}}function R6(Z,$,z){if(!z$($))return z+wZ($);let X=X$($),Y=[];for(let G of["primary","secondary"]){let J=Z?.[G];if(!J)continue;if(J.remainingPercent>=X[G])continue;let B=J.resetsAt?Date.parse(J.resetsAt):Number.NaN;if(!Number.isFinite(B)||B<=z)return z+wZ($);Y.push(B)}if(!Y.length)return z+wZ($);return Math.min(...Y)+60000}function Y$(Z){if(!Z?.quota?.mainQuota||!Z.quota.mainQuotaCheckedAt)return null;return{quota:Z.quota.mainQuota,checkedAt:Z.quota.mainQuotaCheckedAt,tokenFingerprint:Z.quota.mainQuotaToken}}function G$(Z){let $=Z?.quota?.refreshEveryNRequests;return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):0}function b(Z){return e9("sha256").update(Z).digest("hex").slice(0,16)}class e{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!==b(Z))this.main=null,this.mainTokenFp=null;return this.main}getFallback(Z,$){let z=this.fallbacks.get(Z)??null;if(!$||!z)return z;if(this.fallbackTokenFps.get(Z)!==b($))return this.fallbacks.delete(Z),this.fallbackTokenFps.delete(Z),null;return z}getAllFallbacks(){return this.fallbacks}setMain(Z,$,z,X=!1){if(!X&&!S6($.quota))return;if(this.mainTokenFp=b(Z),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=$,b3($.quota))this.clearRateLimited("main")}peekMainForPolicy(Z){if(Z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==Z)return null;return this.main}peekFallbackForPolicy(Z,$){let z=this.fallbacks.get(Z)??null;if($&&z?.accountId&&z.accountId!==$)return null;return z}setFallback(Z,$,z,X=!1,Y){if(!X&&!S6($.quota))return;let G=this.fallbacks.get(Z)?.accountId;if(Y&&G&&Y!==G)this.clearRateLimited(Z);let J=Y??G;if(this.fallbacks.set(Z,{...$,accountId:J}),z)this.fallbackTokenFps.set(Z,b(z));else this.fallbackTokenFps.delete(Z);if(b3($.quota))this.clearRateLimited(Z)}markRateLimited(Z,$){let z=this.rateLimitedUntilMap.get(Z);if(z!==void 0&&z>$)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 $=b(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 z=e.fallbackInflightKey(Z,$),X=this.inflightFallbacks.get(z);if(X)return X;if(this.isFallbackBackedOff(Z,$)){let G=this.getFallback(Z,$);if(G)return G.quota;throw Error("Quota API rate-limited — try again later")}let Y=this._fetchFallback(Z,$);return this.inflightFallbacks.set(z,Y),Y}async refreshAllFallbacks(Z){let $=this.now();for(let z of Z){if(z.enabled===!1)continue;if(VZ(z)||!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&$<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground(Z){let $=b(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 z=this.getFallback(Z,$);if(!z)return!0;return this.now()>=z.refreshAfter}shouldRefreshOnRequestCount(Z){let $=G$(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 z=Y$(Z);if(!z)return;let X=$?b($):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let Y={quota:z.quota,refreshAfter:R6(z.quota,Z,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=Y.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=Y,this.mainTokenFp=z.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=$&&MZ($,this.now())?$:void 0}seedFallbacksFromAccounts(Z){let $=wZ(this.storage);for(let z of Z){if(z.enabled===!1)continue;if(!z.quota)continue;let X=Math.max(z.quota.primary?.checkedAt??0,z.quota.secondary?.checkedAt??0);if(X<=0)continue;let Y=this.getFallback(z.id,z.access);if(Y&&Y.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+$,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return MZ(this.mainLastApiError,this.now())}isFallbackBackedOff(Z,$){if($){if(this.fallbackErrorTokenFps.get(Z)!==b($))return!1}return MZ(this.fallbackApiErrors.get(Z),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(Z,$){return JSON.stringify([Z,b($)])}static quotaLockName(Z){return`opencode-fallback-quota-refresh-${Z.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(Z){let $=async()=>{let X=this.now()-this.lastApiCallAt;if(X<e.API_CALL_GAP_MS)await new Promise((Y)=>{let G=Z$(Y,e.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),Z()},z=this.apiGate.then($,$);return this.apiGate=z.catch(()=>{}),z}async _fetchMain(Z){let $=b(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 z=await A({name:"opencode-main-quota-refresh",ttlMs:30000,path:this.configPath});if(!z){let X=this.main;if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=this.now(),Y=await this._fetchQuota(Z),G=this.now();if(this.mainTokenFp=b(Z),this.main={quota:Y,refreshAfter:R6(Y,this.storage,G),checkedAt:G},b3(Y))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(Y,G,this.mainTokenFp,X),Y}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===$)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(Z,$){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(Z,$)){let X=this.getFallback(Z,$);if(X)return X.quota;throw Error("Quota API rate-limited — try again later")}let z=await A({name:e.quotaLockName(Z),ttlMs:30000,path:this.configPath});if(!z){let X=this.getFallback(Z,$);if(X&&this.now()<X.refreshAfter)return X.quota;throw Error("Quota refresh is already in progress")}try{let X=await this._fetchQuota($),Y=this.now();return this.setFallback(Z,{quota:X,refreshAfter:Y+wZ(this.storage),checkedAt:Y},$,!0),this.fallbackApiErrors.delete(Z),this.fallbackErrorTokenFps.delete(Z),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError(Z,$,z),z}finally{this.inflightFallbacks.delete(e.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(e.isAuthError(Z))return;this.mainLastApiError=EZ({error:Z,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(Z,$,z){if(e.isAuthError(z))return;let X=b($),Y=this.fallbackErrorTokenFps.get(Z)===X?this.fallbackApiErrors.get(Z):void 0;this.fallbackApiErrors.set(Z,EZ({error:z,now:this.now(),previous:Y})),this.fallbackErrorTokenFps.set(Z,X)}}function S6(Z){return Boolean(Z.primary||Z.secondary)}function b3(Z){let{primary:$,secondary:z}=Z;if(!$&&!z)return!1;if($&&$.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{createHash as J$,randomUUID as B$}from"node:crypto";import{setTimeout as H$}from"node:timers/promises";import{readFile as _$}from"node:fs/promises";var FZ=I("refresh"),M0=I("accounts"),K$=1e4,W$=15000,f3=50;function v(Z){return Z.type==="oauth"&&Z.corrupt!==!0}function Q$(Z){let $=Z?.trim();if(!$)return!1;try{let z=new URL($);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}var U$="floors-v1";function K5(Z){return Z.costZeroing?.enabled!==!1}class _0 extends Error{code="ACCOUNT_REMOVED_DURING_REFRESH";constructor(Z){super(`Fallback account ${Z} was removed before refresh`);this.name="AccountRemovedDuringRefreshError"}}var D$=[401,403,429],x6={primary:0,secondary:0},V$=!1,y3={primary:5,secondary:10};function N(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}var F$=new Set(["__proto__","constructor","prototype"]);function N$(Z){return Z.length>0&&!F$.has(Z)}function j$(Z){return Z instanceof _0||N(Z)&&Z.name==="AccountRemovedDuringRefreshError"&&Z.code==="ACCOUNT_REMOVED_DURING_REFRESH"}function O0(Z){return{id:typeof Z.id==="string"&&Z.id.trim()?Z.id.trim():B$(),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 T6(Z){if(!N(Z))return;if(typeof Z.message!=="string")return;let $=Number(Z.checkedAt);if(!Number.isFinite($))return;let z=Number(Z.nextRetryAt),X=Number(Z.retryCount);return{message:Z.message,checkedAt:$,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof Z.tokenHash==="string"?Z.tokenHash:void 0}}function q$(Z){if(!N(Z))return;let $={};for(let Y of["primary","secondary"]){let G=Z[Y];if(!N(G))continue;let J=Number(G.usedPercent),B=Number(G.remainingPercent),H=Number(G.checkedAt);if(!Number.isFinite(J)||!Number.isFinite(B)||!Number.isFinite(H))continue;let Q=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;$[Y]={usedPercent:J,remainingPercent:B,checkedAt:H,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(Q)&&Q>0?{windowMinutes:Q}:{}}}for(let Y of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof Z[Y]==="number"?Z[Y]:Number.NaN;if(Number.isFinite(G)&&G>=0)$[Y]=G}let z=Z.spendControl;if(N(z)){let Y=Number(z.limit),G=Number(z.used),J=Number(z.remaining),B=Number(z.usedPercent),H=Number(z.remainingPercent);if(Number.isFinite(Y)&&Number.isFinite(G)&&Number.isFinite(J)&&Number.isFinite(B)&&Number.isFinite(H)&&typeof z.reached==="boolean")$.spendControl={limit:Y,used:G,remaining:J,usedPercent:B,remainingPercent:H,resetsAt:typeof z.resetsAt==="string"?z.resetsAt:void 0,unit:typeof z.unit==="string"?z.unit:void 0,source:typeof z.source==="string"?z.source:void 0,reached:z.reached}}let X=Z.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&(X.overageLimitReached===void 0||typeof X.overageLimitReached==="boolean")){let Y=Number(X.balance),G=typeof X.checkedAt==="number"?X.checkedAt:Number.NaN;$.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,...typeof X.overageLimitReached==="boolean"?{overageLimitReached:X.overageLimitReached}:{},...Number.isFinite(Y)?{balance:Y}:{},...Number.isFinite(G)?{checkedAt:G}:{}}}return Object.keys($).length?$:void 0}function O$(Z){if(!N(Z))return null;if(Z.type==="api"){let $=typeof Z.baseURL==="string"?Z.baseURL.trim():"",z=typeof Z.apiKey==="string"?Z.apiKey.trim():"";if(!Q$($))return null;let X=Z.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...O0(Z),type:"api",apiKey:z||void 0,baseURL:$,authHeader:X}}if(Z.type!=="oauth")return null;if(Z.corrupt===!0){if(typeof Z.id!=="string"||!Z.id.trim())return null;return{...O0(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{...O0(Z),type:"oauth",corrupt:!0}}return{...O0(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:T6(Z.lastRefreshError),lastQuotaRefreshError:T6(Z.lastQuotaRefreshError),quota:q$(Z.quota)}}function M$(Z){if(!N(Z))return;let $=Object.create(null);for(let[z,X]of Object.entries(Z)){if(!N$(z)||!N(X))continue;let Y={};if(N(X.inFlight))Y.inFlight={...X.inFlight};if(N(X.lastOutcome)&&typeof X.lastOutcome.code==="string"&&X.lastOutcome.code.length>0&&typeof X.lastOutcome.at==="number"&&Number.isFinite(X.lastOutcome.at))Y.lastOutcome={code:X.lastOutcome.code,at:X.lastOutcome.at,...N(X.lastOutcome.previousOutcome)&&typeof X.lastOutcome.previousOutcome.code==="string"&&X.lastOutcome.previousOutcome.code.length>0&&typeof X.lastOutcome.previousOutcome.at==="number"&&Number.isFinite(X.lastOutcome.previousOutcome.at)?{previousOutcome:{code:X.lastOutcome.previousOutcome.code,at:X.lastOutcome.previousOutcome.at}}:{}};if(typeof X.cooldownUntil==="number"&&Number.isFinite(X.cooldownUntil))Y.cooldownUntil=X.cooldownUntil;if(Object.keys(Y).length>0)$[z]=Y}return Object.keys($).length>0?$:void 0}var E6=new Set;function y6(Z){if(Z.length===0)return;let $=JSON.stringify([...Z].sort());if(E6.has($))return;E6.add($),M0.warn("account load-dropped, preserved on disk",{droppedIds:Z})}function h6(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=Z.accounts,z=$.map(O$).filter((X)=>X!=null);if(z.length<$.length){let X=new Set;for(let J of $)if(N(J)&&typeof J.id==="string"&&J.id.trim())X.add(J.id.trim());let Y=new Set(z.map((J)=>J.id)),G=[];for(let J of X)if(!Y.has(J))G.push(J);y6(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N(Z.routing)?Z.routing:void 0,fallbackOn:Array.isArray(Z.fallbackOn)?Z.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N(Z.refresh)?Z.refresh:void 0,quota:N(Z.quota)?Z.quota:void 0,reset:M$(Z.reset),dump:N(Z.dump)?Z.dump:void 0,costZeroing:N(Z.costZeroing)?Z.costZeroing:void 0,killswitch:N(Z.killswitch)?Z.killswitch:void 0,logging:N(Z.logging)?Z.logging:void 0,cachekeep:N(Z.cachekeep)?Z.cachekeep:void 0,cacheKeep:N(Z.cacheKeep)?Z.cacheKeep:void 0,mainAccountId:typeof Z.mainAccountId==="string"?Z.mainAccountId:void 0,accounts:z}}function w6(Z){if(!("claustrum"in Z))return Z;let{claustrum:$,...z}=Z;return z}async function ZZ(Z){try{return{exists:!0,value:JSON.parse(await _$(Z,"utf8"))}}catch($){if($.code==="ENOENT")return{exists:!1,value:null};throw $}}function $Z(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}async function P$(Z){let $;try{$=(await ZZ(Z)).value}catch{return null}return g3($)}function m6(Z,$){if(!N(Z))return Z;let z=N($)?$:{},X=N(z.main)?z.main:void 0,Y=N(z.accounts)?z.accounts:{},G=N(Z.quota)?Z.quota:{},J=N(Z.refresh)?Z.refresh:{},B=X??G,H=X??J,K=J.mainRefreshLeaseId!==void 0?{id:J.mainRefreshLeaseId,until:J.mainRefreshLeaseUntil,tokenHash:J.mainRefreshLeaseTokenHash}:{id:H.refreshLeaseId,until:H.refreshLeaseUntil,tokenHash:H.refreshLeaseTokenHash},U=Array.isArray(Z.accounts)?Z.accounts.map((j)=>{if(!N(j))return j;let D=typeof j.id==="string"&&N(Y[j.id])?Y[j.id]:{};return{...j,...D}}):void 0;return g6({...Z,refresh:$Z({...J,mainLastRefreshError:J.mainLastRefreshError??H.lastRefreshError,mainRefreshLeaseId:K.id,mainRefreshLeaseUntil:K.until,mainRefreshLeaseTokenHash:K.tokenHash}),quota:$Z({...G,mainQuota:B.quota,mainQuotaCheckedAt:B.quotaCheckedAt,mainQuotaToken:B.quotaToken,mainLastQuotaApiError:B.lastQuotaApiError}),accounts:U})}async function L$(Z){let $=await ZZ(Z.configPath);if(!$.exists)return null;let z=await ZZ(Z.statePath);return h6(m6($.value,z.value))}function g6(Z){return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0))}function R$(Z){return $Z({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 v6(Z){if(Z.type==="api")return $Z({apiKey:Z.apiKey,lastUsed:Z.lastUsed});if(Z.corrupt)return{};return $Z({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 P0(Z){return Math.max(Z?.primary?.checkedAt??0,Z?.secondary?.checkedAt??0)}function mZ(Z,$,z){if(z in $)Z[z]=$[z];else delete Z[z]}function S$(Z,$){return Z.access===$.access&&Z.refresh===$.refresh&&Z.expires===$.expires&&Z.lastRefreshedAt===$.lastRefreshedAt}function x$(Z,$){if(!S$(Z,$))return $;if(!("lastRefreshError"in $))return Z;if(!("lastRefreshError"in Z))return $;return($.lastRefreshError?.checkedAt??0)>(Z.lastRefreshError?.checkedAt??0)?$:Z}var T$=300000;function C6(Z,$){if(Z===void 0)return 0;return Z>$+T$?0:Z}function E$(Z,$,z){let X=Date.now(),Y=C6($.lastRefreshedAt,X),G=C6(z.lastRefreshedAt,X),J=$.expires??0,B=z.expires??0,H=G>Y?z:Y>G?$:B>J?z:J>B?$:x$($,z);mZ(Z,H,"access"),mZ(Z,H,"refresh"),mZ(Z,H,"expires"),mZ(Z,H,"lastRefreshedAt"),mZ(Z,H,"lastRefreshError")}function C$(Z,$){if(!N(Z))return $;let z=Z,X=P0(z.quota),Y=P0($.quota),G=X>Y,J=G?{...z,...$,quota:z.quota,lastQuotaRefreshError:z.lastQuotaRefreshError}:{...z,...$};if(!G&&!("lastQuotaRefreshError"in $))delete J.lastQuotaRefreshError;if(!("lastRefreshError"in $))delete J.lastRefreshError;if(typeof z.lastUsed==="number"&&(typeof $.lastUsed!=="number"||z.lastUsed>$.lastUsed))J.lastUsed=z.lastUsed;return E$(J,z,$),J}function p6(Z){let $=Z.refresh?$Z({enabled:Z.refresh.enabled,refreshBeforeExpiryMinutes:Z.refresh.refreshBeforeExpiryMinutes}):void 0,z=Z.quota?$Z({enabled:Z.quota.enabled,checkIntervalMinutes:Z.quota.checkIntervalMinutes,refreshEveryNRequests:Z.quota.refreshEveryNRequests,minimumRemaining:Z.quota.minimumRemaining,failClosedOnUnknownQuota:Z.quota.failClosedOnUnknownQuota}):void 0;return g6({version:1,main:Z.main,routing:Z.routing,fallbackOn:Z.fallbackOn,refresh:$,quota:z,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(R$)})}async function pZ(Z,$=!1){let z=Date.now(),X=z+W$,Y=0;while(Date.now()<=X){Y++;let B=await A({name:"save",ttlMs:K$,path:Z,renew:$});if(B)return B;let H=X-Date.now();if(H<=0)break;await H$(Math.min(f3+i6(f3),H))}let G=Date.now()-z,J=Math.round(G/Math.max(1,Y));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${Z} (${Y} attempts, ~${J}ms apart; retry interval is ${f3}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 l6(Z){let $=Object.fromEntries(Z.accounts.map((z)=>[z.id,v6(z)]));return{version:1,main:$Z({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 g3(Z){if(!N(Z)||!Array.isArray(Z.accounts))return null;let $=new Set;for(let z of Z.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;$.add(X)}return $}function A$(Z,$,z,X){if(!N(Z)||!Array.isArray(Z.accounts))return{preservedRawEntries:[],preservedIds:[]};let Y=[],G=[];for(let J of $){if(z.has(J))continue;if(X.has(J))continue;let B=Z.accounts.find((H)=>N(H)&&typeof H.id==="string"&&H.id.trim()===J);if(!B)continue;Y.push(B),G.push(J)}return{preservedRawEntries:Y,preservedIds:G}}function I$(Z){if(!Array.isArray(Z))return[];let $=[];for(let z of Z){if(!N(z))continue;if(typeof z.id!=="string")continue;$.push(z.id)}return $}function b$(Z,$,z){let X=g3(Z);if(X===null)return[];let{preservedRawEntries:Y,preservedIds:G}=A$(Z,X,$,z);return y6(G),Y}async function Q5(Z,$,z={}){let{configPath:X,statePath:Y}=$,G=await pZ(X);try{let J=await pZ(Y);try{let B=await ZZ(X),H=await ZZ(Y),Q=(B.exists?h6(m6(B.value,H.value)):null)??f$(),K=new Set(Q.accounts.map((V)=>V.id)),W=g3(B.value)??new Set,U=Z(Q,{rawRosterIds:[...W],loadedRosterIds:[...K]})??Q,j=new Set(z.allowDrop??[]),D=b$(B.value,K,j),O=p6(U),q=new Set((Array.isArray(O.accounts)?O.accounts:[]).map((V)=>N(V)&&typeof V.id==="string"?V.id.trim():"").filter(Boolean)),L=D.filter((V)=>{if(!N(V))return!1;if(typeof V.id!=="string")return!1;return!q.has(V.id.trim())}),T=N(B.value)?B.value:{},p={...w6(T),...O,accounts:[...Array.isArray(O.accounts)?O.accounts:[],...L]};if(z.canWrite&&!z.canWrite())return Q;if(await w(X,p),z.canWrite&&!z.canWrite())return Q;return await w(Y,l6(U)),M0.debug("account config written",{accountCount:p.accounts.length,accountIds:I$(p.accounts)}),U}finally{await J.release()}}finally{await G.release()}}function f$(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function k$(Z,$){Z.main=Z.main??{};let z=typeof Z.main.quotaCheckedAt==="number"?Z.main.quotaCheckedAt:P0(Z.main.quota),X=typeof $.quota?.mainQuotaCheckedAt==="number"?$.quota.mainQuotaCheckedAt:P0($.quota?.mainQuota);if(z>X)return;Z.main.quota=$.quota?.mainQuota,Z.main.quotaCheckedAt=$.quota?.mainQuotaCheckedAt,Z.main.quotaToken=$.quota?.mainQuotaToken,Z.main.lastQuotaApiError=$.quota?.mainLastQuotaApiError}function y$(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 h3(Z){if(Array.isArray(Z))return Z.map(h3);if(!N(Z))return Z;return Object.fromEntries(Object.entries(Z).filter(([,$])=>$!==void 0).map(([$,z])=>[$,h3(z)]))}async function h$(Z,$,z={mainQuota:!0,mainRefresh:!0,accounts:!0},X){let Y=$.statePath,G=await pZ(Y);try{let J=(await ZZ(Y)).value,B=N(J)?{...J,version:1}:{version:1};if(z.mainQuota)k$(B,Z);if(z.mainRefresh)y$(B,Z);if(z.accounts){let H=z.accounts===!0?null:new Set(z.accounts),Q=await P$($.configPath);B.accounts={...N(B.accounts)?B.accounts:{}};for(let K of Z.accounts){if(H&&!H.has(K.id))continue;if(Q&&!Q.has(K.id))continue;B.accounts[K.id]=C$(B.accounts[K.id],v6(K))}if(H){for(let K of H)if(!Z.accounts.some((W)=>W.id===K))delete B.accounts[K]}if(Q){for(let K of Object.keys(B.accounts))if(!Q.has(K))delete B.accounts[K]}}if(X&&!X())return;await w(Y,h3(B))}finally{await G.release()}}function w$(Z){return Z?.fallbackOn?.length?Z.fallbackOn:D$}function U5(Z,$){return w$($).includes(Z)}function m$(Z){let $=Z?.quota?.minimumRemaining||{};return{primary:$.primary??$["5h"]??x6.primary,secondary:$.secondary??$["1w"]??x6.secondary}}function w3(Z){return Z?.quota?.enabled!==!1}function lZ(Z){return Z?.quota?.failClosedOnUnknownQuota??V$}function d6(Z,$,z=Date.now()){if(!w3($))return!0;if(!Z)return!lZ($);let X=m$($),Y=lZ($);for(let G of["primary","secondary"]){let J=Z[G];if(!J)continue;if(q0(J,z)){if(Y)return!1;continue}if(J.remainingPercent<X[G])return!1}return!0}function L0(Z){return Z?.killswitch?.enabled===!0}function A6(Z){return{primary:Z?.primary??Z?.["5h"]??y3.primary,secondary:Z?.secondary??Z?.["1w"]??y3.secondary}}function D5(Z){return Z?.cacheKeep??Z?.cachekeep}function I6(Z){return typeof Z==="number"&&Number.isFinite(Z)?Z:0}function c6(Z,$){if(!Z?.killswitch)return y3;if(Z.killswitch.schema===U$){let{accounts:z,defaults:X}=Z.killswitch,Y=$??"main",G=N(z)&&Object.hasOwn(z,Y)&&N(z[Y])?z[Y]:N(X)?X:void 0;return{primary:I6(G?.primary),secondary:I6(G?.secondary)}}if($&&Z.killswitch.accounts?.[$])return A6(Z.killswitch.accounts[$]);return A6(Z.killswitch.main)}function u6(Z,$,z,X=Date.now()){if(!L0($))return!0;if(!Z)return!lZ($);let Y=c6($,z),G=lZ($);for(let J of["primary","secondary"]){let B=Z[J];if(!B)continue;if(q0(B,X)){if(G)return!1;continue}if(B.remainingPercent<Y[J])return!1}return!0}function V5(Z,$,z,X){if(!L0(X))return 300;let Y=[],G=[{accountId:void 0,quota:Z},...$];for(let{accountId:B,quota:H}of G){if(!H)continue;let Q=c6(X,B),K=[],W=!1;for(let U of["primary","secondary"]){let j=H[U];if(!j||q0(j,z))continue;if(j.remainingPercent>=Q[U])continue;let D=j.resetsAt?Date.parse(j.resetsAt):NaN;if(!Number.isFinite(D)||D<=z){W=!0;break}K.push(D)}if(W||K.length===0)continue;Y.push(Math.max(...K))}if(Y.length===0)return 300;let J=Math.min(...Y);return Math.max(1,Math.ceil((J-z)/1000))}function b6(Z){return typeof Z.version==="number"&&Array.isArray(Z.accounts)}async function F5(Z,$){let{configPath:z,statePath:X}=$;if(!Z)return;try{let G=await ZZ(z);if(G.exists&&N(G.value)&&b6(G.value))return}catch{}let Y=await pZ(z);try{let G=await pZ(X);try{let J=await ZZ(z);if(J.exists&&N(J.value)){if(b6(J.value))return}if(!Z)return;let B={version:1,main:{type:"opencode",provider:"openai"},accounts:[]};if(Z.access){let K=eZ({id_token:"",access_token:Z.access,refresh_token:Z.refresh});if(K)B.mainAccountId=K}let H=J.exists&&N(J.value)?J.value:{},Q={...w6(H),...p6(B)};await w(z,Q),await w(X,l6(B))}finally{await G.release()}}finally{await Y.release()}}function g$(Z){return Z?.refresh?.enabled!==!1}function v$(Z){return(Z?.refresh?.refreshBeforeExpiryMinutes??240)*60000}function i6(Z){return Math.floor(Math.random()*(Z+1))}function NZ(Z,$,z){return!Z.access||!Z.expires||Z.expires-z<=v$($)}function p$(Z,$){return Boolean(Z.access&&typeof Z.expires==="number"&&Z.expires>$)}function gZ(Z,$){return Boolean(Z?.mainAccountId&&$.accountId&&$.accountId===Z.mainAccountId)}class s6 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 l$="common-auth-placeholder:v1:openai",n6="main";function N5(Z){return N(Z)&&Z.type==="oauth"&&(Z.refresh===l$||Z.refresh===_6)}function j5(Z){return Z?.accounts.find(($)=>$.id===n6&&$.enabled!==!1&&v($))}function q5(Z){if(!Z)return Z;return{...Z,accounts:Z.accounts.filter(($)=>$.id!==n6)}}function x(Z,$){let z=Z.accounts.findIndex((X)=>X.id===$.id);if(z!==-1)Z.accounts[z]=$}function vZ(Z){return Z instanceof Error?Z.message:String(Z)}function m3(Z,$,z){if($ instanceof hZ)return;Z.lastRefreshError=U4({error:$,now:z,refreshToken:Z.refresh,previous:Z.lastRefreshError})}function k3(Z,$,z){if($ instanceof hZ)return;if(Z.lastQuotaRefreshError=EZ({error:$,now:z,previous:Z.lastQuotaRefreshError}),$?.isRefreshError===!0)m3(Z,$,z)}function f6(Z,$){if(!Z)return!1;if(!Z.resetsAt)return!0;let z=Date.parse(Z.resetsAt);return Number.isFinite(z)?z>$:!0}function d$(Z,$){if(!Z)return!1;return f6(Z.primary,$)||f6(Z.secondary,$)}function c$(Z,$,z){if(!Z)return!1;let X=$?.quota?.checkIntervalMinutes??5,Y=Math.max(1,X)*60000,G=Math.max(Z.primary?.checkedAt??0,Z.secondary?.checkedAt??0);return z-G<Y}function k6(Z,$,z){return!c$(Z.quota,$,z)}function u$(Z,$,z,X){return o0(z)&&d6(Z.quota,$,X)&&d$(Z.quota,X)}function i$(Z){let $=Z?.quota?.checkIntervalMinutes??5;return Math.max(1,$)*60000}var s$=60000,n$=60000,a$=600000;function o$(Z){return`fallback-oauth-refresh-${J$("sha256").update(Z).digest("base64url").slice(0,16)}`}var r$=1e4,t$=100;class e${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)j0(Z.refresh)}seedFallbackQuota(Z,$){if(!this.quotaManager)return;if(!Z.quota)return;let z=Math.max(Z.quota.primary?.checkedAt??0,Z.quota.secondary?.checkedAt??0);if(z<=0)return;let X=this.quotaManager.getFallback(Z.id,Z.access);if(X&&X.checkedAt>=z)return;this.quotaManager.setFallback(Z.id,{quota:Z.quota,refreshAfter:z+i$($),checkedAt:z},Z.access,!1,Z.accountId)}async load(){return L$(this.paths)}selectionBookkeeping=Promise.resolve();selectionBookkeepingSettled(){return this.selectionBookkeeping}async save(Z,$){await h$(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(()=>{})},s$+i6(n$)),"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 z=[],X=!1;for(let Y of $.accounts){if(Y.enabled===!1||!v(Y))continue;if(gZ($,Y))continue;if(VZ(Y))continue;let G=!1,J=Y;try{if(NZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&JZ(B,J.refresh,this.now()))throw G=!0,Error(rZ(B,this.now()));try{J=await this.refreshAccount(J,$),X=!0}catch(H){if(j$(H))continue;G=!0;let Q=$.accounts.find((K)=>K.id===Y.id&&v(K));if(Q&&!JZ(Q.lastRefreshError,Q.refresh,this.now()))m3(Q,H,this.now()),x($,Q),X=!0;throw H}}if(this.seedFallbackQuota(J,$),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(J),$))z.push(J)}catch(B){let H=p$(J,this.now());if(G){if(!H)continue}else if(!H)continue;if(u$(J,$,B,this.now()))FZ.debug("fallback quota using cached quota after refresh error",{pid:process.pid,accountId:J.id,error:vZ(B)}),z.push(J);else if(!lZ($))z.push(J)}}if(X){let Y=structuredClone($);this.selectionBookkeeping=this.selectionBookkeeping.then(()=>this.save(Y)).catch((G)=>{M0.warn("fallback selection bookkeeping not persisted",{pid:process.pid,error:vZ(G)})})}return z}async markUsed(Z){try{let $=await this.load();if(!$)return;let z=$.accounts.find((X)=>X.id===Z.id);if(!z)return;z.lastUsed=this.now(),await this.save($,[z.id])}catch($){M0.warn("lastUsed stamp not persisted",{pid:process.pid,accountId:Z.id,error:vZ($)})}}accountPassesQuotaPolicy(Z,$){return d6(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||!g$(Z))return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!v(z))continue;if(gZ(Z,z))continue;if(VZ(z))continue;if(!NZ(z,Z,this.now()))continue;if(JZ(z.lastRefreshError,z.refresh,this.now()))continue;try{FZ.debug("fallback oauth background due",{pid:process.pid,accountId:z.id,expiresInMs:z.expires?z.expires-this.now():void 0}),await this.refreshAccount(z,Z),$=!0}catch(X){FZ.warn("fallback oauth background failed",{pid:process.pid,accountId:z.id,error:vZ(X)}),m3(z,X,this.now()),x(Z,z),$=!0}}if($)await this.save(Z)}async refreshQuotaForDueAccounts(){let Z=await this.load();if(!Z||!w3(Z))return;if(!this.options.fetchQuotaFn)return;let $=!1;for(let z of Z.accounts){if(z.enabled===!1||!v(z))continue;if(gZ(Z,z))continue;if(VZ(z))continue;let X=z;try{if(NZ(X,Z,this.now())){if(JZ(X.lastRefreshError,X.refresh,this.now()))continue;X=await this.refreshAccount(X,Z),$=!0}if(MZ(X.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(X,Z),!(this.quotaManager?this.quotaManager.isFallbackStale(X.id,X.access):k6(X,Z,this.now())))continue;await this.refreshAccountQuota(X,Z),$=!0}catch(Y){k3(z,Y,this.now()),x(Z,z),$=!0}}if($)await this.save(Z),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(Z={}){let $=await this.load(),z=[];if(!$||!w3($))return{storage:$,errors:z};if(!this.options.fetchQuotaFn)return{storage:$,errors:z};let X=Z.force??!1,Y=!1;for(let G of $.accounts){if(G.enabled===!1||!v(G))continue;if(gZ($,G))continue;if(VZ(G))continue;let J=G;try{if(NZ(J,$,this.now())){let B=J.lastRefreshError;if(B&&JZ(B,J.refresh,this.now()))throw Error(rZ(B,this.now()));J=await this.refreshAccount(J,$),Y=!0}if(!X&&!k6(J,$,this.now())){if(J.lastQuotaRefreshError)J.lastQuotaRefreshError=void 0,x($,J),Y=!0;continue}await this.refreshAccountQuota(J,$),Y=!0}catch(B){k3(G,B,this.now()),x($,G),Y=!0,z.push({accountId:G.id,message:vZ(B)})}}if(Y)await this.save($);return{storage:$,errors:z}}async refreshAccount(Z,$,z={}){let X=this.refreshPromises.get(Z.id);if(X){let J=await X;return x($,J),J}let Y=this.refreshAccountNow(Z,$,z).finally(()=>{this.refreshPromises.delete(Z.id)});this.refreshPromises.set(Z.id,Y);let G=await Y;return x($,G),G}async waitForConcurrentFallbackRefresh(Z,$,z,X){let Y=Date.now()+r$;while(Date.now()<Y){await new Promise((Q)=>setTimeout(Q,t$));let G=await this.load(),J=G?.accounts.find((Q)=>Q.id===Z.id&&v(Q));if(!J)continue;if(this.assertNotTombstoned(J),(J.access!==z.access||J.refresh!==z.refresh||(J.expires??0)>(z.expires??0)+60000)&&(X.force||!NZ(J,G,this.now())))return x($,J),FZ.debug("fallback oauth joined concurrent refresh",{pid:process.pid,accountId:J.id,expiresInMs:J.expires?J.expires-this.now():void 0}),J;let H=J.lastRefreshError;if(H&&JZ(H,J.refresh,this.now()))throw x($,J),Error(rZ(H,this.now()))}return null}assertNotShieldedMainRow(Z,$,z){if(z.asPoolMain||!$)return;if(gZ(Z,$))throw new s6($.id)}async refreshAccountNow(Z,$,z){let X=await this.load(),Y=X?.accounts.find((B)=>B.id===Z.id&&v(B));if(this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!NZ(Y,X,this.now()))return x($,Y),Y;let G=Y??Z,J=await A({name:o$(G.id),ttlMs:a$,path:this.paths.configPath,renew:!0});if(!J){FZ.debug("fallback oauth refresh skipped file lock",{pid:process.pid,accountId:G.id});let B=await this.waitForConcurrentFallbackRefresh(Z,$,G,z);if(B)return B;throw Error("Fallback OAuth refresh is already in progress")}try{if(X=await this.load(),Y=X?.accounts.find((K)=>K.id===Z.id&&v(K)),this.assertNotTombstoned(Y),this.assertNotShieldedMainRow(X,Y,z),Y&&!z.force&&!NZ(Y,X,this.now()))return x($,Y),Y;if(!Y)throw new _0(Z.id);G=Y;let B=this.options.refreshFn??(async()=>{throw Error("No refreshFn injected into FallbackAccountManager")});FZ.debug("fallback oauth refresh request start",{pid:process.pid,accountId:G.id,force:z.force===!0,expiresInMs:G.expires?G.expires-this.now():void 0});let H=await B({refreshToken:G.refresh,fetchImpl:this.fetchImpl,now:this.now});if(G.access=H.access,G.refresh=H.refresh,G.expires=H.expires,G.lastRefreshedAt=H.expires-H.expiresIn*1000,G.lastRefreshError=void 0,x($,G),await this.save($),!(await this.load())?.accounts.some((K)=>K.id===Z.id))throw new _0(Z.id);return FZ.debug("fallback oauth refresh succeeded",{pid:process.pid,accountId:G.id,expiresInMs:G.expires?G.expires-this.now():void 0}),G}finally{await J.release()}}async refreshAccountQuota(Z,$){let z=Z;if(this.assertNotTombstoned(z),!z.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 X=this.options.fetchQuotaFn??(async()=>{throw Error("No fetchQuotaFn injected — wham/usage supplement is disabled")}),Y=(G)=>this.quotaManager?this.quotaManager.refreshFallback(z.id,G):X({accessToken:G,fetchImpl:this.fetchImpl,now:this.now});try{if(!z.access)throw Error(`Fallback account ${Z.id} has no access token`);let G=await Y(z.access);z.quota=G,z.lastQuotaRefreshError=void 0,x($,z),await this.save($)}catch(G){throw k3(Z,G,this.now()),x($,Z),G}}}var a6=["primary","secondary"];function R0(Z){return Z!=null&&typeof Z==="object"&&!Array.isArray(Z)}function RZ(Z){return typeof Z==="number"&&Number.isFinite(Z)}function Z1(Z,$){if(!R0($))return;let z=$.usedPercent;if(!RZ(z)||z<0||z>100)return;return{label:Z,usedPercent:z,...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...RZ($.windowMinutes)&&$.windowMinutes>0?{windowMinutes:$.windowMinutes}:{}}}function $1(Z){let $=Z.spendControl;if(R0($)&&typeof $.reached==="boolean"){let z=(X)=>RZ($[X])?{[X]:$[X]}:{};return{kind:"reading",reached:$.reached,...z("remainingPercent"),...z("usedPercent"),...z("limit"),...z("used"),...z("remaining"),...typeof $.resetsAt==="string"?{resetsAt:$.resetsAt}:{},...typeof $.unit==="string"?{unit:$.unit}:{}}}if(Z.spendControlCleared===!0)return{kind:"cleared"};return}function z1(Z,$){if(!R0(Z)||typeof Z.hasCredits!=="boolean"||typeof Z.unlimited!=="boolean")return;return{hasCredits:Z.hasCredits,unlimited:Z.unlimited,...RZ(Z.balance)&&Z.balance>=0?{balance:Z.balance}:{},...typeof Z.overageLimitReached==="boolean"?{overageLimitReached:Z.overageLimitReached}:{},checkedAt:$}}function _5(Z,$,z){if(!R0(Z)||!RZ($))return;let X=[],Y=[];for(let Q of a6){let K=Z1(Q,Z[Q]);if(K)X.push(K);else if(z)Y.push({label:Q})}let G=$1(Z),J=Z.resetCreditsAvailable,B=typeof J==="number"&&Number.isSafeInteger(J)&&J>=0?{resetCredits:{value:J,checkedAt:$}}:void 0,H=z1(Z.credits,$);if(X.length===0&&Y.length===0&&!G&&!B&&!H)return;return{checkedAt:$,...X.length>0?{readings:X}:{},...Y.length>0?{coverage:Y}:{},...G?{budget:G}:{},...B?{counters:B}:{},...H?{credits:H}:{}}}function o6(Z){if(!XZ(Z))return;let $=C(Z),z={};for(let X of a6){let Y=$.limits.find((J)=>J.label===X&&J.kind==="reading");if(!Y||!RZ(Y.usedPercent))continue;let G={usedPercent:Y.usedPercent,remainingPercent:100-Y.usedPercent,checkedAt:Y.checkedAt,...Y.resetsAt!==void 0?{resetsAt:Y.resetsAt}:{},...Y.windowMinutes!==void 0?{windowMinutes:Y.windowMinutes}:{}};z[X]=G}return z.primary||z.secondary?z:void 0}var t6="main";function T5(Z){return Z.find(($)=>$.id.startsWith("vault:")&&$.credentialId==="chatgpt:openai")?.id??null}function E5(Z,$,z){let X=new Map;if(L0($))for(let Y of Z)X.set(Y.id,u6(o6(Y.quota),$,Y.id===t6?void 0:Y.id,z));return X}var C5=5,X1=5000;function A5(Z){if(Z==="ordered")return"roster";return Z==="fallback-first"?"fallback-first":"main-first"}function I5(Z,$=X1){let z=Z.rows.filter((J)=>J.kind==="oauth"&&Z.killswitch.get(J.id)!==!1&&C(J.quota).limits.length===0);if(z.length===0)return;if(y({rows:Z.rows,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}}).admitted.some((J)=>Z.killswitch.get(J.id)!==!1))return;let Y=[];if(y({rows:z,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:(J)=>{let B=Z.requestPull(J);if(B)Y.push(B.catch(()=>{}))}}),Y.length===0)return;let G;return Promise.race([Promise.all(Y),new Promise((J)=>{G=setTimeout(J,$)})]).then(()=>{}).finally(()=>clearTimeout(G))}function S0(Z){return Z.reason==="exhausted"||Z.reason==="budget-spent"}function Y1(Z,$){if(!h(Z))return!1;let z=Z;if(!($-z.checkedAt<=TZ))return!1;if(z.overageLimitReached===!0)return!1;if(z.unlimited)return!0;return z.hasCredits&&(z.balance===void 0||z.balance>0)}function x0(Z,$,z){let X=(B)=>$.killswitch.get(B)!==!1,Y=new Set(z.admitted.filter((B)=>B.lastPath!==!0&&X(B.id)).map((B)=>B.id)),G=new Map(z.refused.map((B)=>[B.id,B])),J=Z.filter((B)=>{if(B.kind!=="oauth"||!X(B.id))return!1;if(G.get(B.id)?.reason!=="exhausted")return!1;let H=C(B.quota);if(GZ(H,$.now))return!1;return Y1(H.credits,$.now)}).map((B)=>B.id);return{free:Y,credits:J}}function G1(Z,$=Z.rows){return y({rows:$,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:()=>{}})}class J1{#Z=new Set;served(Z,$,z){let X=G1(Z),Y=x0(Z.rows,Z,X),G=new Set(Y.credits);if(Y.free.has($)){this.#Z.clear();return}for(let J of[...this.#Z])if(!G.has(J))this.#Z.delete(J);if(!G.has($)||this.#Z.has($))return;this.#Z.add($),z?.info("serving requests on prepaid credits",{accountId:$,reason:"free quota used up"})}has(Z){return this.#Z.has(Z)}ids(){return new Set(this.#Z)}}function e6(Z,$,z){if(Z===void 0)return{reason:"no-credential"};if(z.get(Z)===!1)return{reason:"killswitch"};let X=$.excluded.find((G)=>G.id===Z);if(X?.reason==="rate-limited")return{reason:"mid-stream-rate-limit",resetAtMs:X.until};if(X)return{reason:"no-credential"};let Y=$.refused.find((G)=>G.id===Z);if(Y&&"resetAtMs"in Y)return{reason:"quota-exhausted",resetAtMs:Y.resetAtMs};if(Y)return{reason:"quota-unknown"};return{reason:"no-credential"}}function r6(Z,$,z){if($.refused.find((Y)=>!S0(Y)&&z.get(Y.id)!==!1))return{reason:"quota-unknown"};return e6(Z[0],$,z)}function b5(Z){let $=Z.replayable!==!1,z=Z.mainId===void 0?t6:Z.mainId??"",X=$?Z.placement:"main-first",Y=v0({rows:Z.rows,placement:X,formerMainId:z,killswitch:Z.killswitch,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),G=aZ(Z.rows.map((W)=>W.id),X,z),J=new Set(Y.admission.refused.filter((W)=>S0(W)&&Z.killswitch.get(W.id)!==!1).map((W)=>W.id)),B=G.filter((W)=>J.has(W)),H=x0(Z.rows,Z,Y.admission),Q=Y.order.filter((W)=>H.free.has(W)),K=G.filter((W)=>H.credits.includes(W));if(!$){let W=G.includes(z),U=W?z:Q[0]??K[0]??Y.order[0]??B[0];if(U!==void 0&&Y.order.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&K.includes(U))return{kind:"send",order:[U],lastPath:!1};if(U!==void 0&&J.has(U))return{kind:"send",order:[U],lastPath:!0};return{kind:"block",block:W?e6(z,Y.admission,Z.killswitch):r6(G,Y.admission,Z.killswitch)}}if(Q.length>0)return{kind:"send",order:Q,lastPath:!1};if(K.length>0){let W=Y.order.length>0?Y.order:B;return{kind:"send",order:[...K,...W.filter((U)=>!K.includes(U))],lastPath:!1}}if(Y.order.length>0)return{kind:"send",order:Y.order,lastPath:!1};if(B.length>0)return{kind:"send",order:B,lastPath:!0};return{kind:"block",block:r6(G,Y.admission,Z.killswitch)}}function f5(Z){let $=y({rows:Z.rows,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,now:Z.now,requestPull:Z.requestPull}),z=new Map;for(let X of Z.rows)z.set(X.id,C(X.quota));for(let X of $.admitted)if(X.projection)z.set(X.id,X.projection);return{projections:z,excluded:new Set($.excluded.map((X)=>X.id))}}function Z8(Z,$,z){let X=z.exclude,Y=X?Z.rows.filter((J)=>!X.has(J.id)):Z.rows,G=new Map;for(let J of Y){let B=$.resetCredits(J.id);if(B!==void 0)G.set(J.id,B)}return u0({rows:Y,now:Z.now,rateLimitMarks:Z.rateLimitMarks,refreshBackoff:Z.refreshBackoff,requestPull:Z.requestPull,killswitch:Z.killswitch,requestBytes:$.requestBytes,...z.pendingBytes?{pendingBytes:z.pendingBytes}:{},rowReservePercent:(J)=>$.reservePercent(J.id),refusedPinPolicy:"move-on-confirmed-exhaustion",resetCreditsApplicable:G,...z.pin===void 0?{}:{pin:{accountId:z.pin}},...$.onEmptyWeightedSet?{onEmptyWeightedSet:$.onEmptyWeightedSet}:{}})}function k5(Z,$,z,X){let Y=Z8(Z,$,{exclude:z,pendingBytes:X}),G=Z.rows.filter((K)=>!z.has(K.id)),J=x0(G,Z,Y.admission),B=Y.outcome==="dispatch"&&Y.source!=="pin"?{accountId:Y.accountId,source:Y.source,...Y.quotaCheckedAt===void 0?{}:{quotaCheckedAt:Y.quotaCheckedAt}}:void 0;if(B&&J.free.has(B.accountId))return B;let H=J.credits[0];if(H===void 0)return B;let Q=C(G.find((K)=>K.id===H)?.quota).checkedAt;return{accountId:H,source:"mode-fallback",...Q===void 0?{}:{quotaCheckedAt:Q}}}function y5(Z,$,z){let X=Z.killswitch.get(z)===!1,Y={kind:"move",reason:X?"killswitch":"exhausted"},G=Z8(Z,$,{pin:z}),J=x0(Z.rows,Z,G.admission),B=J.credits.includes(z),H=J.credits.some((W)=>W!==z);if(G.outcome==="dispatch"){let W=!J.free.has(G.accountId);if(G.pin.action==="assign"){if(W&&B)return{kind:"serve"};return Y}if(G.accountId!==z)return{kind:"detour"};if(W&&H)return Y;return{kind:"serve"}}let Q=G.admission.refused.find((W)=>W.id===z),K=X||Q!==void 0&&S0(Q);if(B)return{kind:"serve"};if(H)return K?Y:{kind:"detour"};if(!X&&Q&&S0(Q))return{kind:"last-path"};return{kind:"none"}}function h5(Z,$,z,X){let Y=Z.killswitch.get(z);return c0({quota:$.projections.get(z),now:Z.now,...X===void 0?{}:{status:X},...Y===void 0?{}:{killswitchPasses:Y}})}import{tmpdir as $8}from"node:os";import{join as z8}from"node:path";var B1=["error","warn","info","debug","trace"];function H1(){return process.env.OPENCODE_OPENAI_AUTH_LOG_FILE??(process.platform==="win32"?z8($8(),"opencode-openai-auth","opencode-openai-auth.log"):z8($8(),"opencode-openai-auth.log"))}function K1(){let Z=process.env.OPENCODE_OPENAI_AUTH_LOG_LEVEL;return Z&&B1.includes(Z)?Z:void 0}X8({file:H1,level:K1});if(process.once("beforeExit",async()=>{try{await T0()}catch{process.emitWarning("OpenAI auth could not flush its log file at shutdown")}}),process.platform!=="win32")process.on("exit",()=>T0());
90
+ export{XZ as xc,xZ as yc,C8 as zc,t3 as Ac,U8 as Bc,$4 as Cc,j8 as Dc,q8 as Ec,C as Fc,G4 as Gc,I8 as Hc,aZ as Ic,b8 as Jc,p0 as Kc,f8 as Lc,h8 as Mc,l8 as Nc,Q4 as Oc,U4 as Pc,JZ as Qc,rZ as Rc,j4 as Sc,O4 as Tc,s8 as Uc,V4 as Vc,F4 as Wc,eZ as Xc,a8 as Yc,WZ as Zc,e8 as _c,Z9 as $c,$9 as ad,z9 as bd,z2 as cd,Y2 as dd,G2 as ed,J2 as fd,F as gd,G3 as hd,S9 as id,x9 as jd,T9 as kd,U3 as ld,A9 as md,Z6 as nd,I9 as od,f as pd,M6 as qd,q7 as rd,VZ as sd,hZ as td,v7 as ud,p7 as vd,n7 as wd,b as xd,e as yd,v as zd,U$ as Ad,K5 as Bd,y3 as Cd,N$ as Dd,P$ as Ed,L$ as Fd,Q5 as Gd,h$ as Hd,w$ as Id,U5 as Jd,d6 as Kd,L0 as Ld,D5 as Md,c6 as Nd,u6 as Od,V5 as Pd,F5 as Qd,v$ as Rd,gZ as Sd,n6 as Td,N5 as Ud,j5 as Vd,q5 as Wd,a$ as Xd,o$ as Yd,e$ as Zd,_5 as _d,o6 as $d,t6 as ae,T5 as be,E5 as ce,C5 as de,A5 as ee,I5 as fe,Y1 as ge,J1 as he,b5 as ie,f5 as je,k5 as ke,y5 as le,h5 as me};