@cortexkit/pi-openai-auth 0.9.0 → 0.10.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.
- package/README.md +1 -1
- package/dist/index.js +19 -19
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@ This package is part of the CortexKit OpenAI Auth monorepo, which supports both
|
|
|
11
11
|
Install with Pi's package manager:
|
|
12
12
|
|
|
13
13
|
```bash
|
|
14
|
-
pi install npm:@cortexkit/pi-openai-auth@0.
|
|
14
|
+
pi install npm:@cortexkit/pi-openai-auth@0.10.0
|
|
15
15
|
```
|
|
16
16
|
|
|
17
17
|
For an unpinned install:
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null,Z)}var T3=($,Z)=>{for(var z in Z)I3($,z,{get:Z[z],enumerable:!0,configurable:!0,set:A3.bind(Z,z)})};var C3=($,Z)=>()=>($&&(Z=$($=0)),Z);var
|
|
2
|
-
`,{encoding:"utf8",mode:384});try{await
|
|
3
|
-
`;if(A0.push(J),A0.length>=50)
|
|
1
|
+
var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null,Z)}var T3=($,Z)=>{for(var z in Z)I3($,z,{get:Z[z],enumerable:!0,configurable:!0,set:A3.bind(Z,z)})};var C3=($,Z)=>()=>($&&(Z=$($=0)),Z);var a$={};T3(a$,{toResetIso:()=>S0,normalizeWsFrame:()=>R4,normalizeWham:()=>A4,normalizeQuotaHeaders:()=>F4,isCompleteQuotaHeaderFrame:()=>I4});function S0($){if($==null||$==="")return;let Z=typeof $==="number"?$:Number($);if(Number.isFinite(Z)){let X=Z<100000000000?Z*1000:Z,J=new Date(X);return Number.isNaN(J.getTime())?void 0:J.toISOString()}let z=new Date($);return Number.isNaN(z.getTime())?void 0:z.toISOString()}function u8($){let Z=Number($);return Number.isFinite(Z)&&Z>0?Z:void 0}function l$($){return typeof $==="number"&&Number.isFinite($)&&$>=0?$:void 0}function d$($,Z){let z=$.get(Z);if(z===null||z.trim()==="")return;let X=Number(z);if(!Number.isFinite(X)||X<0||X>100)return;let J=Z.slice(0,-13),G=u8($.get(`${J}-window-minutes`)),Q=S0($.get(`${J}-reset-at`)??void 0);if(X===0&&$.get(`${J}-window-minutes`)==="0"&&!Q)return;return{usedPercent:X,remainingPercent:100-X,resetsAt:Q,checkedAt:Date.now(),...G!==void 0?{windowMinutes:G}:{}}}function n$($,Z){let z=$.get(Z);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 F4($){if(s$.some((J)=>n$($,J)==="invalid"))return{};let Z={},z=d$($,"x-codex-primary-used-percent");if(z)Z.primary=z;let X=d$($,"x-codex-secondary-used-percent");if(X)Z.secondary=X;return Z}function I4($){let Z=s$.map((z)=>n$($,z));return Z.includes("valid")&&!Z.includes("invalid")}function i$($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=u8($.window_minutes),z=S0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z}:{}}}function R4($){let Z={},z=i$($.rate_limits?.primary);if(z)Z.primary=z;let X=i$($.rate_limits?.secondary);if(X)Z.secondary=X;return Z}function U0($){if($==null||$==="")return;let Z=Number($);return Number.isFinite(Z)&&Z>=0?Z:void 0}function c$($){if(!$)return;if(!Number.isFinite($.used_percent)||$.used_percent<0||$.used_percent>100)return;let Z=u8($.limit_window_seconds),z=S0($.reset_at);if($.used_percent===0&&Z===void 0&&!z)return;return{usedPercent:$.used_percent,remainingPercent:100-$.used_percent,resetsAt:z,checkedAt:Date.now(),...Z!==void 0?{windowMinutes:Z/60}:{}}}function A4($){let Z={},z=c$($.rate_limit?.primary_window);if(z)Z.primary=z;let X=c$($.rate_limit?.secondary_window);if(X)Z.secondary=X;let J=l$($.rate_limit_reset_credits?.available_count);if(J!==void 0)Z.resetCreditsAvailable=J;let G=l$($.rate_limit_reset_credits?.applicable_available_count);if(G!==void 0)Z.resetCreditsApplicable=G;let Q=$.spend_control?.individual_limit;if($.spend_control===null||Q===null)Z.spendControlCleared=!0;if(Q&&typeof $.spend_control?.reached==="boolean"){let W=U0(Q.limit),B=U0(Q.used),V=U0(Q.remaining),j=U0(Q.used_percent),q=U0(Q.remaining_percent);if(W!==void 0&&B!==void 0&&V!==void 0&&j!==void 0&&q!==void 0)Z.spendControl={limit:W,used:B,remaining:V,usedPercent:j,remainingPercent:q,resetsAt:S0(Q.reset_at),unit:Q.unit,source:Q.source,reached:$.spend_control.reached}}let Y=$.credits;if(Y&&typeof Y.has_credits==="boolean"&&typeof Y.unlimited==="boolean"&&typeof Y.overage_limit_reached==="boolean"){let W=U0(Y.balance);Z.credits={hasCredits:Y.has_credits,unlimited:Y.unlimited,overageLimitReached:Y.overage_limit_reached,...W!==void 0?{balance:W}:{}}}return Z}var s$;var l8=C3(()=>{s$=["x-codex-primary-used-percent","x-codex-secondary-used-percent"]});import{createAssistantMessageEventStream as X2}from"@earendil-works/pi-ai";import{streamSimple as J2}from"@earendil-works/pi-ai/compat";import{createHash as z5,randomUUID as c4}from"node:crypto";import{setTimeout as s4}from"node:timers/promises";import{randomUUID as b3}from"node:crypto";import{mkdir as S3,rename as k3,rm as w3,writeFile as f3}from"node:fs/promises";import{dirname as E3}from"node:path";async function x8($,Z){await S3(E3($),{recursive:!0});let z=`${$}.${b3()}.tmp`;await f3(z,`${JSON.stringify(Z,null,2)}
|
|
2
|
+
`,{encoding:"utf8",mode:384});try{await k3(z,$)}catch(X){throw await w3(z,{force:!0}).catch(()=>{}),X}}var y3=60000,v3=900000,h3=300000;function C$($){return $ instanceof Error?$.message:String($)}function b$($){let Z=C$($),z=$?.status;if(typeof z==="number")return z===429||z>=500;if(!($ instanceof Error))return!1;let X=$.code;return $.name==="AbortError"||$.name==="TimeoutError"||Z.includes("fetch failed")||X==="ECONNRESET"||X==="ECONNREFUSED"||X==="ETIMEDOUT"||X==="UND_ERR_CONNECT_TIMEOUT"}function i0($){let z=($.previous?.retryCount??0)+1,X,J=$.error?.retryAfter;if(typeof J==="number"&&J>0)X=J*1000;else if(b$($.error))X=Math.min(v3,y3*2**Math.min(z-1,6));else X=h3;return{message:C$($.error),checkedAt:$.now,nextRetryAt:$.now+X,retryCount:z}}function F0($,Z){if(!$?.nextRetryAt||$.nextRetryAt<=Z)return!1;return!0}function S$($){if(!$)return;let Z=Number($);if(Number.isFinite(Z)&&Z>0)return Math.ceil(Z);let z=Date.parse($);if(Number.isFinite(z)){let X=Math.ceil((z-Date.now())/1000);return X>0?X:void 0}return}import{setTimeout as L4}from"node:timers/promises";import{appendFileSync as m3,chmodSync as g3,existsSync as R8,renameSync as k$,statSync as p3}from"node:fs";var A8={error:0,warn:1,info:2,debug:3,trace:4},u3=5242880,R0,F8,w$;function l3(){if(R0===void 0)return;return(typeof R0==="function"?R0():R0)||void 0}function d3(){if(w$)return w$;let $=typeof F8==="function"?F8():F8;if($&&$ in A8)return $;return"info"}var i3=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;function c3($){if(i3.test($))return!0;let Z=$.toLowerCase().replace(/[-_]/g,"");if(Z==="chatgptaccountid")return!0;if(Z==="email"||Z==="orgname"||Z==="organizationname")return!0;if(Z.includes("apikey"))return!0;if(Z.endsWith("secret")||Z.endsWith("password"))return!0;if(Z.endsWith("token")&&!Z.endsWith("tokens"))return!0;return!1}var f$=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function s3($){return C8($,new WeakSet)}function n3($){return T8($,new WeakSet)}function T8($,Z){if(typeof $==="string")return $.replace(f$,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>T8(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=T8(J,Z);return Z.delete($),z}return $}function C8($,Z){if(typeof $==="string")return $.replace(f$,"***REDACTED***");if(Array.isArray($)){if(Z.has($))return"[Circular]";Z.add($);let z=$.map((X)=>C8(X,Z));return Z.delete($),z}if($&&typeof $==="object"){if(Z.has($))return"[Circular]";Z.add($);let z={};for(let[X,J]of Object.entries($))z[X]=c3(X)?"***REDACTED***":C8(J,Z);return Z.delete($),z}return $}var A0=[],I8,a3=3;function b8($){try{g3($,384)}catch{}}function t3($){try{if(!(R8($)&&p3($).size>u3))return;for(let z=a3-1;z>=1;z--)if(R8(`${$}.${z}`)){let X=`${$}.${z+1}`;k$(`${$}.${z}`,X),b8(X)}let Z=`${$}.1`;k$($,Z),b8(Z)}catch{}}function E$(){if(!A0.length)return;let $=l3(),Z=A0.join("");if(A0=[],!$)return;try{if(t3($),R8($))b8($);m3($,Z,{encoding:"utf8",mode:384})}catch{}}function o3(){if(!I8)I8=setTimeout(()=>{I8=void 0,E$()},500)}function r3($){try{return` ${JSON.stringify(s3($))}`}catch{return" [unserializable]"}}function I0($,Z,z,X){if(R0===void 0)return;if(A8[Z]>A8[d3()])return;let J=`[${new Date().toISOString()}] ${Z.toUpperCase()} [${$}] ${n3(z)}`+(X===void 0?"":r3(X))+`
|
|
3
|
+
`;if(A0.push(J),A0.length>=50)E$();else o3()}function d($){return{error:(Z,z)=>I0($,"error",Z,z),warn:(Z,z)=>I0($,"warn",Z,z),info:(Z,z)=>I0($,"info",Z,z),debug:(Z,z)=>I0($,"debug",Z,z),trace:(Z,z)=>I0($,"trace",Z,z)}}import{createServer as e3}from"node:http";import{setTimeout as $4}from"node:timers/promises";var s0="app_EMoamEEZ73f0CkXaXp7hrann",V0="https://auth.openai.com",T0=1455,Z4=3000,z4="cortexkit-opencode-openai-auth";function y$($){return`${z4}/${$}`}var v$="main",X4=`"${v$}" is a reserved account id; choose a different label.`;function h$($){let Z=new Uint8Array($),z=String.fromCharCode(...Z);return btoa(z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function J4(){let Z=Array.from(crypto.getRandomValues(new Uint8Array(43))).map((X)=>"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"[X%66]).join(""),z=h$(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Z)));return{verifier:Z,challenge:z}}function k8($){if($.length>16384)return;let Z=$.split(".");if(Z.length!==3)return;let z=Z[1];if(!z||z.length>8192)return;try{return JSON.parse(Buffer.from(z,"base64url").toString())}catch{return}}function w8($){let Z=$.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let 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=$.organizations;if(Array.isArray(X)){let J=X[0];if(J&&typeof J==="object"&&!Array.isArray(J)&&typeof J.id==="string"&&J.id.length>0)return J.id}return}function f8($){if($.id_token){let Z=k8($.id_token),z=Z&&w8(Z);if(z)return z}if($.access_token){let Z=k8($.access_token);return Z?w8(Z):void 0}return}function G4($){return typeof $==="string"&&$.toLowerCase()===v$}function S8($){if(G4($))throw Error(X4);return $}function Q4($,Z,z){let X=new URLSearchParams({response_type:"code",client_id:s0,redirect_uri:$,scope:"openid profile email offline_access",code_challenge:Z.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:z,originator:"opencode"});return`${V0}/oauth/authorize?${X.toString()}`}async function Y4($,Z,z){let X=await fetch(`${V0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:$,redirect_uri:Z,client_id:s0,code_verifier:z.verifier}).toString()});if(!X.ok)throw Error(`Token exchange failed: ${X.status}`);return await X.json()}function W4($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var B4=`<!doctype html>
|
|
4
4
|
<html>
|
|
5
5
|
<head>
|
|
6
6
|
<title>CortexKit OpenAI Auth - Authorization Successful</title>
|
|
@@ -86,11 +86,11 @@ var I3=Object.defineProperty;var R3=($)=>$;function A3($,Z){this[$]=R3.bind(null
|
|
|
86
86
|
<div class="error">${W4($)}</div>
|
|
87
87
|
</div>
|
|
88
88
|
</body>
|
|
89
|
-
</html>`,b0,C0,$0=new Map;function W0(){return $0.size}function j0($){if($0.delete($),W0()===0)B0()}async function V4(){let $=`http://localhost:${T0}/auth/callback`;if(b0)return{port:T0,redirectUri:$};if(C0)return C0;C0=(async()=>{let Z=e3((z,X)=>{let J=new URL(z.url||"/",`http://127.0.0.1:${T0}`);if(J.pathname==="/auth/callback"){let G=J.searchParams.get("code"),Q=J.searchParams.get("state"),Y=J.searchParams.get("error"),W=J.searchParams.get("error_description");if(Y){let V=W||Y;if(Q){let j=$0.get(Q);if(j)j.reject(Error(V)),j0(Q);else if(W0()===0)B0()}else if(W0()===0)B0();X.writeHead(200,{"Content-Type":"text/html"}),X.end(c0(V));return}if(!Q){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing state parameter"));return}if(!G){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing authorization code"));return}let B=$0.get(Q);if(!B){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Unknown state — authorization may have expired"));return}j0(Q),Y4(G,$,B.pkce).then((V)=>B.resolve(V)).catch((V)=>B.reject(V)),X.writeHead(200,{"Content-Type":"text/html"}),X.end(B4);return}if(J.pathname==="/cancel"){let G=J.searchParams.get("state"),Q=G?[G]:[...$0.keys()];X.writeHead(200),X.end("Login cancelled");for(let Y of Q){let W=$0.get(Y);if(!W)continue;W.reject(Error("Login cancelled")),j0(Y)}if(W0()===0)B0();return}X.writeHead(404),X.end("Not found")});return await new Promise((z,X)=>{Z.once("error",X),Z.listen(T0,"127.0.0.1",()=>{Z.off("error",X),z()})}),b0=Z,{port:T0,redirectUri:$}})();try{return await C0}finally{C0=void 0}}function B0(){if(b0){let $=b0;b0=void 0,$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}}function j4($,Z,z=300000,X){return new Promise((J,G)=>{if(X?.aborted){j0(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if($0.get(Z))j0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),Y=()=>{if(clearTimeout(Q),$0.get(Z))j0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",Y);$0.set(Z,{pkce:$,state:Z,resolve:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);J(W)},reject:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);G(W)}})})}async function q4($){let Z=await fetch(`${V0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y9($)},body:JSON.stringify({client_id:s0})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${V0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function H4($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,J=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(J)&&J>0?J*1000:900000,Q=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let Y=await fetch(`${V0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y9(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Y.ok){let V=await Y.json(),j=await fetch(`${V0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:V.authorization_code,redirect_uri:`${V0}/deviceauth/callback`,client_id:s0,code_verifier:V.code_verifier}).toString()});if(!j.ok)throw Error(`Token exchange failed: ${j.status}`);return await j.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let W=G-(Date.now()-Q);if(W<=0)throw Error("Device authorization expired");let B=Math.min(X+Z4,W);try{await $4(B,void 0,{signal:z})}catch(V){if(V instanceof Error&&V.name==="AbortError")throw Error("Device authorization cancelled");throw V}}}function m9($,Z){let z=-1;if(Z.accountId)z=$.findIndex((X)=>X.accountId&&X.accountId===Z.accountId);if(z<0)z=$.findIndex((X)=>X.id===Z.id);if(z<0&&Z.label&&!Z.accountId)z=$.findIndex((X)=>X.label===Z.label);if(z>=0)return $[z]={...$[z],...Z,addedAt:$[z]?.addedAt??Z.addedAt},z;return $.push(Z),$.length-1}async function g9($){let{label:Z,headless:z=!1,signal:X,version:J}=$;if(S8(Z),z){let{deviceData:V,url:j,instructions:q}=await q4(J),K=(async()=>{let L=await H4(V,J,X),U=Date.now(),D=f8(L);return{id:S8(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:L.access_token,refresh:L.refresh_token,expires:U+(L.expires_in??3600)*1000,enabled:!0,addedAt:U,lastUsed:U,lastRefreshedAt:U,accountId:D}})();return{url:j,instructions:q,completion:K}}let{redirectUri:G}=await V4(),Q=await J4(),Y=h9(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Q4(G,Q,Y),B=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let V=await j4(Q,Y,void 0,X),j=Date.now(),q=f8(V);return{id:S8(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:j+(V.expires_in??3600)*1000,enabled:!0,addedAt:j,lastUsed:j,lastRefreshedAt:j,accountId:q}}finally{j0(Y)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}var N4=d("custody");var U4="claustrum-tombstone:v1:",D4=Symbol("custody-refuse"),P4=Symbol("custody-excluded");function y8($){return`${U4}${$}`}function p9($,Z){if($.corrupt)return!1;return $.refresh===y8(Z)}var E8=3600000;class O4{#z;#J=new Map;#B=new Map;#Y=new Map;#G=new Map;#$=new Set;#X=new Map;#Q=new Map;#W;#Z=!1;constructor($){this.#z=$.connector({connectionFile:"",handshakeTimeoutMs:5000}),this.#W=$.now??Date.now}async peek($){return this.#J.get($)}async peekMetadata($){let Z=this.#J.get($);if(!Z)return;return{recordVersion:Z.recordVersion,expiresAtMs:Z.expiresAtMs}}isBlocked($){return this.#$.has($)}isReauth($,Z=this.#W()){let z=this.#X.get($);if(z===void 0)return!1;return z>Z}markVaultSuccess($){this.#X.delete($),this.#Q.delete($),this.#Y.delete($)}async get($,Z,z={}){if(this.#Z)throw Error("Claustrum cache is closed");if(!z.force){let Y=this.#J.get($);if(Y)return Y}let X=!!z.force,J=this.#B.get($);if(J&&J.force===X)return J.promise;let G=this.#V($,Z),Q={force:X,promise:G.finally(()=>{this.#B.delete($)})};return this.#B.set($,Q),Q.promise}async#V($,Z){let z=await this.#z,X=8;for(let J=0;J<8;J++){let G=await z.getCredential($,Z),Q=G.expiresAtMs??Number.MAX_SAFE_INTEGER;if(!this.#G.get($)?.has(G.recordVersion)){let W={payload:{access:G.material},recordVersion:G.recordVersion,expiresAtMs:Q,servedAccountId:G.accountId};return this.#J.set($,W),this.#$.delete($),this.#G.delete($),W}await L4(5*(J+1))}throw Error("custody credential rejected version after retries")}async reportAuthFailure($){if(this.#Z)return;let{handle:Z,recordVersion:z,providerStatus:X}=$,J=this.#W(),G=this.#Y.get(Z);if(G!==void 0&&G>=z)return;let Q=this.#Q.get(Z);if(Q&&Q.count>=2)if(Q.reauthUntil!==void 0&&J>=Q.reauthUntil)this.#Q.delete(Z),this.#X.delete(Z),this.#Y.delete(Z),Q=void 0;else return;let Y=await this.#z;try{await Y.reportAuthFailure({handle:Z,providerStatus:X,recordVersion:z,reporterSource:"direct"}),this.#Y.set(Z,z),this.#$.add(Z);let W=this.#Q.get(Z);if(this.#Q.set(Z,{count:(W?.count??0)+1,firstReportedAt:W?.firstReportedAt??J,reauthUntil:(W?.count??0)+1>=2?J+E8:void 0}),(W?.count??0)+1>=2)this.#X.set(Z,J+E8),N4.warn("custody report bound reached; entering reauth",{reauthMs:E8})}finally{let W=this.#J.get(Z);if(W&&W.recordVersion===z)this.#J.delete(Z);let B=this.#G.get(Z);if(!B)B=new Set,this.#G.set(Z,B);B.add(z)}}close(){if(this.#Z)return;this.#Z=!0,this.#J.clear(),this.#B.clear(),this.#Y.clear(),this.#G.clear(),this.#$.clear(),this.#X.clear(),this.#Q.clear(),this.#z.then(($)=>$.close()).catch(()=>{})}}class v8 extends Error{code="CUSTODY_TOMBSTONED";status=503;isRefreshError=!0;constructor($){super(`custody tombstoned: ${y8($)}`);this.name="CustodyTombstoneRefreshError"}}function h8($,Z){if(p9($,Z))throw new v8(Z)}import{basename as M4,dirname as _4,join as x4}from"node:path";var n0="openai-auth.json",u9="openai-auth-state.json";function g8($){return M4($)===n0?x4(_4($),u9):`${$}.state.json`}function p8($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var T4=d("quota");var C4="https://chatgpt.com/backend-api/wham/usage";async function d8($){let Z=$.logger??T4,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let J=await $.fetchImpl(C4,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!J.ok){let Y=S9(J.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${J.status}`),{status:J.status,retryAfter:Y})}let{normalizeWham:G}=await Promise.resolve().then(() => (l8(),a9)),Q=G(await J.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:J.status,elapsedMs:Date.now()-X}),Q}catch(J){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof J?.status==="number"?J.status:"error",elapsedMs:Date.now()-X,error:p8(J)}),J}}import{createHash as v4}from"node:crypto";import{randomUUID as i8}from"node:crypto";import{mkdir as t9,readFile as c8,rename as b4,rm as D0,stat as o9,writeFile as a0}from"node:fs/promises";import{dirname as S4,join as r9}from"node:path";var w4=globalThis.setTimeout.bind(globalThis),k4=globalThis.clearTimeout.bind(globalThis);function f4($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function w0($){let Z=`${$.path}.${$.name}.lock`,z=r9(Z,"owner.json"),X=i8(),J=$.now??Date.now,G=null,Q=!1,Y=null,W=`${Z}.evicting`,B=r9(W,"owner.json"),V=i8(),j=5000,q=8;async function K(){try{return JSON.parse(await c8(Z,"utf8"))}catch(O){if(O.code!=="EISDIR")throw O;return JSON.parse(await c8(z,"utf8"))}}async function L(){await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
89
|
+
</html>`,b0,C0,$0=new Map;function W0(){return $0.size}function j0($){if($0.delete($),W0()===0)B0()}async function V4(){let $=`http://localhost:${T0}/auth/callback`;if(b0)return{port:T0,redirectUri:$};if(C0)return C0;C0=(async()=>{let Z=e3((z,X)=>{let J=new URL(z.url||"/",`http://127.0.0.1:${T0}`);if(J.pathname==="/auth/callback"){let G=J.searchParams.get("code"),Q=J.searchParams.get("state"),Y=J.searchParams.get("error"),W=J.searchParams.get("error_description");if(Y){let V=W||Y;if(Q){let j=$0.get(Q);if(j)j.reject(Error(V)),j0(Q);else if(W0()===0)B0()}else if(W0()===0)B0();X.writeHead(200,{"Content-Type":"text/html"}),X.end(c0(V));return}if(!Q){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing state parameter"));return}if(!G){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Missing authorization code"));return}let B=$0.get(Q);if(!B){if(W0()===0)B0();X.writeHead(400,{"Content-Type":"text/html"}),X.end(c0("Unknown state — authorization may have expired"));return}j0(Q),Y4(G,$,B.pkce).then((V)=>B.resolve(V)).catch((V)=>B.reject(V)),X.writeHead(200,{"Content-Type":"text/html"}),X.end(B4);return}if(J.pathname==="/cancel"){let G=J.searchParams.get("state"),Q=G?[G]:[...$0.keys()];X.writeHead(200),X.end("Login cancelled");for(let Y of Q){let W=$0.get(Y);if(!W)continue;W.reject(Error("Login cancelled")),j0(Y)}if(W0()===0)B0();return}X.writeHead(404),X.end("Not found")});return await new Promise((z,X)=>{Z.once("error",X),Z.listen(T0,"127.0.0.1",()=>{Z.off("error",X),z()})}),b0=Z,{port:T0,redirectUri:$}})();try{return await C0}finally{C0=void 0}}function B0(){if(b0){let $=b0;b0=void 0,$.close(()=>{}),$.closeIdleConnections?.(),setTimeout(()=>{$.closeAllConnections?.()},25).unref?.()}}function j4($,Z,z=300000,X){return new Promise((J,G)=>{if(X?.aborted){j0(Z),G(Error("Login cancelled"));return}let Q=setTimeout(()=>{if($0.get(Z))j0(Z),G(Error("OAuth callback timeout — authorization took too long"))},z),Y=()=>{if(clearTimeout(Q),$0.get(Z))j0(Z),G(Error("Login cancelled"))};if(X)X.addEventListener("abort",Y);$0.set(Z,{pkce:$,state:Z,resolve:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);J(W)},reject:(W)=>{if(clearTimeout(Q),X)X.removeEventListener("abort",Y);G(W)}})})}async function q4($){let Z=await fetch(`${V0}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y$($)},body:JSON.stringify({client_id:s0})});if(!Z.ok)throw Error("Failed to initiate device authorization");let z=await Z.json();return{deviceData:z,url:`${V0}/codex/device`,instructions:`Enter code: ${z.user_code}`}}async function H4($,Z,z){let X=Math.max(parseInt($.interval,10)||5,1)*1000,J=typeof $.expires_in==="number"?$.expires_in:parseInt($.expires_in||"",10),G=!Number.isNaN(J)&&J>0?J*1000:900000,Q=Date.now();while(!0){if(z?.aborted)throw Error("Device authorization cancelled");if(Date.now()-Q>G)throw Error("Device authorization expired");let Y=await fetch(`${V0}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":y$(Z)},body:JSON.stringify({device_auth_id:$.device_auth_id,user_code:$.user_code})});if(Y.ok){let V=await Y.json(),j=await fetch(`${V0}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:V.authorization_code,redirect_uri:`${V0}/deviceauth/callback`,client_id:s0,code_verifier:V.code_verifier}).toString()});if(!j.ok)throw Error(`Token exchange failed: ${j.status}`);return await j.json()}if(Y.status!==403&&Y.status!==404)throw Error(`Device authorization failed: ${Y.status}`);let W=G-(Date.now()-Q);if(W<=0)throw Error("Device authorization expired");let B=Math.min(X+Z4,W);try{await $4(B,void 0,{signal:z})}catch(V){if(V instanceof Error&&V.name==="AbortError")throw Error("Device authorization cancelled");throw V}}}function m$($,Z){let z=-1;if(Z.accountId)z=$.findIndex((X)=>X.accountId&&X.accountId===Z.accountId);if(z<0)z=$.findIndex((X)=>X.id===Z.id);if(z<0&&Z.label&&!Z.accountId)z=$.findIndex((X)=>X.label===Z.label);if(z>=0)return $[z]={...$[z],...Z,addedAt:$[z]?.addedAt??Z.addedAt},z;return $.push(Z),$.length-1}async function g$($){let{label:Z,headless:z=!1,signal:X,version:J}=$;if(S8(Z),z){let{deviceData:V,url:j,instructions:q}=await q4(J),K=(async()=>{let L=await H4(V,J,X),U=Date.now(),D=f8(L);return{id:S8(Z||D||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:L.access_token,refresh:L.refresh_token,expires:U+(L.expires_in??3600)*1000,enabled:!0,addedAt:U,lastUsed:U,lastRefreshedAt:U,accountId:D}})();return{url:j,instructions:q,completion:K}}let{redirectUri:G}=await V4(),Q=await J4(),Y=h$(crypto.getRandomValues(new Uint8Array(32)).buffer),W=Q4(G,Q,Y),B=(async()=>{try{if(X?.aborted)throw Error("Login cancelled");let V=await j4(Q,Y,void 0,X),j=Date.now(),q=f8(V);return{id:S8(Z||q||crypto.randomUUID()),label:Z||void 0,type:"oauth",access:V.access_token,refresh:V.refresh_token,expires:j+(V.expires_in??3600)*1000,enabled:!0,addedAt:j,lastUsed:j,lastRefreshedAt:j,accountId:q}}finally{j0(Y)}})();return{url:W,instructions:"Complete authorization in your browser. This window will close automatically.",completion:B}}var N4=d("custody");var U4="claustrum-tombstone:v1:",D4=Symbol("custody-refuse"),P4=Symbol("custody-excluded");function y8($){return`${U4}${$}`}function p$($,Z){if($.corrupt)return!1;return $.refresh===y8(Z)}var E8=3600000;class O4{#z;#J=new Map;#B=new Map;#Y=new Map;#G=new Map;#$=new Set;#X=new Map;#Q=new Map;#W;#Z=!1;constructor($){this.#z=$.connector({connectionFile:"",handshakeTimeoutMs:5000}),this.#W=$.now??Date.now}async peek($){return this.#J.get($)}async peekMetadata($){let Z=this.#J.get($);if(!Z)return;return{recordVersion:Z.recordVersion,expiresAtMs:Z.expiresAtMs}}isBlocked($){return this.#$.has($)}isReauth($,Z=this.#W()){let z=this.#X.get($);if(z===void 0)return!1;return z>Z}markVaultSuccess($){this.#X.delete($),this.#Q.delete($),this.#Y.delete($)}async get($,Z,z={}){if(this.#Z)throw Error("Claustrum cache is closed");if(!z.force){let Y=this.#J.get($);if(Y)return Y}let X=!!z.force,J=this.#B.get($);if(J&&J.force===X)return J.promise;let G=this.#V($,Z),Q={force:X,promise:G.finally(()=>{this.#B.delete($)})};return this.#B.set($,Q),Q.promise}async#V($,Z){let z=await this.#z,X=8;for(let J=0;J<8;J++){let G=await z.getCredential($,Z),Q=G.expiresAtMs??Number.MAX_SAFE_INTEGER;if(!this.#G.get($)?.has(G.recordVersion)){let W={payload:{access:G.material},recordVersion:G.recordVersion,expiresAtMs:Q,servedAccountId:G.accountId};return this.#J.set($,W),this.#$.delete($),this.#G.delete($),W}await L4(5*(J+1))}throw Error("custody credential rejected version after retries")}async reportAuthFailure($){if(this.#Z)return;let{handle:Z,recordVersion:z,providerStatus:X}=$,J=this.#W(),G=this.#Y.get(Z);if(G!==void 0&&G>=z)return;let Q=this.#Q.get(Z);if(Q&&Q.count>=2)if(Q.reauthUntil!==void 0&&J>=Q.reauthUntil)this.#Q.delete(Z),this.#X.delete(Z),this.#Y.delete(Z),Q=void 0;else return;let Y=await this.#z;try{await Y.reportAuthFailure({handle:Z,providerStatus:X,recordVersion:z,reporterSource:"direct"}),this.#Y.set(Z,z),this.#$.add(Z);let W=this.#Q.get(Z);if(this.#Q.set(Z,{count:(W?.count??0)+1,firstReportedAt:W?.firstReportedAt??J,reauthUntil:(W?.count??0)+1>=2?J+E8:void 0}),(W?.count??0)+1>=2)this.#X.set(Z,J+E8),N4.warn("custody report bound reached; entering reauth",{reauthMs:E8})}finally{let W=this.#J.get(Z);if(W&&W.recordVersion===z)this.#J.delete(Z);let B=this.#G.get(Z);if(!B)B=new Set,this.#G.set(Z,B);B.add(z)}}close(){if(this.#Z)return;this.#Z=!0,this.#J.clear(),this.#B.clear(),this.#Y.clear(),this.#G.clear(),this.#$.clear(),this.#X.clear(),this.#Q.clear(),this.#z.then(($)=>$.close()).catch(()=>{})}}class v8 extends Error{code="CUSTODY_TOMBSTONED";status=503;isRefreshError=!0;constructor($){super(`custody tombstoned: ${y8($)}`);this.name="CustodyTombstoneRefreshError"}}function h8($,Z){if(p$($,Z))throw new v8(Z)}import{basename as M4,dirname as _4,join as x4}from"node:path";var n0="openai-auth.json",u$="openai-auth-state.json";function g8($){return M4($)===n0?x4(_4($),u$):`${$}.state.json`}function p8($){if($ instanceof Error)return $.message;if(typeof $==="string")return $;try{return JSON.stringify($)}catch{return String($)}}var T4=d("quota");var C4="https://chatgpt.com/backend-api/wham/usage";async function d8($){let Z=$.logger??T4,z=$.accountKey??"unknown",X=Date.now();Z.debug("wham usage fetch started",{pid:process.pid,accountId:z});try{let J=await $.fetchImpl(C4,{signal:AbortSignal.timeout(15000),headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId??"","oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":"/backend-api/wham/usage"}});if(!J.ok){let Y=S$(J.headers.get("retry-after"));throw Object.assign(Error(`wham usage check failed: ${J.status}`),{status:J.status,retryAfter:Y})}let{normalizeWham:G}=await Promise.resolve().then(() => (l8(),a$)),Q=G(await J.json());return Z.debug("wham usage fetch succeeded",{pid:process.pid,accountId:z,status:J.status,elapsedMs:Date.now()-X}),Q}catch(J){throw Z.warn("wham usage fetch failed",{pid:process.pid,accountId:z,status:typeof J?.status==="number"?J.status:"error",elapsedMs:Date.now()-X,error:p8(J)}),J}}import{createHash as v4}from"node:crypto";import{randomUUID as i8}from"node:crypto";import{mkdir as t$,readFile as c8,rename as b4,rm as D0,stat as o$,writeFile as a0}from"node:fs/promises";import{dirname as S4,join as r$}from"node:path";var k4=globalThis.setTimeout.bind(globalThis),w4=globalThis.clearTimeout.bind(globalThis);function f4($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function k0($){let Z=`${$.path}.${$.name}.lock`,z=r$(Z,"owner.json"),X=i8(),J=$.now??Date.now,G=null,Q=!1,Y=null,W=`${Z}.evicting`,B=r$(W,"owner.json"),V=i8(),j=5000,q=8;async function K(){try{return JSON.parse(await c8(Z,"utf8"))}catch(O){if(O.code!=="EISDIR")throw O;return JSON.parse(await c8(z,"utf8"))}}async function L(){await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
90
90
|
`,{encoding:"utf8",mode:384})}async function U(){try{return await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
91
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(O){let R=O.code;if(R==="EEXIST"||R==="EISDIR")return!1;if(R==="ENOENT"){await
|
|
92
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(T){let d0=T.code;if(d0==="EEXIST"||d0==="EISDIR")return!1;throw T}}throw O}}async function D(){await new Promise((O)=>setTimeout(O,Math.floor(Math.random()*4)))}async function P(){try{let O=await K();return Number(O?.expiresAt)>J()}catch{try{return(await
|
|
93
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(O){if(f4(O))return!1;throw await x0(),O}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function N0(){let O;try{O=await o9(W)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if(O.mtimeMs+j>J())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let R=`${W}.${i8()}`;try{await b4(W,R)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if($.onStep)await $.onStep("stale-marker-claimed");return await D0(R,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function w(O){try{if(!await _8())return!1}catch(R){if(R.code==="EEXIST")return!1;throw R}try{await O()}finally{await x0()}return!0}async function x3(){for(let O=0;O<q;O++){if($.onStep)await $.onStep("relinquish-read");let R;try{R=await K()}catch{return}if(R?.ownerId!==X)return;try{await D0(Z,{recursive:!0,force:!0});return}catch{await D()}}}function A9(){if(!$.renew||Q)return;let O=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=w4(()=>{let R=(async()=>{let T=!Q;try{if(!await w(async()=>{let T9=await K(),F3=J();if(Q||T9?.ownerId!==X){T=!1;return}if(Number(T9?.expiresAt)<=F3){T=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-ready");if(await L(),!await A()){T=!1,await x3();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(T&&!Q)A9()}})();Y=R,R.finally(()=>{if(Y===R)Y=null})},O),"unref"in G)G.unref()}let Y0=await U();if(!Y0)for(let O=0;O<q;O++){if(Y0=await U(),Y0)break;if(await P())return null;try{if(!await _8()){await D();continue}}catch(R){if(R.code!=="EEXIST")throw R;if(await N0()==="fresh")return null;await D();continue}try{if(await P())return null;if(!await A())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await A())return null;if(await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(Y0=await U(),!Y0)return null;if(!await A())return await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),Y0=!1,null;break}finally{await x0()}}if(!Y0)return null;return A9(),{release:async()=>{if(Q=!0,G)k4(G),G=null;await Y;for(let O=0;O<q;O++){try{if(await w(async()=>{if((await K())?.ownerId!==X)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await A())return;await D0(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await N0()}catch{return}await D()}}}}var h4=globalThis.setTimeout,m4=5;function k0($){let Z=$?.quota?.checkIntervalMinutes??m4;return Math.max(1,Z)*60000}function g4($){return $?.quota?.enabled!==!1}function p4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function e9($,Z,z){if(!g4(Z))return z+k0(Z);let X=p4(Z),J=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=X[G])continue;let Y=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=z)return z+k0(Z);J.push(Y)}if(!J.length)return z+k0(Z);return Math.min(...J)+60000}function u4($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function l4($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function l($){return v4("sha256").update($).digest("hex").slice(0,16)}class n{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($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==l($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==l(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!$$(Z.quota))return;if(this.mainTokenFp=l($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,s8(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,J){if(!X&&!$$(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(J&&G&&J!==G)this.clearRateLimited($);let Q=J??G;if(this.fallbacks.set($,{...Z,accountId:Q}),z)this.fallbackTokenFps.set($,l(z));else this.fallbackTokenFps.delete($);if(s8(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=l($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)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=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=n.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 J=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,J),J}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(h8(z,"openai"),!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=l($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).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($){let Z=l4(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=u4($);if(!z)return;let X=Z?l(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let J={quota:z.quota,refreshAfter:e9(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=J.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=J,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&F0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=k0(this.storage);for(let z of $){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 J=this.getFallback(z.id,z.access);if(J&&J.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return F0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==l(Z))return!1}return F0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,l(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<n.API_CALL_GAP_MS)await new Promise((J)=>{let G=h4(J,n.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=l($);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 w0({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(),J=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=l($),this.main={quota:J,refreshAfter:e9(J,this.storage,G),checkedAt:G},s8(J))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(J,G,this.mainTokenFp,X),J}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)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 w0({name:n.quotaLockName($),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(Z),J=this.now();return this.setFallback($,{quota:X,refreshAfter:J+k0(this.storage),checkedAt:J},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(n.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(n.isAuthError($))return;this.mainLastApiError=i0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(n.isAuthError(z))return;let X=l(Z),J=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,i0({error:z,now:this.now(),previous:J})),this.fallbackErrorTokenFps.set($,X)}}function $$($){return Boolean($.primary||$.secondary)}function s8($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{readFile as X6}from"node:fs/promises";var K5=d("refresh"),J$=d("accounts"),n4=1e4,a4=15000,n8=50;function m8($){return $.type==="oauth"&&$.corrupt!==!0}function t4($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}function N($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var o4=new Set(["__proto__","constructor","prototype"]);function i($){return $.length>0&&!o4.has($)}function t0($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():c4(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function Z$($){if(!N($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function r4($){if(!N($))return;let Z={};for(let J of["primary","secondary"]){let G=$[J];if(!N(G))continue;let Q=Number(G.usedPercent),Y=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(W))continue;let B=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[J]={usedPercent:Q,remainingPercent:Y,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(B)&&B>0?{windowMinutes:B}:{}}}for(let J of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[J]==="number"?$[J]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[J]=G}let z=$.spendControl;if(N(z)){let J=Number(z.limit),G=Number(z.used),Q=Number(z.remaining),Y=Number(z.usedPercent),W=Number(z.remainingPercent);if(Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(Y)&&Number.isFinite(W)&&typeof z.reached==="boolean")Z.spendControl={limit:J,used:G,remaining:Q,usedPercent:Y,remainingPercent:W,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=$.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&typeof X.overageLimitReached==="boolean"){let J=Number(X.balance);Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,overageLimitReached:X.overageLimitReached,...Number.isFinite(J)?{balance:J}:{}}}return Object.keys(Z).length?Z:void 0}function e4($){if(!N($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!t4(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...t0($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}return{...t0($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:Z$($.lastRefreshError),lastQuotaRefreshError:Z$($.lastQuotaRefreshError),quota:r4($.quota)}}function $6($){if(!N($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!i(z)||!N(X))continue;let J={};if(N(X.inFlight))J.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))J.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))J.cooldownUntil=X.cooldownUntil;if(Object.keys(J).length>0)Z[z]=J}return Object.keys(Z).length>0?Z:void 0}var z$=new Set;function G$($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(z$.has(Z))return;z$.add(Z),J$.warn("account load-dropped, preserved on disk",{droppedIds:$})}function Q$($){if(!N($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(e4).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let Q of Z)if(N(Q)&&typeof Q.id==="string"&&Q.id.trim())X.add(Q.id.trim());let J=new Set(z.map((Q)=>Q.id)),G=[];for(let Q of X)if(!J.has(Q))G.push(Q);G$(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N($.refresh)?$.refresh:void 0,quota:N($.quota)?$.quota:void 0,reset:$6($.reset),dump:N($.dump)?$.dump:void 0,costZeroing:N($.costZeroing)?$.costZeroing:void 0,killswitch:N($.killswitch)?$.killswitch:void 0,logging:N($.logging)?$.logging:void 0,cachekeep:N($.cachekeep)?$.cachekeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,claustrum:Z6($.claustrum),accounts:z}}function Z6($){if(!N($))return;let Z=$.mode==="claustrum"?"claustrum":"local",z=z6($.transition),X=Array.isArray($.rowHistory)?$.rowHistory.filter((J)=>typeof J==="string"):void 0;return{mode:Z,transition:z,rowHistory:X}}function z6($){if(!N($)||!N($.fingerprints))return;if(typeof $.manifestRevision!=="string"||typeof $.storeGeneration!=="string"||!N($.fingerprints.fallbacks))return;let Z=Object.fromEntries(Object.entries($.fingerprints.fallbacks).filter((z)=>typeof z[1]==="string"));return{manifestRevision:$.manifestRevision,storeGeneration:$.storeGeneration,fingerprints:{main:typeof $.fingerprints.main==="string"?$.fingerprints.main:void 0,fallbacks:Z}}}async function f0($){try{return{exists:!0,value:JSON.parse(await X6($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function J0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function Y$($){return(await J6($)).roster}async function J6($){let Z;try{Z=(await f0($)).value}catch{return{roster:null,mode:"claustrum"}}return{roster:a8(Z),mode:f(N(Z)?Z:void 0)}}function W$($,Z){if(!N($))return $;let z=N(Z)?Z:{},X=N(z.main)?z.main:void 0,J=N(z.accounts)?z.accounts:{},G=N($.quota)?$.quota:{},Q=N($.refresh)?$.refresh:{},Y=X??G,W=X??Q,V=Array.isArray($.accounts)?$.accounts.map((j)=>{if(!N(j))return j;let q=typeof j.id==="string"&&N(J[j.id])?J[j.id]:{};return{...j,...q}}):void 0;return V$({...$,refresh:J0({...Q,mainLastRefreshError:W.lastRefreshError,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:J0({...G,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:V})}async function B$($){let Z=await f0($.configPath);if(!Z.exists)return null;let z=await f0($.statePath);return Q$(W$(Z.value,z.value))}function V$($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function G6($){return J0({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function Q6($){if($.type==="api")return J0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return J0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function Y6($){let Z=$.refresh?J0({enabled:$.refresh.enabled,intervalMinutes:$.refresh.intervalMinutes,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?J0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota,showToasts:$.quota.showToasts}):void 0;return V$({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,mainAccountId:$.mainAccountId,...$.claustrum!==void 0?{claustrum:{mode:$.claustrum.mode??"local",...$.claustrum.transition?{transition:$.claustrum.transition}:{},...$.claustrum.rowHistory?{rowHistory:$.claustrum.rowHistory}:{}}}:{},accounts:$.accounts.map(G6)})}async function X$($,Z=!1){let z=Date.now(),X=z+a4,J=0;while(Date.now()<=X){J++;let Y=await w0({name:"save",ttlMs:n4,path:$,renew:Z});if(Y)return Y;let W=X-Date.now();if(W<=0)break;await s4(Math.min(n8+H6(n8),W))}let G=Date.now()-z,Q=Math.round(G/Math.max(1,J));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${J} attempts, ~${Q}ms apart; retry interval is ${n8}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 f($){return $?.claustrum?.mode==="claustrum"?"claustrum":"local"}function W6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,Q6(z)]));return{version:1,main:J0({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function a8($){if(!N($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function B6($,Z,z,X){if(!N($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let J=[],G=[];for(let Q of Z){if(z.has(Q))continue;if(X.has(Q))continue;let Y=$.accounts.find((W)=>N(W)&&typeof W.id==="string"&&W.id.trim()===Q);if(!Y)continue;J.push(Y),G.push(Q)}return{preservedRawEntries:J,preservedIds:G}}function V6($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!N(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function j6($,Z,z){let X=a8($);if(X===null)return[];let{preservedRawEntries:J,preservedIds:G}=B6($,X,Z,z);return G$(G),J}async function G0($,Z,z={}){let{configPath:X,statePath:J}=Z,G=await X$(X);try{let Q=await X$(J);try{let Y=await f0(X),W=await f0(J),B=(Y.exists?Q$(W$(Y.value,W.value)):null)??q6(),V=new Set(B.accounts.map((w)=>w.id)),j=a8(Y.value)??new Set,q=$(B,{rawRosterIds:[...j],loadedRosterIds:[...V]})??B,K=new Set(q.accounts.map((w)=>w.id)),L=[...V].filter((w)=>!K.has(w));if(L.length>0)q.claustrum={...q.claustrum,mode:q.claustrum?.mode??"local",rowHistory:[...new Set([...q.claustrum?.rowHistory??[],...L])]};let U=new Set(z.allowDrop??[]),D=j6(Y.value,V,U),P=Y6(q),A=new Set((Array.isArray(P.accounts)?P.accounts:[]).map((w)=>N(w)&&typeof w.id==="string"?w.id.trim():"").filter(Boolean)),x0=D.filter((w)=>{if(!N(w))return!1;if(typeof w.id!=="string")return!1;return!A.has(w.id.trim())}),N0={...N(Y.value)?Y.value:{},...P,accounts:[...Array.isArray(P.accounts)?P.accounts:[],...x0]};return await x8(X,N0),await x8(J,W6(q)),J$.debug("account config written",{accountCount:N0.accounts.length,accountIds:V6(N0.accounts)}),q}finally{await Q.release()}}finally{await G.release()}}function q6(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function H6($){return Math.floor(Math.random()*($+1))}var N5=globalThis.setTimeout.bind(globalThis),U5=globalThis.clearTimeout.bind(globalThis);var t8="/backend-api/wham/rate-limit-reset-credits",K6=`https://chatgpt.com${t8}`,L$=`${t8}/consume`,L6=`https://chatgpt.com${L$}`,N6=300000,U6=60000,D6=15000,P6=60000;function o0($){return{configPath:$.configPath,statePath:$.statePath}}class c extends Error{kind;cooldownUntil;constructor($,Z,z){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=z}}class q0 extends Error{kind;status;constructor($,Z,z){super(Z);this.name="ResetCreditError",this.kind=$,this.status=z}}function N$($,Z,z){return{authorization:`Bearer ${$}`,...z?{"chatgpt-account-id":z}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function r0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U$($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function o8($){if(!r0($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt}}function D$($){return Boolean($&&Object.hasOwn($,"inFlight"))}function P$($,Z){return Z-$.startedAt<N6}function e0($,Z){if(!i(Z))return;return $.reset?.[Z]}function O$($){if(!$.reset)$.reset=Object.create(null);return $.reset}function M$($,Z,z){if(!i(Z))return;let X=O$($),J=X[Z]??{},G=J.lastOutcome;delete J.inFlight,J.lastOutcome={code:"ambiguous_local",at:z,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=J}function _$($,Z){let z=U$($),X=o8($?.inFlight);if(D$($)&&!X)return{kind:"corrupt",beforeState:z};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:z,cooldownUntil:$.cooldownUntil};if(X&&P$(X,Z))return{kind:"claim",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:z}}async function O6($,Z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let z=await $.loadAccountsFn(o0($));return _$(z?e0(z,Z):void 0,$.now())}async function M6($,Z){let z;if(await $.mutateAccountsFn((X)=>{let J=$.now(),G=e0(X,Z);if(z=_$(G,J),z.kind==="corrupt")M$(X,Z,J);return X},o0($)),!z)throw Error("corrupt reset state mutation did not run");return z}async function _6($,Z,z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let X;if(await $.mutateAccountsFn((J)=>{let G=$.now(),Q=e0(J,Z),Y=U$(Q),W=o8(Q?.inFlight);if(D$(Q)&&!W)return M$(J,Z,G),X={kind:"corrupt",beforeState:Y},J;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>G)return X={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},J;if(W&&P$(W,G))return X={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;if(W)return X={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;let B=$8(z);if(!B)return X={kind:"fresh",beforeState:Y},J;let V={redeemRequestId:$.randomUUID(),creditId:B.id,startedAt:G},j=O$(J);return j[Z]={...Q,inFlight:V},X={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:B}},J},o0($)),!X)throw Error("reset claim mutation did not run");return X}async function x6($,Z,z,X){if(!i(Z))return;if(!$9(X.kind))return;await $.mutateAccountsFn((J)=>{let G=e0(J,Z),Q=o8(G?.inFlight);if(!G||!Q||Q.redeemRequestId!==z.redeemRequestId||Q.creditId!==z.creditId)return J;let Y=$.now();if(delete G.inFlight,G.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")G.cooldownUntil=Y+P6;else delete G.cooldownUntil;return J},o0($))}function E0($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return!Number.isFinite(z)||z>Z}function r8($,Z,z){if(!(Z||E0($.primary,z)||E0($.secondary,z)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function j$($,Z){let z=$[Z];if(z===void 0||z===null)return;return typeof z==="string"?z:null}function F6($){if(!r0($))return;let Z=j$($,"granted_at"),z=j$($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||z===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...z===void 0?{}:{resetType:z},isSupportedByPlan:$.is_supported_by_plan}}async function e8($,Z,z){let X;try{X=await $(K6,{method:"GET",headers:N$(Z,t8,z),signal:AbortSignal.timeout(D6)})}catch{throw new q0("http_error","reset credit list request failed")}if(!X.ok)throw new q0("http_error",`reset credit list request failed: ${X.status}`,X.status);let J;try{J=await X.json()}catch{throw new q0("invalid_response","reset credit list response was not valid JSON",X.status)}if(!r0(J))throw new q0("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(J.credits)?J.credits:[]).flatMap((Q)=>{let Y=F6(Q);return Y===void 0?[]:[Y]}),availableCount:typeof J.available_count==="number"&&Number.isFinite(J.available_count)?J.available_count:void 0}}function $8($){return[...$].filter(x$).sort((Z,z)=>Date.parse(Z.expiresAt)-Date.parse(z.expiresAt))[0]}function x$($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function F$($){return $.filter(x$).length}function $9($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function I6($,Z,z,X,J){let G;try{G=await $(L6,{method:"POST",headers:{...N$(Z,L$,z),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:J,credit_id:X}),signal:AbortSignal.timeout(U6)})}catch(B){return{kind:"ambiguous",raw:B}}let Q;try{Q=await G.text()}catch(B){return G.ok?{kind:"ambiguous",raw:B}:{kind:"http_error",raw:B,status:G.status}}let Y=Q,W=!1;try{Y=JSON.parse(Q),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Y,status:G.status};if(!W||!r0(Y)||!$9(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function q$($){if($.kind==="cooldown")throw new c("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function H$(){throw new c("expired_unreconciled","the previous reset attempt outcome is unknown")}function K$($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function R6($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}async function I$($,Z){if(!i(Z.accountKey))throw new c("invalid_account_key","the reset account key is reserved");let z=await $.resolveTarget(Z.accountKey);if(z.chatgptAccountId!==Z.expectedChatgptAccountId)throw new c("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=z.accountKey==="main"?void 0:z.chatgptAccountId,J=await O6($,Z.accountKey);if(J.kind==="corrupt"){if(J=await M6($,Z.accountKey),J.kind==="corrupt")return K$(z,J.beforeState)}if(J.kind==="cooldown")q$(J);let G;if(J.kind==="claim")G=J.claim;else if(J.kind==="expired_unreconciled"){if(!Z.retry)H$();G=J.claim}else{if(Z.retry)throw new c("retry_without_inflight","there is no active reset credit redemption to retry");let[W,B]=await Promise.all([$.fetchUsage(z),e8($.fetchImpl,z.accessToken,X)]),V=r8(W,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!V.ok)throw new c("not_exhausted",V.reason);if(!$8(B.credits))throw new c("no_eligible_credit","no eligible reset credit was returned");let j=await _6($,Z.accountKey,B.credits);if(j.kind==="corrupt")return K$(z,j.beforeState);if(j.kind==="cooldown")q$(j);if(j.kind==="expired_unreconciled")H$();if(j.kind!=="claim")throw new c("no_eligible_credit","no eligible reset credit was available while claiming");G=j.claim}let Q=await I6($.fetchImpl,z.accessToken,X,G.inFlight.creditId,G.inFlight.redeemRequestId),Y=!1;try{await x6($,Z.accountKey,G.inFlight,Q)}catch{Y=$9(Q.kind)}return{target:z,selectedCredit:G.selectedCredit,beforeState:J.beforeState,outcome:Q,retrySafety:Y?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":R6(Q),...Y?{finalizeStateWriteFailed:!0}:{}}}function R$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var z8="openai-quota",X8="openai-account",J8="openai-routing";var y0="openai-reset";var _=d("commands");function m($){return{configPath:$.accountStoragePath,statePath:$.accountStatePath}}function A$($){if($==="fallback-first")return"Try usable fallback accounts before the main account.";if($==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var A6=900000;function T$($,Z){if(typeof $!=="number"||!Number.isFinite($))return" (age unknown)";let z=Z-$;if(z<A6)return"";let X=Math.floor(z/3600000);if(X>=24)return` (${Math.floor(X/24)}d old)`;if(X>=1)return` (${X}h old)`;return` (${Math.floor(z/60000)}m old)`}function C$($,Z=""){let z=$.resetsAt?` · resets ${$.resetsAt}`:"",X=(Q)=>Math.round(Q).toLocaleString("en-US"),J=$.unit??"unit",G=$.limit===1||J.endsWith("s")?J:`${J}s`;return`${Z}- credits: ${Math.round($.usedPercent)}% used (${X($.used)} / ${X($.limit)} ${G}, ${X($.remaining)} remaining)${z}`}async function T6($){let Z=await $.refreshAllQuota?.(),z=$.quotaManager.getMain(),X=Date.now(),J=["## OpenAI Quota",""];if(z?.quota){let Y=z.quota;J.push("### Main account");for(let W of["primary","secondary"]){let B=Y[W];if(B){let V=Math.round(B.usedPercent),j="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));J.push(`- ${W}: ${j} ${V}% used (${Math.round(B.remainingPercent)}% remaining)${T$(B.checkedAt??z.checkedAt,X)}`)}}if(Y.resetCreditsAvailable!==void 0)J.push(`- resets: ${Y.resetCreditsAvailable}`);if(Y.spendControl)J.push(C$(Y.spendControl))}else J.push("No main quota snapshot available. Send a request first.");let Q=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(Q.length>0){J.push(""),J.push("### Fallback accounts");for(let[Y,W]of Q){if(!W?.quota)continue;J.push(`**${Y}**`);for(let B of["primary","secondary"]){let V=W.quota[B];if(V){let j=Math.round(V.usedPercent);J.push(` - ${B}: ${j}% used (${Math.round(V.remainingPercent)}% remaining)${T$(V.checkedAt??W.checkedAt,X)}`)}}if(W.quota.resetCreditsAvailable!==void 0)J.push(` - resets: ${W.quota.resetCreditsAvailable}`);if(W.quota.spendControl)J.push(C$(W.quota.spendControl," "))}}if(Z?.length){let Y=Z.filter((W)=>!W.ok);if(Y.length>0){J.push("");for(let W of Y)J.push(W.permanent?`- ${W.account}: sign-in no longer accepted — remove and add this account again`:`- ${W.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:J.join(`
|
|
91
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(O){let R=O.code;if(R==="EEXIST"||R==="EISDIR")return!1;if(R==="ENOENT"){await t$(S4(Z),{recursive:!0});try{return await a0(Z,`${JSON.stringify({ownerId:X,expiresAt:J()+$.ttlMs})}
|
|
92
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(T){let d0=T.code;if(d0==="EEXIST"||d0==="EISDIR")return!1;throw T}}throw O}}async function D(){await new Promise((O)=>setTimeout(O,Math.floor(Math.random()*4)))}async function P(){try{let O=await K();return Number(O?.expiresAt)>J()}catch{try{return(await o$(Z)).mtimeMs+$.ttlMs>J()}catch{return!1}}}async function A(){try{return JSON.parse(await c8(B,"utf8"))?.ownerId===V}catch{return!1}}async function x0(){if(await A())await D0(W,{recursive:!0,force:!0}).catch(()=>{})}async function _8(){await t$(W);try{await a0(B,`${JSON.stringify({ownerId:V,createdAt:J()})}
|
|
93
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(O){if(f4(O))return!1;throw await x0(),O}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function N0(){let O;try{O=await o$(W)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if(O.mtimeMs+j>J())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let R=`${W}.${i8()}`;try{await b4(W,R)}catch(T){if(T.code==="ENOENT")return"missing";throw T}if($.onStep)await $.onStep("stale-marker-claimed");return await D0(R,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function k(O){try{if(!await _8())return!1}catch(R){if(R.code==="EEXIST")return!1;throw R}try{await O()}finally{await x0()}return!0}async function x3(){for(let O=0;O<q;O++){if($.onStep)await $.onStep("relinquish-read");let R;try{R=await K()}catch{return}if(R?.ownerId!==X)return;try{await D0(Z,{recursive:!0,force:!0});return}catch{await D()}}}function A$(){if(!$.renew||Q)return;let O=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(G=k4(()=>{let R=(async()=>{let T=!Q;try{if(!await k(async()=>{let T$=await K(),F3=J();if(Q||T$?.ownerId!==X){T=!1;return}if(Number(T$?.expiresAt)<=F3){T=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-fenced");if(Q){T=!1;return}if(!await A())return;if($.onStep)await $.onStep("renewal-write-ready");if(await L(),!await A()){T=!1,await x3();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(T&&!Q)A$()}})();Y=R,R.finally(()=>{if(Y===R)Y=null})},O),"unref"in G)G.unref()}let Y0=await U();if(!Y0)for(let O=0;O<q;O++){if(Y0=await U(),Y0)break;if(await P())return null;try{if(!await _8()){await D();continue}}catch(R){if(R.code!=="EEXIST")throw R;if(await N0()==="fresh")return null;await D();continue}try{if(await P())return null;if(!await A())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await A())return null;if(await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),!await A())return null;if(Y0=await U(),!Y0)return null;if(!await A())return await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),Y0=!1,null;break}finally{await x0()}}if(!Y0)return null;return A$(),{release:async()=>{if(Q=!0,G)w4(G),G=null;await Y;for(let O=0;O<q;O++){try{if(await k(async()=>{if((await K())?.ownerId!==X)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await A())return;await D0(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await N0()}catch{return}await D()}}}}var h4=globalThis.setTimeout,m4=5;function w0($){let Z=$?.quota?.checkIntervalMinutes??m4;return Math.max(1,Z)*60000}function g4($){return $?.quota?.enabled!==!1}function p4($){let Z=$?.quota?.minimumRemaining||{};return{primary:Z.primary??Z["5h"]??15,secondary:Z.secondary??Z["1w"]??10}}function e$($,Z,z){if(!g4(Z))return z+w0(Z);let X=p4(Z),J=[];for(let G of["primary","secondary"]){let Q=$?.[G];if(!Q)continue;if(Q.remainingPercent>=X[G])continue;let Y=Q.resetsAt?Date.parse(Q.resetsAt):Number.NaN;if(!Number.isFinite(Y)||Y<=z)return z+w0(Z);J.push(Y)}if(!J.length)return z+w0(Z);return Math.min(...J)+60000}function u4($){if(!$?.quota?.mainQuota||!$.quota.mainQuotaCheckedAt)return null;return{quota:$.quota.mainQuota,checkedAt:$.quota.mainQuotaCheckedAt,tokenFingerprint:$.quota.mainQuotaToken}}function l4($){let Z=$?.quota?.refreshEveryNRequests;return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):0}function l($){return v4("sha256").update($).digest("hex").slice(0,16)}class n{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($){this.storage=$.storage,this.fetchImpl=$.fetchImpl??fetch,this.configPath=$.configPath,this.now=$.now??Date.now,this.fetchQuotaFn=$.fetchQuotaFn,this.onMainQuotaFetched=$.onMainQuotaFetched,this.onApiError=$.onApiError,this.seedMainFromStorage($.storage),this.seedMainBackoffFromStorage($.storage)}getMain($){if($&&this.main&&this.mainTokenFp&&this.mainTokenFp!==l($))this.main=null,this.mainTokenFp=null;return this.main}getFallback($,Z){let z=this.fallbacks.get($)??null;if(!Z||!z)return z;if(this.fallbackTokenFps.get($)!==l(Z))return this.fallbacks.delete($),this.fallbackTokenFps.delete($),null;return z}getAllFallbacks(){return this.fallbacks}setMain($,Z,z,X=!1){if(!X&&!$1(Z.quota))return;if(this.mainTokenFp=l($),z&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==z)this.clearRateLimited("main");if(z)this.mainQuotaAccountId=z;if(this.main=Z,s8(Z.quota))this.clearRateLimited("main")}peekMainForPolicy($){if($&&this.mainQuotaAccountId&&this.mainQuotaAccountId!==$)return null;return this.main}peekFallbackForPolicy($,Z){let z=this.fallbacks.get($)??null;if(Z&&z?.accountId&&z.accountId!==Z)return null;return z}setFallback($,Z,z,X=!1,J){if(!X&&!$1(Z.quota))return;let G=this.fallbacks.get($)?.accountId;if(J&&G&&J!==G)this.clearRateLimited($);let Q=J??G;if(this.fallbacks.set($,{...Z,accountId:Q}),z)this.fallbackTokenFps.set($,l(z));else this.fallbackTokenFps.delete($);if(s8(Z.quota))this.clearRateLimited($)}markRateLimited($,Z){let z=this.rateLimitedUntilMap.get($);if(z!==void 0&&z>Z)return;this.rateLimitedUntilMap.set($,Z)}isRateLimited($){let Z=this.rateLimitedUntilMap.get($);return Z!==void 0&&this.now()<Z}rateLimitedUntil($){return this.rateLimitedUntilMap.get($)}clearRateLimited($){this.rateLimitedUntilMap.delete($)}async refreshMain($){let Z=l($);if(this.mainTokenFp&&this.mainTokenFp!==Z)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===Z)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=Z,this.inflightMain=this._fetchMain($),this.inflightMain}async refreshFallback($,Z){let z=n.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 J=this._fetchFallback($,Z);return this.inflightFallbacks.set(z,J),J}async refreshAllFallbacks($){let Z=this.now();for(let z of $){if(z.enabled===!1)continue;if(h8(z,"openai"),!z.access)continue;let X=this.getFallback(z.id,z.access);if(X&&Z<X.refreshAfter)continue;try{await this.refreshFallback(z.id,z.access)}catch{}}}refreshMainInBackground($){let Z=l($);if(this.inflightMain&&this.inflightMainFp===Z)return;if(this.isBackedOff())return;this.refreshMain($).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($){let Z=l4(this.storage);if(Z<=0)return!1;return $>0&&$%Z===0}needsRefresh($){return this.isMainStale()||this.shouldRefreshOnRequestCount($)}updateStorage($){this.storage=$,this.seedMainFromStorage($),this.seedMainBackoffFromStorage($)}seedMainFromStorage($,Z){let z=u4($);if(!z)return;let X=Z?l(Z):null;if(X&&z.tokenFingerprint&&z.tokenFingerprint!==X)return;let J={quota:z.quota,refreshAfter:e$(z.quota,$,z.checkedAt),checkedAt:z.checkedAt};if(this.main&&this.main.checkedAt>=J.checkedAt&&(!X||!this.mainTokenFp||this.mainTokenFp===X))return;if(this.main=J,this.mainTokenFp=z.tokenFingerprint??null,$?.mainAccountId){if(this.mainQuotaAccountId&&this.mainQuotaAccountId!==$.mainAccountId)this.clearRateLimited("main");this.mainQuotaAccountId=$.mainAccountId}}seedMainBackoffFromStorage($){let Z=$?.quota?.mainLastQuotaApiError;this.mainLastApiError=Z&&F0(Z,this.now())?Z:void 0}seedFallbacksFromAccounts($){let Z=w0(this.storage);for(let z of $){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 J=this.getFallback(z.id,z.access);if(J&&J.checkedAt>=X)continue;this.setFallback(z.id,{quota:z.quota,refreshAfter:X+Z,checkedAt:X},z.access,!1,z.accountId)}}isBackedOff(){return F0(this.mainLastApiError,this.now())}isFallbackBackedOff($,Z){if(Z){if(this.fallbackErrorTokenFps.get($)!==l(Z))return!1}return F0(this.fallbackApiErrors.get($),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey($,Z){return JSON.stringify([$,l(Z)])}static quotaLockName($){return`opencode-fallback-quota-refresh-${$.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch($){let Z=async()=>{let X=this.now()-this.lastApiCallAt;if(X<n.API_CALL_GAP_MS)await new Promise((J)=>{let G=h4(J,n.API_CALL_GAP_MS-X);if(typeof G==="object"&&"unref"in G)G.unref()});return this.lastApiCallAt=this.now(),$()},z=this.apiGate.then(Z,Z);return this.apiGate=z.catch(()=>{}),z}async _fetchMain($){let Z=l($);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 k0({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(),J=await this._fetchQuota($),G=this.now();if(this.mainTokenFp=l($),this.main={quota:J,refreshAfter:e$(J,this.storage,G),checkedAt:G},s8(J))this.clearRateLimited("main");return this.mainLastApiError=void 0,this.onMainQuotaFetched?.(J,G,this.mainTokenFp,X),J}catch(X){throw this._handleMainFetchError(X),X}finally{await z.release()}}finally{if(this.inflightMainFp===Z)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 k0({name:n.quotaLockName($),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(Z),J=this.now();return this.setFallback($,{quota:X,refreshAfter:J+w0(this.storage),checkedAt:J},Z,!0),this.fallbackApiErrors.delete($),this.fallbackErrorTokenFps.delete($),X}finally{await z.release()}}catch(z){throw this._handleFallbackFetchError($,Z,z),z}finally{this.inflightFallbacks.delete(n.fallbackInflightKey($,Z))}})}async _fetchQuota($){if(!this.fetchQuotaFn)throw Error("Quota fetch not available — no fetchQuotaFn injected (push-only mode)");return this.fetchQuotaFn({accessToken:$,fetchImpl:this.fetchImpl,now:this.now})}static isAuthError($){return $?.status===401}_handleMainFetchError($){if(n.isAuthError($))return;this.mainLastApiError=i0({error:$,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError($,Z,z){if(n.isAuthError(z))return;let X=l(Z),J=this.fallbackErrorTokenFps.get($)===X?this.fallbackApiErrors.get($):void 0;this.fallbackApiErrors.set($,i0({error:z,now:this.now(),previous:J})),this.fallbackErrorTokenFps.set($,X)}}function $1($){return Boolean($.primary||$.secondary)}function s8($){let{primary:Z,secondary:z}=$;if(!Z&&!z)return!1;if(Z&&Z.usedPercent>=100)return!1;if(z&&z.usedPercent>=100)return!1;return!0}import{readFile as X6}from"node:fs/promises";var K5=d("refresh"),J1=d("accounts"),n4=1e4,a4=15000,n8=50;function m8($){return $.type==="oauth"&&$.corrupt!==!0}function t4($){let Z=$?.trim();if(!Z)return!1;try{let z=new URL(Z);return(z.protocol==="http:"||z.protocol==="https:")&&!z.username&&!z.password}catch{return!1}}function N($){return $!=null&&typeof $==="object"&&!Array.isArray($)}var o4=new Set(["__proto__","constructor","prototype"]);function i($){return $.length>0&&!o4.has($)}function t0($){return{id:typeof $.id==="string"&&$.id.trim()?$.id.trim():c4(),label:typeof $.label==="string"?$.label:void 0,enabled:typeof $.enabled==="boolean"?$.enabled:void 0,addedAt:typeof $.addedAt==="number"?$.addedAt:void 0,lastUsed:typeof $.lastUsed==="number"?$.lastUsed:void 0,accountId:typeof $.accountId==="string"?$.accountId:void 0}}function Z1($){if(!N($))return;if(typeof $.message!=="string")return;let Z=Number($.checkedAt);if(!Number.isFinite(Z))return;let z=Number($.nextRetryAt),X=Number($.retryCount);return{message:$.message,checkedAt:Z,nextRetryAt:Number.isFinite(z)?z:void 0,retryCount:Number.isFinite(X)?X:void 0,tokenHash:typeof $.tokenHash==="string"?$.tokenHash:void 0}}function r4($){if(!N($))return;let Z={};for(let J of["primary","secondary"]){let G=$[J];if(!N(G))continue;let Q=Number(G.usedPercent),Y=Number(G.remainingPercent),W=Number(G.checkedAt);if(!Number.isFinite(Q)||!Number.isFinite(Y)||!Number.isFinite(W))continue;let B=typeof G.windowMinutes==="number"?G.windowMinutes:Number.NaN;Z[J]={usedPercent:Q,remainingPercent:Y,checkedAt:W,resetsAt:typeof G.resetsAt==="string"?G.resetsAt:void 0,...Number.isFinite(B)&&B>0?{windowMinutes:B}:{}}}for(let J of["resetCreditsAvailable","resetCreditsApplicable"]){let G=typeof $[J]==="number"?$[J]:Number.NaN;if(Number.isFinite(G)&&G>=0)Z[J]=G}let z=$.spendControl;if(N(z)){let J=Number(z.limit),G=Number(z.used),Q=Number(z.remaining),Y=Number(z.usedPercent),W=Number(z.remainingPercent);if(Number.isFinite(J)&&Number.isFinite(G)&&Number.isFinite(Q)&&Number.isFinite(Y)&&Number.isFinite(W)&&typeof z.reached==="boolean")Z.spendControl={limit:J,used:G,remaining:Q,usedPercent:Y,remainingPercent:W,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=$.credits;if(N(X)&&typeof X.hasCredits==="boolean"&&typeof X.unlimited==="boolean"&&typeof X.overageLimitReached==="boolean"){let J=Number(X.balance);Z.credits={hasCredits:X.hasCredits,unlimited:X.unlimited,overageLimitReached:X.overageLimitReached,...Number.isFinite(J)?{balance:J}:{}}}return Object.keys(Z).length?Z:void 0}function e4($){if(!N($))return null;if($.type==="api"){let Z=typeof $.baseURL==="string"?$.baseURL.trim():"",z=typeof $.apiKey==="string"?$.apiKey.trim():"";if(!t4(Z))return null;let X=$.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...t0($),type:"api",apiKey:z||void 0,baseURL:Z,authHeader:X}}if($.type!=="oauth")return null;if($.corrupt===!0){if(typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}if(typeof $.refresh!=="string"||!$.refresh.trim()){if(!Object.hasOwn($,"refresh")||typeof $.id!=="string"||!$.id.trim())return null;return{...t0($),type:"oauth",corrupt:!0}}return{...t0($),type:"oauth",access:typeof $.access==="string"?$.access:void 0,refresh:$.refresh,expires:typeof $.expires==="number"?$.expires:void 0,lastRefreshedAt:typeof $.lastRefreshedAt==="number"?$.lastRefreshedAt:void 0,lastRefreshError:Z1($.lastRefreshError),lastQuotaRefreshError:Z1($.lastQuotaRefreshError),quota:r4($.quota)}}function $6($){if(!N($))return;let Z=Object.create(null);for(let[z,X]of Object.entries($)){if(!i(z)||!N(X))continue;let J={};if(N(X.inFlight))J.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))J.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))J.cooldownUntil=X.cooldownUntil;if(Object.keys(J).length>0)Z[z]=J}return Object.keys(Z).length>0?Z:void 0}var z1=new Set;function G1($){if($.length===0)return;let Z=JSON.stringify([...$].sort());if(z1.has(Z))return;z1.add(Z),J1.warn("account load-dropped, preserved on disk",{droppedIds:$})}function Q1($){if(!N($)||!Array.isArray($.accounts))return null;let Z=$.accounts,z=Z.map(e4).filter((X)=>X!=null);if(z.length<Z.length){let X=new Set;for(let Q of Z)if(N(Q)&&typeof Q.id==="string"&&Q.id.trim())X.add(Q.id.trim());let J=new Set(z.map((Q)=>Q.id)),G=[];for(let Q of X)if(!J.has(Q))G.push(Q);G1(G)}return{version:1,main:{type:"opencode",provider:"openai"},routing:N($.routing)?$.routing:void 0,fallbackOn:Array.isArray($.fallbackOn)?$.fallbackOn.filter((X)=>Number.isInteger(X)):void 0,refresh:N($.refresh)?$.refresh:void 0,quota:N($.quota)?$.quota:void 0,reset:$6($.reset),dump:N($.dump)?$.dump:void 0,costZeroing:N($.costZeroing)?$.costZeroing:void 0,killswitch:N($.killswitch)?$.killswitch:void 0,logging:N($.logging)?$.logging:void 0,cachekeep:N($.cachekeep)?$.cachekeep:void 0,mainAccountId:typeof $.mainAccountId==="string"?$.mainAccountId:void 0,claustrum:Z6($.claustrum),accounts:z}}function Z6($){if(!N($))return;let Z=$.mode==="claustrum"?"claustrum":"local",z=z6($.transition),X=Array.isArray($.rowHistory)?$.rowHistory.filter((J)=>typeof J==="string"):void 0;return{mode:Z,transition:z,rowHistory:X}}function z6($){if(!N($)||!N($.fingerprints))return;if(typeof $.manifestRevision!=="string"||typeof $.storeGeneration!=="string"||!N($.fingerprints.fallbacks))return;let Z=Object.fromEntries(Object.entries($.fingerprints.fallbacks).filter((z)=>typeof z[1]==="string"));return{manifestRevision:$.manifestRevision,storeGeneration:$.storeGeneration,fingerprints:{main:typeof $.fingerprints.main==="string"?$.fingerprints.main:void 0,fallbacks:Z}}}async function f0($){try{return{exists:!0,value:JSON.parse(await X6($,"utf8"))}}catch(Z){if(Z.code==="ENOENT")return{exists:!1,value:null};throw Z}}function J0($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}async function Y1($){return(await J6($)).roster}async function J6($){let Z;try{Z=(await f0($)).value}catch{return{roster:null,mode:"claustrum"}}return{roster:a8(Z),mode:f(N(Z)?Z:void 0)}}function W1($,Z){if(!N($))return $;let z=N(Z)?Z:{},X=N(z.main)?z.main:void 0,J=N(z.accounts)?z.accounts:{},G=N($.quota)?$.quota:{},Q=N($.refresh)?$.refresh:{},Y=X??G,W=X??Q,V=Array.isArray($.accounts)?$.accounts.map((j)=>{if(!N(j))return j;let q=typeof j.id==="string"&&N(J[j.id])?J[j.id]:{};return{...j,...q}}):void 0;return V1({...$,refresh:J0({...Q,mainLastRefreshError:W.lastRefreshError,mainRefreshLeaseId:W.refreshLeaseId,mainRefreshLeaseUntil:W.refreshLeaseUntil,mainRefreshLeaseTokenHash:W.refreshLeaseTokenHash}),quota:J0({...G,mainQuota:Y.quota,mainQuotaCheckedAt:Y.quotaCheckedAt,mainQuotaToken:Y.quotaToken,mainLastQuotaApiError:Y.lastQuotaApiError}),accounts:V})}async function B1($){let Z=await f0($.configPath);if(!Z.exists)return null;let z=await f0($.statePath);return Q1(W1(Z.value,z.value))}function V1($){return Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0))}function G6($){return J0({id:$.id,label:$.label,type:$.type,corrupt:$.type==="oauth"&&$.corrupt===!0?!0:void 0,enabled:$.enabled,addedAt:$.addedAt,accountId:$.accountId,baseURL:$.type==="api"?$.baseURL:void 0,authHeader:$.type==="api"?$.authHeader:void 0})}function Q6($){if($.type==="api")return J0({apiKey:$.apiKey,lastUsed:$.lastUsed});if($.corrupt)return{};return J0({access:$.access,refresh:$.refresh,expires:$.expires,lastUsed:$.lastUsed,lastRefreshedAt:$.lastRefreshedAt,lastRefreshError:$.lastRefreshError,lastQuotaRefreshError:$.lastQuotaRefreshError,quota:$.quota})}function Y6($){let Z=$.refresh?J0({enabled:$.refresh.enabled,refreshBeforeExpiryMinutes:$.refresh.refreshBeforeExpiryMinutes}):void 0,z=$.quota?J0({enabled:$.quota.enabled,checkIntervalMinutes:$.quota.checkIntervalMinutes,refreshEveryNRequests:$.quota.refreshEveryNRequests,minimumRemaining:$.quota.minimumRemaining,failClosedOnUnknownQuota:$.quota.failClosedOnUnknownQuota}):void 0;return V1({version:1,main:$.main,routing:$.routing,fallbackOn:$.fallbackOn,refresh:Z,quota:z,reset:$.reset,dump:$.dump,costZeroing:$.costZeroing,killswitch:$.killswitch,logging:$.logging,cachekeep:$.cachekeep,mainAccountId:$.mainAccountId,...$.claustrum!==void 0?{claustrum:{mode:$.claustrum.mode??"local",...$.claustrum.transition?{transition:$.claustrum.transition}:{},...$.claustrum.rowHistory?{rowHistory:$.claustrum.rowHistory}:{}}}:{},accounts:$.accounts.map(G6)})}async function X1($,Z=!1){let z=Date.now(),X=z+a4,J=0;while(Date.now()<=X){J++;let Y=await k0({name:"save",ttlMs:n4,path:$,renew:Z});if(Y)return Y;let W=X-Date.now();if(W<=0)break;await s4(Math.min(n8+H6(n8),W))}let G=Date.now()-z,Q=Math.round(G/Math.max(1,J));throw Error(`Timed out after ${G}ms waiting for the account store lock on ${$} (${J} attempts, ~${Q}ms apart; retry interval is ${n8}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 f($){return $?.claustrum?.mode==="claustrum"?"claustrum":"local"}function W6($){let Z=Object.fromEntries($.accounts.map((z)=>[z.id,Q6(z)]));return{version:1,main:J0({quota:$.quota?.mainQuota,quotaCheckedAt:$.quota?.mainQuotaCheckedAt,quotaToken:$.quota?.mainQuotaToken,lastQuotaApiError:$.quota?.mainLastQuotaApiError,lastRefreshError:$.refresh?.mainLastRefreshError,refreshLeaseId:$.refresh?.mainRefreshLeaseId,refreshLeaseUntil:$.refresh?.mainRefreshLeaseUntil,refreshLeaseTokenHash:$.refresh?.mainRefreshLeaseTokenHash}),accounts:Z}}function a8($){if(!N($)||!Array.isArray($.accounts))return null;let Z=new Set;for(let z of $.accounts){if(!N(z))continue;if(typeof z.id!=="string")continue;let X=z.id.trim();if(!X)continue;Z.add(X)}return Z}function B6($,Z,z,X){if(!N($)||!Array.isArray($.accounts))return{preservedRawEntries:[],preservedIds:[]};let J=[],G=[];for(let Q of Z){if(z.has(Q))continue;if(X.has(Q))continue;let Y=$.accounts.find((W)=>N(W)&&typeof W.id==="string"&&W.id.trim()===Q);if(!Y)continue;J.push(Y),G.push(Q)}return{preservedRawEntries:J,preservedIds:G}}function V6($){if(!Array.isArray($))return[];let Z=[];for(let z of $){if(!N(z))continue;if(typeof z.id!=="string")continue;Z.push(z.id)}return Z}function j6($,Z,z){let X=a8($);if(X===null)return[];let{preservedRawEntries:J,preservedIds:G}=B6($,X,Z,z);return G1(G),J}async function G0($,Z,z={}){let{configPath:X,statePath:J}=Z,G=await X1(X);try{let Q=await X1(J);try{let Y=await f0(X),W=await f0(J),B=(Y.exists?Q1(W1(Y.value,W.value)):null)??q6(),V=new Set(B.accounts.map((k)=>k.id)),j=a8(Y.value)??new Set,q=$(B,{rawRosterIds:[...j],loadedRosterIds:[...V]})??B,K=new Set(q.accounts.map((k)=>k.id)),L=[...V].filter((k)=>!K.has(k));if(L.length>0)q.claustrum={...q.claustrum,mode:q.claustrum?.mode??"local",rowHistory:[...new Set([...q.claustrum?.rowHistory??[],...L])]};let U=new Set(z.allowDrop??[]),D=j6(Y.value,V,U),P=Y6(q),A=new Set((Array.isArray(P.accounts)?P.accounts:[]).map((k)=>N(k)&&typeof k.id==="string"?k.id.trim():"").filter(Boolean)),x0=D.filter((k)=>{if(!N(k))return!1;if(typeof k.id!=="string")return!1;return!A.has(k.id.trim())}),N0={...N(Y.value)?Y.value:{},...P,accounts:[...Array.isArray(P.accounts)?P.accounts:[],...x0]};return await x8(X,N0),await x8(J,W6(q)),J1.debug("account config written",{accountCount:N0.accounts.length,accountIds:V6(N0.accounts)}),q}finally{await Q.release()}}finally{await G.release()}}function q6(){return{version:1,main:{type:"opencode",provider:"openai"},accounts:[]}}function H6($){return Math.floor(Math.random()*($+1))}var N5=globalThis.setTimeout.bind(globalThis),U5=globalThis.clearTimeout.bind(globalThis);var t8="/backend-api/wham/rate-limit-reset-credits",K6=`https://chatgpt.com${t8}`,L1=`${t8}/consume`,L6=`https://chatgpt.com${L1}`,N6=300000,U6=60000,D6=15000,P6=60000;function o0($){return{configPath:$.configPath,statePath:$.statePath}}class c extends Error{kind;cooldownUntil;constructor($,Z,z){super(Z);this.name="ResetRedemptionError",this.kind=$,this.cooldownUntil=z}}class q0 extends Error{kind;status;constructor($,Z,z){super(Z);this.name="ResetCreditError",this.kind=$,this.status=z}}function N1($,Z,z){return{authorization:`Bearer ${$}`,...z?{"chatgpt-account-id":z}:{},"oai-client-platform":"web","oai-client-version":"0","x-openai-target-path":Z}}function r0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function U1($){if(!$)return;return{...$.inFlight?{inFlight:{...$.inFlight}}:{},...$.lastOutcome?{lastOutcome:{...$.lastOutcome}}:{},...$.cooldownUntil!==void 0?{cooldownUntil:$.cooldownUntil}:{}}}function o8($){if(!r0($)||typeof $.redeemRequestId!=="string"||$.redeemRequestId.length===0||typeof $.creditId!=="string"||$.creditId.length===0||typeof $.startedAt!=="number"||!Number.isFinite($.startedAt))return;return{redeemRequestId:$.redeemRequestId,creditId:$.creditId,startedAt:$.startedAt}}function D1($){return Boolean($&&Object.hasOwn($,"inFlight"))}function P1($,Z){return Z-$.startedAt<N6}function e0($,Z){if(!i(Z))return;return $.reset?.[Z]}function O1($){if(!$.reset)$.reset=Object.create(null);return $.reset}function M1($,Z,z){if(!i(Z))return;let X=O1($),J=X[Z]??{},G=J.lastOutcome;delete J.inFlight,J.lastOutcome={code:"ambiguous_local",at:z,...G?{previousOutcome:{code:G.code,at:G.at}}:{}},X[Z]=J}function _1($,Z){let z=U1($),X=o8($?.inFlight);if(D1($)&&!X)return{kind:"corrupt",beforeState:z};if($?.cooldownUntil!==void 0&&$.cooldownUntil>Z)return{kind:"cooldown",beforeState:z,cooldownUntil:$.cooldownUntil};if(X&&P1(X,Z))return{kind:"claim",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};if(X)return{kind:"expired_unreconciled",beforeState:z,claim:{inFlight:X,selectedCredit:{id:X.creditId}}};return{kind:"fresh",beforeState:z}}async function O6($,Z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let z=await $.loadAccountsFn(o0($));return _1(z?e0(z,Z):void 0,$.now())}async function M6($,Z){let z;if(await $.mutateAccountsFn((X)=>{let J=$.now(),G=e0(X,Z);if(z=_1(G,J),z.kind==="corrupt")M1(X,Z,J);return X},o0($)),!z)throw Error("corrupt reset state mutation did not run");return z}async function _6($,Z,z){if(!i(Z))return{kind:"fresh",beforeState:void 0};let X;if(await $.mutateAccountsFn((J)=>{let G=$.now(),Q=e0(J,Z),Y=U1(Q),W=o8(Q?.inFlight);if(D1(Q)&&!W)return M1(J,Z,G),X={kind:"corrupt",beforeState:Y},J;if(Q?.cooldownUntil!==void 0&&Q.cooldownUntil>G)return X={kind:"cooldown",beforeState:Y,cooldownUntil:Q.cooldownUntil},J;if(W&&P1(W,G))return X={kind:"claim",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;if(W)return X={kind:"expired_unreconciled",beforeState:Y,claim:{inFlight:W,selectedCredit:{id:W.creditId}}},J;let B=$8(z);if(!B)return X={kind:"fresh",beforeState:Y},J;let V={redeemRequestId:$.randomUUID(),creditId:B.id,startedAt:G},j=O1(J);return j[Z]={...Q,inFlight:V},X={kind:"claim",beforeState:Y,claim:{inFlight:V,selectedCredit:B}},J},o0($)),!X)throw Error("reset claim mutation did not run");return X}async function x6($,Z,z,X){if(!i(Z))return;if(!$$(X.kind))return;await $.mutateAccountsFn((J)=>{let G=e0(J,Z),Q=o8(G?.inFlight);if(!G||!Q||Q.redeemRequestId!==z.redeemRequestId||Q.creditId!==z.creditId)return J;let Y=$.now();if(delete G.inFlight,G.lastOutcome={code:X.kind,at:Y},X.kind==="reset"||X.kind==="already_redeemed")G.cooldownUntil=Y+P6;else delete G.cooldownUntil;return J},o0($))}function E0($,Z){if(!$||$.usedPercent<100)return!1;if(!$.resetsAt)return!0;let z=Date.parse($.resetsAt);return!Number.isFinite(z)||z>Z}function r8($,Z,z){if(!(Z||E0($.primary,z)||E0($.secondary,z)))return{ok:!1,reason:"not exhausted"};return{ok:!0}}function j1($,Z){let z=$[Z];if(z===void 0||z===null)return;return typeof z==="string"?z:null}function F6($){if(!r0($))return;let Z=j1($,"granted_at"),z=j1($,"reset_type");if(typeof $.id!=="string"||typeof $.status!=="string"||typeof $.expires_at!=="string"||Number.isNaN(Date.parse($.expires_at))||typeof $.is_supported_by_plan!=="boolean"||Z===null||z===null)return;return{id:$.id,status:$.status,...Z===void 0?{}:{grantedAt:Z},expiresAt:$.expires_at,...z===void 0?{}:{resetType:z},isSupportedByPlan:$.is_supported_by_plan}}async function e8($,Z,z){let X;try{X=await $(K6,{method:"GET",headers:N1(Z,t8,z),signal:AbortSignal.timeout(D6)})}catch{throw new q0("http_error","reset credit list request failed")}if(!X.ok)throw new q0("http_error",`reset credit list request failed: ${X.status}`,X.status);let J;try{J=await X.json()}catch{throw new q0("invalid_response","reset credit list response was not valid JSON",X.status)}if(!r0(J))throw new q0("invalid_response","reset credit list response was not an object",X.status);return{credits:(Array.isArray(J.credits)?J.credits:[]).flatMap((Q)=>{let Y=F6(Q);return Y===void 0?[]:[Y]}),availableCount:typeof J.available_count==="number"&&Number.isFinite(J.available_count)?J.available_count:void 0}}function $8($){return[...$].filter(x1).sort((Z,z)=>Date.parse(Z.expiresAt)-Date.parse(z.expiresAt))[0]}function x1($){return $.status==="available"&&$.isSupportedByPlan&&$.resetType==="codex_rate_limits"}function F1($){return $.filter(x1).length}function $$($){return $==="reset"||$==="already_redeemed"||$==="nothing_to_reset"||$==="no_credit"}async function I6($,Z,z,X,J){let G;try{G=await $(L6,{method:"POST",headers:{...N1(Z,L1,z),"content-type":"application/json"},body:JSON.stringify({redeem_request_id:J,credit_id:X}),signal:AbortSignal.timeout(U6)})}catch(B){return{kind:"ambiguous",raw:B}}let Q;try{Q=await G.text()}catch(B){return G.ok?{kind:"ambiguous",raw:B}:{kind:"http_error",raw:B,status:G.status}}let Y=Q,W=!1;try{Y=JSON.parse(Q),W=!0}catch{}if(!G.ok)return{kind:"http_error",raw:Y,status:G.status};if(!W||!r0(Y)||!$$(Y.code))return{kind:"ambiguous",raw:Y};return{kind:Y.code,raw:Y}}function q1($){if($.kind==="cooldown")throw new c("cooldown_active","reset credit redemption is cooling down",$.cooldownUntil);throw Error(`unexpected reset state decision: ${$.kind}`)}function H1(){throw new c("expired_unreconciled","the previous reset attempt outcome is unknown")}function K1($,Z){return{target:$,selectedCredit:void 0,beforeState:Z,outcome:{kind:"ambiguous_local",raw:{reason:"corrupt_in_flight"}},retrySafety:"No request was sent because the saved redemption identity was incomplete."}}function R6($){if($.kind==="reset"||$.kind==="already_redeemed")return"The server returned a terminal result; cooldown blocks an immediate new redemption.";if($.kind==="nothing_to_reset"||$.kind==="no_credit")return"The server returned a terminal no-op. No cooldown was set; a new attempt starts fresh and remains gated by fresh preconditions.";return"The outcome is uncertain. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing."}async function I1($,Z){if(!i(Z.accountKey))throw new c("invalid_account_key","the reset account key is reserved");let z=await $.resolveTarget(Z.accountKey);if(z.chatgptAccountId!==Z.expectedChatgptAccountId)throw new c("identity_mismatch","the resolved ChatGPT account identity changed before redemption");let X=z.accountKey==="main"?void 0:z.chatgptAccountId,J=await O6($,Z.accountKey);if(J.kind==="corrupt"){if(J=await M6($,Z.accountKey),J.kind==="corrupt")return K1(z,J.beforeState)}if(J.kind==="cooldown")q1(J);let G;if(J.kind==="claim")G=J.claim;else if(J.kind==="expired_unreconciled"){if(!Z.retry)H1();G=J.claim}else{if(Z.retry)throw new c("retry_without_inflight","there is no active reset credit redemption to retry");let[W,B]=await Promise.all([$.fetchUsage(z),e8($.fetchImpl,z.accessToken,X)]),V=r8(W,$.hasActiveRateLimitMark(Z.accountKey),$.now());if(!V.ok)throw new c("not_exhausted",V.reason);if(!$8(B.credits))throw new c("no_eligible_credit","no eligible reset credit was returned");let j=await _6($,Z.accountKey,B.credits);if(j.kind==="corrupt")return K1(z,j.beforeState);if(j.kind==="cooldown")q1(j);if(j.kind==="expired_unreconciled")H1();if(j.kind!=="claim")throw new c("no_eligible_credit","no eligible reset credit was available while claiming");G=j.claim}let Q=await I6($.fetchImpl,z.accessToken,X,G.inFlight.creditId,G.inFlight.redeemRequestId),Y=!1;try{await x6($,Z.accountKey,G.inFlight,Q)}catch{Y=$$(Q.kind)}return{target:z,selectedCredit:G.selectedCredit,beforeState:J.beforeState,outcome:Q,retrySafety:Y?"The server returned a terminal result, but the state write failed. A retry within five minutes reuses the same request and credit identifiers.":R6(Q),...Y?{finalizeStateWriteFailed:!0}:{}}}function R1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var z8="openai-quota",X8="openai-account",J8="openai-routing";var y0="openai-reset";var _=d("commands");function m($){return{configPath:$.accountStoragePath,statePath:$.accountStatePath}}function A1($){if($==="fallback-first")return"Try usable fallback accounts before the main account.";if($==="sticky-balanced")return"Keep each session on its assigned account while balancing new sessions.";return"Try the main account first. Use fallback accounts only when required."}var A6=900000;function T1($,Z){if(typeof $!=="number"||!Number.isFinite($))return" (age unknown)";let z=Z-$;if(z<A6)return"";let X=Math.floor(z/3600000);if(X>=24)return` (${Math.floor(X/24)}d old)`;if(X>=1)return` (${X}h old)`;return` (${Math.floor(z/60000)}m old)`}function C1($,Z=""){let z=$.resetsAt?` · resets ${$.resetsAt}`:"",X=(Q)=>Math.round(Q).toLocaleString("en-US"),J=$.unit??"unit",G=$.limit===1||J.endsWith("s")?J:`${J}s`;return`${Z}- credits: ${Math.round($.usedPercent)}% used (${X($.used)} / ${X($.limit)} ${G}, ${X($.remaining)} remaining)${z}`}async function T6($){let Z=await $.refreshAllQuota?.(),z=$.quotaManager.getMain(),X=Date.now(),J=["## OpenAI Quota",""];if(z?.quota){let Y=z.quota;J.push("### Main account");for(let W of["primary","secondary"]){let B=Y[W];if(B){let V=Math.round(B.usedPercent),j="█".repeat(Math.max(0,Math.min(Math.round(V/10),10)))+"░".repeat(Math.max(0,10-Math.min(Math.round(V/10),10)));J.push(`- ${W}: ${j} ${V}% used (${Math.round(B.remainingPercent)}% remaining)${T1(B.checkedAt??z.checkedAt,X)}`)}}if(Y.resetCreditsAvailable!==void 0)J.push(`- resets: ${Y.resetCreditsAvailable}`);if(Y.spendControl)J.push(C1(Y.spendControl))}else J.push("No main quota snapshot available. Send a request first.");let Q=[...$.quotaManager.getAllFallbacks().entries()].filter(([,Y])=>Y);if(Q.length>0){J.push(""),J.push("### Fallback accounts");for(let[Y,W]of Q){if(!W?.quota)continue;J.push(`**${Y}**`);for(let B of["primary","secondary"]){let V=W.quota[B];if(V){let j=Math.round(V.usedPercent);J.push(` - ${B}: ${j}% used (${Math.round(V.remainingPercent)}% remaining)${T1(V.checkedAt??W.checkedAt,X)}`)}}if(W.quota.resetCreditsAvailable!==void 0)J.push(` - resets: ${W.quota.resetCreditsAvailable}`);if(W.quota.spendControl)J.push(C1(W.quota.spendControl," "))}}if(Z?.length){let Y=Z.filter((W)=>!W.ok);if(Y.length>0){J.push("");for(let W of Y)J.push(W.permanent?`- ${W.account}: sign-in no longer accepted — remove and add this account again`:`- ${W.account}: fetch failed — Refresh to retry`)}}return{command:"openai-quota",text:J.join(`
|
|
94
94
|
`),knobs:{}}}function h($){return{id:$.id,type:$.type??"oauth",enabled:$.enabled,label:$.label}}async function C6($,Z){let z=$.trim().split(/\s+/).filter(Boolean);_.info("account command parsed",{args:$,tokens:z});let X=await Z.loadAccounts(m(Z))??{version:1,accounts:[]},J=X.accounts??[];if(z[0]==="claustrum"){if(_.info("claustrum mode requested",{hasEnterFn:typeof Z.enterClaustrumMode==="function",accounts:J.length}),!Z.enterClaustrumMode)return _.warn("claustrum refused: transition fn absent from command context"),{command:"openai-account",text:`## Claustrum Unavailable
|
|
95
95
|
|
|
96
96
|
The custody runtime is not ready. Try again after OpenAI auth finishes initializing.`,knobs:{accounts:J.map(h),claustrumMode:f(X)}};_.info("claustrum transition starting",{});let G;try{G=await Z.enterClaustrumMode()}catch(W){throw _.error("claustrum transition threw",{error:W instanceof Error?W.message:String(W)}),W}_.info("claustrum transition finished",{status:G.status,reason:G.reason,outcomes:G.outcomes});let Q=await Z.loadAccounts(m(Z))??{version:1,accounts:[]},Y=Object.entries(G.outcomes).map(([W,B])=>`- \`${W}\`: ${B}`);return{command:"openai-account",text:[`## Claustrum ${G.status}`,"","do not run a login in another OpenCode window during this transition","",...Y.length>0?Y:["- No enabled OAuth accounts."],...G.reason?["",`Reason: ${G.reason}`]:[]].join(`
|
|
@@ -105,7 +105,7 @@ No account with id \`${G}\` exists.`,knobs:{accounts:j.accounts.map(h),claustrum
|
|
|
105
105
|
\`${G}\` is ${Q?"enabled":"disabled"}.`,knobs:{accounts:j.accounts.map(h),claustrumMode:f(j)}}}if(z.length===0||z.length===1&&z[0]==="list"){let G=["## OpenAI Accounts",""];if(J.length===0)G.push("No accounts configured. Use `/login openai` to add your main account, or `/openai-account add` to add a fallback account.");else{let Q=X.routing?.mode??"main-first";G.push(`Routing: \`${Q}\` (set with \`/openai-routing\`). Modes: main-first, fallback-first, or sticky-balanced. \`/openai-routing reset\` clears this session's pin.`),G.push("");for(let Y of J){let W=Y.type??"oauth";G.push(`- \`${Y.id}\` (${W})`)}}return G.push(""),G.push(`Claustrum mode: \`${f(X)}\`
|
|
106
106
|
|
|
107
107
|
Commands: \`/openai-account claustrum\` | \`/openai-account local\` | \`/openai-account add [label]\` | \`/openai-account enable <id>\` | \`/openai-account disable <id>\` | \`/openai-account remove <id>\``),{command:"openai-account",text:G.join(`
|
|
108
|
-
`),knobs:{accounts:J.map(h),claustrumMode:f(X)}}}if(z[0]==="remove"&&z[1]){let G=z[1],Q=await
|
|
108
|
+
`),knobs:{accounts:J.map(h),claustrumMode:f(X)}}}if(z[0]==="remove"&&z[1]){let G=z[1],Q=await Y1(Z.accountStoragePath),Y=Q?Q.has(G):!1,W=!1,B=await G0((j)=>{let q=j.accounts.findIndex((K)=>K.id===G);if(q===-1)return j;return j.accounts.splice(q,1),W=!0,j},m(Z),{allowDrop:[G]});if(!(W||Y))return{command:"openai-account",text:`## Account Not Found
|
|
109
109
|
|
|
110
110
|
No account with id \`${G}\` exists.`,knobs:{accounts:B.accounts.map(h)}};return _.info("account removed",{id:G}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Account Removed
|
|
111
111
|
|
|
@@ -113,7 +113,7 @@ Removed account \`${G}\`.`,knobs:{accounts:B.accounts.map(h)}}}if(z[0]==="order"
|
|
|
113
113
|
|
|
114
114
|
Both account IDs must exist.`,knobs:{accounts:Q.accounts.map(h)}};return _.info("accounts reordered",{a:z[1],b:z[2]}),Z.refreshSidebar?.().catch(()=>{}),{command:"openai-account",text:`## Accounts Reordered
|
|
115
115
|
|
|
116
|
-
Swapped positions of \`${z[1]}\` and \`${z[2]}\`.`,knobs:{accounts:Q.accounts.map(h)}}}if(z[0]==="add"){if(X.claustrum?.mode==="claustrum")return{command:"openai-account",text:"## Add Failed\n\nThat account cannot be added while Claustrum mode is active. Run `/openai-account local` first.",knobs:{}};let G=z.includes("--headless"),Q=z.filter((K)=>K!=="add"&&K!=="--headless"),Y=Q.length>0?Q.join(" "):void 0,{url:W,instructions:B,completion:V}=await(Z.beginAccountLogin??
|
|
116
|
+
Swapped positions of \`${z[1]}\` and \`${z[2]}\`.`,knobs:{accounts:Q.accounts.map(h)}}}if(z[0]==="add"){if(X.claustrum?.mode==="claustrum")return{command:"openai-account",text:"## Add Failed\n\nThat account cannot be added while Claustrum mode is active. Run `/openai-account local` first.",knobs:{}};let G=z.includes("--headless"),Q=z.filter((K)=>K!=="add"&&K!=="--headless"),Y=Q.length>0?Q.join(" "):void 0,{url:W,instructions:B,completion:V}=await(Z.beginAccountLogin??g$)({label:Y,headless:G,version:Z.packageVersion}),j=Z.notify,q=Z.sessionId;if(V.then(async(K)=>{let L;if(await(Z.withFallbackAccountLock??(async(D,P)=>P()))(K.id,async()=>{let D=await Z.loadAccounts(m(Z));if(f(D??{})==="claustrum"){L="claustrum mode";return}await G0((P)=>{if(K.accountId&&P.mainAccountId&&K.accountId===P.mainAccountId)return L="main identity",P;return m$(P.accounts,K),P},m(Z))}),L){let D=L==="claustrum mode"?"That account cannot be added while Claustrum mode is active. Run `/openai-account local` first.":"That account is already your main account — not added as a fallback.";_.warn(`account add rejected (${L})`,{id:K.id,sessionId:q}),j?.({command:"openai-account",text:`## Add Failed
|
|
117
117
|
|
|
118
118
|
${D}`,knobs:{}});return}_.info("account added",{id:K.id,label:K.label}),Z.refreshSidebar?.().catch(()=>{}),j?.({command:"openai-account",text:`## Account Added
|
|
119
119
|
|
|
@@ -148,17 +148,17 @@ This runtime cannot clear the current session pin.`,knobs:{mode:J}};return await
|
|
|
148
148
|
This session's pin was cleared. The next request may choose the same account if it remains the best selection.`,knobs:{mode:J}}}if(z.length===1&&(z[0]==="main-first"||z[0]==="fallback-first"||z[0]==="sticky-balanced")){let Y=z[0];return await G0((W)=>{return W.routing={...W.routing??{},mode:Y},W},m(Z)),_.info("routing mode changed",{mode:Y}),{command:"openai-routing",text:`## OpenAI Routing Updated
|
|
149
149
|
|
|
150
150
|
Mode: \`${Y}\`
|
|
151
|
-
- ${
|
|
151
|
+
- ${A1(Y)}
|
|
152
152
|
|
|
153
153
|
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:Y}}}let G=J==="sticky-balanced"&&Z.sessionId?await Z.getStickyRouting?.(Z.sessionId):void 0,Q=J==="sticky-balanced"?G?`
|
|
154
154
|
- Session pin: \`${G}\`. Use \`/openai-routing reset\` to clear it.`:`
|
|
155
155
|
- Session pin: none yet. A request will choose one when a usable account is available.`:"";return{command:"openai-routing",text:`## OpenAI Routing
|
|
156
156
|
|
|
157
157
|
- Mode: \`${J}\`
|
|
158
|
-
- ${
|
|
158
|
+
- ${A1(J)}${Q}
|
|
159
159
|
|
|
160
|
-
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:J}}}function
|
|
161
|
-
`)}function
|
|
160
|
+
Usage: \`/openai-routing\`, \`/openai-routing main-first\`, \`/openai-routing fallback-first\`, or \`/openai-routing sticky-balanced\`.`,knobs:{mode:J}}}function k1($){let Z=[$.primary?.usedPercent,$.secondary?.usedPercent].filter((z)=>z!==void 0);return Z.length>0?Math.max(...Z):void 0}function S6($,Z){let z=[$.primary,$.secondary].filter((J)=>J!==void 0),X=z.filter((J)=>E0(J,Z));return(X.length>0?X:z).sort((J,G)=>G.usedPercent-J.usedPercent)[0]?.resetsAt}function k6($,Z){if(!$)return!1;let z=[$.primary,$.secondary].filter((X)=>X!==void 0);if(z.length===0)return!1;return z.every((X)=>!E0(X,Z))}function Z$($){if(!$)return;try{return decodeURIComponent($)}catch{return}}async function b1($,Z){let z;try{z=await Z.resolveResetTarget($);let X=z.accountKey==="main"?void 0:z.chatgptAccountId,[J,G]=await Promise.all([d8({accessToken:z.accessToken,fetchImpl:Z.fetchImpl,now:Z.now,accountId:z.chatgptAccountId}),e8(Z.fetchImpl,z.accessToken,X)]),Q=$8(G.credits),Y=F1(G.credits),W=G.availableCount??J.resetCreditsAvailable??(Y>0?Y:void 0),B=J.resetCreditsApplicable,V=r8(J,Z.quotaManager.isRateLimited($),Z.now()),j;if(!z.chatgptAccountId)j="stable ChatGPT account identity unavailable";else if(!V.ok)j=V.reason;else if(!Q)j="no eligible credit";return{accountKey:z.accountKey,label:z.label,chatgptAccountId:z.chatgptAccountId,usedPercent:k1(J),resetTime:S6(J,Z.now()),availableCount:W,applicableAvailableCount:B,eligible:j===void 0,reason:j,selectedCreditId:Q?.id,selectedCreditExpiresAt:Q?.expiresAt}}catch(X){if(X?.status===401)await z?.onAuthFailure?.(401);return _.warn("reset preview row failed",{accountKey:$,error:X?.message??String(X)}),{accountKey:$,label:$==="main"?"Main account":$,eligible:!1,reason:X?.message??String(X)}}}function w6($){let Z=["## Reset credits","","Select an account to fetch a fresh confirmation preview:",""];for(let z of $){let X=z.usedPercent===void 0?"quota unavailable":`${z.usedPercent}% used`,J=z.availableCount===void 0?"credits unavailable":`${z.applicableAvailableCount===void 0?"?":z.applicableAvailableCount}/${z.availableCount} applicable/available`,G=z.eligible?`eligible · credit ${z.selectedCreditId} expires ${z.selectedCreditExpiresAt}`:z.reason;Z.push(`- **${z.label}** (\`${z.accountKey}\`) — ${X}; ${J}; ${G}`)}return Z.push(""),Z.push("Command: `/openai-reset select <encodedAccountKey>`"),Z.join(`
|
|
161
|
+
`)}function S1($){let Z=["## Confirm reset credit","",`Account: **${$.label}** (\`${$.accountKey}\`)`,`Current quota: **${$.usedPercent??"unknown"}% used**`,`Credit: **Spend 1 of ${$.availableCount??"unknown"}**`,`Credit expires: **${$.selectedCreditExpiresAt??"unavailable"}**`,`Quota resets: **${$.resetTime??"unavailable"}**`,""];if(($.availableCount??0)>0&&$.applicableAvailableCount===0)Z.push("The server does not currently count this credit as applicable; redemption may return a no-op, and a no-op does not spend the credit."),Z.push("");if($.eligible&&$.chatgptAccountId)Z.push(`Confirm: \`/openai-reset confirm ${encodeURIComponent($.accountKey)} ${encodeURIComponent($.chatgptAccountId)}\``);else Z.push(`Cannot reset: **${$.reason??"not eligible"}**`);return Z.join(`
|
|
162
162
|
`)}function g($,Z,z,X={}){return{command:y0,text:z,knobs:{stage:"result",accountKey:$,code:Z,...X}}}function f6($,Z,z){if(Z instanceof c){let J={identity_mismatch:"The account identity changed before redemption. Reopen the reset account list.",invalid_account_key:"The selected account key is reserved. Reopen the reset account list.",cooldown_active:"This account just reset — re-checking quota. Wait for the cooldown before another redemption.",expired_unreconciled:"The previous attempt outcome is unknown — retry replays the same identifiers, or wait until quota reflects the earlier attempt.",retry_without_inflight:"There is no active reset redemption to retry. Reopen the account list.",not_exhausted:"No credit was spent: the fresh account state is not exhausted.",no_eligible_credit:"No credit was spent: no eligible credit was returned."};return g($,Z.kind,`## Reset credit
|
|
163
163
|
|
|
164
164
|
${J[Z.kind]}
|
|
@@ -173,11 +173,11 @@ No redemption was attempted: reset credit availability could not be loaded.
|
|
|
173
173
|
|
|
174
174
|
Code: \`${Z.kind}\``);return _.warn("reset command failed before a known result",{accountKey:$,error:Z?.message??String(Z)}),g($,"error",`## Reset credit
|
|
175
175
|
|
|
176
|
-
The reset request failed before a known result: internal command failure — see plugin log.`)}async function
|
|
176
|
+
The reset request failed before a known result: internal command failure — see plugin log.`)}async function w1($,Z,z){let{accountKey:X}=$.target,J=$.outcome.kind;if($.finalizeStateWriteFailed)return g(X,J,`## Reset credit result
|
|
177
177
|
|
|
178
178
|
Account: **${$.target.label}** (\`${X}\`)
|
|
179
179
|
|
|
180
|
-
The server outcome recorded as \`${J}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:$.retrySafety,chatgptAccountId:z});if(J==="reset"||J==="already_redeemed"){let Q={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await Z.refreshResetTargetQuota(X)}catch(K){Q.error=K?.message??String(K)}let Y=!Q.ok&&Q.error!==void 0;if(Y)_.warn("reset quota re-check failed",{accountKey:X,error:Q.error});let W=X==="main"?Z.quotaManager.getMain():Z.quotaManager.getFallback(X),B=Q.ok&&
|
|
180
|
+
The server outcome recorded as \`${J}\`, but the state write failed. A retry within five minutes reuses the same request and credit identifiers; this does not prove the server did nothing.`,{stateWriteFailed:!0,retryGuidance:$.retrySafety,chatgptAccountId:z});if(J==="reset"||J==="already_redeemed"){let Q={account:X,ok:!1,error:"targeted quota refresh did not complete"};try{Q=await Z.refreshResetTargetQuota(X)}catch(K){Q.error=K?.message??String(K)}let Y=!Q.ok&&Q.error!==void 0;if(Y)_.warn("reset quota re-check failed",{accountKey:X,error:Q.error});let W=X==="main"?Z.quotaManager.getMain():Z.quotaManager.getFallback(X),B=Q.ok&&k6(W?.quota,Z.now()),V=W?.quota.resetCreditsApplicable,j=B?"Post-verification: **window fresh**.":`Post-verification: **window not yet refreshed** (server code \`${J}\`).`,q=Y?`
|
|
181
181
|
|
|
182
182
|
quota re-check failed — see log.`:"";return g(X,J,`## Reset credit result
|
|
183
183
|
|
|
@@ -187,7 +187,7 @@ Code: \`${J}\`
|
|
|
187
187
|
|
|
188
188
|
${j}${q}${V===void 0?"":`
|
|
189
189
|
|
|
190
|
-
Remaining applicable credits: **${V}**`}`,{verifiedFresh:B,afterUsedPercent:
|
|
190
|
+
Remaining applicable credits: **${V}**`}`,{verifiedFresh:B,afterUsedPercent:k1(W?.quota??{}),remainingCredits:V})}if(J==="ambiguous_local")return g(X,J,`## Reset credit result
|
|
191
191
|
|
|
192
192
|
Account: **${$.target.label}** (\`${X}\`)
|
|
193
193
|
|
|
@@ -207,10 +207,10 @@ Code: \`${J}\`
|
|
|
207
207
|
|
|
208
208
|
${G[J]??"The server returned a no-op result. No reset was confirmed."}`)}async function E6($,Z){let z=[Z.resolveResetTarget?void 0:"resolveResetTarget",Z.fetchImpl?void 0:"fetchImpl",Z.now?void 0:"now",Z.randomUUID?void 0:"randomUUID",Z.refreshResetTargetQuota?void 0:"refreshResetTargetQuota"].filter((Q)=>Q!==void 0);if(z.length>0)return _.warn("reset command dependencies unwired",{missingDeps:z}),{command:y0,text:`## Reset credit
|
|
209
209
|
|
|
210
|
-
Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(m(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];_.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>b$(B,X)));return _.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:y0,text:k6(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=Z9(J[1]);if(!Q||!i(Q)||J.length!==2)return g("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await b$(Q,X);if(!Y.eligible)return g(Q,"not_eligible",S$(Y));return{command:y0,text:S$(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=Z9(J[1]),Y=Z9(J[2]);if(!Q||!i(Q)||!Y||J.length!==3)return g(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);_.info("reset redemption decision",{accountKey:Q,action:G}),_.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await I$({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:G0,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>d8({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return _.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),k$(W,X,Y)}catch(W){let B=f6(Q,W,Y);return _.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return g("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var y6=new Set(["access","refresh","apikey","authheader","password","secret"]);function v6($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(y6.has(Z))return!0;return Z.endsWith("token")}function Z8($,Z,z){if(Array.isArray($))return $.map((J,G)=>Z8(J,`${Z}[${G}]`,z));if(!R$($))return $;let X={};for(let[J,G]of Object.entries($)){if(v6(J)){z.push(`${Z}.${J}`);continue}X[J]=Z8(G,`${Z}.${J}`,z)}return X}async function z9($,Z,z,X={}){let J=await h6($,Z,z,X),G=[],Q=Z8(J.knobs,"knobs",G);if(G.length>0)return _.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function h6($,Z,z,X){switch($){case"openai-quota":return T6(z);case"openai-account":return C6(Z,z);case"openai-routing":return b6(Z,z);case"openai-reset":return E6(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}import{readdirSync as x1,statSync as F1}from"node:fs";import{tmpdir as I1,userInfo as R1}from"node:os";import{join as p0}from"node:path";import{debuglog as t6}from"node:util";import{createHmac as l6,randomBytes as d6,timingSafeEqual as i6}from"node:crypto";import u6 from"node:net";var p=2,G8=21,Q8=5,X9=67108864,H;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(H||(H={}));var f$=H.Goodbye;function E$($){return $===H.Cancel||$===H.Ping||$===H.Pong||$===H.Goodbye}var C;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(C||(C={}));var k;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(k||(k={}));var m6=1,y$=6,J9=1,g6=8,v$=48,G9=4,h$=192;function v($,Z,z,X=k.Normal){let J=0;if($)J|=m6;if(J|=Z<<J9,z)J|=g6;return J|=X<<G9,J}function m$($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class x extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function p6($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new x(`unsupported envelope version ${z}`,"unsupported_version");if(X>f$)throw new x(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&h$)!==0)throw new x(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&y$)>>J9===3)throw new x(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&v$)>>G9;if(W===3)throw new x(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===k.Sheddable&&Y!==H.Push&&Y!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new x(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(E$(Y)&&Z!==0)throw new x(`pure-header frame ${H[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function Q9($){if($.length<5)throw new x(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new x(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new x(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>f$)throw new x(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&h$)!==0)throw new x(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&y$)>>J9===3)throw new x(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&v$)>>G9;if(Y===3)throw new x(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===k.Sheddable&&G!==H.Push&&G!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new x(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(E$(G)&&X!==0)throw new x(`pure-header frame ${H[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function E($,Z,z,X,J,G){return a(2,$,Z,z,X,J,G)}function a($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new x(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return p6(Y),{header:Y,body:Q}}function t($){if($.header.len!==$.body.length)throw new x(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=m$($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class Z0 extends Error{}class s extends Error{}class o extends Error{cause;constructor($,Z){super($);this.cause=Z}}class Q0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g$($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var p$=Symbol("subc.socket.writeBorrowed"),u$=Symbol("subc.socket.writeTrackedBorrowed");function r($,Z,z){let X=$[p$];return X?X.call($,Z,z):$.write(Z,z)}function Y9($,Z,z){let X=$[u$];return X?X.call($,Z,z):$.writeTracked(Z,z)}class H0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(z)=>{this.chunks.push(z),this.buffered+=z.length,this.tryServe()});let Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new Z0("subc closed the connection"))),$.on("close",()=>Z(new Z0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=u6.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new s(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new H0(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(Q8,$),J=X[4];if(J!==p)throw new x(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(G8-Q8,$),Q=new Uint8Array(G8);Q.set(X),Q.set(G,Q8);let Y=Q9(Q);if(Y.len>X9)throw new x(`frame body ${Y.len} exceeds max ${X9}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new s(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new s(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[p$]($,Z){await this.writeBuffer(g$($),Z)}[u$]($,Z){return this.writeTrackedBuffer(g$($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof o||z instanceof Q0)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new o("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(V)=>{if(X)return;if(X=!0,J)clearTimeout(J);V()},B=Z-Date.now();if(B<=0){W(()=>Y(new o("timed out before bytes could be queued to subc",new s("timed out writing to subc"))));return}J=setTimeout(()=>{let V=new s("timed out writing to subc");W(()=>Y(z?new Q0("timed out after bytes were handed to the subc socket",V):new o("timed out before bytes could be queued to subc",V)))},B);try{this.sock.write($,(V)=>{W(()=>{if(V)Y(new Q0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else Q()})}),z=!0}catch(V){W(()=>Y(new o("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var i$=32;var Y8=4096,c$="subc-server-v1",s$="subc-client-v1",c6="client";class y extends Error{}function B9($,Z,z,X,J){let G=l6("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function l$($,Z){if($.length!==Z.length)return!1;return i6(Buffer.from($),Buffer.from(Z))}async function d$($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>Y8)throw new y(`auth message too large: ${X.length} > ${Y8}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await r($,J,z),await r($,X,z)}async function s6($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>Y8)throw new y(`auth message too large: ${X} > ${Y8}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new y(`auth message JSON decode failed: ${String(G)}`)}}function W9($,Z){if(!Array.isArray($))throw new y(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new y(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function v0($,Z,z){let X=new Uint8Array(d6(i$));await d$($,{client_nonce:Array.from(X),role:c6},z);let J=await s6($,z),G=W9(J.server_nonce,"server_nonce"),Q=W9(J.daemon_id,"daemon_id"),Y=W9(J.server_proof,"server_proof"),W=B9(Z.key,c$,X,G,Q);if(!l$(W,Y))throw new y("server proof mismatch — wrong key or impostor daemon");if(!l$(Q,Z.daemonId))throw new y("daemon id mismatch — connection file points at a different daemon");let B=B9(Z.key,s$,X,G,Q);await d$($,{client_auth:Array.from(B)},z)}import{promises as V9}from"node:fs";var n$=1,a$=32,t$=16;class b extends Error{}function o$($,Z){if(!Array.isArray($))throw new b(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new b(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function n6($){if($.schema!==n$)throw new b(`unsupported connection file schema ${$.schema}; expected ${n$}`);if($.endpoints.length===0)throw new b("connection file must include at least one endpoint");if($.key.length<a$)throw new b(`connection file key is too short: ${$.key.length} bytes, need at least ${a$}`);if($.daemonId.length!==t$)throw new b(`connection file daemon_id must be ${t$} bytes, got ${$.daemonId.length}`)}async function a6($){if(process.platform==="win32")return;let z=(await V9.stat($)).mode&511;if((z&63)!==0)throw new b(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function P0($){await a6($);let Z=await V9.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new b(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==p)throw new b(`connection file wire_version ${String(X)} but this client speaks ${p}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new b("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new b("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:o$(z.key,"key"),daemonId:o$(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return n6(Q),Q}var r$=new WeakMap;class W8{channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,r$.set(this,z),Object.freeze(this)}static create($,Z,z){return new W8($,Z,z)}}function B8($,Z,z){return W8.create($,Z,z)}class z0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function O0(){return Object.freeze({})}function h0($,Z){return r$.get($)===Z}function V8($,Z){return $===Z}var o6=t6("subc-client"),r6=1e4,m0=30000,e6=50,$1=2000,e$="request_deadline",j9="deadline_exceeded_no_drop_observed",Z1=30000,z1=30000,$3=new Uint8Array(0),X1="management_surface",z3="SUBC_MODULE_ID",X3="SUBC_LAUNCH_NONCE",L8={baseMs:100,capMs:2000,maxAttempts:6};class S extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class F extends Error{code;constructor($,Z){super($);this.code=Z}}class K0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=O0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=G1($),z=await K0.openConnection(Z);return new K0(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=q9(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==H.Response)return!0;let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new F(`route.open returned no route handle: ${JSON.stringify(V)}`);return Q=this.installRoute(V.route_channel,V.route_epoch),!0},W=(B)=>{if(B.header.ty!==H.Response)return;try{let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new F("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new F("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??k.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof S))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==j9)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===j9)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??C.Interactive,Q=X.admissionClass??k.Normal,Y=this.allocateCorr(),W=q8($,Y),B=null,V=null,j=new Promise((L,U)=>{if(this.closedErr){U(this.closedErr);return}V=L,B={handle:$,resolve:()=>L(),reject:U,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let D=E(H.Request,v(!1,G,!1,Q),$.channel,$.epoch,Y,J);r(this.sock,t(D),Date.now()+m0).catch((P)=>{let A=this.pending.get(W);if(A)this.rejectPending(W,A,P instanceof Error?P:new F(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&V)this.settle(W,B,V);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:j}}cancel($,Z,z=C.Interactive){this.assertLiveHandle($);let X=E(H.Cancel,v(!1,z,!1),$.channel,$.epoch,Z,$3);r(this.sock,t(X),Date.now()+m0).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==H.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&V8(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new F("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=Z3($,Z,q9(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new F("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=E(H.Goodbye,v(!1,C.Interactive,!1),$.channel,$.epoch,0n,$3),X=Y9(this.sock,t(z),Date.now()+m0);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await P0($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??r6),X=Z.endpoints[0],J=await H0.connect(X.host,X.port,z);try{await v0(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,C.Interactive,k.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=q8($,W),V=$?.channel??0,j=$?.epoch??0,q=E(H.Request,v(!1,z,!1,X),V,j,W,Z);return new Promise((K,L)=>{let U=J??m0,D={handle:$,resolve:K,reject:L,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};D.timer=setTimeout(()=>this.arbitrateTimeout(B,D,V,W,U),U),this.pending.set(B,D),r(this.sock,t(q),Date.now()+U).catch((P)=>{let A=this.pending.get(B);if(A)this.rejectPending(B,A,P instanceof Error?P:new F(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new F(this.timeoutMessage(z,X,J),e$))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??k.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof S)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let Y=q8($,Q),W=E(H.Request,v(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,V=(j)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof F&&j.code===e$)return new S("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${j8(j)}`,j9,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,q)=>{let K=J??m0,L={handle:$,resolve:j,reject:q,onProgress:G,timer:null,classifyFailure:V};L.timer=setTimeout(()=>this.arbitrateTimeout(Y,L,$.channel,Q,K),K),this.pending.set(Y,L);let U=Y9(this.sock,t(W),Date.now()+K);B=U.queued,U.completed.catch((D)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,D instanceof Error?D:new F(String(D)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new S("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=q9(Z),G=Z3(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+Z1,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof S&&J.code==="route_closed")throw J;if(!this.closeStarted&&H8(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof F&&J1(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=E(H.Ping,v(!1,C.Interactive,!1,k.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await r($,t(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new Z0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new F("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new F("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new F("client closed");Z+=1;try{let X=await K0.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new F("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!H8(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof y&&Z>1)throw new y(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new S("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:z1},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new F(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===H.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=q8(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case H.Push:case H.StreamData:try{X.onProgress?.($.body)}catch{}return;case H.Response:case H.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case H.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===H.Response||$.header.ty===H.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===H.Goodbye&&Z){if(this.failHandle(Z,new F("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===H.Response||$.header.ty===H.Error||$.header.ty===H.StreamEnd)o6("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new F(Z.message??"subc error",Z.code)}catch{return new F(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&V8(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&V8(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new S("not_sent",`${$}${j8(Z)}`,K8(Z),Z)}outcomeUnknownCallError($,Z){return new S("outcome_unknown",`${$}${j8(Z)}`,K8(Z),Z)}terminalCallError($,Z){if(Z instanceof S)return Z;return new S("terminal",`${$}${j8(Z)}`,K8(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof S)return Z;if(H8(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=B8($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!h0($,this.connectionToken))throw new z0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new F("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new F("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function H8($){if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof S)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof y)return!0;if($ instanceof F||$ instanceof b)return!1;let Z=K8($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function J1($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function G1($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??X1,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??e6,livenessProbeWindowMs:$.livenessProbeWindowMs??$1,onControlPush:$.onControlPush}}function Z3($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function q9($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[z3],z=process.env[X3];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function K8($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function j8($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function q8($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as N9}from"node:buffer";var Q1=1e4,Y1=30000,G3=30000,W1=250,H9=64,L9="health.check",Q3=1n;class U8{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new I("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class I extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class g0{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=O0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new U8(H9);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=N8($,X),G=z.timeoutMs??G3,Q=E(H.Request,v(!1,z.priority??C.Interactive,!1,z.admissionClass??k.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new I("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(V)=>Y(V.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((V)=>{let j=this.pending.get(J);if(!j)return;this.pending.delete(J),clearTimeout(j.timer),W(V instanceof Error?V:new I(String(V)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,E(H.Push,v(!1,z.priority??C.Interactive,!1,z.admissionClass??k.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,E(H.Cancel,e(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,E(H.Goodbye,e(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==p)throw new I(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${p}`,"invalid_manifest");let Z=q1($),z=await g0.openConnection(Z);return new g0(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await K9($,E(H.Goodbye,e(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await P0($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??Q1),J=z.endpoints[0],G=await H0.connect(J.host,J.port,X);try{Z?.(G),await v0(G,z,X),await K9(G,K1($));let Q=await D1(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:Y1});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new I(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=N8(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===H.Push||$.header.ty===H.StreamData)return!0;if($.header.ty===H.Response||$.header.ty===H.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===H.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(B1($)),!0}}switch($.header.ty){case H.Ping:if($.header.channel===0)await this.sendOn(Z,z,a($.header.ver,H.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case H.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case H.Cancel:if(X)this.inflight.get(N8(X,$.header.corr))?.abort();return!0;case H.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new z0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new I("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=P8($.body);if(X.op===L9){this.handleHealthRequest($,Z,z).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new I(`unsupported module control request ${X.op??"<missing op>"}`);let J=J3(X.route_channel,"route_channel"),G=J3(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,e(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=B8(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let V=P1(B);if(V){try{await this.sendError($,V.code,V.message,e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,a($.header.ver,H.Response,e(),0,0,$.header.corr,D8({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(Y),j}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=N8(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,a(G,H.StreamData,v(!1,q.priority??C.Interactive,!1,q.admissionClass??k.Normal),Z.channel,Z.epoch,J,j))}},B=await(this.requestGate??new U8(H9)).acquire(),V=v(!1,C.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}let j=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(z,X,a(G,H.StreamEnd,V,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(z,X,a(G,H.Response,V,Z.channel,Z.epoch,J,j));else throw new I("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof z0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}await this.sendError($,j instanceof I&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new U8(H9)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,a(J,H.Response,e(),0,0,X,D8({op:L9,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof I&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),e(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,a($.header.ver,H.Error,X,$.header.channel,$.header.epoch,$.header.corr,D8({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await K9($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new I(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new I("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await g0.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new I("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new I("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!L1(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:z}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await U1();continue}console.warn("SubcProvider connection-state callback failed",z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new I("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function N8($,Z){return`${$.channel}:${$.epoch}:${Z}`}function B1($){try{let Z=P8($.body);return new I(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new I(N9.from($.body).toString("utf8")||"subc error")}}function V1($){let Z=$.launchNonce??process.env[j1];return Z&&Z.length>0?Z:void 0}var j1="SUBC_LAUNCH_NONCE";function q1($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??W1,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function H1($){if($===null)return null;let Z=new Set($??[]);return Z.add(L9),[...Z]}function K1($){let Z=V1($);return E(H.Hello,e(),0,0,Q3,D8({manifest:O1($.manifest),protocol_ver:p,control_ops:H1($.controlOps),...Z?{launch_nonce:Z}:{}}))}function L1($){if($ instanceof I)return $.code==="duplicate_module_id";if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof y)return!0;if($ instanceof b)return!1;let Z=N1($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function N1($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function U1(){await new Promise(($)=>setTimeout($,0))}function e(){return v(!1,C.Passive,!1)}async function K9($,Z){await r($,t(Z),Date.now()+G3)}async function D1($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case H.HelloAck:{let X=P8(z.body);if(X.negotiated_ver!==p)throw new I(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${p}`,"unsupported_version");return X}case H.Error:{let X=P8(z.body);throw new I(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new I(`unexpected frame ${H[z.header.ty]} awaiting HELLO_ACK`)}}function D8($){return new Uint8Array(N9.from(JSON.stringify($),"utf8"))}function P8($){return JSON.parse(N9.from($).toString("utf8"))}function J3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new I(`route.bind ${Z} must be an integer`);return $}function P1($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function O1($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(M1),consumes:$.consumes.map(_1),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function M1($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function _1($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var O8="subc-connection.json",A1="subc-",T1=".connection.json";function Y3(){let $=process.env.HOME;return $?p0($,".local","share","cortexkit","run",O8):void 0}function C1(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return p0($,O8);let Z=Y3();if(Z)return Z;return p0(R1().homedir,".local","share","cortexkit","run",O8)}function b1(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=p0($,O8);if(U9(X))return X}let Z=Y3();if(Z&&U9(Z))return Z;let z=S1(I1());return z.length===1?z[0]:void 0}function D9(){return b1()??C1()}function P9($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||D9()}function U9($){try{return F1($).isFile()}catch{return!1}}function S1($){let Z;try{Z=x1($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(A1)||!X.endsWith(T1))continue;let J=p0($,X);if(U9(J))z.push(J)}return z.sort(),z}import{createHash as w1}from"node:crypto";import{existsSync as k1,realpathSync as W3}from"node:fs";import{dirname as f1,relative as E1,resolve as y1}from"node:path";function B3($){let Z=$,z;try{z=W3(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!k1(J)){let G=f1(J);if(G===J)break;J=G}z=y1(W3(J),E1(J,Z))}return w1("sha256").update(z).digest("hex")}function O9($,Z){return{project_root:$,harness:"opencode",session:`store-${B3(Z)}`}}var V3=["transient","permanent","auth_required","context_overflow"];class _0 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function M($,Z="invalid_response",z=(X)=>console.warn(X)){let X=M0($)&&M0($.result)?$.result:void 0,J=X&&M0(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&V3.includes(G),W=typeof Q==="string",V=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new _0(W?Q:Z,V,j3(V))}function L0($){return M0($)&&M0($.result)&&M0($.result.error)}var q3="claustrum",m1=60000;function u($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _9($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function X0($){return $===void 0||typeof $==="string"}function H3($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw M($,"invalid_response",Z);let J=_9(z?.record_version);if(J===void 0)throw M($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw M($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,V=z?.email,j=z?.org_name;if(!X0(Y)||!X0(W)||!X0(B)||!X0(V)||!X0(j))throw M($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:V,orgName:j}}function g1($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=_9(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw M($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class M8{#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=P9($.connectionFile),z=$.connector??((G)=>K0.connect(G)),X=$.identity??O9($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new M8(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return H3(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return g1(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return p1(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return H3(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=M9(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw M(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return u1(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=M9(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw M(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#j(z)){try{await this.#q()}catch(X){throw this.#V(X)}try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#V(X)}}throw this.#V(z)}}#V($){if($ instanceof _0)return $;let Z=$ instanceof S&&$.code?$.code:"transport_error";return new _0(Z,"transient","retry")}#j($){return!this.#W&&$ instanceof S&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#q(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+m1,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function p1($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw M($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw M($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!u(Q))throw M($,"invalid_response",Z);let Y=_9(Q.record_version);if(Y===void 0)throw M($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw M($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw M($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw M($,"invalid_response",Z);if(!X0(Q.refresh_adapter))throw M($,"invalid_response",Z);if(!X0(Q.account_id)||!X0(Q.email)||!X0(Q.org_name))throw M($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function M9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0;if(z===void 0)throw M($,"invalid_response",Z);return z}function u1($,Z){let z=M9($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw M($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw M($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}l8();var VZ=d("quota");var K3={name:"@cortexkit/pi-openai-auth",version:"0.9.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=0.80.10","@earendil-works/pi-coding-agent":">=0.80.10","@earendil-works/pi-tui":">=0.80.10"}};import{homedir as i1}from"node:os";import{join as L3}from"node:path";function c1(){return process.env.PI_AGENT_DIR?.trim()||L3(i1(),".pi","agent")}function N3(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||L3(c1(),n0)}function s1($=N3()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||g8($)}function U3($=N3()){return{configPath:$,statePath:s1($)}}var D3=new Map;function P3($){return D3.get($)}function O3($){return D3.delete($)}var n1={auth:{set:async()=>{}}};async function a1($,Z){let z=(Z.accountPaths??U3)(),X=Z.loadAccounts??B$,J=await X(z),G=new n({storage:null,configPath:z.configPath,fetchImpl:Z.fetchImpl,now:Z.now});return G.seedFallbacksFromAccounts((J?.accounts??[]).filter(m8)),{accountStoragePath:z.configPath,accountStatePath:z.statePath,packageVersion:Z.packageVersion??K3.version,quotaManager:G,loadAccounts:X,client:n1,sessionId:$.sessionManager.getSessionId(),notify:(Q)=>$.ui.notify(Q.text),clearStickyRouting:async(Q)=>O3(Q),getStickyRouting:async(Q)=>P3(Q),fetchImpl:Z.fetchImpl,now:Z.now,randomUUID:Z.randomUUID,beginAccountLogin:Z.beginAccountLogin}}async function t1($,Z,z,X={}){return z9($,Z,await a1(z,X))}async function x9($,Z,z,X){let J=await t1($,Z,z,X);z.ui.notify(J.text)}function M3($,Z={}){$.registerCommand(X8,{description:"List, add, remove, or reorder OpenAI fallback accounts",handler:(z,X)=>x9(X8,z,X,Z)}),$.registerCommand(z8,{description:"Show persisted OpenAI quota for fallback accounts",handler:(z,X)=>x9(z8,z,X,Z)}),$.registerCommand(J8,{description:"Show or change OpenAI account routing mode",handler:(z,X)=>x9(J8,z,X,Z)})}import{connect as o1}from"node:net";import{connect as r1}from"node:tls";var e1="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_3=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class F9{url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,z){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let z of[...this.listeners[$]??[]])try{z(Z)}catch{}}async connect($,Z){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,G=`${z.pathname}${z.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+e1));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[q,K]of Object.entries(Z))B[q.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let q of _3)if(B[q]!==void 0)V.push(`${$2(q)}: ${B[q]}`);for(let[q,K]of Object.entries(Z))if(!_3.includes(q.toLowerCase())&&q.toLowerCase()!=="content-length")V.push(`${q}: ${K}`);let j=`${V.join(`\r
|
|
210
|
+
Unavailable: reset command runtime dependencies are not wired.`,knobs:{}};let X=Z,J=$.trim().split(/\s+/).filter(Boolean),G=J[0];if(!G||G==="refresh"){let Y=["main",...((await Z.loadAccounts(m(Z)))?.accounts??[]).filter((B)=>B.enabled!==!1&&B.type==="oauth").map((B)=>B.id)];_.debug("reset accounts stage requested",{accountKeys:Y});let W=await Promise.all(Y.map((B)=>b1(B,X)));return _.debug("reset accounts stage built",{rows:W.map((B)=>({accountKey:B.accountKey,eligible:B.eligible,reason:B.reason,usedPercent:B.usedPercent,availableCount:B.availableCount,applicableAvailableCount:B.applicableAvailableCount}))}),{command:y0,text:w6(W),knobs:{stage:"accounts",accounts:W}}}if(G==="select"){let Q=Z$(J[1]);if(!Q||!i(Q)||J.length!==2)return g("","invalid_command","Usage: `/openai-reset select <encodedAccountKey>`");let Y=await b1(Q,X);if(!Y.eligible)return g(Q,"not_eligible",S1(Y));return{command:y0,text:S1(Y),knobs:{stage:"confirm",preview:Y}}}if(G==="confirm"||G==="retry"){let Q=Z$(J[1]),Y=Z$(J[2]);if(!Q||!i(Q)||!Y||J.length!==3)return g(Q??"","invalid_command",`Usage: \`/openai-reset ${G} <encodedAccountKey> <encodedChatgptAccountId>\``);_.info("reset redemption decision",{accountKey:Q,action:G}),_.debug("reset redemption identity binding",{accountKey:Q,expectedChatgptAccountId:Y});try{let W=await I1({configPath:Z.accountStoragePath,statePath:Z.accountStatePath,mutateAccountsFn:G0,loadAccountsFn:Z.loadAccounts,now:X.now,randomUUID:X.randomUUID,fetchImpl:X.fetchImpl,resolveTarget:X.resolveResetTarget,fetchUsage:(B)=>d8({accessToken:B.accessToken,fetchImpl:X.fetchImpl,now:X.now,accountId:B.chatgptAccountId}),hasActiveRateLimitMark:(B)=>Z.quotaManager.isRateLimited(B)},{accountKey:Q,expectedChatgptAccountId:Y,retry:G==="retry"});return _.info("reset redemption outcome",{accountKey:Q,code:W.outcome.kind}),w1(W,X,Y)}catch(W){let B=f6(Q,W,Y);return _.info("reset redemption outcome",{accountKey:Q,code:B.knobs.code}),B}}return g("","invalid_command","Usage: `/openai-reset` | `/openai-reset select <encodedAccountKey>` | `/openai-reset confirm <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset retry <encodedAccountKey> <encodedChatgptAccountId>` | `/openai-reset refresh`")}var y6=new Set(["access","refresh","apikey","authheader","password","secret"]);function v6($){let Z=$.toLowerCase().replace(/[-_]/g,"");if(y6.has(Z))return!0;return Z.endsWith("token")}function Z8($,Z,z){if(Array.isArray($))return $.map((J,G)=>Z8(J,`${Z}[${G}]`,z));if(!R1($))return $;let X={};for(let[J,G]of Object.entries($)){if(v6(J)){z.push(`${Z}.${J}`);continue}X[J]=Z8(G,`${Z}.${J}`,z)}return X}async function z$($,Z,z,X={}){let J=await h6($,Z,z,X),G=[],Q=Z8(J.knobs,"knobs",G);if(G.length>0)return _.warn("credential-shaped knob stripped before RPC",{command:$,fields:G}),{...J,knobs:Q};return J}async function h6($,Z,z,X){switch($){case"openai-quota":return T6(z);case"openai-account":return C6(Z,z);case"openai-routing":return b6(Z,z);case"openai-reset":return E6(Z,z);default:{let J=X[$];if(!J)throw Error(`unhandled command: ${$}`);return J(Z,z)}}}import{readdirSync as x9,statSync as F9}from"node:fs";import{tmpdir as I9,userInfo as R9}from"node:os";import{join as p0}from"node:path";import{debuglog as t6}from"node:util";import{createHmac as l6,randomBytes as d6,timingSafeEqual as i6}from"node:crypto";import u6 from"node:net";var p=2,G8=21,Q8=5,X$=67108864,H;(function($){$[$.Request=0]="Request",$[$.Response=1]="Response",$[$.Push=2]="Push",$[$.StreamData=3]="StreamData",$[$.StreamEnd=4]="StreamEnd",$[$.Error=5]="Error",$[$.Cancel=6]="Cancel",$[$.Ping=7]="Ping",$[$.Pong=8]="Pong",$[$.Hello=9]="Hello",$[$.HelloAck=10]="HelloAck",$[$.Goodbye=11]="Goodbye"})(H||(H={}));var f1=H.Goodbye;function E1($){return $===H.Cancel||$===H.Ping||$===H.Pong||$===H.Goodbye}var C;(function($){$[$.Passive=0]="Passive",$[$.Interactive=1]="Interactive",$[$.Background=2]="Background"})(C||(C={}));var w;(function($){$[$.Normal=0]="Normal",$[$.Expedite=1]="Expedite",$[$.Sheddable=2]="Sheddable"})(w||(w={}));var m6=1,y1=6,J$=1,g6=8,v1=48,G$=4,h1=192;function v($,Z,z,X=w.Normal){let J=0;if($)J|=m6;if(J|=Z<<J$,z)J|=g6;return J|=X<<G$,J}function m1($){let Z=new Uint8Array(21),z=new DataView(Z.buffer);return z.setUint32(0,$.len,!0),Z[4]=$.ver,Z[5]=$.ty,Z[6]=$.flags,z.setUint16(7,$.channel,!0),z.setUint32(9,$.epoch,!0),z.setBigUint64(13,$.corr,!0),Z}class x extends Error{code;constructor($,Z){super($);this.code=Z,this.name="DecodeError"}}function p6($){let Z=$.len>>>0,z=$.ver>>>0&255,X=$.ty>>>0&255,J=$.flags>>>0&255,G=$.channel>>>0&65535,Q=$.epoch>>>0;if(BigInt.asUintN(64,$.corr),z!==2)throw new x(`unsupported envelope version ${z}`,"unsupported_version");if(X>f1)throw new x(`unknown frame type byte ${X}`,"unknown_frame_type");let Y=X;if((J&h1)!==0)throw new x(`reserved flag bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((J&y1)>>J$===3)throw new x(`reserved priority bits set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let W=(J&v1)>>G$;if(W===3)throw new x(`reserved admission class set in flags 0b${J.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(W===w.Sheddable&&Y!==H.Push&&Y!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[Y]} in flags 0b${J.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");if(G===0&&Q!==0)throw new x(`control channel carried nonzero epoch ${Q}`,"nonzero_epoch_on_control_channel");if(E1(Y)&&Z!==0)throw new x(`pure-header frame ${H[Y]} declared non-zero body length ${Z}`,"pure_header_frame_with_body")}function Q$($){if($.length<5)throw new x(`header shorter than frozen prefix: have ${$.length} bytes`,"too_short_for_prefix");let Z=$[4];if(Z!==2)throw new x(`unsupported envelope version ${Z}`,"unsupported_version");if($.length<21)throw new x(`header too short for version: have ${$.length} bytes, need 21`,"too_short_for_header");let z=new DataView($.buffer,$.byteOffset,$.byteLength),X=z.getUint32(0,!0),J=$[5];if(J>f1)throw new x(`unknown frame type byte ${J}`,"unknown_frame_type");let G=J,Q=$[6];if((Q&h1)!==0)throw new x(`reserved flag bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_flag_bits");if((Q&y1)>>J$===3)throw new x(`reserved priority bits set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_priority_bits");let Y=(Q&v1)>>G$;if(Y===3)throw new x(`reserved admission class set in flags 0b${Q.toString(2).padStart(8,"0")}`,"reserved_admission_class");if(Y===w.Sheddable&&G!==H.Push&&G!==H.StreamData)throw new x(`SHEDDABLE admission class is illegal on ${H[G]} in flags 0b${Q.toString(2).padStart(8,"0")}`,"sheddable_illegal_frame_type");let W=z.getUint16(7,!0),B=z.getUint32(9,!0);if(W===0&&B!==0)throw new x(`control channel carried nonzero epoch ${B}`,"nonzero_epoch_on_control_channel");if(E1(G)&&X!==0)throw new x(`pure-header frame ${H[G]} declared non-zero body length ${X}`,"pure_header_frame_with_body");return{len:X,ver:Z,ty:G,flags:Q,channel:W,epoch:B,corr:z.getBigUint64(13,!0)}}function E($,Z,z,X,J,G){return a(2,$,Z,z,X,J,G)}function a($,Z,z,X,J,G,Q){if(Q.length>67108864)throw new x(`frame body ${Q.length} exceeds max 67108864`,"frame_body_too_large");let Y={len:Q.length,ver:$,ty:Z,flags:z,channel:X,epoch:J,corr:G};return p6(Y),{header:Y,body:Q}}function t($){if($.header.len!==$.body.length)throw new x(`frame header length ${$.header.len} does not match body length ${$.body.length}`,"frame_length_mismatch");let Z=m1($.header),z=new Uint8Array(Z.length+$.body.length);return z.set(Z,0),z.set($.body,Z.length),z}class Z0 extends Error{}class s extends Error{}class o extends Error{cause;constructor($,Z){super($);this.cause=Z}}class Q0 extends Error{cause;constructor($,Z){super($);this.cause=Z}}function g1($){return Buffer.from($.buffer,$.byteOffset,$.byteLength)}var p1=Symbol("subc.socket.writeBorrowed"),u1=Symbol("subc.socket.writeTrackedBorrowed");function r($,Z,z){let X=$[p1];return X?X.call($,Z,z):$.write(Z,z)}function Y$($,Z,z){let X=$[u1];return X?X.call($,Z,z):$.writeTracked(Z,z)}class H0{sock;chunks=[];buffered=0;waiter=null;closedErr=null;bufferedBytes(){return this.buffered}constructor($){this.sock=$,$.on("data",(z)=>{this.chunks.push(z),this.buffered+=z.length,this.tryServe()});let Z=(z)=>{if(!this.closedErr)this.closedErr=z;this.tryServe()};$.on("error",(z)=>Z(z instanceof Error?z:Error(String(z)))),$.on("end",()=>Z(new Z0("subc closed the connection"))),$.on("close",()=>Z(new Z0("subc connection closed")))}localPort(){return this.sock.localPort??null}static connect($,Z,z){return new Promise((X,J)=>{let G=u6.connect({host:$,port:Z});G.setNoDelay(!0);let Q=setTimeout(()=>{G.destroy(),J(new s(`timed out connecting to ${$}:${Z}`))},Math.max(0,z-Date.now()));G.once("connect",()=>{clearTimeout(Q),X(new H0(G))}),G.once("error",(Y)=>{clearTimeout(Q),J(Y)})})}async readFrame($,Z,z){let X=await this.readExact(Q8,$),J=X[4];if(J!==p)throw new x(`unsupported envelope version ${J}`,"unsupported_version");let G=await this.readExact(G8-Q8,$),Q=new Uint8Array(G8);Q.set(X),Q.set(G,Q8);let Y=Q$(Q);if(Y.len>X$)throw new x(`frame body ${Y.len} exceeds max ${X$}`,"frame_body_too_large");z?.();let W=typeof Z==="number"?Z:Date.now()+Z.afterHeaderMs,B=Y.len===0?new Uint8Array(0):await this.readExact(Y.len,W);return{header:Y,body:B}}readExact($,Z){if(this.waiter)return Promise.reject(Error("concurrent readExact is not supported"));if($===0)return Promise.resolve(new Uint8Array(0));return new Promise((z,X)=>{let J=null;if(Number.isFinite(Z)){let G=Z-Date.now();if(G<=0){X(new s(`timed out waiting for ${$} bytes`));return}J=setTimeout(()=>{this.waiter=null,X(new s(`timed out waiting for ${$} bytes`))},G)}this.waiter={need:$,resolve:z,reject:X,timer:J},this.tryServe()})}async write($,Z){await this.writeBuffer(Buffer.from($),Z)}writeTracked($,Z){return this.writeTrackedBuffer(Buffer.from($),Z)}async[p1]($,Z){await this.writeBuffer(g1($),Z)}[u1]($,Z){return this.writeTrackedBuffer(g1($),Z)}async writeBuffer($,Z){try{await this.writeTrackedBuffer($,Z).completed}catch(z){if(z instanceof o||z instanceof Q0)throw z.cause??z;throw z}}writeTrackedBuffer($,Z){if(this.closedErr)return{queued:!1,completed:Promise.reject(new o("subc socket was closed before bytes could be queued",this.closedErr))};let z=!1,X=!1,J=null,G=new Promise((Q,Y)=>{let W=(V)=>{if(X)return;if(X=!0,J)clearTimeout(J);V()},B=Z-Date.now();if(B<=0){W(()=>Y(new o("timed out before bytes could be queued to subc",new s("timed out writing to subc"))));return}J=setTimeout(()=>{let V=new s("timed out writing to subc");W(()=>Y(z?new Q0("timed out after bytes were handed to the subc socket",V):new o("timed out before bytes could be queued to subc",V)))},B);try{this.sock.write($,(V)=>{W(()=>{if(V)Y(new Q0("subc socket reported a write error after bytes were handed to the socket",V instanceof Error?V:Error(String(V))));else Q()})}),z=!0}catch(V){W(()=>Y(new o("subc socket write threw before bytes could be queued",V instanceof Error?V:Error(String(V)))))}});return{queued:z,completed:G}}close(){this.sock.destroy()}tryServe(){let $=this.waiter;if(!$)return;if(this.buffered>=$.need){let Z=this.take($.need);if(this.waiter=null,$.timer)clearTimeout($.timer);$.resolve(Z);return}if(this.closedErr){if(this.waiter=null,$.timer)clearTimeout($.timer);$.reject(this.closedErr)}}take($){let Z=Buffer.allocUnsafe($),z=0;while(z<$){let X=this.chunks[0],J=$-z;if(X.length<=J)X.copy(Z,z),z+=X.length,this.chunks.shift();else X.copy(Z,z,0,J),this.chunks[0]=X.subarray(J),z+=J}return this.buffered-=$,Z}}var i1=32;var Y8=4096,c1="subc-server-v1",s1="subc-client-v1",c6="client";class y extends Error{}function B$($,Z,z,X,J){let G=l6("sha256",Buffer.from($));return G.update(Buffer.from(Z,"utf8")),G.update(Buffer.from(z)),G.update(Buffer.from(X)),G.update(Buffer.from(J)),new Uint8Array(G.digest())}function l1($,Z){if($.length!==Z.length)return!1;return i6(Buffer.from($),Buffer.from(Z))}async function d1($,Z,z){let X=Buffer.from(JSON.stringify(Z),"utf8");if(X.length>Y8)throw new y(`auth message too large: ${X.length} > ${Y8}`);let J=new Uint8Array(4);new DataView(J.buffer).setUint32(0,X.length,!0),await r($,J,z),await r($,X,z)}async function s6($,Z){let z=await $.readExact(4,Z),X=new DataView(z.buffer,z.byteOffset,4).getUint32(0,!0);if(X>Y8)throw new y(`auth message too large: ${X} > ${Y8}`);let J=X===0?new Uint8Array(0):await $.readExact(X,Z);try{return JSON.parse(Buffer.from(J).toString("utf8"))}catch(G){throw new y(`auth message JSON decode failed: ${String(G)}`)}}function W$($,Z){if(!Array.isArray($))throw new y(`auth field '${Z}' must be a byte array`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new y(`auth field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}async function v0($,Z,z){let X=new Uint8Array(d6(i1));await d1($,{client_nonce:Array.from(X),role:c6},z);let J=await s6($,z),G=W$(J.server_nonce,"server_nonce"),Q=W$(J.daemon_id,"daemon_id"),Y=W$(J.server_proof,"server_proof"),W=B$(Z.key,c1,X,G,Q);if(!l1(W,Y))throw new y("server proof mismatch — wrong key or impostor daemon");if(!l1(Q,Z.daemonId))throw new y("daemon id mismatch — connection file points at a different daemon");let B=B$(Z.key,s1,X,G,Q);await d1($,{client_auth:Array.from(B)},z)}import{promises as V$}from"node:fs";var n1=1,a1=32,t1=16;class b extends Error{}function o1($,Z){if(!Array.isArray($))throw new b(`connection file field '${Z}' must be a JSON array of bytes`);for(let z of $)if(typeof z!=="number"||!Number.isInteger(z)||z<0||z>255)throw new b(`connection file field '${Z}' has invalid byte ${String(z)}`);return Uint8Array.from($)}function n6($){if($.schema!==n1)throw new b(`unsupported connection file schema ${$.schema}; expected ${n1}`);if($.endpoints.length===0)throw new b("connection file must include at least one endpoint");if($.key.length<a1)throw new b(`connection file key is too short: ${$.key.length} bytes, need at least ${a1}`);if($.daemonId.length!==t1)throw new b(`connection file daemon_id must be ${t1} bytes, got ${$.daemonId.length}`)}async function a6($){if(process.platform==="win32")return;let z=(await V$.stat($)).mode&511;if((z&63)!==0)throw new b(`connection file ${$} has insecure permissions 0o${z.toString(8)}; expected owner-only 0600`)}async function P0($){await a6($);let Z=await V$.readFile($,"utf8"),z;try{z=JSON.parse(Z)}catch(Y){throw new b(`connection file JSON read failed for ${$}: ${String(Y)}`)}let X=z.wire_version;if(X!==void 0&&X!==p)throw new b(`connection file wire_version ${String(X)} but this client speaks ${p}; the client library must be upgraded`);let J=z.endpoints;if(!Array.isArray(J))throw new b("connection file 'endpoints' must be an array");let G=J.map((Y)=>{let W=Y;if(typeof W.host!=="string"||typeof W.port!=="number")throw new b("connection file endpoint must be { host: string, port: number }");return{host:W.host,port:W.port}}),Q={schema:z.schema,endpoints:G,key:o1(z.key,"key"),daemonId:o1(z.daemon_id,"daemon_id"),pid:z.pid,daemonVer:z.daemon_ver??""};return n6(Q),Q}var r1=new WeakMap;class W8{channel;epoch;constructor($,Z,z){if(!Number.isInteger($)||$<=0||$>65535)throw RangeError(`route channel must be an integer in 1..65535, got ${$}`);if(!Number.isInteger(Z)||Z<=0||Z>4294967295)throw RangeError(`route epoch must be an integer in 1..4294967295, got ${Z}`);this.channel=$,this.epoch=Z,r1.set(this,z),Object.freeze(this)}static create($,Z,z){return new W8($,Z,z)}}function B8($,Z,z){return W8.create($,Z,z)}class z0 extends Error{handle;code="stale_route_handle";constructor($){super(`route handle (${$.channel}, ${$.epoch}) is not live on the current connection`);this.handle=$,this.name="StaleRouteHandleError"}}function O0(){return Object.freeze({})}function h0($,Z){return r1.get($)===Z}function V8($,Z){return $===Z}var o6=t6("subc-client"),r6=1e4,m0=30000,e6=50,$9=2000,e1="request_deadline",j$="deadline_exceeded_no_drop_observed",Z9=30000,z9=30000,$3=new Uint8Array(0),X9="management_surface",z3="SUBC_MODULE_ID",X3="SUBC_LAUNCH_NONCE",L8={baseMs:100,capMs:2000,maxAttempts:6};class S extends Error{kind;code;cause;constructor($,Z,z,X){super(Z);this.kind=$,this.code=z,this.cause=X,this.name="SubcCallError"}}class F extends Error{code;constructor($,Z){super($);this.code=Z}}class K0{sock;currentConn;opts;nextCorr=1n;pending=new Map;lateResponses=new Map;routes=new Map;liveRoutes=new Map;connectionToken=O0();ingressEpochDropCount=0;closedErr=null;closeStarted=!1;reconnecting=null;generation=1;readerActive=!1;constructor($,Z,z){this.sock=$,this.currentConn=Z,this.opts=z,this.readLoop($,this.generation)}get conn(){return this.currentConn}static async connect($){let Z=G9($),z=await K0.openConnection(Z);return new K0(z.sock,z.conn,Z)}async catalogList($){let Z=this.encode($===void 0?{op:"catalog.list"}:{op:"catalog.list",module_id:$}),z=await this.controlRpc(Z);return this.parseJson(z).modules??[]}async routeOpen($,Z,z={}){let X=q$(z),J=z.consumerCapabilities,G=this.encode({op:"route.open",target:$,identity:Z,...X?{consumer_identity:X}:{},...J!==void 0?{consumer_capabilities:J}:{}}),Q=null,Y=(B)=>{if(B.header.ty!==H.Response)return!0;let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")throw new F(`route.open returned no route handle: ${JSON.stringify(V)}`);return Q=this.installRoute(V.route_channel,V.route_epoch),!0},W=(B)=>{if(B.header.ty!==H.Response)return;try{let V=this.parseJson(B);if(typeof V.route_channel!=="number"||typeof V.route_epoch!=="number")return;let j=this.installRoute(V.route_channel,V.route_epoch);this.failHandle(j,new F("late route.open was closed","route_closed")),this.liveRoutes.delete(j.channel),this.sendRouteGoodbye(j,!0)}catch{this.closeConnectionAfterCleanupFailure()}};if(await this.controlRpc(G,Y,W),!Q)throw new F("route.open response was not installed");return Q}async request($,Z,z={}){this.assertLiveHandle($);let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal,Q=await this.send($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}async call($,Z,z,X={}){let J=z===void 0?{method:Z}:{method:Z,params:z},G=!1;for(;;){let Q=await this.cachedRouteHandle($,X);try{return await this.managedRequest(Q,J,X)}catch(Y){if(!(Y instanceof S))throw this.terminalCallError("managed call failed",Y);let W=Y.code==="unknown_channel"||Y.code==="stale_route_epoch";if(W&&!G&&!this.closeStarted){G=!0,this.evictRouteHandle(Q);continue}if(W&&G)this.evictRouteHandle(Q);if(Y.kind==="not_sent"){try{await this.reconnectAfterDrop(Y)}catch(B){throw this.notSentRecoveryError("managed call was not sent",B)}continue}if(Y.kind==="outcome_unknown"&&Y.code!==j$)this.scheduleReconnectAfterDrop(Y);else if(Y.kind==="outcome_unknown"&&Y.code===j$)this.probeLivenessAfterDeadline();throw Y}}}subscribe($,Z,z,X={}){this.assertLiveHandle($);let J=Z instanceof Uint8Array?Z:this.encode(Z),G=X.priority??C.Interactive,Q=X.admissionClass??w.Normal,Y=this.allocateCorr(),W=q8($,Y),B=null,V=null,j=new Promise((L,U)=>{if(this.closedErr){U(this.closedErr);return}V=L,B={handle:$,resolve:()=>L(),reject:U,onProgress:z,timer:null,subscription:!0},this.pending.set(W,B);let D=E(H.Request,v(!1,G,!1,Q),$.channel,$.epoch,Y,J);r(this.sock,t(D),Date.now()+m0).catch((P)=>{let A=this.pending.get(W);if(A)this.rejectPending(W,A,P instanceof Error?P:new F(String(P)))})}),q=!1;return{unsubscribe:()=>{if(q)return;if(q=!0,B&&V)this.settle(W,B,V);if(this.isLiveHandle($))this.cancel($,Y,G)},closed:j}}cancel($,Z,z=C.Interactive){this.assertLiveHandle($);let X=E(H.Cancel,v(!1,z,!1),$.channel,$.epoch,Z,$3);r(this.sock,t(X),Date.now()+m0).catch(()=>{return})}async routePoll($,Z){this.assertLiveHandle($);let z=this.encode({op:"route.poll",route_channel:$.channel,route_epoch:$.epoch,kind:Z}),X=await this.controlRpc(z,(J)=>{if(J.header.ty!==H.Response)return!0;let G=this.parseJson(J);return G.route_channel===$.channel&&G.route_epoch===$.epoch});return this.parseJson(X)}async closeRoute($,Z={}){this.assertLiveHandle($);for(let[z,X]of this.routes)if(X.handle&&V8(X.handle,$))X.closed=!0,X.handle=null,this.routes.delete(z);if(Z.drain)await this.drainUnaryOnHandle($);if(this.failHandle($,new F("route closed by closeRoute","route_closed")),this.liveRoutes.get($.channel)===$)this.liveRoutes.delete($.channel);this.sendRouteGoodbye($)}async closeManagedRoute($,Z,z={}){let X=Z3($,Z,q$(z)),J=this.routes.get(X);if(!J)return;J.closed=!0,this.routes.delete(X);let G=J.handle;if(J.handle=null,G)await this.closeRoute(G,z)}async closeRouteChannel($,Z={}){await this.closeRoute($,Z)}close(){this.closeStarted=!0,this.fail(new F("client closed")),this.sock.close()}drainUnaryOnHandle($){let Z=[];for(let z of this.pending.values())if(z.handle===$&&!z.subscription)Z.push(new Promise((X)=>{let J=z.onSettle;z.onSettle=()=>{J?.(),X()}}));return Promise.all(Z).then(()=>{return})}sendRouteGoodbye($,Z=!1){if(this.assertLiveConnection($),this.closedErr){if(Z)this.closeConnectionAfterCleanupFailure();return}let z=E(H.Goodbye,v(!1,C.Interactive,!1),$.channel,$.epoch,0n,$3),X=Y$(this.sock,t(z),Date.now()+m0);if(!X.queued&&Z)this.closeConnectionAfterCleanupFailure();X.completed.catch(()=>{if(Z&&!X.queued)this.closeConnectionAfterCleanupFailure()})}static async openConnection($){let Z=await P0($.connectionFile),z=Date.now()+($.handshakeTimeoutMs??r6),X=Z.endpoints[0],J=await H0.connect(X.host,X.port,z);try{await v0(J,Z,z)}catch(G){throw J.close(),G}return{sock:J,conn:Z}}async controlRpc($,Z,z){return this.send(null,$,C.Interactive,w.Normal,void 0,void 0,Z,z)}send($,Z,z,X,J,G,Q,Y){if($)this.assertLiveHandle($);if(this.closedErr)return Promise.reject(this.closedErr);let W;try{W=this.allocateCorr()}catch(K){return Promise.reject(K)}let B=q8($,W),V=$?.channel??0,j=$?.epoch??0,q=E(H.Request,v(!1,z,!1,X),V,j,W,Z);return new Promise((K,L)=>{let U=J??m0,D={handle:$,resolve:K,reject:L,onProgress:G,timer:null,acceptFrame:Q,onLateResponse:Y};D.timer=setTimeout(()=>this.arbitrateTimeout(B,D,V,W,U),U),this.pending.set(B,D),r(this.sock,t(q),Date.now()+U).catch((P)=>{let A=this.pending.get(B);if(A)this.rejectPending(B,A,P instanceof Error?P:new F(String(P)))})})}arbitrateTimeout($,Z,z,X,J){let G=()=>{if(Z.onLateResponse)this.lateResponses.set($,Z.onLateResponse);this.rejectPending($,Z,new F(this.timeoutMessage(z,X,J),e1))},Q=Date.now()+this.opts.timeoutArbitrationGraceMs,Y=()=>{if(this.pending.get($)!==Z)return;if((this.readerActive||this.sock.bufferedBytes()>0)&&Date.now()<Q){setImmediate(Y);return}G()};setImmediate(Y)}async managedRequest($,Z,z){let X=Z instanceof Uint8Array?Z:this.encode(Z),J=z.priority??C.Interactive,G=z.admissionClass??w.Normal;try{let Q=await this.sendManaged($,X,J,G,z.timeoutMs,z.onProgress);return this.parseJson(Q)}catch(Q){if(Q instanceof S)throw Q;throw this.terminalCallError("managed call failed",Q)}}sendManaged($,Z,z,X,J,G){try{this.assertLiveHandle($)}catch(j){return Promise.reject(this.notSentCallError("request used a stale route handle",j))}if(this.closedErr)return Promise.reject(this.notSentCallError("request was not sent because the subc connection was already closed",this.closedErr));let Q;try{Q=this.allocateCorr()}catch(j){return Promise.reject(this.notSentCallError("request correlation allocator was exhausted",j))}let Y=q8($,Q),W=E(H.Request,v(!1,z,!1,X),$.channel,$.epoch,Q,Z),B=!1,V=(j)=>{if(!B)return this.notSentCallError("request bytes were not queued to the subc socket",j);if(j instanceof F&&j.code===e1)return new S("outcome_unknown",`managed call deadline exceeded after request bytes were queued to the local socket; no terminal response was observed; outcome unknown${j8(j)}`,j$,j);return this.outcomeUnknownCallError("connection dropped before the managed call returned a response",j)};return new Promise((j,q)=>{let K=J??m0,L={handle:$,resolve:j,reject:q,onProgress:G,timer:null,classifyFailure:V};L.timer=setTimeout(()=>this.arbitrateTimeout(Y,L,$.channel,Q,K),K),this.pending.set(Y,L);let U=Y$(this.sock,t(W),Date.now()+K);B=U.queued,U.completed.catch((D)=>{let P=this.pending.get(Y);if(P)this.rejectPending(Y,P,D instanceof Error?D:new F(String(D)))})})}async cachedRouteHandle($,Z){let z=Z.identity??this.opts.identity;if(!z)throw new S("terminal","managed call requires a BindIdentity in SubcClient.connect({ identity }) or call(..., { identity })","missing_identity");let X={kind:Z.targetKind??this.opts.targetKind,module_id:$},J=q$(Z),G=Z3(X,z,J),Q=this.routes.get(G);if(!Q)Q={key:G,moduleId:$,target:X,identity:z,consumerIdentity:J,handle:null,opening:null},this.routes.set(G,Q);if(Q.handle&&this.isLiveHandle(Q.handle))return Q.handle;if(!Q.opening)Q.opening=this.openCachedRoute(Q).finally(()=>{Q.opening=null});return Q.opening}async openCachedRoute($){let Z=Date.now()+Z9,z=this.opts.reconnectBackoff.baseMs,X=0;for(;;){if($.closed)throw this.routeClosedDuringOpen();try{await this.ensureConnectedForManaged()}catch(J){throw this.notSentRecoveryError("route.open could not run because reconnect failed",J)}if($.handle&&this.isLiveHandle($.handle))return $.handle;try{let J=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed)throw this.liveRoutes.delete(J.channel),this.sendRouteGoodbye(J),this.routeClosedDuringOpen();return $.handle=J,J}catch(J){if(J instanceof S&&J.code==="route_closed")throw J;if(!this.closeStarted&&H8(J)){try{await this.reconnectAfterDrop(J)}catch(G){throw this.notSentRecoveryError("route.open was not sent and reconnect failed",G)}continue}if(!this.closeStarted&&J instanceof F&&J9(J.code)){if(X+=1,X<this.opts.reconnectBackoff.maxAttempts&&Date.now()<Z){await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs);continue}throw this.notSentCallError(`route.open failed for module ${$.moduleId}: ${J.code} (retry budget exhausted)`,J)}throw this.terminalCallError(`route.open failed for module ${$.moduleId}`,J)}}}lastInboundAtMs=0;livenessProbe=null;hasControlPending(){for(let $ of this.pending.values())if($.handle===null)return!0;return!1}probeLivenessAfterDeadline(){if(this.livenessProbe||this.closeStarted||this.closedErr)return;if(this.hasControlPending())return;let $=this.sock,Z=this.generation,z;try{z=this.allocateCorr()}catch{return}let X=Date.now(),J=E(H.Ping,v(!1,C.Interactive,!1,w.Normal),0,0,z,new Uint8Array),G=(async()=>{if(await r($,t(J),X+this.opts.livenessProbeWindowMs).catch(()=>{}),await this.opts.sleep(this.opts.livenessProbeWindowMs),this.sock!==$||this.generation!==Z||this.closeStarted)return;if(this.lastInboundAtMs>=X)return;if(this.hasControlPending())return;this.fail(new Z0(`liveness probe convicted a half-open socket: no inbound frame for ${this.opts.livenessProbeWindowMs}ms after a channel-0 Ping (deadline-no-drop settles preceded this); closing so the next call reconnects`)),$.close()})().finally(()=>{this.livenessProbe=null});this.livenessProbe=G}async ensureConnectedForManaged(){if(this.closeStarted)throw new F("client closed");if(this.reconnecting)await this.reconnecting;if(this.closedErr)await this.reconnectAfterDrop(this.closedErr)}scheduleReconnectAfterDrop($){if(this.closeStarted||this.reconnecting)return;this.reconnectAfterDrop($).catch(()=>{})}reconnectAfterDrop($){if(this.closeStarted)return Promise.reject(new F("client closed"));if(this.reconnecting)return this.reconnecting;let Z=this.reconnectWithRetry($).finally(()=>{if(this.reconnecting===Z)this.reconnecting=null});return this.reconnecting=Z,Z}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(this.closeStarted)throw new F("client closed");Z+=1;try{let X=await K0.openConnection(this.opts);if(this.closeStarted)throw X.sock.close(),new F("client closed");this.replaceConnection(X),await this.reopenCachedRoutes();return}catch(X){if(!H8(X)||Z>=this.opts.reconnectBackoff.maxAttempts){if(X instanceof y&&Z>1)throw new y(`reconnect gave up after ${Z} attempts: ${X.message} — the connection file and the daemon's key disagree persistently `+"(daemon restarting in a loop, split connection-file paths, or a genuinely foreign daemon on this port); check the daemon, then restart this host app");throw X}await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}replaceConnection($){this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.closedErr=null,this.generation+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.lateResponses.clear(),this.nextCorr=1n,this.readLoop($.sock,this.generation)}async reopenCachedRoutes(){for(let $ of this.routes.values())$.handle=null;for(let $ of this.routes.values()){if($.closed)continue;let Z=await this.routeOpen($.target,$.identity,{consumerIdentity:$.consumerIdentity??null});if($.closed){this.liveRoutes.delete(Z.channel),this.sendRouteGoodbye(Z);continue}$.handle=Z}}timeoutMessage($,Z,z){let X=this.sock.localPort();return`request on ${X===null?"channel":`local_port=${X} channel`} ${$} corr ${Z} timed out after ${z}ms`}routeClosedDuringOpen(){return new S("not_sent","route was closed before route.open completed","route_closed")}async readLoop($,Z){try{for(;;){this.readerActive=!1;let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:z9},()=>{this.readerActive=!0});try{if(this.sock===$&&this.generation===Z)this.dispatch(z)}finally{this.readerActive=!1}}}catch(z){if(this.sock===$&&this.generation===Z)this.fail(z instanceof Error?z:new F(String(z)))}}dispatch($){if(this.lastInboundAtMs=Date.now(),$.header.channel===0&&$.header.ty===H.Push){let G=this.opts.onControlPush;if(G){let Q=null;try{let Y=this.parseJson($);if(Y&&typeof Y.op==="string")Q={op:Y.op,body:Y}}catch{}if(Q)try{G(Q)}catch{}}return}let Z=null;if($.header.channel!==0){if(Z=this.liveRoutes.get($.header.channel)??null,!Z||Z.epoch!==$.header.epoch){this.ingressEpochDropCount+=1;return}}let z=q8(Z,$.header.corr),X=this.pending.get(z);if(X){if(X.acceptFrame&&!X.acceptFrame($))return;switch($.header.ty){case H.Push:case H.StreamData:try{X.onProgress?.($.body)}catch{}return;case H.Response:case H.StreamEnd:this.settle(z,X,()=>X.resolve($));return;case H.Error:this.settle(z,X,()=>X.reject(this.errorFromFrame($)));return;default:return}}let J=this.lateResponses.get(z);if(J&&($.header.ty===H.Response||$.header.ty===H.Error)){this.lateResponses.delete(z),J($);return}if($.header.ty===H.Goodbye&&Z){if(this.failHandle(Z,new F("route closed by subc (GOODBYE)","route_closed")),this.liveRoutes.get(Z.channel)===Z)this.liveRoutes.delete(Z.channel);this.evictRouteHandle(Z);return}if($.header.ty===H.Response||$.header.ty===H.Error||$.header.ty===H.StreamEnd)o6("dropped terminal frame with no waiter: type=%d channel=%d epoch=%d corr=%s port=%s",$.header.ty,$.header.channel,$.header.epoch,$.header.corr,this.sock.localPort()??"?")}settle($,Z,z){if(this.pending.get($)!==Z)return!1;if(this.pending.delete($),Z.timer)clearTimeout(Z.timer);return z(),Z.onSettle?.(),!0}rejectPending($,Z,z){this.settle($,Z,()=>Z.reject(Z.classifyFailure?.(z)??z))}errorFromFrame($){try{let Z=JSON.parse(Buffer.from($.body).toString("utf8"));return new F(Z.message??"subc error",Z.code)}catch{return new F(Buffer.from($.body).toString("utf8")||"subc error")}}evictRouteHandle($){for(let Z of this.routes.values())if(Z.handle&&V8(Z.handle,$))Z.handle=null}failHandle($,Z){for(let[z,X]of this.pending)if(X.handle&&V8(X.handle,$))this.rejectPending(z,X,Z)}fail($){if(!this.closedErr)this.closedErr=$;for(let[Z,z]of this.pending)this.rejectPending(Z,z,$)}notSentCallError($,Z){return new S("not_sent",`${$}${j8(Z)}`,K8(Z),Z)}outcomeUnknownCallError($,Z){return new S("outcome_unknown",`${$}${j8(Z)}`,K8(Z),Z)}terminalCallError($,Z){if(Z instanceof S)return Z;return new S("terminal",`${$}${j8(Z)}`,K8(Z),Z)}notSentRecoveryError($,Z){if(Z instanceof S)return Z;if(H8(Z))return this.notSentCallError($,Z);return this.terminalCallError($,Z)}get droppedIngressFrames(){return this.ingressEpochDropCount}installRoute($,Z){let z=B8($,Z,this.connectionToken);return this.liveRoutes.set($,z),z}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveConnection($){if(!h0($,this.connectionToken))throw new z0($)}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new F("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.fail(z),this.sock.close(),this.scheduleReconnectAfterDrop(z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}closeConnectionAfterCleanupFailure(){let $=new F("late route cleanup could not be queued","late_route_cleanup_failed");this.fail($),this.sock.close(),this.scheduleReconnectAfterDrop($)}encode($){return Buffer.from(JSON.stringify($),"utf8")}parseJson($){let Z=$.body;return JSON.parse(Buffer.from(Z.buffer,Z.byteOffset,Z.byteLength).toString("utf8"))}}function H8($){if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof S)return $.kind==="not_sent"||$.kind==="outcome_unknown";if($ instanceof y)return!0;if($ instanceof F||$ instanceof b)return!1;let Z=K8($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function J9($){return $==="unknown_module"||$==="module_reloading"||$==="module_warming"||$==="target_unavailable"||$==="module_timeout"}function G9($){return{connectionFile:$.connectionFile,handshakeTimeoutMs:$.handshakeTimeoutMs,identity:$.identity,targetKind:$.targetKind??X9,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),timeoutArbitrationGraceMs:$.timeoutArbitrationGraceMs??e6,livenessProbeWindowMs:$.livenessProbeWindowMs??$9,onControlPush:$.onControlPush}}function Z3($,Z,z){let X=z?`${z.module_id}\x00${z.launch_nonce}`:"";return`${$.kind}\x00${$.module_id}\x00${Z.project_root}\x00${Z.harness}\x00${Z.session}\x00${X}`}function q$($={}){if($.consumerIdentity!==void 0)return $.consumerIdentity??void 0;let Z=process.env[z3],z=process.env[X3];if(!Z||!z)return;return{module_id:Z,launch_nonce:z}}function K8($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}function j8($){if($===void 0)return"";return`: ${$ instanceof Error?$.message:String($)}`}function q8($,Z){return $?`${$.channel}:${$.epoch}:${Z}`:`0:0:${Z}`}import{Buffer as N$}from"node:buffer";var Q9=1e4,Y9=30000,G3=30000,W9=250,H$=64,L$="health.check",Q3=1n;class U8{available;waiters=[];constructor($){if(!Number.isInteger($)||$<=0)throw new I("provider handler capacity must be a positive integer","invalid_handler_capacity");this.available=$}async acquire(){if(this.available>0)return this.available-=1,this.releaseOnce();return await new Promise(($)=>{this.waiters.push($)}),this.releaseOnce()}releaseOnce(){let $=!1;return()=>{if($)return;$=!0;let Z=this.waiters.shift();if(Z)Z();else this.available+=1}}}class I extends Error{code;kind;constructor($,Z,z="terminal"){super($);this.code=Z,this.kind=z}}class g0{sock;currentConn;opts;closed;resolveClosed=()=>{return};closeStarted=!1;closedErr=null;inflight=new Map;pending=new Map;liveRoutes=new Map;connectionToken=O0();nextCorr=1n;ingressEpochDropCount=0;requestGate=new U8(H$);reconnecting=null;generation=1;connectionEpoch=1;stateQueue=[];drainingStateQueue=!1;restoredDebounceToken=0;storage;constructor($,Z,z,X){this.sock=$,this.currentConn=Z,this.opts=z,this.storage=X,this.closed=new Promise((J)=>{this.resolveClosed=J}),this.readLoop($,this.generation),this.enqueueConnectionState({state:"connected",epoch:this.connectionEpoch})}get droppedIngressFrames(){return this.ingressEpochDropCount}get conn(){return this.currentConn}currentEpoch(){return this.connectionEpoch}async request($,Z,z={}){this.assertLiveHandle($);let X=this.allocateCorr(),J=N8($,X),G=z.timeoutMs??G3,Q=E(H.Request,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,X,Z);return await new Promise((Y,W)=>{let B=setTimeout(()=>{if(this.pending.delete(J))W(new I("reverse request timed out","request_timeout"))},G);this.pending.set(J,{resolve:(V)=>Y(V.body),reject:W,timer:B}),this.sendOn(this.sock,this.generation,Q).catch((V)=>{let j=this.pending.get(J);if(!j)return;this.pending.delete(J),clearTimeout(j.timer),W(V instanceof Error?V:new I(String(V)))})})}async push($,Z,z={}){this.assertLiveHandle($),await this.sendOn(this.sock,this.generation,E(H.Push,v(!1,z.priority??C.Interactive,!1,z.admissionClass??w.Normal),$.channel,$.epoch,0n,Z))}cancel($,Z){this.assertLiveHandle($),this.sendOn(this.sock,this.generation,E(H.Cancel,e(),$.channel,$.epoch,Z,new Uint8Array(0))).catch(()=>{return})}closeRoute($){this.assertLiveHandle($),this.liveRoutes.delete($.channel),this.abortHandle($),this.sendOn(this.sock,this.generation,E(H.Goodbye,e(),$.channel,$.epoch,0n,new Uint8Array(0))).catch(()=>{return})}static async connect($){if($.manifest.protocol_ver!==p)throw new I(`manifest protocol_ver ${$.manifest.protocol_ver} does not match client protocol ${p}`,"invalid_manifest");let Z=q9($),z=await g0.openConnection(Z);return new g0(z.sock,z.conn,Z,z.ack.storage)}async close(){if(!this.closeStarted){this.closeStarted=!0,this.cancelRestoredDebounce();let $=this.sock;try{await K$($,E(H.Goodbye,e(),0,0,0n,new Uint8Array(0)))}catch{}finally{$.close(),this.finishClosed()}}await this.closed}static async openConnection($,Z){let z=await P0($.connectionFile),X=Date.now()+($.handshakeTimeoutMs??Q9),J=z.endpoints[0],G=await H0.connect(J.host,J.port,X);try{Z?.(G),await v0(G,z,X),await K$(G,K9($));let Q=await D9(G,X);return{sock:G,conn:z,ack:Q}}catch(Q){throw G.close(),Q}}async readLoop($,Z){try{for(;;){let z=await $.readFrame(Number.POSITIVE_INFINITY,{afterHeaderMs:Y9});if(!await this.dispatch(z,$,Z)){if(this.sock===$&&this.generation===Z)this.closeStarted=!0;break}}}catch(z){if(this.sock===$&&this.generation===Z&&!this.closeStarted){this.handleUnexpectedDrop($,Z,z instanceof Error?z:new I(String(z)));return}}finally{if(this.sock===$&&this.generation===Z){if($.close(),this.closeStarted)this.finishClosed()}}}async dispatch($,Z,z){let X=null;if($.header.channel!==0){if(X=this.liveRoutes.get($.header.channel)??null,!X||X.epoch!==$.header.epoch)return this.ingressEpochDropCount+=1,!0}if(X){let J=N8(X,$.header.corr),G=this.pending.get(J);if(G){if($.header.ty===H.Push||$.header.ty===H.StreamData)return!0;if($.header.ty===H.Response||$.header.ty===H.StreamEnd)return this.pending.delete(J),clearTimeout(G.timer),G.resolve($),!0;if($.header.ty===H.Error)return this.pending.delete(J),clearTimeout(G.timer),G.reject(B9($)),!0}}switch($.header.ty){case H.Ping:if($.header.channel===0)await this.sendOn(Z,z,a($.header.ver,H.Pong,$.header.flags,0,0,$.header.corr,new Uint8Array(0)));return!0;case H.Goodbye:if(!X)return!1;return this.liveRoutes.delete(X.channel),this.abortHandle(X),await this.opts.onRouteGone?.(X),!0;case H.Cancel:if(X)this.inflight.get(N8(X,$.header.corr))?.abort();return!0;case H.Request:if($.header.channel===0)await this.handleControlRequest($,Z,z);else if(X)this.handleDataRequest($,X,Z,z).catch((J)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider handler failed after its request was dispatched",J)});return!0;default:return!0}}abortHandle($){let Z=`${$.channel}:${$.epoch}:`;for(let[z,X]of this.inflight)if(z.startsWith(Z))X.abort();for(let[z,X]of this.pending){if(!z.startsWith(Z))continue;this.pending.delete(z),clearTimeout(X.timer),X.reject(new z0($))}}abortGeneration($){this.abortAllInflight();for(let[Z,z]of this.pending)this.pending.delete(Z),clearTimeout(z.timer),z.reject(new I("provider connection dropped","connection_dropped"));this.liveRoutes.clear()}abortAllInflight(){for(let $ of this.inflight.values())$.abort()}async handleControlRequest($,Z,z){let X=P8($.body);if(X.op===L$){this.handleHealthRequest($,Z,z).catch((j)=>{if(!this.closeStarted&&this.sock===Z&&this.generation===z)console.warn("SubcProvider health handler failed after its request was dispatched",j)});return}if(X.op!=="route.bind")throw new I(`unsupported module control request ${X.op??"<missing op>"}`);let J=J3(X.route_channel,"route_channel"),G=J3(X.epoch,"epoch"),Q=this.liveRoutes.get(J);if(Q){if(G<=Q.epoch){await this.sendError($,"route_rejected",`route.bind epoch ${G} does not supersede installed epoch ${Q.epoch} on channel ${J}`,e(),Z,z);return}this.liveRoutes.delete(Q.channel),this.abortHandle(Q),await this.opts.onRouteGone?.(Q)}let Y=B8(J,G,this.connectionToken),W={handle:Y,target:X.target,identity:X.identity,principal:X.principal,consumer_capabilities:X.consumer_capabilities},B;try{B=await this.opts.onBind?.(W)}catch(j){try{await this.sendError($,"route_rejected",j instanceof Error?j.message:String(j),e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}let V=P9(B);if(V){try{await this.sendError($,V.code,V.message,e(),Z,z)}finally{await this.opts.onRouteGone?.(Y)}return}try{await this.sendOn(Z,z,a($.header.ver,H.Response,e(),0,0,$.header.corr,D8({op:"route.bind"})))}catch(j){throw await this.opts.onRouteGone?.(Y),j}if(this.sock!==Z||this.generation!==z||this.closeStarted||this.closedErr){await this.opts.onRouteGone?.(Y);return}this.liveRoutes.set(Y.channel,Y),await this.opts.onBound?.(Y)}async handleDataRequest($,Z,z,X){let{corr:J,ver:G}=$.header,Q=N8(Z,J),Y=new AbortController;this.inflight.set(Q,Y);let W={handle:Z,signal:Y.signal,currentEpoch:()=>this.connectionEpoch,emit:async(j,q={})=>{if(this.assertLiveHandle(Z),Y.signal.aborted)return;await this.sendOn(z,X,a(G,H.StreamData,v(!1,q.priority??C.Interactive,!1,q.admissionClass??w.Normal),Z.channel,Z.epoch,J,j))}},B=await(this.requestGate??new U8(H$)).acquire(),V=v(!1,C.Interactive,!1);try{if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}let j=await this.opts.handler(Z,$.body,W);if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}if(this.assertLiveHandle(Z),j===void 0)await this.sendOn(z,X,a(G,H.StreamEnd,V,Z.channel,Z.epoch,J,new Uint8Array(0)));else if(j instanceof Uint8Array)await this.sendOn(z,X,a(G,H.Response,V,Z.channel,Z.epoch,J,j));else throw new I("provider handler must return a Uint8Array or void","invalid_handler_response")}catch(j){if(j instanceof z0)return;if(Y.signal.aborted){await this.sendError($,"cancelled","request cancelled",V,z,X);return}await this.sendError($,j instanceof I&&j.code?j.code:"handler_error",j instanceof Error?j.message:String(j),V,z,X)}finally{if(B(),this.inflight.get(Q)===Y)this.inflight.delete(Q)}}async handleHealthRequest($,Z,z){let{corr:X,ver:J}=$.header,G=`control:${z}:${X}`,Q=new AbortController;this.inflight.set(G,Q);let Y=await(this.requestGate??new U8(H$)).acquire();try{if(Q.signal.aborted)return;let W=await this.opts.health();await this.sendOn(Z,z,a(J,H.Response,e(),0,0,X,D8({op:L$,status:W.status,...W.detail===void 0?{}:{detail:W.detail},...W.metrics===void 0?{}:{metrics:W.metrics}})))}catch(W){await this.sendError($,W instanceof I&&W.code?W.code:"health_error",W instanceof Error?W.message:String(W),e(),Z,z)}finally{if(Y(),this.inflight.get(G)===Q)this.inflight.delete(G)}}async sendError($,Z,z,X,J,G){if($.header.channel!==0){let Q=this.liveRoutes.get($.header.channel);if(!Q||Q.epoch!==$.header.epoch||!this.isLiveHandle(Q))return}await this.sendOn(J,G,a($.header.ver,H.Error,X,$.header.channel,$.header.epoch,$.header.corr,D8({code:Z,message:z})))}async sendOn($,Z,z){if(this.sock!==$||this.generation!==Z||this.closeStarted||this.closedErr)return;await K$($,z)}handleUnexpectedDrop($,Z,z){if(this.closeStarted||this.sock!==$||this.generation!==Z)return;this.cancelRestoredDebounce(),this.abortGeneration(Z),this.generation+=1,$.close(),this.scheduleReconnectAfterDrop(z,this.generation,$)}scheduleReconnectAfterDrop($,Z,z){if(this.closeStarted)return;let X=this.reconnecting;if(X){if(!this.shouldSupersedeReconnect(X,Z,z))return;X.superseded=!0,X.socket?.close()}let J={generation:Z,socket:null,socketDied:!1,superseded:!1};this.reconnecting=J,this.enqueueConnectionState({state:"down",cause:$}),this.reconnectWithRetry(J).catch((G)=>{if(this.isCurrentReconnect(J)&&!this.closeStarted)this.failFatal(G instanceof Error?G:new I(String(G)))}).finally(()=>{if(this.isCurrentReconnect(J))this.reconnecting=null})}async reconnectWithRetry($){let Z=0,z=this.opts.reconnectBackoff.baseMs;for(;;){if(!this.isCurrentReconnect($))return;if(this.closeStarted)throw new I("provider closed");$.socket=null,$.socketDied=!1,Z+=1,this.enqueueReconnectState($,Z);try{let X=await g0.openConnection(this.opts,(G)=>{if(!this.isCurrentReconnect($)){G.close();return}$.socket=G});if(!this.isCurrentReconnect($)||this.closeStarted){if(X.sock.close(),this.closeStarted)throw new I("provider closed");return}let J=this.replaceConnection(X,$.generation);if(this.reconnecting=null,this.reconnecting!==null)throw new I("reconnect state must clear before restored","reconnect_state");this.scheduleRestored($.generation,J);return}catch(X){if(!this.isCurrentReconnect($))return;if($.socket)$.socketDied=!0;if(this.closeStarted)throw X;if(!L9(X))throw X;await this.opts.sleep(z),z=Math.min(z*2,this.opts.reconnectBackoff.capMs)}}}isCurrentReconnect($){return!$.superseded&&this.reconnecting===$&&this.generation===$.generation}shouldSupersedeReconnect($,Z,z){return $.generation<Z||$.socketDied||$.socket===z}enqueueReconnectState($,Z){if(!this.isCurrentReconnect($))return;this.enqueueConnectionState({state:"reconnecting",attempt:Z},$.generation,$)}replaceConnection($,Z){return this.sock.close(),this.sock=$.sock,this.currentConn=$.conn,this.storage=$.ack.storage,this.closedErr=null,this.connectionEpoch+=1,this.connectionToken=O0(),this.liveRoutes.clear(),this.nextCorr=1n,this.readLoop($.sock,Z),this.connectionEpoch}scheduleRestored($,Z){if(!this.opts.onConnectionState)return;let z=++this.restoredDebounceToken;this.opts.sleep(this.opts.restoredDebounceMs).then(()=>{if(z===this.restoredDebounceToken&&!this.closeStarted&&this.sock&&this.generation===$&&this.connectionEpoch===Z)this.enqueueConnectionState({state:"restored",epoch:Z},$)}).catch((X)=>{if(z===this.restoredDebounceToken&&!this.closeStarted)console.warn("SubcProvider restored debounce timer failed",X)})}cancelRestoredDebounce(){this.restoredDebounceToken+=1}enqueueConnectionState($,Z,z){if(!this.opts.onConnectionState)return;if(this.stateQueue.push({event:$,generation:Z,reconnect:z}),!this.drainingStateQueue)this.drainConnectionStateQueue()}async drainConnectionStateQueue(){if(this.drainingStateQueue)return;this.drainingStateQueue=!0;try{while(this.stateQueue.length>0){let $=this.stateQueue[0];if(this.closeStarted||$.generation!==void 0&&$.generation!==this.generation||$.reconnect?.superseded){this.stateQueue.shift();continue}let{event:Z}=$;try{await this.opts.onConnectionState?.(Z),this.stateQueue.shift()}catch(z){if(Z.state==="restored"){console.warn("SubcProvider restored callback failed; retrying delivery",z),await U9();continue}console.warn("SubcProvider connection-state callback failed",z),this.stateQueue.shift()}}}finally{if(this.drainingStateQueue=!1,this.stateQueue.length>0)this.drainConnectionStateQueue()}}isLiveHandle($){return h0($,this.connectionToken)&&this.liveRoutes.get($.channel)===$}assertLiveHandle($){if(!this.isLiveHandle($))throw new z0($)}allocateCorr(){let $=0xffffffffffffffffn;if(this.nextCorr>$){let z=new I("channel-0 correlation id allocator exhausted","corr_exhausted");throw this.handleUnexpectedDrop(this.sock,this.generation,z),z}let Z=this.nextCorr;return this.nextCorr+=1n,Z}failFatal($){if(!this.closedErr)this.closedErr=$;this.closeStarted=!0,this.cancelRestoredDebounce(),this.abortAllInflight(),this.sock.close(),this.finishClosed()}finishClosed(){this.resolveClosed()}}function N8($,Z){return`${$.channel}:${$.epoch}:${Z}`}function B9($){try{let Z=P8($.body);return new I(Z.message??"subc error",Z.code,Z.code==="stale_route_epoch"||Z.code==="unknown_channel"?"not_sent":"terminal")}catch{return new I(N$.from($.body).toString("utf8")||"subc error")}}function V9($){let Z=$.launchNonce??process.env[j9];return Z&&Z.length>0?Z:void 0}var j9="SUBC_LAUNCH_NONCE";function q9($){return{connectionFile:$.connectionFile,manifest:$.manifest,handler:$.handler,health:$.health??(()=>({status:"ok"})),handshakeTimeoutMs:$.handshakeTimeoutMs,controlOps:$.controlOps,onBind:$.onBind,onBound:$.onBound,onRouteGone:$.onRouteGone,reconnectBackoff:$.reconnectBackoff??L8,sleep:$.sleep??((Z)=>new Promise((z)=>setTimeout(z,Z))),restoredDebounceMs:$.restoredDebounceMs??W9,onConnectionState:$.onConnectionState,launchNonce:$.launchNonce}}function H9($){if($===null)return null;let Z=new Set($??[]);return Z.add(L$),[...Z]}function K9($){let Z=V9($);return E(H.Hello,e(),0,0,Q3,D8({manifest:O9($.manifest),protocol_ver:p,control_ops:H9($.controlOps),...Z?{launch_nonce:Z}:{}}))}function L9($){if($ instanceof I)return $.code==="duplicate_module_id";if($ instanceof Z0||$ instanceof s)return!0;if($ instanceof o||$ instanceof Q0)return!0;if($ instanceof y)return!0;if($ instanceof b)return!1;let Z=N9($);return Z==="ECONNREFUSED"||Z==="ECONNRESET"||Z==="EPIPE"||Z==="ETIMEDOUT"||Z==="ENOENT"}function N9($){if(typeof $==="object"&&$!==null&&"code"in $){let Z=$.code;if(typeof Z==="string")return Z}return}async function U9(){await new Promise(($)=>setTimeout($,0))}function e(){return v(!1,C.Passive,!1)}async function K$($,Z){await r($,t(Z),Date.now()+G3)}async function D9($,Z){let z=await $.readFrame(Z,Z);switch(z.header.ty){case H.HelloAck:{let X=P8(z.body);if(X.negotiated_ver!==p)throw new I(`subc negotiated protocol ${X.negotiated_ver}; expected exactly ${p}`,"unsupported_version");return X}case H.Error:{let X=P8(z.body);throw new I(`subc rejected HELLO: ${X.code??"unknown"} — ${X.message??"subc error"}`,X.code)}default:throw new I(`unexpected frame ${H[z.header.ty]} awaiting HELLO_ACK`)}}function D8($){return new Uint8Array(N$.from(JSON.stringify($),"utf8"))}function P8($){return JSON.parse(N$.from($).toString("utf8"))}function J3($,Z){if(typeof $!=="number"||!Number.isInteger($))throw new I(`route.bind ${Z} must be an integer`);return $}function P9($){if($===void 0||$===!0)return null;if($===!1)return{code:"route_rejected",message:"route.bind rejected by provider"};if($.accept)return null;return{code:$.code??"route_rejected",message:$.message??"route.bind rejected by provider"}}function O9($){return{module_id:$.module_id,module_version:$.module_version,protocol_ver:$.protocol_ver,trust_tier:$.trust_tier,provides:$.provides.map(M9),consumes:$.consumes.map(_9),bindings:{storage:{kind:$.bindings.storage.kind,scope:$.bindings.storage.scope,owns_schema:$.bindings.storage.owns_schema},vault_grants:$.bindings.vault_grants.map((Z)=>({secret:Z.secret,reason:Z.reason})),identity:{requires:[...$.bindings.identity.requires],optional:[...$.bindings.identity.optional]}}}}function M9($){switch($.role){case"tool_provider":return{role:"tool_provider",tools:$.tools.map((Z)=>({name:Z.name,...Z.description===void 0?{}:{description:Z.description},execution_mode:Z.execution_mode,schema:Z.schema})),identity_scope:[...$.identity_scope],concurrency:$.concurrency,emits_push:$.emits_push,sub_supervises:$.sub_supervises};case"pipeline_stage":return{role:"pipeline_stage",stage:$.stage,applies_to:{provider:$.applies_to.provider,model:$.applies_to.model},interface:$.interface,declares_frozen_floor:$.declares_frozen_floor,needs_signals:[...$.needs_signals],conformance_class:$.conformance_class};case"management_surface":return{role:"management_surface",operations:$.operations.map((Z)=>({name:Z.name,kind:Z.kind})),config_schema:$.config_schema,observability:$.observability.map((Z)=>({name:Z.name,kind:Z.kind})),identity_scope:[...$.identity_scope],concurrency:$.concurrency};case"internal_service":return{role:"internal_service",service_id:$.service_id,transport:$.transport,agent_facing:$.agent_facing,operations:[...$.operations]}}}function _9($){switch($.role){case"tool_client":return{role:"tool_client",of:[...$.of]};case"llm_client":return{role:"llm_client",via:$.via,auth:$.auth};case"service_client":return{role:"service_client",of:[...$.of]}}}var O8="subc-connection.json",A9="subc-",T9=".connection.json";function Y3(){let $=process.env.HOME;return $?p0($,".local","share","cortexkit","run",O8):void 0}function C9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($)return p0($,O8);let Z=Y3();if(Z)return Z;return p0(R9().homedir,".local","share","cortexkit","run",O8)}function b9(){let $=process.env.XDG_RUNTIME_DIR?.trim();if($){let X=p0($,O8);if(U$(X))return X}let Z=Y3();if(Z&&U$(Z))return Z;let z=S9(I9());return z.length===1?z[0]:void 0}function D$(){return b9()??C9()}function P$($){return $?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||D$()}function U$($){try{return F9($).isFile()}catch{return!1}}function S9($){let Z;try{Z=x9($)}catch{return[]}let z=[];for(let X of Z){if(typeof X!=="string")continue;if(!X.startsWith(A9)||!X.endsWith(T9))continue;let J=p0($,X);if(U$(J))z.push(J)}return z.sort(),z}import{createHash as k9}from"node:crypto";import{existsSync as w9,realpathSync as W3}from"node:fs";import{dirname as f9,relative as E9,resolve as y9}from"node:path";function B3($){let Z=$,z;try{z=W3(Z)}catch(X){if(X.code!=="ENOENT")throw X;let J=Z;while(!w9(J)){let G=f9(J);if(G===J)break;J=G}z=y9(W3(J),E9(J,Z))}return k9("sha256").update(z).digest("hex")}function O$($,Z){return{project_root:$,harness:"opencode",session:`store-${B3(Z)}`}}var V3=["transient","permanent","auth_required","context_overflow"];class _0 extends Error{code;action;["class"];constructor($,Z,z){super(`Claustrum credential request failed: ${$}`);this.code=$,this.action=z,this.name="ClaustrumCredentialError",this.class=Z}}function M0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function j3($){switch($){case"permanent":return"gone";case"auth_required":return"reauth";case"context_overflow":return"reduce_and_retry";case"transient":return"retry"}}function M($,Z="invalid_response",z=(X)=>console.warn(X)){let X=M0($)&&M0($.result)?$.result:void 0,J=X&&M0(X.error)?X.error:void 0,G=J?.class,Q=J?.code,Y=typeof G==="string"&&V3.includes(G),W=typeof Q==="string",V=Y&&W?G:"transient";if(typeof G!=="string")z("unknown");else if(!Y)z(G);return new _0(W?Q:Z,V,j3(V))}function L0($){return M0($)&&M0($.result)&&M0($.result.error)}var q3="claustrum",m9=60000;function u($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function _$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0?$:void 0}function X0($){return $===void 0||typeof $==="string"}function H3($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.payload;if(!Array.isArray(X)||X.length===0||!X.every((q)=>typeof q==="number"&&Number.isInteger(q)&&q>=0&&q<=255))throw M($,"invalid_response",Z);let J=_$(z?.record_version);if(J===void 0)throw M($,"invalid_record_version",Z);let G=z?.expires_at_ms,Q=G===void 0||G===null?null:typeof G==="number"&&Number.isFinite(G)?G:void 0;if(Q===void 0)throw M($,"invalid_expiry",Z);let Y=z?.credential_id,W=z?.project_id,B=z?.account_id,V=z?.email,j=z?.org_name;if(!X0(Y)||!X0(W)||!X0(B)||!X0(V)||!X0(j))throw M($,"invalid_response",Z);return{material:new TextDecoder().decode(Uint8Array.from(X)),recordVersion:J,expiresAtMs:Q,credentialId:Y,projectId:W,accountId:B,email:V,orgName:j}}function g9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=_$(z?.record_version);if(typeof z?.ready!=="boolean"||z?.last_error_code!==void 0&&z?.last_error_code!==null&&typeof z?.last_error_code!=="string"||typeof z?.lease_held!=="boolean"||X===void 0||z?.stale_pending!==void 0&&typeof z.stale_pending!=="boolean")throw M($,"invalid_status",Z);return{ready:z.ready,lastErrorCode:z.last_error_code??null,leaseHeld:z.lease_held,recordVersion:X,...z.stale_pending===void 0?{}:{stalePending:z.stale_pending}}}class M8{#z;#J;#B;#Y;#G;#$;#X=null;#Q=0;#W=!1;constructor($,Z,z,X,J,G){this.#z=$,this.#J=Z,this.#B=z,this.#Y=X,this.#G=J,this.#$=G}static async connect($={}){let Z=P$($.connectionFile),z=$.connector??((G)=>K0.connect(G)),X=$.identity??O$($.projectRoot??process.cwd(),$.storagePath??process.cwd()),J=await z({connectionFile:Z,handshakeTimeoutMs:$.handshakeTimeoutMs});return new M8(J,z,Z,$.handshakeTimeoutMs,X,$.logger??((G)=>console.warn(G)))}async getCredential($,Z){let z=await this.#Z("credential.get",{handle:$,min_ttl_ms:Z,force_refresh:!1});return H3(z,this.#$)}async statusCredential($){let Z=await this.#Z("credential.status",{handle:$});return g9(Z,this.#$)}async reportAuthFailure($){let Z=await this.#Z("credential.report_auth_failure",{handle:$.handle,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async listScoped($){let Z=await this.#Z("credential.list_scoped",$===void 0?{}:{enrollment_token:$});return p9(Z,this.#$)}async getScoped($){let Z=await this.#Z("credential.get_scoped",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,min_ttl_ms:$.minTtlMs});return H3(Z,this.#$)}async reportAuthFailureScoped($){let Z=await this.#Z("credential.report_auth_failure",{credential_id:$.credentialId,enrollment_token:$.enrollmentToken,provider_status:$.providerStatus,record_version:$.recordVersion,reporter_source:$.reporterSource});if(L0(Z))throw M(Z,"invalid_response",this.#$);if((u(Z)&&u(Z.result)?Z.result:void 0)?.accepted!==!0)throw M(Z,"invalid_response",this.#$)}async enrollPropose($){let Z=await this.#Z("auth.enroll_propose",{proposed_name:$.name,request_secret_hash:$.requestSecretHash}),X=M$(Z,this.#$).request_id;if(typeof X!=="string"||X.length===0)throw M(Z,"invalid_response",this.#$);return{requestId:X}}async enrollPoll($){let Z=await this.#Z("auth.enroll_poll",{request_id:$.requestId,request_secret:$.requestSecret});return u9(Z,this.#$)}async enrollRotate($){let Z=await this.#Z("auth.enroll_rotate",{token:$.token,expected_token_generation:$.expectedTokenGeneration}),z=M$(Z,this.#$),X=z.token,J=z.token_generation;if(typeof X!=="string"||X.length===0||typeof J!=="number")throw M(Z,"invalid_response",this.#$);return{token:X,tokenGeneration:J}}close(){this.#W=!0,this.#z.close()}async#Z($,Z){try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(z){if(this.#j(z)){try{await this.#q()}catch(X){throw this.#V(X)}try{return await this.#z.call(q3,$,Z,{identity:this.#G,consumerIdentity:null})}catch(X){throw this.#V(X)}}throw this.#V(z)}}#V($){if($ instanceof _0)return $;let Z=$ instanceof S&&$.code?$.code:"transport_error";return new _0(Z,"transient","retry")}#j($){return!this.#W&&$ instanceof S&&$.kind==="terminal"&&$.code!=="missing_identity"&&$.code!=="invalid_control_body"}async#q(){if(this.#W)throw Error("Claustrum client is closed");if(this.#X){await this.#X;return}let $=Date.now();if($<this.#Q)throw Error("Claustrum client reconnect is backed off");this.#Q=$+m9,this.#X=this.#J({connectionFile:this.#B,handshakeTimeoutMs:this.#Y}).then((Z)=>{if(this.#W)throw Z.close(),Error("Claustrum client is closed");let z=this.#z;this.#z=Z,z.close()}).finally(()=>{this.#X=null}),await this.#X}}function p9($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0,X=z?.credentials;if(!Array.isArray(X))throw M($,"invalid_response",Z);let J=z?.view;if(typeof J!=="string"||J.length===0)throw M($,"invalid_response",Z);return{rows:X.map((Q)=>{if(!u(Q))throw M($,"invalid_response",Z);let Y=_$(Q.record_version);if(Y===void 0)throw M($,"invalid_record_version",Z);let W=(V)=>{if(!Array.isArray(V)||!V.every((j)=>typeof j==="string"))throw M($,"invalid_response",Z);return V};if(typeof Q.id!=="string"||typeof Q.type!=="string"||typeof Q.state!=="string")throw M($,"invalid_response",Z);let B=Q.created_at_ms===void 0||Q.created_at_ms===null?null:typeof Q.created_at_ms==="number"&&Number.isFinite(Q.created_at_ms)?Q.created_at_ms:void 0;if(B===void 0)throw M($,"invalid_response",Z);if(!X0(Q.refresh_adapter))throw M($,"invalid_response",Z);if(!X0(Q.account_id)||!X0(Q.email)||!X0(Q.org_name))throw M($,"invalid_response",Z);return{id:Q.id,categories:W(Q.categories),credentialType:Q.type,serves:W(Q.serves),state:Q.state,refreshAdapter:Q.refresh_adapter,recordVersion:Y,operations:W(Q.operations),createdAtMs:B,accountId:Q.account_id,email:Q.email,orgName:Q.org_name}}),view:J}}function M$($,Z){if(L0($))throw M($,"invalid_response",Z);let z=u($)&&u($.result)?$.result:void 0;if(z===void 0)throw M($,"invalid_response",Z);return z}function u9($,Z){let z=M$($,Z),X=z.status;if(X==="pending")return{status:"pending"};if(X==="denied")return{status:"denied"};if(X!=="approved")throw M($,"invalid_response",Z);let{name:J,token:G,token_generation:Q}=z;if(typeof J!=="string"||typeof G!=="string"||G.length===0||typeof Q!=="number"||!Number.isInteger(Q))throw M($,"invalid_response",Z);return{status:"approved",name:J,token:G,tokenGeneration:Q}}l8();var VZ=d("quota");var K3={name:"@cortexkit/pi-openai-auth",version:"0.10.0",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --minify && bun run build:types","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/openai-auth-core":"workspace:*"},peerDependencies:{"@earendil-works/pi-ai":">=0.80.10","@earendil-works/pi-coding-agent":">=0.80.10","@earendil-works/pi-tui":">=0.80.10"}};import{homedir as i9}from"node:os";import{join as L3}from"node:path";function c9(){return process.env.PI_AGENT_DIR?.trim()||L3(i9(),".pi","agent")}function N3(){return process.env.PI_OPENAI_AUTH_FILE?.trim()||L3(c9(),n0)}function s9($=N3()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||g8($)}function U3($=N3()){return{configPath:$,statePath:s9($)}}var D3=new Map;function P3($){return D3.get($)}function O3($){return D3.delete($)}var n9={auth:{set:async()=>{}}};async function a9($,Z){let z=(Z.accountPaths??U3)(),X=Z.loadAccounts??B1,J=await X(z),G=new n({storage:null,configPath:z.configPath,fetchImpl:Z.fetchImpl,now:Z.now});return G.seedFallbacksFromAccounts((J?.accounts??[]).filter(m8)),{accountStoragePath:z.configPath,accountStatePath:z.statePath,packageVersion:Z.packageVersion??K3.version,quotaManager:G,loadAccounts:X,client:n9,sessionId:$.sessionManager.getSessionId(),notify:(Q)=>$.ui.notify(Q.text),clearStickyRouting:async(Q)=>O3(Q),getStickyRouting:async(Q)=>P3(Q),fetchImpl:Z.fetchImpl,now:Z.now,randomUUID:Z.randomUUID,beginAccountLogin:Z.beginAccountLogin}}async function t9($,Z,z,X={}){return z$($,Z,await a9(z,X))}async function x$($,Z,z,X){let J=await t9($,Z,z,X);z.ui.notify(J.text)}function M3($,Z={}){$.registerCommand(X8,{description:"List, add, remove, or reorder OpenAI fallback accounts",handler:(z,X)=>x$(X8,z,X,Z)}),$.registerCommand(z8,{description:"Show persisted OpenAI quota for fallback accounts",handler:(z,X)=>x$(z8,z,X,Z)}),$.registerCommand(J8,{description:"Show or change OpenAI account routing mode",handler:(z,X)=>x$(J8,z,X,Z)})}import{connect as o9}from"node:net";import{connect as r9}from"node:tls";var e9="258EAFA5-E914-47DA-95CA-C5AB0DC85B11",_3=["chatgpt-account-id","authorization","user-agent","originator","openai-beta","version","x-codex-beta-features","x-codex-turn-metadata","x-client-request-id","session-id","thread-id","x-codex-window-id"];class F${url;readyState=0;socket;listeners={open:new Set,message:new Set,error:new Set,close:new Set};rxBuffer=new Uint8Array(0);handshakeDone=!1;expectedAccept="";fragOpcode=0;fragChunks=[];constructor($,Z){this.url=$,this.connect($,Z)}addEventListener($,Z,z){this.listeners[$]?.add(Z)}removeEventListener($,Z){this.listeners[$]?.delete(Z)}emit($,Z){for(let z of[...this.listeners[$]??[]])try{z(Z)}catch{}}async connect($,Z){let z=new URL($.replace(/^ws:/,"http:").replace(/^wss:/,"https:")),X=z.hostname,J=z.port?Number(z.port):z.protocol==="https:"?443:80,G=`${z.pathname}${z.search}`,Q=crypto.getRandomValues(new Uint8Array(16)),Y=Buffer.from(Q).toString("base64"),W=await crypto.subtle.digest("SHA-1",new TextEncoder().encode(Y+e9));this.expectedAccept=Buffer.from(new Uint8Array(W)).toString("base64");let B={};for(let[q,K]of Object.entries(Z))B[q.toLowerCase()]=K;let V=[`GET ${G} HTTP/1.1`,`Host: ${X}`,"Connection: Upgrade","Upgrade: websocket","Sec-WebSocket-Version: 13",`Sec-WebSocket-Key: ${Y}`];for(let q of _3)if(B[q]!==void 0)V.push(`${$2(q)}: ${B[q]}`);for(let[q,K]of Object.entries(Z))if(!_3.includes(q.toLowerCase())&&q.toLowerCase()!=="content-length")V.push(`${q}: ${K}`);let j=`${V.join(`\r
|
|
211
211
|
`)}\r
|
|
212
212
|
\r
|
|
213
|
-
`;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let q=()=>{this.socket?.write(j)},K=z.protocol==="https:"?
|
|
213
|
+
`;try{this.log("connect_start",{host:X,port:J,tls:z.protocol==="https:"});let q=()=>{this.socket?.write(j)},K=z.protocol==="https:"?r9({host:X,port:J,servername:X},q):o9({host:X,port:J},q);this.socket=K,K.on("data",(L)=>{this.onData(typeof L==="string"?Buffer.from(L,"binary"):L)}),K.on("error",(L)=>{this.readyState=3;let U=L instanceof Error?L.message:String(L);this.log("socket_error",{message:U}),this.emit("error",{message:U})}),K.on("close",(L)=>{this.readyState=3,this.log("socket_close",{hadError:L}),this.emit("close",{code:1006,reason:"socket closed"})})}catch(q){this.readyState=3,this.log("connect_exception",{message:q instanceof Error?q.message:String(q)}),this.emit("error",{message:q instanceof Error?q.message:String(q)})}}onData($){if(this.rxBuffer=Z2(this.rxBuffer,$),!this.handshakeDone){let Z=Buffer.from(this.rxBuffer).toString("latin1"),z=Z.indexOf(`\r
|
|
214
214
|
\r
|
|
215
215
|
`);if(z===-1)return;let X=Z.slice(0,z),J=X.split(`\r
|
|
216
|
-
`)[0]??"",G=X.match(/sec-websocket-accept:\s*(\S+)/i);if(!J.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:J}),this.emit("error",{message:`WS upgrade failed: ${J}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:J}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(z+4),this.log("open",{statusLine:J}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],z=$[1],X=(Z&128)!==0,J=Z&15,G=(z&128)!==0,Q=z&127,Y=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],Y=4}else if(Q===127){if($.length<10)return;Q=0;for(let B=0;B<8;B++)Q=Q*256+$[2+B];Y=10}if(G)Y+=4;if($.length<Y+Q)return;let W=$.slice(Y,Y+Q);this.rxBuffer=$.slice(Y+Q),this.handleFrame(X,J,W)}}handleFrame($,Z,z){if(Z===9){this.writeFrame(10,z);return}if(Z===10)return;if(Z===8){let J=1005,G="";if(z.length>=2)J=z[0]<<8|z[1],G=Buffer.from(z.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:J,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[z];else if(Z===0)this.fragChunks.push(z);if(!$)return;let X=z2(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let J=Buffer.from(X).toString("utf-8");this.emit("message",{data:J})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let z=Z.length,X=crypto.getRandomValues(new Uint8Array(4)),J;if(z<126)J=[128|$,128|z];else if(z<65536)J=[128|$,254,z>>8&255,z&255];else{J=[128|$,255];for(let Y=7;Y>=0;Y--)J.push(z/2**(8*Y)&255)}let G=new Uint8Array(z);for(let Y=0;Y<z;Y++)G[Y]=Z[Y]^X[Y%4];let Q=new Uint8Array(J.length+4+z);Q.set(J,0),Q.set(X,J.length),Q.set(G,J.length+4);try{this.socket?.write(Q)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function $2($){return $}function Z2($,Z){let z=new Uint8Array($.length+Z.length);return z.set($,0),z.set(Z,$.length),z}function z2($){let Z=0;for(let J of $)Z+=J.length;let z=new Uint8Array(Z),X=0;for(let J of $)z.set(J,X),X+=J.length;return z}var l0="https://chatgpt.com/backend-api";class
|
|
216
|
+
`)[0]??"",G=X.match(/sec-websocket-accept:\s*(\S+)/i);if(!J.includes(" 101")){this.readyState=3,this.socket?.destroy?.(),this.log("upgrade_failed",{statusLine:J}),this.emit("error",{message:`WS upgrade failed: ${J}`});return}if(!G||G[1]!==this.expectedAccept){this.readyState=3,this.socket?.destroy?.(),this.log("accept_mismatch",{statusLine:J}),this.emit("error",{message:"WS upgrade Sec-WebSocket-Accept mismatch"});return}this.handshakeDone=!0,this.readyState=1,this.rxBuffer=this.rxBuffer.slice(z+4),this.log("open",{statusLine:J}),this.emit("open",{})}this.drainFrames()}drainFrames(){for(;;){let $=this.rxBuffer;if($.length<2)return;let Z=$[0],z=$[1],X=(Z&128)!==0,J=Z&15,G=(z&128)!==0,Q=z&127,Y=2;if(Q===126){if($.length<4)return;Q=$[2]<<8|$[3],Y=4}else if(Q===127){if($.length<10)return;Q=0;for(let B=0;B<8;B++)Q=Q*256+$[2+B];Y=10}if(G)Y+=4;if($.length<Y+Q)return;let W=$.slice(Y,Y+Q);this.rxBuffer=$.slice(Y+Q),this.handleFrame(X,J,W)}}handleFrame($,Z,z){if(Z===9){this.writeFrame(10,z);return}if(Z===10)return;if(Z===8){let J=1005,G="";if(z.length>=2)J=z[0]<<8|z[1],G=Buffer.from(z.slice(2)).toString("utf-8");this.readyState=3;try{this.socket?.end()}catch{}this.emit("close",{code:J,reason:G});return}if(Z===1||Z===2)this.fragOpcode=Z,this.fragChunks=[z];else if(Z===0)this.fragChunks.push(z);if(!$)return;let X=z2(this.fragChunks);if(this.fragChunks=[],this.fragOpcode===1){let J=Buffer.from(X).toString("utf-8");this.emit("message",{data:J})}}send($){if(this.readyState!==1)return;this.writeFrame(1,new TextEncoder().encode($))}writeFrame($,Z){let z=Z.length,X=crypto.getRandomValues(new Uint8Array(4)),J;if(z<126)J=[128|$,128|z];else if(z<65536)J=[128|$,254,z>>8&255,z&255];else{J=[128|$,255];for(let Y=7;Y>=0;Y--)J.push(z/2**(8*Y)&255)}let G=new Uint8Array(z);for(let Y=0;Y<z;Y++)G[Y]=Z[Y]^X[Y%4];let Q=new Uint8Array(J.length+4+z);Q.set(J,0),Q.set(X,J.length),Q.set(G,J.length+4);try{this.socket?.write(Q)}catch{}}close(){if(this.readyState===3)return;this.readyState=2;try{this.writeFrame(8,new Uint8Array([3,232])),this.socket?.end()}catch{}this.readyState=3}log($,Z){return Promise.resolve()}}function $2($){return $}function Z2($,Z){let z=new Uint8Array($.length+Z.length);return z.set($,0),z.set(Z,$.length),z}function z2($){let Z=0;for(let J of $)Z+=J.length;let z=new Uint8Array(Z),X=0;for(let J of $)z.set(J,X),X+=J.length;return z}var l0="https://chatgpt.com/backend-api";class R$ extends F${constructor($,Z){let z=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z.headers??{}:{};super(String($),z)}}var u0=0,I$;function G2(){let $=globalThis;if(u0===0)I$=$.WebSocket,$.WebSocket=R$;return u0++,()=>{if(u0=Math.max(0,u0-1),u0===0){if($.WebSocket===R$)$.WebSocket=I$;I$=void 0}}}var Q2=[{id:"gpt-5.5",name:"GPT-5.5",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:5,output:30,cacheRead:0.5,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4",name:"GPT-5.4",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:2.5,output:15,cacheRead:0.25,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.4-mini",name:"GPT-5.4 mini",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text","image"],cost:{input:0.75,output:4.5,cacheRead:0.075,cacheWrite:0},contextWindow:272000,maxTokens:128000},{id:"gpt-5.3-codex-spark",name:"GPT-5.3 Codex Spark",api:"openai-codex-responses",provider:"openai-codex",baseUrl:l0,reasoning:!0,thinkingLevelMap:{xhigh:"xhigh",minimal:"low"},input:["text"],cost:{input:1.75,output:14,cacheRead:0.175,cacheWrite:0},contextWindow:128000,maxTokens:128000}];function Y2($,Z,z){let X=X2(),J=G2(),G;try{G=J2($,Z,z)}catch(Q){throw J(),Q}return(async()=>{try{for await(let Q of G)X.push(Q);X.end()}catch(Q){X.push({type:"error",reason:"error",error:{role:"assistant",content:[],api:$.api,provider:$.provider,model:$.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"error",errorMessage:Q instanceof Error?Q.message:String(Q),timestamp:Date.now()}}),X.end()}finally{J()}})(),X}function W2($){M3($),$.registerProvider("openai-codex",{name:"OpenAI Codex (CortexKit OAuth)",baseUrl:l0,api:"openai-codex-responses",models:Q2,streamSimple:Y2})}export{G2 as installRawCodexWebSocket,W2 as default};
|