@cortexkit/opencode-anthropic-auth 1.15.1 → 1.17.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 +14 -6
- package/dist/cli.js +6 -6
- package/dist/fable-fallback.d.ts +2 -0
- package/dist/{index-qejbx8c9.js → index-63keqwnf.js} +1 -1
- package/dist/{index-jkbar3k3.js → index-am5pq04s.js} +1 -1
- package/dist/{index-qsaph2g4.js → index-f5r96vyv.js} +1 -1
- package/dist/index-gj7emmj5.js +2 -0
- package/dist/index-xvfesm3w.js +422 -0
- package/dist/{index-6gdd6e4s.js → index-y2n9h7p6.js} +1 -1
- package/dist/index.js +12 -12
- package/dist/{logger-vxnb5hjr.js → logger-ywfmddsw.js} +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.d.ts +52 -2
- package/dist/sidebar-state.js +1 -1
- package/dist/tui/command-dialogs.d.ts +12 -0
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +2 -0
- package/package.json +2 -2
- package/src/sidebar-state.ts +381 -4
- package/src/tui/command-dialogs.tsx +35 -13
- package/src/tui-compiled/sidebar-state.ts +381 -4
- package/src/tui-compiled/tui/command-dialogs.tsx +22 -10
- package/src/tui-compiled/tui.tsx +147 -104
- package/src/tui.tsx +34 -2
- package/dist/index-bxs26mw4.js +0 -2
- package/dist/index-z03wayzs.js +0 -417
package/dist/index-z03wayzs.js
DELETED
|
@@ -1,417 +0,0 @@
|
|
|
1
|
-
import{Bb as w,Cb as u,Db as L,xb as Z_}from"./index-6gdd6e4s.js";import{Xb as t_}from"./index-qsaph2g4.js";var Hf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",J0={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.com/cai/oauth/authorize"},kf="https://platform.claude.com/oauth/code/callback",lf="https://platform.claude.com/v1/oauth/token",pf="axios/1.15.2",W0=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],Y0="user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload",gD="mcp_";var Z0="fast-mode-2026-02-01";function sD(f,_){let $=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...$,..._])].join(",")}function rD(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var nD="You are OpenCode",cD="You are Claude Code, Anthropic's official CLI for Claude.",tD=["<use_parallel_tool_calls>","For maximum efficiency, whenever you perform multiple independent operations, invoke all relevant tools simultaneously rather than sequentially. Prioritize calling independent tools in parallel whenever possible. For example, when reading 3 known files, run 3 tool calls in parallel to read all 3 files into context at the same time. When running multiple independent read-only commands like `ls` or `list_dir`, run all of those commands in parallel. Err on the side of maximizing parallel tool calls for independent work rather than running too many tools sequentially.","","Do not parallelize tool calls when one call depends on the output of another call. If a tool call needs an ID, filename, search result, or any other value returned by a previous tool call, run the first call, wait for its result, then run the dependent call using the real returned value. Never invent placeholder IDs, guessed task IDs, or other guessed values for dependent tool calls just to place them in the same parallel block.","</use_parallel_tool_calls>"].join(`
|
|
2
|
-
`);var p="2.1.177",vf="3bf",X0="cli",F0="0.94.0",V0="v24.3.0",m0="claude-cli/2.1.177 (external, cli)",A0=["explicit","automatic","hybrid"],Of="explicit",oD=["github.com/anomalyco/opencode","opencode.ai/docs"],aD=[{match:"if OpenCode honestly",replacement:"if the assistant honestly"},{match:"Here is some useful information about the environment you are running in:",replacement:"Environment context you are running in:"}];function Q0(f){let _="";for(let $ of f)_+=String.fromCharCode($);return btoa(_).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function R0(){let f=new Uint8Array(64);crypto.getRandomValues(f);let _=Q0(f),$=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:Q0(new Uint8Array($)),method:"S256"}}function uf(f){if(!f)return;let _=Number(f);if(Number.isFinite(_)&&_>0)return Math.ceil(_);let $=Date.parse(f);if(Number.isFinite($)){let D=Math.ceil(($-Date.now())/1000);return D>0?D:void 0}return}class df extends Error{status;body;retryAfter;isRefreshError=!0;constructor(f,_,$){super(`Claude OAuth refresh failed: ${f} — ${_}`);this.status=f,this.body=_,this.name="ClaudeOAuthRefreshError",this.retryAfter=uf($??void 0)}}function s_(f){if(!(f instanceof Error))return!1;let _=f.code;return f.message.includes("fetch failed")||_==="ECONNRESET"||_==="ECONNREFUSED"||_==="ETIMEDOUT"||_==="UND_ERR_CONNECT_TIMEOUT"}async function P0(f){let _=f.fetchImpl??fetch,$=f.maxRetries??2,D=f.baseDelayMs??500;for(let C=0;C<=$;C++)try{if(C>0){let K=D*2**(C-1);await new Promise((U)=>setTimeout(U,K))}let E=await _(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:Hf,scope:Y0})});if(!E.ok){if(E.status>=500&&C<$){await E.body?.cancel().catch(()=>{});continue}let K=await E.text().catch(()=>"");throw new df(E.status,K,E.headers.get("retry-after"))}let N=await E.json(),b=f.now?.()??Date.now();return{access:N.access_token,refresh:N.refresh_token??f.refreshToken,expires:b+N.expires_in*1000,expiresIn:N.expires_in}}catch(E){if(E instanceof df)throw E;if(C<$&&s_(E))continue;throw E}throw Error("Token refresh exhausted all retries")}function r_(){return crypto.randomUUID().replace(/-/g,"")}function n_(f){let _=f.trim();try{let N=new URL(_),b=N.searchParams.get("code"),K=N.searchParams.get("state");if(b&&K)return{code:b,state:K}}catch{}let $=_.split("#");if($.length===2&&$[0]&&$[1])return{code:$[0],state:$[1]};let D=new URLSearchParams(_),C=D.get("code"),E=D.get("state");if(C&&E)return{code:C,state:E};return null}async function c_(f,_,$){let D=await fetch(lf,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":pf},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:Hf,redirect_uri:$,code_verifier:_})});if(!D.ok)return{type:"failed"};let C=await D.json();return{type:"success",refresh:C.refresh_token,access:C.access_token,expires:Date.now()+C.expires_in*1000}}async function DC(f){let _=await R0(),$=r_(),D=new URL(J0[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",Hf),D.searchParams.set("response_type","code"),D.searchParams.set("redirect_uri",kf),D.searchParams.set("scope",W0.join(" ")),D.searchParams.set("code_challenge",_.challenge),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",$),{url:D.toString(),redirectUri:kf,state:$,verifier:_.verifier}}async function CC(f,_,$,D){let C=n_(f);if(!C)return{type:"failed"};if(D&&C.state!==D)return{type:"failed"};return c_(C,_,$)}import{createHash as p0,randomUUID as Cf}from"node:crypto";import{mkdir as v0,readFile as Lf,rename as d0,rm as t,stat as q0,writeFile as Sf}from"node:fs/promises";import{homedir as o_}from"node:os";import{dirname as i0,join as o}from"node:path";var a_=globalThis.setTimeout.bind(globalThis),e_=globalThis.clearTimeout.bind(globalThis),u0="anthropic-auth.json",f1="anthropic-auth-state.json",_1="https://api.anthropic.com/api/oauth/usage";function T(f){return f.type==="oauth"}function MC(f){return f.type==="api"}function $1(f){let _=f?.trim();if(!_)return!1;try{let $=new URL(_);return($.protocol==="http:"||$.protocol==="https:")&&!$.username&&!$.password}catch{return!1}}function HC(f){return f.costZeroing?.enabled!==!1}var D1=[401,403,429],g0=240,C1=g0;var E1=300000,N1=3600000,s0=86400000,b1=60000,K1=900000,U1=300000,G1=5,I0={five_hour:0,seven_day:0},j1=!0,B1=60000,M1=60000,H1=600000,O1=1e4,L1=100;function S1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o(process.env.XDG_CONFIG_HOME||o(o_(),".config"),"opencode")}function S(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||o(S1(),u0)}function r0(f=S()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(u0)?o(i0(f),f1):`${f}.state.json`}function M(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function x0(f){return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Cf(),label:typeof f.label==="string"?f.label:void 0,enabled:typeof f.enabled==="boolean"?f.enabled:void 0,addedAt:typeof f.addedAt==="number"?f.addedAt:void 0,lastUsed:typeof f.lastUsed==="number"?f.lastUsed:void 0}}function z1(f){if(!M(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",$=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!$1(_))return null;let D=f.authHeader==="x-api-key"?"x-api-key":"authorization-bearer";return{...x0(f),type:"api",apiKey:$||void 0,baseURL:_,authHeader:D}}if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{...x0(f),type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires:void 0,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:T0(f.lastRefreshError),lastQuotaRefreshError:T0(f.lastQuotaRefreshError),quota:J1(f.quota)}}function T0(f){if(!M(f))return;if(typeof f.message!=="string")return;let _=Number(f.checkedAt);if(!Number.isFinite(_))return;let $=Number(f.nextRetryAt),D=Number(f.retryCount),C=Number(f.status);return{message:f.message,checkedAt:_,nextRetryAt:Number.isFinite($)?$:void 0,retryCount:Number.isFinite(D)?D:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0,status:Number.isFinite(C)?C:void 0,permanent:typeof f.permanent==="boolean"?f.permanent:void 0}}function h0(f){if(!M(f))return;let _=Number(f.usedPercent),$=Number(f.remainingPercent),D=Number(f.checkedAt);if(!Number.isFinite(_)||!Number.isFinite($)||!Number.isFinite(D))return;return{usedPercent:_,remainingPercent:$,checkedAt:D,resetsAt:typeof f.resetsAt==="string"?f.resetsAt:void 0}}function J1(f){if(!M(f))return;let _={};for(let $ of["five_hour","seven_day"]){let D=h0(f[$]);if(D)_[$]=D}if(typeof f.checkedAt==="number"&&Number.isFinite(f.checkedAt))_.checkedAt=f.checkedAt;if(Array.isArray(f.scoped)){let $=f.scoped.map((D)=>{if(!M(D))return;let C=h0(D);if(!C)return;if(typeof D.id!=="string"||!D.id.trim())return;if(typeof D.title!=="string"||!D.title.trim())return;if(typeof D.modelName!=="string"||!D.modelName.trim())return;let E=typeof D.modelId==="string"&&D.modelId.trim()?D.modelId.trim():void 0;return{...C,id:D.id.trim(),title:D.title.trim(),...E&&{modelId:E},modelName:D.modelName.trim()}}).filter((D)=>D!=null);_.scoped=$}return Object.keys(_).length?_:void 0}function Q(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function W1(f){if(!M(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:M(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:M(f.refresh)?f.refresh:void 0,quota:M(f.quota)?f.quota:void 0,claudeCache:M(f.claudeCache)?f.claudeCache:void 0,dump:M(f.dump)?f.dump:void 0,claudeFast:M(f.claudeFast)?f.claudeFast:void 0,costZeroing:M(f.costZeroing)?f.costZeroing:void 0,cacheKeep:M(f.cacheKeep)?f.cacheKeep:void 0,relay:M(f.relay)?f.relay:void 0,logging:M(f.logging)?f.logging:void 0,killswitch:M(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(z1).filter((_)=>_!=null)}}async function Jf(f){try{return{exists:!0,value:JSON.parse(await Lf(f,"utf8"))}}catch(_){if(_.code==="ENOENT")return{exists:!1,value:null};let $=_ instanceof Error?_.message:String(_);throw Error(`account store at ${f} is corrupt or unreadable (${$}) — fix or remove it`)}}function s(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function zf(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function nf(f){return Math.max(zf(f.lastRefreshedAt),zf(f.lastUsed),zf(f.addedAt))}function Y1(f,_){if(f.type!=="oauth")return!1;if(typeof f.refresh!=="string"||!f.refresh.trim())return!1;if(!Boolean(typeof f.access==="string"&&typeof _.access==="string"&&f.access!==_.access||typeof f.refresh==="string"&&typeof _.refresh==="string"&&f.refresh!==_.refresh))return!1;return nf(f)>nf(_)}function Z1(f,_){if(Y1(f,_)){let $={..._,...f},D=nf(f);if(D>zf($.lastRefreshedAt))$.lastRefreshedAt=D;return delete $.quota,delete $.lastRefreshError,delete $.lastQuotaRefreshError,$}return{...f,..._}}function X1(f,_){if(!M(f))return f;let $=M(_)?_:{},D=M($.main)?$.main:void 0,C=M($.accounts)?$.accounts:{},E=M(f.quota)?f.quota:{},N=M(f.refresh)?f.refresh:{},b=D??E,K=D??N,U=Array.isArray(f.accounts)?f.accounts.map((G)=>{if(!M(G))return G;let O=typeof G.id==="string"&&M(C[G.id])?C[G.id]:{};return Z1(G,O)}):[];return{...f,refresh:s({...N,mainLastRefreshError:K.lastRefreshError,mainRefreshLeaseId:K.refreshLeaseId,mainRefreshLeaseUntil:K.refreshLeaseUntil,mainRefreshLeaseTokenHash:K.refreshLeaseTokenHash}),quota:s({...E,mainQuota:b.quota,mainQuotaCheckedAt:b.quotaCheckedAt,mainQuotaToken:b.quotaToken,mainLastQuotaApiError:b.lastQuotaApiError}),accounts:U}}async function F(f=S()){let _=await Jf(f),$=await Jf(r0(f));if(!_.exists&&!$.exists)return null;let D=_.exists?_.value:Q();return W1(X1(D,$.value))}async function F1(f){let _=await Jf(f);return M(_.value)?_.value:{}}function V1(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function m1(f){return s({id:f.id,label:f.label,type:f.type,enabled:f.enabled,addedAt:f.addedAt,baseURL:f.type==="api"?f.baseURL:void 0,authHeader:f.type==="api"?f.authHeader:void 0})}function A1(f){if(f.type==="api")return s({apiKey:f.apiKey,lastUsed:f.lastUsed});return s({access:f.access,refresh:f.refresh,expires:f.expires,lastUsed:f.lastUsed,lastRefreshedAt:f.lastRefreshedAt,lastRefreshError:f.lastRefreshError,lastQuotaRefreshError:f.lastQuotaRefreshError,quota:f.quota})}function Ef(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0,...f?.scoped?.map((_)=>_.checkedAt)??[],f?.checkedAt??0)}function Q1(f,_){if(!M(f))return _;let $=f,D=Ef($.quota),C=Ef(_.quota),E=Boolean($.access&&_.access&&$.access!==_.access||$.refresh&&_.refresh&&$.refresh!==_.refresh);if(D>C){let b=$.lastRefreshedAt??0,K=_.lastRefreshedAt??0;if(E&&K<=b){let G={...$};if(typeof _.lastUsed==="number"&&(typeof $.lastUsed!=="number"||_.lastUsed>$.lastUsed))G.lastUsed=_.lastUsed;return G}let U={...$,..._};if(E){if("quota"in _)if(U.quota=$.quota,"lastQuotaRefreshError"in $)U.lastQuotaRefreshError=$.lastQuotaRefreshError;else delete U.lastQuotaRefreshError;else delete U.quota,delete U.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete U.lastRefreshError;return U}return{...U,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let N={...$,..._};if(!("lastQuotaRefreshError"in _))delete N.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete N.lastRefreshError;return N}function R1(f){let _=f.refresh?s({enabled:f.refresh.enabled,intervalMinutes:f.refresh.intervalMinutes,refreshBeforeExpiryMinutes:f.refresh.refreshBeforeExpiryMinutes}):void 0,$=f.quota?s({enabled:f.quota.enabled,checkIntervalMinutes:f.quota.checkIntervalMinutes,refreshEveryNRequests:f.quota.refreshEveryNRequests,minimumRemaining:f.quota.minimumRemaining,failClosedOnUnknownQuota:f.quota.failClosedOnUnknownQuota,showToasts:f.quota.showToasts}):void 0;return V1({version:1,main:f.main,routing:f.routing,fallbackOn:f.fallbackOn,refresh:_,quota:$,claudeCache:f.claudeCache,dump:f.dump,logging:f.logging,claudeFast:f.claudeFast,costZeroing:f.costZeroing,cacheKeep:f.cacheKeep,relay:f.relay,killswitch:f.killswitch,accounts:f.accounts.map(m1)})}var w0=Promise.resolve();function n0(f){return new Promise((_,$)=>{w0=w0.then(()=>f().then(_,$),()=>f().then(_,$))})}async function c0(f,_){await v0(i0(f),{recursive:!0});let $=`${f}.${Cf()}.tmp`;await Sf($,`${JSON.stringify(_,null,2)}
|
|
3
|
-
`,{encoding:"utf8",mode:384});try{await d0($,f)}catch(D){throw await t($,{force:!0}).catch(()=>{}),D}}function m(f,_=S()){let $=_;return n0(()=>P1(f,$))}async function P1(f,_){let D={...await F1(_),...R1(f)};await c0(_,D),await t0(f,_,{mainQuota:!0,mainRefresh:!0,accounts:!0})}function q1(f,_){f.main=f.main??{};let $=typeof f.main.quotaCheckedAt==="number"?f.main.quotaCheckedAt:Ef(f.main.quota),D=typeof _.quota?.mainQuotaCheckedAt==="number"?_.quota.mainQuotaCheckedAt:Ef(_.quota?.mainQuota);if($>D)return;f.main.quota=_.quota?.mainQuota,f.main.quotaCheckedAt=_.quota?.mainQuotaCheckedAt,f.main.quotaToken=_.quota?.mainQuotaToken,f.main.lastQuotaApiError=_.quota?.mainLastQuotaApiError}function I1(f,_){f.main=f.main??{},f.main.lastRefreshError=_.refresh?.mainLastRefreshError,f.main.refreshLeaseId=_.refresh?.mainRefreshLeaseId,f.main.refreshLeaseUntil=_.refresh?.mainRefreshLeaseUntil,f.main.refreshLeaseTokenHash=_.refresh?.mainRefreshLeaseTokenHash}function cf(f){if(Array.isArray(f))return f.map(cf);if(!M(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,$])=>[_,cf($)]))}function x1(f,_=S(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=_;return n0(()=>t0(f,D,$))}async function t0(f,_,$){let D=r0(_),C=(await Jf(D)).value,E=M(C)?{...C,version:1}:{version:1};if($.mainQuota)q1(E,f);if($.mainRefresh)I1(E,f);if($.accounts){let N=$.accounts===!0?null:new Set($.accounts);E.accounts={...M(E.accounts)?E.accounts:{}};for(let b of f.accounts){if(N&&!N.has(b.id))continue;E.accounts[b.id]=Q1(E.accounts[b.id],A1(b))}if(N){for(let b of N)if(!f.accounts.some((K)=>K.id===b))delete E.accounts[b]}else{let b=new Set(f.accounts.map((K)=>K.id));for(let K of Object.keys(E.accounts))if(!b.has(K))delete E.accounts[K]}}await c0(D,cf(E))}async function Zf(f){let $=`${f.path??S()}.${f.name}.lock`,D=o($,"owner.json"),C=Cf(),E=f.now??Date.now,N=null,b=!1;async function K(){try{return JSON.parse(await Lf($,"utf8"))}catch(H){if(H.code!=="EISDIR")throw H;return JSON.parse(await Lf(D,"utf8"))}}async function U(){await Sf($,`${JSON.stringify({ownerId:C,expiresAt:E()+f.ttlMs})}
|
|
4
|
-
`,{encoding:"utf8",mode:384})}async function G(){try{return await Sf($,`${JSON.stringify({ownerId:C,expiresAt:E()+f.ttlMs})}
|
|
5
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(H){let X=H.code;if(X==="EEXIST"||X==="EISDIR")return!1;throw H}}function O(){if(!f.renew||b)return;let H=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(N=a_(()=>{(async()=>{try{let X=await K(),W=E();if(b||X?.ownerId!==C||Number(X?.expiresAt)<=W)return;await U(),O()}catch{}})()},H),"unref"in N)N.unref()}let Z=await G();if(!Z){let H=`${$}.evicting`,X=o(H,"owner.json"),W=Cf(),B=5000,d=8;async function q(){await new Promise((V)=>setTimeout(V,Math.floor(Math.random()*4)))}async function y(){try{let V=await K();return Number(V?.expiresAt)>E()}catch{try{return(await q0($)).mtimeMs+f.ttlMs>E()}catch{return!1}}}async function x(){try{return JSON.parse(await Lf(X,"utf8"))?.ownerId===W}catch{return!1}}async function j(){await v0(H);try{await Sf(X,`${JSON.stringify({ownerId:W,createdAt:E()})}
|
|
6
|
-
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(V){if(V.code==="ENOENT")return!1;throw await Y(),V}return await f.onStep?.("eviction-marker-acquired"),!0}async function Y(){if(await x())await t(H,{recursive:!0,force:!0}).catch(()=>{})}for(let V=0;V<8;V++){if(Z=await G(),Z)break;if(await y())return null;try{if(!await j()){await q();continue}}catch(Bf){if(Bf.code!=="EEXIST")throw Bf;let Mf;try{Mf=await q0(H)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}if(Mf.mtimeMs+5000>E())return null;await f.onStep?.("stale-marker-stat");let l=`${H}.${Cf()}`;try{await d0(H,l)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}await f.onStep?.("stale-marker-claimed"),await t(l,{recursive:!0,force:!0}).catch(()=>{}),await q();continue}try{if(await y())return null;if(!await x())return null;if(await f.onStep?.("stale-lock-confirmed"),!await x())return null;if(await t($,{recursive:!0,force:!0}).catch(()=>{}),!await x())return null;if(Z=await G(),!Z)return null;if(!await x())return await t($,{recursive:!0,force:!0}).catch(()=>{}),Z=!1,null;break}finally{await Y()}}}if(!Z)return null;return O(),{release:async()=>{if(b=!0,N)e_(N),N=null;try{if((await K())?.ownerId!==C)return}catch{return}await t($,{recursive:!0,force:!0}).catch(()=>{})}}}function OC(f){return f?.claudeCache?.enabled===!0}function T1(f){return typeof f==="string"&&A0.includes(f)?f:Of}function h1(f){return T1(f?.claudeCache?.mode)}async function LC(f,_,$=S()){let D=await F($)??Q();return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??h1(D)},await m(D,$),D}async function SC(f,_=S()){let $=await F(_)??Q();return $.claudeCache={...$.claudeCache??{},enabled:$.claudeCache?.enabled===!0,mode:f},await m($,_),$}function zC(f){return f?.dump?.enabled===!0}async function JC(f,_=S()){let $=await F(_)??Q();return $.dump={...$.dump??{},enabled:f},await m($,_),$}function WC(f){return f?.claudeFast?.enabled===!0}async function YC(f,_=S()){let $=await F(_)??Q();return $.claudeFast={...$.claudeFast??{},enabled:f},await m($,_),$}async function ZC(f,_,$=S()){let D=await F($)??Q();return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await m(D,$),D}async function XC(f,_=S()){let $=await F(_)??Q();return $.cacheKeep={...$.cacheKeep??{},enabled:f},await m($,_),$}function FC(f){return f?.cacheKeep?.subagents===!0}async function VC(f,_=S()){let $=await F(_)??Q();return $.cacheKeep={...$.cacheKeep??{},subagents:f},await m($,_),$}function w1(f){return f?.fallbackOn?.length?f.fallbackOn:D1}function mC(f,_){return w1(_).includes(f)}function o0(f){let _=f?.quota?.minimumRemaining||{};return{five_hour:_.five_hour??_["5h"]??I0.five_hour,seven_day:_.seven_day??_["1w"]??I0.seven_day}}function Nf(f){return f?.quota?.enabled!==!1}function y1(f){return f?.refresh?.enabled!==!1}function k1(f){return Math.floor(Math.random()*Math.max(0,f))}function l1(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??C1;return Math.max(g0,_)*60000}function a0(f){return p0("sha256").update(f).digest("hex")}function p1(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_))return _===429||_>=500;if(!(f instanceof Error))return!1;return f.message.includes("fetch failed")||"code"in f&&(f.code==="ECONNRESET"||f.code==="ECONNREFUSED"||f.code==="ETIMEDOUT"||f.code==="UND_ERR_CONNECT_TIMEOUT")}function v1(f){let _=a0(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,C=f.error.retryAfter,E;if(typeof C==="number"&&C>0)E=C*1000;else if(p1(f.error))E=Math.min(N1,E1*2**Math.min(D-1,6));else E=s0;let N=f.error.status,b=typeof N==="number"&&Number.isFinite(N)?N:void 0,K=e(f.error),G=(typeof f.error.body==="string"?f.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:f.now,nextRetryAt:f.now+E,retryCount:D,tokenHash:_,status:b,permanent:b===400&&G}}function AC(f){if(!f)return!1;if(typeof f.permanent==="boolean")return f.permanent;if(typeof f.status==="number")return f.status===400;if(typeof f.nextRetryAt==="number")return f.nextRetryAt-f.checkedAt>=s0;return!1}function Df(f,_,$){if(!f?.nextRetryAt||f.nextRetryAt<=$)return!1;if(!_)return!0;return f.tokenHash===a0(_)}function gf(f,_){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function tf(f){if(f.status===403)return!0;return/Claude quota check failed: 403\b/.test(e(f))}function Xf(f){let $=(f.previous?.retryCount??0)+1,D=D_(f.error)?Math.min(K1,b1*2**Math.min($-1,6)):U1;return{message:e(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:$}}function a(f,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;return!0}function QC(f,_){return`Quota API backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??_)-_)/1000))}s after: ${f.message}`}function h(f){let _=f?.quota?.checkIntervalMinutes??G1;return Math.max(1,_)*60000}function RC(f){return f?.logging?.level}async function PC(f,_=S()){let{setLogLevel:$}=await import("./logger-vxnb5hjr.js"),D=await F(_)??Q();D.logging={...D.logging??{},level:f},await m(D,_),$(f)}function e0(f){if(!f?.quota?.mainQuota||!f.quota.mainQuotaCheckedAt)return null;return{quota:f.quota.mainQuota,checkedAt:f.quota.mainQuotaCheckedAt,tokenFingerprint:f.quota.mainQuotaToken}}function f_(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function Wf(f){return f?.quota?.failClosedOnUnknownQuota??j1}function d1(f){if(typeof f!=="string")return null;let _=f.toLowerCase();if(_.includes("fable"))return"fable";if(_.includes("mythos"))return"mythos";return null}function of(f,_){let $=d1(_);if(!$)return;return f?.scoped?.find((D)=>{return[D.modelId,D.modelName,D.title].filter((E)=>typeof E==="string").join(" ").toLowerCase().includes($)})}function i1(f,_){let $=of(f,_);return Boolean($&&Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)}function y0(f,_){return!i1(f,_)}function __(f,_){if(!Nf(_))return!0;let $=o0(_);for(let D of["five_hour","seven_day"]){let C=f?.[D];if(!C)return!Wf(_);if(!Number.isFinite(C.remainingPercent))return!Wf(_);if(C.remainingPercent<$[D])return!1}return!0}var g={five_hour:5,seven_day:10,scoped:0};function bf(f){let _=f?.five_hour??f?.["5h"],$=f?.seven_day??f?.["1w"],D=f?.scoped;return{five_hour:typeof _==="number"&&Number.isFinite(_)?_:g.five_hour,seven_day:typeof $==="number"&&Number.isFinite($)?$:g.seven_day,scoped:typeof D==="number"&&Number.isFinite(D)?D:g.scoped}}function u1(f){return f?.killswitch?.enabled===!0}function g1(f,_){if(!f?.killswitch)return g;if(_&&f.killswitch.accounts?.[_])return bf(f.killswitch.accounts[_]);return bf(f.killswitch.main)}function qC(f,_,$,D){if(!u1(_))return!0;let C=g1(_,$),E=!1;for(let N of["five_hour","seven_day"]){let b=f?.[N];if(!b){E=!0;continue}if(!Number.isFinite(b.remainingPercent)){E=!0;continue}if(b.remainingPercent<C[N])return!1}if(D){let N=of(f,D);if(N&&Number.isFinite(N.remainingPercent)&&N.remainingPercent<=C.scoped)return!1}if(E)return!Wf(_);return!0}function IC(f,_,$,D){let C=[],E=[f,..._.map((N)=>N.quota)];for(let N of E)if(D){let K=of(N,D)?.resetsAt;if(!K)continue;let U=Date.parse(K);if(Number.isFinite(U)&&U>$)C.push(U)}else for(let b of["five_hour","seven_day"]){let K=N?.[b]?.resetsAt;if(!K)continue;let U=Date.parse(K);if(Number.isFinite(U)&&U>$)C.push(U)}if(!C.length)return 300;return Math.max(1,Math.ceil((Math.min(...C)-$)/1000))+60}function xC(f){return f?.killswitch??{enabled:!1}}async function TC(f,_=S()){let $=await F(_)??Q();return $.killswitch=f,await m($,_),$}async function hC(f,_=S()){let $=await F(_);if(!$)return!1;let D=a1($,f);if(D)await m($,_);return D}async function wC(f,_=S()){let $=await F(_);if(!$)return;e1($,f),await m($,_)}async function yC(f,_,$=S()){let D=await F($);if(!D)return!1;let C=f$(D,f,_);if(C)await m(D,$);return C}async function kC(f,_=S()){let $=await F(_)??Q();o1($,f),await m($,_)}function af(f,_,$){if(!Nf(_))return $+h(_);let D=o0(_),C=[];for(let E of["five_hour","seven_day"]){let N=f?.[E];if(!N)return $+h(_);if(N.remainingPercent>=D[E])continue;let b=N.resetsAt?Date.parse(N.resetsAt):Number.NaN;if(!Number.isFinite(b)||b<=$)return $+h(_);C.push(b)}if(!C.length)return $+h(_);return Math.min(...C)+60000}function i(f,_,$){return!f.access||!f.expires||f.expires-$<=l1(_)}function $_(f,_,$){if(!Nf(_))return!0;let D=h(_);return["five_hour","seven_day"].every((C)=>{let E=f?.[C];return Boolean(E&&$-E.checkedAt<D)})}function sf(f,_,$){return!$_(f.quota,_,$)}function s1(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let $=Date.parse(f.resetsAt);return!Number.isFinite($)||$>_}function r1(f,_){return["five_hour","seven_day"].every(($)=>s1(f?.[$],_))}function D_(f){let _=f.status;if(typeof _==="number"&&Number.isFinite(_)){if(_===429||_>=500)return!0}let $=e(f);if(/Claude quota check failed: (429|5\d\d)\b/.test($))return!0;if($.includes("Quota refresh is already in progress"))return!0;if(!(f instanceof Error))return!1;let{message:D,code:C}=f;return D.includes("fetch failed")||C==="ECONNRESET"||C==="ECONNREFUSED"||C==="ETIMEDOUT"||C==="UND_ERR_CONNECT_TIMEOUT"}function n1(f,_,$,D){return D_($)&&__(f.quota,_)&&r1(f.quota,D)}function Yf(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function rf(f){return typeof f==="string"&&f.trim()?f.trim():void 0}function c1(f){return f.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function t1(f,_){if(!Array.isArray(f))return[];let $=new Set,D=[];for(let C of f){if(C?.kind!=="weekly_scoped"||C.group!=="weekly")continue;if(typeof C.percent!=="number"||!Number.isFinite(C.percent))continue;let E=rf(C.scope?.model?.display_name);if(!E)continue;let N=rf(C.scope?.model?.id)??E,b=c1(N);if(!b)continue;let K=`claude-weekly-scoped-${b}`;if($.has(K))continue;$.add(K);let U=Yf(C.percent),G=rf(C.scope?.model?.id);D.push({id:K,title:`${E} only`,...G&&{modelId:G},modelName:E,usedPercent:U,remainingPercent:Yf(100-U),resetsAt:C.resets_at,checkedAt:_})}return D}function k0(f,_){if(typeof f?.utilization!=="number")return;if(!Number.isFinite(f.utilization))return;let $=Yf(f.utilization);return{usedPercent:$,remainingPercent:Yf(100-$),resetsAt:f.resets_at,checkedAt:_}}async function Ff(f){let $=await(f.fetchImpl??fetch)(_1,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${p}`}});if(!$.ok){let E=await $.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${$.status} — ${E}`),{status:$.status,retryAfter:uf($.headers.get("Retry-After"))})}let D=f.now?.()??Date.now(),C=await $.json();return{five_hour:k0(C.five_hour,D),seven_day:k0(C.seven_day,D),scoped:t1(C.limits,D),checkedAt:D}}function A(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id);if($>=0)f.accounts[$]=_}function o1(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id||_.label&&D.label===_.label);if($>=0){f.accounts[$]={...f.accounts[$],..._,addedAt:f.accounts[$]?.addedAt??_.addedAt,..._.type==="oauth"&&{quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,lastRefreshError:_.lastRefreshError,lastQuotaRefreshError:_.lastQuotaRefreshError}};return}f.accounts.push(_)}function a1(f,_){let $=f.accounts.findIndex((D)=>D.id===_);if($<0)return!1;return f.accounts.splice($,1),!0}function e1(f,_){let $=new Map(_.map((E,N)=>[E,N])),D=f.accounts.filter((E)=>$.has(E.id)),C=f.accounts.filter((E)=>!$.has(E.id));D.sort((E,N)=>($.get(E.id)??0)-($.get(N.id)??0)),f.accounts=[...D,...C]}function f$(f,_,$){let D=f.accounts.find((C)=>C.id===_);if(!D)return!1;return D.enabled=$,!0}function e(f){return f instanceof Error?f.message:String(f)}function C_(f,_,$){f.lastRefreshError=v1({error:_,now:$,refreshToken:f.refresh,previous:f.lastRefreshError})}function l0(f,_,$){if(tf(_))return;if(f.lastQuotaRefreshError=Xf({error:_,now:$,previous:f.lastQuotaRefreshError}),_.isRefreshError)C_(f,_,$)}function _$(f){return`fallback-oauth-refresh-${p0("sha256").update(f).digest("hex").slice(0,16)}`}class $${now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;quotaManager;onFallbackStorageChanged;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??S(),this.quotaManager=f.quotaManager??null,this.onFallbackStorageChanged=f.onFallbackStorageChanged}seedFallbackQuota(f,_){if(!this.quotaManager)return;if(!f.quota)return;let $=Math.max(f.quota.five_hour?.checkedAt??0,f.quota.seven_day?.checkedAt??0);if($<=0)return;let D=this.quotaManager.getFallback(f.id,f.access);if(D&&D.checkedAt>=$)return;let C=h(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:$+C,checkedAt:$},f.access)}async load(){return F(this.configPath)}async save(f,_){await x1(f,this.configPath,{accounts:_??!0})}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},B1+k1(M1)),"unref"in this.refreshTimer)this.refreshTimer.unref()}}stopBackgroundRefresh(){if(this.refreshTimer)clearInterval(this.refreshTimer);if(this.quotaTimer)clearInterval(this.quotaTimer);this.refreshTimer=null,this.quotaTimer=null}async getUsableFallbackAccounts(f,_={}){let $=f!==void 0?f:await this.load();if(!$)return[];let D=[],C=!1;for(let E of $.accounts){if(E.enabled===!1||!T(E))continue;try{let N=E;if(i(N,$,this.now())){let K=N.lastRefreshError;if(K&&Df(K,N.refresh,this.now()))throw Error(gf(K,this.now()));N=await this.refreshAccount(N,$),C=!0}if(this.seedFallbackQuota(N,$),(this.quotaManager?this.quotaManager.isFallbackStale(N.id,N.access):sf(N,$,this.now()))&&!a(N.lastQuotaRefreshError,this.now()))N=await this.refreshAccountQuota(N,$),C=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(N),$,{modelId:_.modelId}))D.push(N)}catch(N){if(n1(E,$,N,this.now())){if(u("[refresh] fallback quota using cached quota after refresh error",{accountId:E.id,error:e(N)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(E),$,{modelId:_.modelId}))D.push(E)}else if(!Wf($)&&y0(E.quota,_.modelId))D.push(E)}}if(C)await this.save($);return D}async markUsed(f){let _=await this.load();if(!_)return;let $=_.accounts.find((D)=>D.id===f.id);if(!$)return;$.lastUsed=this.now(),await this.save(_)}accountPassesQuotaPolicy(f,_,$={}){return __(f.quota,_)&&y0(f.quota,$.modelId)}quotaPolicyAccount(f){if(!this.quotaManager)return f;let _=this.quotaManager.getFallback(f.id,f.access)?.quota;return _?{...f,quota:_}:f}async refreshDueAccounts(){let f=await this.load();if(!f||!y1(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!T($))continue;if(!i($,f,this.now()))continue;if(Df($.lastRefreshError,$.refresh,this.now()))continue;try{u("[refresh] fallback oauth background due",{accountId:$.id,expiresInMs:$.expires?$.expires-this.now():void 0}),await this.refreshAccount($,f),_=!0}catch(D){w.warn("refresh","fallback oauth background failed",{accountId:$.id,error:D instanceof Error?D.message:String(D)}),C_($,D,this.now()),A(f,$),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!Nf(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!T($))continue;let D=$;try{if(i(D,f,this.now())){if(Df(D.lastRefreshError,D.refresh,this.now()))continue;D=await this.refreshAccount(D,f),_=!0}if(a(D.lastQuotaRefreshError,this.now()))continue;if(this.seedFallbackQuota(D,f),!(this.quotaManager?this.quotaManager.isFallbackStale(D.id,D.access):sf(D,f,this.now())))continue;await this.refreshAccountQuota(D,f),_=!0}catch(C){l0($,C,this.now()),A(f,$),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),$=[];if(!_||!Nf(_))return{storage:_,errors:$};let D=f.force??!1,C=!1;for(let E of _.accounts){if(E.enabled===!1||!T(E))continue;let N=E;try{if(i(N,_,this.now())){let b=N.lastRefreshError;if(b&&Df(b,N.refresh,this.now()))throw Error(gf(b,this.now()));N=await this.refreshAccount(N,_),C=!0}if(!D&&!sf(N,_,this.now())){if(N.lastQuotaRefreshError)N.lastQuotaRefreshError=void 0,A(_,N),C=!0;continue}await this.refreshAccountQuota(N,_),C=!0}catch(b){l0(E,b,this.now()),A(_,E),C=!0,$.push({accountId:E.id,message:e(b)})}}if(C)await this.save(_);return{storage:_,errors:$}}async refreshAccount(f,_,$={}){let D=this.refreshPromises.get(f.id);if(D){let N=await D;return A(_,N),N}let C=this.refreshAccountNow(f,_,$).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,C);let E=await C;return A(_,E),E}async waitForConcurrentFallbackRefresh(f,_,$,D){let C=Date.now()+O1;while(Date.now()<C){await new Promise((U)=>setTimeout(U,L1));let E=await this.load(),N=E?.accounts.find((U)=>U.id===f.id&&T(U));if(!N)continue;if((N.access!==$.access||N.refresh!==$.refresh||(N.expires??0)>($.expires??0)+60000)&&(D.force||!i(N,E,this.now())))return A(_,N),u("[refresh] fallback oauth joined concurrent refresh",{accountId:N.id,expiresInMs:N.expires?N.expires-this.now():void 0}),N;let K=N.lastRefreshError;if(K&&Df(K,N.refresh,this.now()))throw A(_,N),Error(gf(K,this.now()))}return null}async refreshAccountNow(f,_,$){let D=await this.load(),C=D?.accounts.find((b)=>b.id===f.id&&T(b));if(C&&!$.force&&!i(C,D,this.now()))return A(_,C),C;let E=C??f,N=await Zf({name:_$(E.id),ttlMs:H1,path:this.configPath,now:this.now,renew:!0});if(!N){u("[refresh] fallback oauth refresh skipped file lock",{accountId:E.id});let b=await this.waitForConcurrentFallbackRefresh(f,_,E,$);if(b)return b;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),C=D?.accounts.find((U)=>U.id===f.id&&T(U)),C&&!$.force&&!i(C,D,this.now()))return A(_,C),C;E=C??E;let b=E.refresh;u("[refresh] fallback oauth refresh request start",{accountId:E.id,force:$.force===!0,expiresInMs:E.expires?E.expires-this.now():void 0});let K=await P0({refreshToken:b,fetchImpl:this.fetchImpl,now:this.now});return E.access=K.access,E.refresh=K.refresh,E.expires=K.expires,E.lastRefreshedAt=K.expires-K.expiresIn*1000,E.lastRefreshError=void 0,A(_,E),await this.save(_),u("[refresh] fallback oauth refresh succeeded",{accountId:E.id,expiresInMs:E.expires?E.expires-this.now():void 0}),E}finally{await N.release()}}async refreshAccountQuota(f,_){let $=f;if(!$.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(b)=>this.quotaManager?this.quotaManager.refreshFallback($.id,b):Ff({accessToken:b,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();try{$.quota=await D($.access)}catch(b){if(!(b instanceof Error?b.message:String(b)).includes("Claude quota check failed: 401"))throw b;if($=await this.refreshAccount(f,_,{force:!0}),!$.access)throw b;$.quota=await D($.access)}let E=await this.load(),N=E?.accounts.find((b)=>b.id===$.id&&T(b));if(E&&N&&N.access!==$.access)return this.seedFallbackQuota(N,E),A(_,N),N;if(E&&N?.access===$.access&&N.quota&&Ef(N.quota)>=C&&$_(N.quota,E,this.now()))return this.seedFallbackQuota(N,E),A(_,N),N;if($.lastQuotaRefreshError=void 0,A(_,$),this.quotaManager&&$.quota){let b=this.now();this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:b+h(_),checkedAt:b},$.access)}return $}}var vC="claude-cache",E_="## Claude Cache Status",D$="## Claude Cache Enabled",C$="## Claude Cache Disabled",E$="## Claude Cache Usage",N$="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Vf=!1,mf=Of;function dC(){return Vf}function iC(){return mf}function uC(f){Vf=f.enabled,mf=f.mode}function b$(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};if(_.length===2&&_[0]==="mode"&&(_[1]==="explicit"||_[1]==="automatic"||_[1]==="hybrid"))return{type:"mode",mode:_[1]};return{type:"usage"}}function Kf(f){let _=f?.enabled??Vf,$=f?.mode??mf;return[E_,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Mode: ${$}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: main sessions only; subagent sessions keep default ephemeral cache behavior","- Modes: explicit = existing OpenCode breakpoints; automatic = top-level cache_control only; hybrid = system + messages[0] + top-level cache_control","- TTL: 1h when enabled for main sessions; default ephemeral cache behavior otherwise"].join(`
|
|
7
|
-
`)}function gC(f){let _=b$(f.argumentsText),$=f.enabled??Vf,D=f.mode??mf;if(_.type==="status")return Kf({enabled:$,mode:D});if(_.type==="enable")return[D$,"",Kf({enabled:!0,mode:D})].join(`
|
|
8
|
-
`);if(_.type==="disable")return[C$,"",Kf({enabled:!1,mode:D})].join(`
|
|
9
|
-
`);if(_.type==="mode")return[E_,"",`Mode updated to \`${_.mode}\`.`,"",Kf({enabled:$,mode:_.mode})].join(`
|
|
10
|
-
`);return[E$,"",N$,"",Kf({enabled:$,mode:D})].join(`
|
|
11
|
-
`)}import{randomBytes as K$,randomUUID as K_}from"node:crypto";var U$=1000,r=new Map;function Uf(f,_,$){if(!f.has(_)&&f.size>=U$){let D=f.keys().next().value;if(D!==void 0)f.delete(D)}f.set(_,$)}function U_(f){let _=f||"anonymous",$=r.get(_);if($)return $;let D={deviceId:K$(32).toString("hex"),sessionId:K_()};return Uf(r,_,D),D}var G$=86400000,j$=300000,ef=new Map,N_=new Map;async function B$(f,_){if(!f.startsWith("sk-ant-oat"))return null;let $=new AbortController,D=setTimeout(()=>$.abort(),5000);try{let C=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(C.searchParams.set("entrypoint",X0),_)C.searchParams.set("model",_);let E=await fetch(C,{method:"GET",headers:{accept:"application/json, text/plain, */*",authorization:`Bearer ${f}`,"content-type":"application/json","anthropic-beta":"oauth-2025-04-20","user-agent":`claude-code/${p}`},signal:$.signal});if(!E.ok)return null;let b=(await E.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof b==="string"&&b?b:null}catch{return null}finally{clearTimeout(D)}}async function cC(f,_){let $=U_(f);if(!f.startsWith("sk-ant-oat"))return $;let D=Date.now(),C=N_.get(f);if(C&&C.expiresAt>D){if(!C.accountUuid)return $;let U=`account:${C.accountUuid}`,G=r.get(U);if(G)return Uf(r,f,G),G}let E=ef.get(f);if(!E)E=B$(f,_),ef.set(f,E);let N=await E.finally(()=>{ef.delete(f)});if(Uf(N_,f,{accountUuid:N,expiresAt:D+(N?G$:j$)}),!N)return $;let b=`account:${N}`,K=r.get(b);if(K)return Uf(r,f,K),K;return $.accountUuid=N,Uf(r,b,$),$}function n(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function M$(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function tC(f,_){let $=M$(_);if(!$){if(n(f.metadata))delete f.metadata.user_id;return!1}if(!n(f.metadata))f.metadata={};let D=f.metadata;if(n(D))D.user_id=$;return!0}var H$=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","claude-code-20250219","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],O$=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","structured-outputs-2025-12-15","cache-diagnosis-2026-04-07"],b_=["oauth-2025-04-20","interleaved-thinking-2025-05-14","thinking-token-count-2026-05-13","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"];function L$(f){return f.output_config?.format?.type==="json_schema"}function S$(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&n(f.thinking)&&n(f.context_management)&&n(f.output_config)&&n(f.diagnostics)}function z$(f,_=[]){let $=f?S$(f)?[...H$]:L$(f)?[...O$]:[...b_]:[...b_];if(f?.speed==="fast")$.push(Z0);for(let D of _){let C=D.trim();if(C)$.push(C)}return[...new Set($)].join(",")}function J$(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function W$(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function oC(f,_,$={}){let D=$.identity??U_(_),E=[...(f.get("anthropic-beta")??"").split(",").map((N)=>N.trim()).filter(Boolean),...$.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${_}`),f.set("content-type","application/json"),f.set("user-agent",m0),f.set("anthropic-beta",z$($.body,E)),f.set("anthropic-dangerous-direct-browser-access","true"),f.set("anthropic-version","2023-06-01"),f.set("x-app","cli"),f.set("x-client-request-id",K_()),f.set("x-claude-code-session-id",D.sessionId),f.set("x-stainless-arch",W$()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",J$()),f.set("x-stainless-package-version",F0),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",V0),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var Y$=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function G_(f){let _={};for(let $ of Y$)if(Object.hasOwn(f,$))_[$]=f[$];for(let[$,D]of Object.entries(f))if(!Object.hasOwn(_,$))_[$]=D;return _}import{createHash as X$}from"node:crypto";var Z$=new Uint8Array([0,97,115,109,1,0,0,0,1,48,8,96,3,127,127,127,1,127,96,3,127,127,127,0,96,2,127,127,0,96,1,127,1,127,96,3,127,127,126,1,126,96,3,126,127,127,1,126,96,2,127,126,0,96,1,127,1,126,3,11,10,0,0,2,1,3,4,5,6,1,7,5,3,1,0,1,7,85,9,3,109,101,109,2,0,5,120,120,104,51,50,0,0,6,105,110,105,116,51,50,0,2,8,117,112,100,97,116,101,51,50,0,3,8,100,105,103,101,115,116,51,50,0,4,5,120,120,104,54,52,0,5,6,105,110,105,116,54,52,0,7,8,117,112,100,97,116,101,54,52,0,8,8,100,105,103,101,115,116,54,52,0,9,10,251,22,10,242,1,1,4,127,32,0,32,1,106,33,3,32,1,65,16,79,4,127,32,3,65,16,107,33,6,32,2,65,168,136,141,161,2,106,33,3,32,2,65,137,235,208,208,7,107,33,4,32,2,65,207,140,162,142,6,106,33,5,3,64,32,3,32,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,4,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,2,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,5,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,6,32,0,65,4,106,34,0,79,13,0,11,32,2,65,12,119,32,5,65,18,119,106,32,4,65,7,119,106,32,3,65,1,119,106,5,32,2,65,177,207,217,178,1,106,11,32,1,106,32,0,32,1,65,15,113,16,1,11,146,1,0,32,1,32,2,106,33,2,3,64,32,1,65,4,106,32,2,75,69,4,64,32,0,32,1,40,2,0,65,189,220,202,149,124,108,106,65,17,119,65,175,214,211,190,2,108,33,0,32,1,65,4,106,33,1,12,1,11,11,3,64,32,1,32,2,79,69,4,64,32,0,32,1,45,0,0,65,177,207,217,178,1,108,106,65,11,119,65,177,243,221,241,121,108,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,65,15,118,115,65,247,148,175,175,120,108,34,0,65,13,118,32,0,115,65,189,220,202,149,124,108,34,0,65,16,118,32,0,115,11,63,0,32,0,65,8,106,32,1,65,168,136,141,161,2,106,54,2,0,32,0,65,12,106,32,1,65,137,235,208,208,7,107,54,2,0,32,0,65,16,106,32,1,54,2,0,32,0,65,20,106,32,1,65,207,140,162,142,6,106,54,2,0,11,195,4,1,6,127,32,1,32,2,106,33,6,32,0,65,24,106,33,4,32,0,65,40,106,40,2,0,33,3,32,0,32,0,40,2,0,32,2,106,54,2,0,32,0,65,4,106,34,5,32,5,40,2,0,32,2,65,16,79,32,0,40,2,0,65,16,79,114,114,54,2,0,32,2,32,3,106,65,16,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,40,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,16,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,40,2,0,32,4,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,12,106,34,3,32,3,40,2,0,32,4,65,4,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,16,106,34,3,32,3,40,2,0,32,4,65,8,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,20,106,34,3,32,3,40,2,0,32,4,65,12,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,54,2,0,32,0,65,40,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,32,6,65,16,107,77,4,64,32,6,65,16,107,33,8,32,0,65,8,106,40,2,0,33,2,32,0,65,12,106,40,2,0,33,3,32,0,65,16,106,40,2,0,33,5,32,0,65,20,106,40,2,0,33,7,3,64,32,2,32,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,2,32,3,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,3,32,5,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,5,32,7,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,7,32,8,32,1,65,4,106,34,1,79,13,0,11,32,0,65,8,106,32,2,54,2,0,32,0,65,12,106,32,3,54,2,0,32,0,65,16,106,32,5,54,2,0,32,0,65,20,106,32,7,54,2,0,11,32,1,32,6,73,4,64,32,4,32,1,32,6,32,1,107,34,1,252,10,0,0,32,0,65,40,106,32,1,54,2,0,11,11,97,1,1,127,32,0,65,16,106,40,2,0,33,1,32,0,65,4,106,40,2,0,4,127,32,1,65,12,119,32,0,65,20,106,40,2,0,65,18,119,106,32,0,65,12,106,40,2,0,65,7,119,106,32,0,65,8,106,40,2,0,65,1,119,106,5,32,1,65,177,207,217,178,1,106,11,32,0,40,2,0,106,32,0,65,24,106,32,0,65,40,106,40,2,0,16,1,11,255,3,2,3,126,1,127,32,0,32,1,106,33,6,32,1,65,32,79,4,126,32,6,65,32,107,33,6,32,2,66,214,235,130,238,234,253,137,245,224,0,124,33,3,32,2,66,177,169,172,193,173,184,212,166,61,125,33,4,32,2,66,249,234,208,208,231,201,161,228,225,0,124,33,5,3,64,32,3,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,3,32,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,2,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,6,32,0,65,8,106,34,0,79,13,0,11,32,2,66,12,137,32,5,66,18,137,124,32,4,66,7,137,124,32,3,66,1,137,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,2,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,32,0,32,1,65,31,113,16,6,11,134,2,0,32,1,32,2,106,33,2,3,64,32,2,32,1,65,8,106,79,4,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,33,0,32,1,65,8,106,33,1,12,1,11,11,32,1,65,4,106,32,2,77,4,64,32,0,32,1,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,0,32,1,65,4,106,33,1,11,3,64,32,1,32,2,73,4,64,32,0,32,1,49,0,0,66,197,207,217,178,241,229,186,234,39,126,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,32,0,66,33,136,133,66,207,214,211,190,210,199,171,217,66,126,34,0,32,0,66,29,136,133,66,249,243,221,241,153,246,153,171,22,126,34,0,32,0,66,32,136,133,11,77,0,32,0,65,8,106,32,1,66,214,235,130,238,234,253,137,245,224,0,124,55,3,0,32,0,65,16,106,32,1,66,177,169,172,193,173,184,212,166,61,125,55,3,0,32,0,65,24,106,32,1,55,3,0,32,0,65,32,106,32,1,66,249,234,208,208,231,201,161,228,225,0,124,55,3,0,11,244,4,2,3,127,4,126,32,1,32,2,106,33,5,32,0,65,40,106,33,4,32,0,65,200,0,106,40,2,0,33,3,32,0,32,0,41,3,0,32,2,173,124,55,3,0,32,2,32,3,106,65,32,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,200,0,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,32,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,32,3,41,3,0,32,4,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,16,106,34,3,32,3,41,3,0,32,4,65,8,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,24,106,34,3,32,3,41,3,0,32,4,65,16,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,32,106,34,3,32,3,41,3,0,32,4,65,24,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,55,3,0,32,0,65,200,0,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,65,32,106,32,5,77,4,64,32,5,65,32,107,33,2,32,0,65,8,106,41,3,0,33,6,32,0,65,16,106,41,3,0,33,7,32,0,65,24,106,41,3,0,33,8,32,0,65,32,106,41,3,0,33,9,3,64,32,6,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,7,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,7,32,8,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,8,32,9,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,9,32,2,32,1,65,8,106,34,1,79,13,0,11,32,0,65,8,106,32,6,55,3,0,32,0,65,16,106,32,7,55,3,0,32,0,65,24,106,32,8,55,3,0,32,0,65,32,106,32,9,55,3,0,11,32,1,32,5,73,4,64,32,4,32,1,32,5,32,1,107,34,1,252,10,0,0,32,0,65,200,0,106,32,1,54,2,0,11,11,188,2,1,5,126,32,0,65,24,106,41,3,0,33,1,32,0,41,3,0,34,2,66,32,90,4,126,32,0,65,8,106,41,3,0,34,3,66,1,137,32,0,65,16,106,41,3,0,34,4,66,7,137,124,32,1,66,12,137,32,0,65,32,106,41,3,0,34,5,66,18,137,124,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,4,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,1,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,32,5,66,207,214,211,190,210,199,171,217,66,126,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,157,163,181,234,131,177,141,138,250,0,125,5,32,1,66,197,207,217,178,241,229,186,234,39,124,11,32,2,124,32,0,65,40,106,32,2,66,31,131,167,16,6,11]);async function j_(){return function(f){let{exports:{mem:_,xxh32:$,xxh64:D,init32:C,update32:E,digest32:N,init64:b,update64:K,digest64:U}}=f,G=new Uint8Array(_.buffer);function O(j,Y){if(_.buffer.byteLength<j+Y){let V=Math.ceil((j+Y-_.buffer.byteLength)/65536);_.grow(V),G=new Uint8Array(_.buffer)}}function Z(j,Y,V,Bf,z0,Mf){O(j);let l=new Uint8Array(j);return G.set(l),V(0,Y),l.set(G.subarray(0,j)),{update(P){let yf;return G.set(l),typeof P=="string"?(O(3*P.length,j),yf=B.encodeInto(P,G.subarray(j)).written):(O(P.byteLength,j),G.set(P,j),yf=P.byteLength),Bf(0,j,yf),l.set(G.subarray(0,j)),this},digest:()=>(G.set(l),Mf(z0(0)))}}function H(j){return j>>>0}let X=2n**64n-1n;function W(j){return j&X}let B=new TextEncoder,d=0,q=0n;function y(j,Y=d){return O(3*j.length,0),H($(0,B.encodeInto(j,G).written,Y))}function x(j,Y=q){return O(3*j.length,0),W(D(0,B.encodeInto(j,G).written,Y))}return{h32:y,h32ToString:(j,Y=d)=>y(j,Y).toString(16).padStart(8,"0"),h32Raw:(j,Y=d)=>(O(j.byteLength,0),G.set(j),H($(0,j.byteLength,Y))),create32:(j=d)=>Z(48,j,C,E,N,H),h64:x,h64ToString:(j,Y=q)=>x(j,Y).toString(16).padStart(16,"0"),h64Raw:(j,Y=q)=>(O(j.byteLength,0),G.set(j),W(D(0,j.byteLength,Y))),create64:(j=q)=>Z(88,j,b,K,U,W)}}((await WebAssembly.instantiate(Z$)).instance)}var F$=0x6e52736ac806831en,V$="cch=00000;";var _0=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=([0-9a-f]{5});/,m$=/("system":\[\{"type":"text","text":"x-anthropic-billing-header: cc_version=[^;"]+; cc_entrypoint=[^;"]+; )cch=00000;/,B_=null,f0=null;async function A$(){if(f0)return;B_??=(async()=>{f0=(await j_()).h64Raw})(),await B_}async function Q$(f){return await A$(),((f0?.(f,F$)??0n)&0xfffffn).toString(16).padStart(5,"0")}function R$(f){return f.replace(_0,`$1${V$}`)}function M_(f){return _0.exec(f)?.[2]??null}async function H_(f){if(!_0.test(f))return f;let _=R$(f),$=await Q$(new TextEncoder().encode(_));return _.replace(m$,`$1cch=${$};`)}function P$(f=p,_=new Date){if(f===p)return vf;return X$("sha256").update(f).digest("hex").slice(0,3)}function DE(f,_=p,$,D=new Date){let C=P$(_,D);return`x-anthropic-billing-header: cc_version=${_}.${C}; cc_entrypoint=${$}; cch=00000;`}var KE="claude-cachekeep",C0=3600000,$0=300000,q$=60000,UE="extended-cache-ttl-2025-04-11",I$=32,O_=16777216,x$=2*C0,T$=30000,L_="## Claude Cache Keep Status",h$="## Claude Cache Keep Enabled",w$="## Claude Cache Keep Disabled",y$="## Claude Cache Keep Usage",k$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function Af(f){return String(f).padStart(2,"0")}function l$(f){let _=f.trim();if(!_)return{type:"status"};if(_==="off")return{type:"disable"};if(_==="subagents on")return{type:"subagents",enabled:!0};if(_==="subagents off")return{type:"subagents",enabled:!1};let $=/^(\d{1,2})-(\d{1,2})$/.exec(_);if(!$)return{type:"usage"};let D=Number($[1]),C=Number($[2]);if(!Number.isInteger(D)||!Number.isInteger(C)||D<0||D>23||C<0||C>23||D===C)return{type:"usage"};return{type:"window",startHour:D,endHour:C}}function E0(f){let _=Number(f?.cacheKeep?.startHour),$=Number(f?.cacheKeep?.endHour);if(!Number.isInteger(_)||!Number.isInteger($)||_<0||_>23||$<0||$>23||_===$)return;return{startHour:_,endHour:$}}function J_(f){return f?.cacheKeep?.enabled===!0&&!!E0(f)}function p$(f){return J_(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function S_(f,_=new Date){if(!f)return!1;let $=_.getHours();if(f.startHour<f.endHour)return $>=f.startHour&&$<f.endHour;return $>=f.startHour||$<f.endHour}function z_(f=new Date){return`${f.getFullYear()}-${Af(f.getMonth()+1)}-${Af(f.getDate())}`}function D0(f,_=new Date){if(f&&f.startHour>f.endHour&&_.getHours()<f.endHour){let $=new Date(_);return $.setDate($.getDate()-1),z_($)}return z_(_)}function Gf(f){let _=f.window?`${Af(f.window.startHour)}-${Af(f.window.endHour)}`:"not configured",$=[`Cache keep: ${f.enabled?"enabled":"disabled"}`,`Window: ${_}`,"Mode requirement: `/claude-cache mode hybrid` must be active."];if(typeof f.hybridActive==="boolean")$.push(`Hybrid active: ${f.hybridActive?"yes":"no"}`);if(typeof f.trackedSessions==="number")$.push(`Tracked sessions: ${f.trackedSessions}`);if(f.nextPrewarmAt)$.push(`Next prewarm: ${new Date(f.nextPrewarmAt).toLocaleString()}`);return $.join(`
|
|
12
|
-
`)}function GE(f){let _=l$(f.argumentsText),$={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if(_.type==="status")return[L_,"",Gf($)].join(`
|
|
13
|
-
`);if(_.type==="disable")return[w$,"",Gf({...$,enabled:!1})].join(`
|
|
14
|
-
`);if(_.type==="window")return[h$,"",Gf({...$,enabled:!0,window:{startHour:_.startHour,endHour:_.endHour}})].join(`
|
|
15
|
-
`);if(_.type==="subagents")return[L_,"",Gf($),"",`Subagent tracking: ${_.enabled?"enabled":"disabled"}`].join(`
|
|
16
|
-
`);return[y$,"",k$,"",Gf($)].join(`
|
|
17
|
-
`)}function N0(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(N0);let _=f,$=_.cache_control;if($&&typeof $==="object"&&$.type==="ephemeral")return!0;return Object.values(_).some(N0)}async function v$(f){let _;try{_=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!N0(_))return{ok:!1,reason:"body has no explicit cache breakpoints"};let $=structuredClone(_);if($.max_tokens=0,delete $.stream,$.thinking?.type==="enabled")delete $.thinking;if($.output_config?.format)delete $.output_config;let E=$.tool_choice;if(E?.type==="tool"||E?.type==="any")delete $.tool_choice;return{ok:!0,bodyText:await H_(JSON.stringify(G_($)))}}class d${options;targets=new Map;timer=null;constructor(f){this.options=f}start(){if(this.timer)return;if(w.debug("cachekeep","started"),this.timer=setInterval(()=>{this.tick().catch((f)=>{w.warn("cachekeep","tick failed",{error:f instanceof Error?f.message:String(f)})})},q$),"unref"in this.timer)this.timer.unref()}stop(){if(!this.timer)return;w.debug("cachekeep","stopped"),clearInterval(this.timer),this.timer=null}stats(f,_=this.options.now?.()??Date.now()){let $=D0(f,new Date(_)),D=[...this.targets.values()].filter((E)=>E.dayKey===$),C=D.length?Math.min(...D.map((E)=>E.cacheExpiresAt-$0)):void 0;return{trackedSessions:D.length,nextPrewarmAt:C}}trackedCount(){return this.targets.size}totalBodyBytes(){return[...this.targets.values()].reduce((f,_)=>f+_.bodyText.length,0)}evictOldestTarget(){let f=this.targets.keys().next().value;if(f!==void 0)this.targets.delete(f)}pruneTargets(f,_){for(let[$,D]of this.targets){if(_&&D.dayKey!==_){this.targets.delete($);continue}if(f-D.cacheExpiresAt>x$)this.targets.delete($)}while(this.targets.size>I$)this.evictOldestTarget();while(this.totalBodyBytes()>O_){let $=this.targets.size;if(this.evictOldestTarget(),this.targets.size===$)break}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!J_(f.storage))return{tracked:!1,reason:"cachekeep disabled"};if(f.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};if(f.bodyText.length>O_)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let _=this.options.now?.()??Date.now(),$=E0(f.storage);if(!S_($,new Date(_)))return{tracked:!1,reason:"outside configured window"};let D=D0($,new Date(_));if(this.pruneTargets(_,D),this.targets.has(f.sessionId))this.targets.delete(f.sessionId);let C={};return f.headers.forEach((E,N)=>{C[N]=E}),this.targets.set(f.sessionId,{id:f.sessionId,url:f.url,headers:C,bodyText:f.bodyText,cacheExpiresAt:_+C0,dayKey:D,oauthAccountId:f.oauthAccountId}),this.pruneTargets(_,D),this.start(),{tracked:!0}}async prewarmNow(f){let _={};f.headers.forEach((D,C)=>{_[C]=D});let $={id:f.sessionId,url:f.url,headers:_,bodyText:f.bodyText,cacheExpiresAt:this.options.now?.()??Date.now(),dayKey:"",oauthAccountId:f.oauthAccountId};return this.sendPrewarm($)}async tick(){let f=await this.options.loadStorage(),_=E0(f),$=this.options.now?.()??Date.now(),D=D0(_,new Date($));if(this.pruneTargets($,D),!this.targets.size){this.stop();return}if(!p$(f))return;if(!S_(_,new Date($)))return;w.debug("cachekeep","fired",{targets:this.targets.size});let C=$+$0;for(let E of this.targets.values()){if(E.cacheExpiresAt>C)continue;await this.prewarm(E,$)}}async sendPrewarm(f){let _=await v$(f.bodyText);if(!_.ok)return _;let $=this.options.fetchImpl??fetch,D={...f,bodyText:_.bodyText},C=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),D):new Headers(f.headers);C.delete("content-length"),C.delete("transfer-encoding");let E=await $(f.url,{method:"POST",headers:C,body:_.bodyText,signal:AbortSignal.timeout(this.options.prewarmTimeoutMs??T$)});if(!E.ok)return{ok:!1,reason:await E.text().catch(()=>"").then((K)=>K||`HTTP ${E.status}`),status:E.status};let b=(await E.json().catch(()=>null))?.usage;return{ok:!0,...b&&{usage:b}}}async prewarm(f,_){let $=await this.sendPrewarm(f);if(!$.ok){if($.status==null)w.debug("cachekeep","prewarm skipped",{session:f.id,reason:$.reason}),this.targets.delete(f.id);else w.warn("cachekeep","prewarm failed",{session:f.id,status:$.status,reason:$.reason}),f.cacheExpiresAt=_+$0+300000;return}f.cacheExpiresAt=_+C0,w.debug("cachekeep","prewarm succeeded",{session:f.id,...$.usage&&{usage:$.usage}})}}var BE="claude-account";function i$(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};let $=_[0],D=_.slice(1).join(" ");if($==="enable"&&D)return{type:"enable",id:D};if($==="disable"&&D)return{type:"disable",id:D};if($==="remove"&&D)return{type:"remove",id:D};if($==="move-up"&&D)return{type:"move-up",id:D};if($==="move-down"&&D)return{type:"move-down",id:D};if($==="add-apikey"&&D){let C=D,E,N,b=C.match(/--base-url\s+(\S+)/);if(b)E=b[1],C=C.replace(b[0],"").trim();let K=C.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(K)N=K[1],C=C.replace(K[0],"").trim();let U,G=C.match(/--label\s+(.+)/);if(G)U=G[1]?.trim()||void 0,C=C.replace(G[0],"").trim();let O=C.indexOf(" ");if(O===-1){if(!C)return{type:"usage"};return{type:"add-apikey",apiKey:C,baseURL:E,authHeader:N,label:U}}let Z=C.slice(0,O),H=C.slice(O+1).trim();return{type:"add-apikey",apiKey:Z,label:U??(H||void 0),baseURL:E,authHeader:N}}if($==="add-oauth-start")return{type:"add-oauth-start"};if($==="add-oauth-finish"&&D){let C=D,E,N=C.match(/--label\s+(.+)/);if(N)E=N[1]?.trim()||void 0,C=C.replace(N[0],"").trim();if(!C)return{type:"usage"};return{type:"add-oauth-finish",code:C,label:E}}return{type:"usage"}}function u$(f){let _=[],$=f.quota?.mainQuota?.five_hour;_.push({id:"main",label:f.main?.provider==="anthropic"?"OpenCode anthropic":"Main",role:"main",enabled:!0,quotaPercent:$?.usedPercent??null});for(let D of f.accounts){let C=D.quota?.five_hour;_.push({id:D.id,label:D.label??D.id,role:"fallback",enabled:D.enabled!==!1,quotaPercent:C?.usedPercent??null})}return _}var b0=["Usage:"," /claude-account Show account list"," /claude-account enable <id> Enable a fallback account"," /claude-account disable <id> Disable a fallback account"," /claude-account remove <id> Remove a fallback account"," /claude-account move-up <id> Move a fallback account up"," /claude-account move-down <id> Move a fallback account down"," /claude-account add-apikey <key> Add an API key fallback account"," /claude-account add-oauth-start Start OAuth device flow"," /claude-account add-oauth-finish <code> Complete OAuth flow"].join(`
|
|
18
|
-
`);function ME(f){let _=i$(f.argumentsText),$=f.storage.accounts,D="main";if(_.type==="status"){let E=u$(f.storage),N=["## Claude Accounts",""];for(let b of E){let K=b.quotaPercent!=null?` ${Math.round(b.quotaPercent)}%`:"",U=!b.enabled?" (disabled)":"";N.push(`- **${b.label}** [${b.role}]${U}${K}`)}return N.push("",b0),{text:N.join(`
|
|
19
|
-
`)}}if(_.type==="usage")return{text:b0};if(_.type==="add-apikey")return{text:"add-apikey"};if(_.type==="add-oauth-start")return{text:"add-oauth-start"};if(_.type==="add-oauth-finish")return{text:"add-oauth-finish"};let C=_.id;if(C==="main")return{text:`Cannot ${_.type} the main account (OpenCode managed).`};if(_.type==="enable"||_.type==="disable"){let E=$.find((N)=>N.id===C);if(!E)return{text:`Account "${C}" not found.`};return{text:`Account "${E.label??C}" ${_.type}d.`,updated:{id:C,action:_.type,enabled:_.type==="enable"}}}if(_.type==="remove"){let E=$.find((N)=>N.id===C);if(!E)return{text:`Account "${C}" not found.`};return{text:`Account "${E.label??C}" removed.`,updated:{id:C,action:"remove"}}}if(_.type==="move-up"){let E=$.findIndex((U)=>U.id===C);if(E<0)return{text:`Account "${C}" not found.`};if(E===0)return{text:`Account "${$[E]?.label??C}" is already first.`};let N=$.map((U)=>U.id),b=[...$];[b[E-1],b[E]]=[b[E],b[E-1]];let K=b.map((U)=>U.id);return{text:`Account "${$[E]?.label??C}" moved up.`,updated:{id:C,action:"reorder",previousOrder:N,newOrder:K}}}if(_.type==="move-down"){let E=$.findIndex((U)=>U.id===C);if(E<0)return{text:`Account "${C}" not found.`};if(E===$.length-1)return{text:`Account "${$[E]?.label??C}" is already last.`};let N=$.map((U)=>U.id),b=[...$];[b[E],b[E+1]]=[b[E+1],b[E]];let K=b.map((U)=>U.id);return{text:`Account "${$[E]?.label??C}" moved down.`,updated:{id:C,action:"reorder",previousOrder:N,newOrder:K}}}return{text:b0}}import{createHash as g$}from"node:crypto";import{mkdir as s$,writeFile as Qf}from"node:fs/promises";import{tmpdir as r$}from"node:os";import{join as X_}from"node:path";var YE="claude-dump",n$="## Claude Dump Status",c$="## Claude Dump Enabled",t$="## Claude Dump Disabled",o$="## Claude Dump Usage",a$="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",e$="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",fD=X_(r$(),"opencode-anthropic-auth-dumps"),jf=!1,W_=0,_D=100,ff=new Map;function ZE(f){jf=f}function F_(){return process.env[e$]||fD}function $D(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};return{type:"usage"}}function Rf(f){let _=f?.enabled??jf;return[n$,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Directory: ${F_()}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Captures: final rewritten Anthropic body in direct and relay modes; request/relay metadata is redacted","- Warning: body dumps may contain prompt/session content; turn this off after debugging"].join(`
|
|
20
|
-
`)}function XE(f){let _=$D(f.argumentsText),$=f.enabled??jf;if(_.type==="status")return Rf({enabled:$});if(_.type==="enable")return[c$,"",Rf({enabled:!0})].join(`
|
|
21
|
-
`);if(_.type==="disable")return[t$,"",Rf({enabled:!1})].join(`
|
|
22
|
-
`);return[o$,"",a$,"",Rf({enabled:$})].join(`
|
|
23
|
-
`)}function Y_(f){return f.length<=16?f:`${f.slice(0,12)}…`}function V_(f){let _=f.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!_)return"session-unknown";return _.length<=80?_:_.slice(0,80)}function DD(f){if(f.transport!=="direct")return`${f.transport}-p${f.protocol}-${f.mode}`;return`direct${f.route?`-${V_(f.route)}`:""}`}function CD(f){let _=f.affinity?.trim();if(_)return`session:${_}`;return`request:${f.route??"direct"}:${f.url??""}`}function ED(f,_){if(!ff.has(f))while(ff.size>=_D){let $=ff.keys().next().value;if($===void 0)break;ff.delete($)}ff.set(f,_)}function ND(f){if(f==null)return;return Object.fromEntries(new Headers(f).entries())}function m_(f){return g$("sha256").update(f).digest("hex")}function bD(f){return M_(f)}function KD(f,_){if(f==null)return null;if(f===_)return{changed:!1,firstByte:-1,lastPreviousByte:-1,lastCurrentByte:-1,previousBytes:f.length,currentBytes:_.length};let $=0;while($<f.length&&$<_.length&&f[$]===_[$])$+=1;let D=f.length-1,C=_.length-1;while(D>=$&&C>=$&&f[D]===_[C])D-=1,C-=1;return{changed:!0,firstByte:$,lastPreviousByte:D,lastCurrentByte:C,changedPreviousBytes:D-$+1,changedCurrentBytes:C-$+1,previousBytes:f.length,currentBytes:_.length}}function UD(f){try{let _=JSON.parse(f);return _!=null&&typeof _==="object"&&!Array.isArray(_)?_:null}catch(_){return L(`dump body parse failed: ${_ instanceof Error?_.message:String(_)}`),null}}function K0(f){return m_(JSON.stringify(f))}function GD(f){let _=UD(f);if(!_)return{parseable:!1};let $=Array.isArray(_.messages)?_.messages:[],D=Array.isArray(_.system)?_.system:[],C=$[0],E=$.slice(1);return{parseable:!0,model:typeof _.model==="string"?_.model:void 0,stream:_.stream,systemCount:D.length,messagesCount:$.length,systemHash:K0(D),message0Hash:C===void 0?null:K0(C),message0Bytes:C===void 0?0:JSON.stringify(C).length,messagesAfter0Hash:K0(E),messagesAfter0Bytes:JSON.stringify(E).length,cch:bD(f)}}function Pf(f){if(Array.isArray(f))return f.map(Pf);if(f==null||typeof f!=="object")return f;let _={};for(let[$,D]of Object.entries(f)){let C=$.toLowerCase();if(C==="authorization"||C==="x-api-key"||C==="cookie"||C==="set-cookie"||Z_($)){_[$]="[redacted]";continue}_[$]=Pf(D)}return _}async function A_(f){if(!jf)return;W_+=1;let _=f.affinity?.trim()||"session-unknown",$=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(W_).padStart(5,"0")}-${V_(_)}-${DD(f)}`,D=F_(),C=X_(D,$),E={body:`${C}.body.json`,metadata:`${C}.meta.json`};if(f.payload!==void 0)E.relay=`${C}.relay.json`;if(f.request!==void 0)E.request=`${C}.request.json`;try{await s$(D,{recursive:!0});let N={id:$,createdAt:new Date().toISOString(),session:Y_(_),transport:f.transport,protocol:f.protocol,mode:f.mode,route:f.route,status:f.status,error:f.error,bodyBytes:f.bodyText.length,relayBytes:f.relayBytes,bodyHash:m_(f.bodyText),diff:KD(f.previousBodyText,f.bodyText),body:GD(f.bodyText),files:E},b=[Qf(E.body,f.bodyText,"utf8"),Qf(E.metadata,`${JSON.stringify(N,null,2)}
|
|
24
|
-
`,"utf8")];if(f.payload!==void 0&&E.relay)b.push(Qf(E.relay,`${JSON.stringify(Pf(f.payload),null,2)}
|
|
25
|
-
`,"utf8"));if(f.request!==void 0&&E.request)b.push(Qf(E.request,`${JSON.stringify(Pf({...f.request,headers:ND(f.request.headers)}),null,2)}
|
|
26
|
-
`,"utf8"));await Promise.all(b),L(`dumped request id=${$} session=${Y_(_)} body=${E.body} meta=${E.metadata}`)}catch(N){L(`dump failed: ${N instanceof Error?N.message:String(N)}`)}}async function FE(f){if(!jf)return;let _=CD(f),$=ff.get(_);await A_({affinity:f.affinity,transport:"direct",route:f.route,status:f.status,error:f.error,bodyText:f.bodyText,previousBodyText:$,request:{url:f.url,method:f.method,headers:f.headers}}),ED(_,f.bodyText)}async function Q_(f){await A_({affinity:f.affinity,transport:f.transport,protocol:f.protocol,mode:f.mode,status:f.status,bodyText:f.bodyText,previousBodyText:f.previousBodyText,payload:f.payload,relayBytes:f.relayBytes})}var mE="claude-fast";var If=!1;function AE(){return If}function QE(f){If=f}function jD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"enable"};if(_.length===1&&_[0]==="off")return{type:"disable"};return{type:"usage"}}function qf(f){return["## Claude Fast Mode Status","",`- Enabled: ${f?.enabled??If?"enabled":"disabled"}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: adds Anthropic fast mode to supported Opus requests","- Supported models: claude-opus-4-6, claude-opus-4-7, and claude-opus-4-8",'- Request changes: adds `speed: "fast"` and the `fast-mode-2026-02-01` beta header',"- Note: fast and standard speeds do not share prompt-cache prefixes"].join(`
|
|
27
|
-
`)}function RE(f){let _=jD(f.argumentsText),$=f.enabled??If;if(_.type==="status")return qf({enabled:$});if(_.type==="enable")return["## Claude Fast Mode Enabled","",qf({enabled:!0})].join(`
|
|
28
|
-
`);if(_.type==="disable")return["## Claude Fast Mode Disabled","",qf({enabled:!1})].join(`
|
|
29
|
-
`);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",qf({enabled:$})].join(`
|
|
30
|
-
`)}var _f="claude-killswitch";function BD(f){let _=f.trim().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&_[0]==="on")return{type:"on"};if(_.length===1&&_[0]==="off")return{type:"off"};if(_[0]==="set"){let $=[];for(let D=1;D<_.length;D++){let C=_[D]?.match(/^([^:]+):(\d+),(\d+)(?:,(\d+))?$/);if(!C)return{type:"usage"};let[,E,N,b,K]=C,U=typeof K==="string"&&K.length>0?Number.parseInt(K,10):void 0,G={account:E,fh:Number.parseInt(N,10),sd:Number.parseInt(b,10)};if(U!==void 0)G.scoped=U;$.push(G)}if($.length===0)return{type:"usage"};return{type:"set",entries:$}}return{type:"usage"}}function xf(f,_){let $=f.enabled===!0,D=["## Killswitch","",`Status: **${$?"ON":"OFF"}**`];if($){D.push(""),D.push("| Account | 5h threshold | 1w threshold | Scoped |"),D.push("| ------- | ------------ | ------------ | ------ |");let C=bf(f.main);D.push(`| main | ≥ ${C.five_hour}% | ≥ ${C.seven_day}% | ≤ ${C.scoped}% |`);for(let E of _){let N=bf(f.accounts?.[E]??f.main);D.push(`| ${E} | ≥ ${N.five_hour}% | ≥ ${N.seven_day}% | ≤ ${N.scoped}% |`)}}return D.join(`
|
|
31
|
-
`)}var R_=["## Killswitch Commands","","```",`/${_f} — show status`,`/${_f} on — enable with current or default thresholds`,`/${_f} off — disable`,`/${_f} set all:5,10 — set all accounts to 5h≥5%, 1w≥10%`,`/${_f} set main:3,8,0 — set 5h≥3%, 1w≥8%, scoped≤0%`,`/${_f} set main:3,8 work-alt:5,10 — per-account`,"```"].join(`
|
|
32
|
-
`);function IE(f){let _=BD(f.argumentsText);if(_.type==="status")return{text:`${xf(f.config,f.accountIds)}
|
|
33
|
-
|
|
34
|
-
${R_}`};if(_.type==="on"){let D={...f.config,enabled:!0,main:f.config.main??{five_hour:g.five_hour,seven_day:g.seven_day}};return{text:`## Killswitch Enabled
|
|
35
|
-
|
|
36
|
-
${xf(D,f.accountIds)}`,updatedConfig:D}}if(_.type==="off")return{text:"## Killswitch Disabled",updatedConfig:{...f.config,enabled:!1}};if(_.type==="set"){let D={...f.config.accounts??{}},C={...f.config,enabled:!0,accounts:D};for(let N of _.entries){let b={five_hour:N.fh,seven_day:N.sd};if(N.scoped!==void 0)b.scoped=N.scoped;if(N.account==="main")C.main=b;else if(N.account==="all"){C.main=b;for(let K of f.accountIds)D[K]=b}else D[N.account]=b}return{text:`## Killswitch Updated
|
|
37
|
-
|
|
38
|
-
${xf(C,f.accountIds)}`,updatedConfig:C}}return{text:`${xf(f.config,f.accountIds)}
|
|
39
|
-
|
|
40
|
-
${R_}`}}var TE="claude-logging",MD=["error","warn","info","debug","trace"];function HD(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&MD.includes(_[0]))return{type:"level",level:_[0]};return{type:"usage"}}function U0(f){return["## Claude Log Level","",`Current log level: \`${f?.level??"info"}\``,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Valid levels: error, warn, info, debug, trace","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`."].join(`
|
|
41
|
-
`)}function hE(f){let _=HD(f.argumentsText),$=f.level??"info";if(_.type==="status")return U0({level:$});if(_.type==="level")return["## Claude Log Level Updated","",`Level set to \`${_.level}\`.`,"",...U0({level:_.level}).split(`
|
|
42
|
-
`).slice(2)].join(`
|
|
43
|
-
`);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...U0({level:$}).split(`
|
|
44
|
-
`).slice(2)].join(`
|
|
45
|
-
`)}var yE="claude-fable-5";var OD=["claude-fable-5","claude-mythos-5"],LD={type:"adaptive",display:"summarized"},kE={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},lE=1e6,pE=128000,vE="2026-06-09",dE={["claude-fable-5"]:{id:"claude-fable-5",name:"Claude Fable 5"},["claude-mythos-5"]:{id:"claude-mythos-5",name:"Claude Mythos 5",limited:!0}};function iE(f){return typeof f==="string"&&OD.some((_)=>f===_||f.startsWith(`${_}-`))}var P_="claude-sonnet-5",uE=LD;function gE(f){return typeof f==="string"&&(f===P_||f.startsWith(`${P_}-`))}function sE(f){if(typeof f!=="string")return!1;if(f.startsWith("gAAAA"))return!0;if(!f.startsWith("{"))return!1;try{let _=JSON.parse(f);return _.type==="reasoning"&&typeof _.id==="string"&&_.id.startsWith("rs_")&&typeof _.encrypted_content==="string"&&_.encrypted_content.startsWith("gAAAA")}catch{return!1}}import{createHash as SD}from"node:crypto";var zD=globalThis.setTimeout;function I(f){return SD("sha256").update(f).digest("hex").slice(0,16)}class v{main=null;mainTokenFp=null;fallbacks=new Map;fallbackTokenFps=new Map;inflightMain=null;inflightMainFp=null;inflightFallbacks=new Map;mainLastApiError=void 0;fallbackApiErrors=new Map;fallbackErrorTokenFps=new Map;apiGate=Promise.resolve();lastApiCallAt=0;storage;fetchImpl;now;onMainQuotaFetched;onApiError;constructor(f){this.storage=f.storage,this.fetchImpl=f.fetchImpl??fetch,this.now=f.now??Date.now,this.onMainQuotaFetched=f.onMainQuotaFetched,this.onApiError=f.onApiError,this.seedMainFromStorage(f.storage),this.seedMainBackoffFromStorage(f.storage)}getMain(f){if(f&&this.main&&this.mainTokenFp&&this.mainTokenFp!==I(f))this.main=null,this.mainTokenFp=null;return this.main}getFallback(f,_){let $=this.fallbacks.get(f)??null;if(!_||!$)return $;if(this.fallbackTokenFps.get(f)!==I(_))return this.fallbacks.delete(f),this.fallbackTokenFps.delete(f),null;return $}getAllFallbacks(){return this.fallbacks}setMain(f,_){this.mainTokenFp=I(f),this.main=_}setFallback(f,_,$){if(this.fallbacks.set(f,_),$)this.fallbackTokenFps.set(f,I($));else this.fallbackTokenFps.delete(f)}async refreshMain(f){let _=I(f);if(this.mainTokenFp&&this.mainTokenFp!==_)this.main=null,this.mainTokenFp=null;if(this.inflightMain&&this.inflightMainFp===_)return this.inflightMain;if(this.isBackedOff()){if(this.main)return this.main.quota;throw Error("Quota API rate-limited — try again later")}return this.inflightMainFp=_,this.inflightMain=this._fetchMain(f),this.inflightMain}async refreshFallback(f,_){let $=v.fallbackInflightKey(f,_),D=this.inflightFallbacks.get($);if(D)return D;if(this.isFallbackBackedOff(f,_)){let E=this.getFallback(f,_);if(E)return E.quota;throw Error("Quota API rate-limited — try again later")}let C=this._fetchFallback(f,_);return this.inflightFallbacks.set($,C),C}async refreshAllFallbacks(f){let _=this.now();for(let $ of f){if($.enabled===!1)continue;if(!$.access)continue;let D=this.getFallback($.id,$.access);if(D&&_<D.refreshAfter)continue;try{await this.refreshFallback($.id,$.access)}catch{}}}refreshMainInBackground(f){if(this.inflightMain)return;if(this.isBackedOff())return;this.refreshMain(f).catch(()=>{})}isMainStale(){if(!this.main)return!0;return this.now()>=this.main.refreshAfter}isFallbackStale(f,_){let $=this.getFallback(f,_);if(!$)return!0;return this.now()>=$.refreshAfter}shouldRefreshOnRequestCount(f){let _=f_(this.storage);if(_<=0)return!1;return f>0&&f%_===0}needsRefresh(f){return this.isMainStale()||this.shouldRefreshOnRequestCount(f)}updateStorage(f){this.storage=f,this.seedMainFromStorage(f),this.seedMainBackoffFromStorage(f)}seedMainFromStorage(f,_){let $=e0(f);if(!$)return;let D=_?I(_):null;if(D&&$.tokenFingerprint&&$.tokenFingerprint!==D)return;let C={quota:$.quota,refreshAfter:af($.quota,f,$.checkedAt),checkedAt:$.checkedAt};if(this.main&&this.main.checkedAt>=C.checkedAt&&(!D||!this.mainTokenFp||this.mainTokenFp===D))return;this.main=C,this.mainTokenFp=$.tokenFingerprint??null}seedMainBackoffFromStorage(f){let _=f?.quota?.mainLastQuotaApiError;this.mainLastApiError=_&&a(_,this.now())?_:void 0}seedFallbacksFromAccounts(f){let _=h(this.storage);for(let $ of f){if($.enabled===!1)continue;if(!$.quota)continue;let D=Math.max($.quota.five_hour?.checkedAt??0,$.quota.seven_day?.checkedAt??0);if(D<=0)continue;let C=this.getFallback($.id,$.access);if(C&&C.checkedAt>=D)continue;this.setFallback($.id,{quota:$.quota,refreshAfter:D+_,checkedAt:D},$.access)}}isBackedOff(){return a(this.mainLastApiError,this.now())}isFallbackBackedOff(f,_){if(_){if(this.fallbackErrorTokenFps.get(f)!==I(_))return!1}return a(this.fallbackApiErrors.get(f),this.now())}getLastApiError(){return this.mainLastApiError}static API_CALL_GAP_MS=1000;static fallbackInflightKey(f,_){return JSON.stringify([f,I(_)])}static quotaLockName(f){return`opencode-fallback-quota-refresh-${f.replace(/[^a-zA-Z0-9._-]+/g,"-")||"account"}`}_enqueueApiFetch(f){let _=async()=>{let D=this.now()-this.lastApiCallAt;if(D<v.API_CALL_GAP_MS)await new Promise((C)=>{let E=zD(C,v.API_CALL_GAP_MS-D);if(typeof E==="object"&&"unref"in E)E.unref()});return this.lastApiCallAt=this.now(),f()},$=this.apiGate.then(_,_);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(f){let _=I(f);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 $=await Zf({name:"opencode-main-quota-refresh",ttlMs:30000});if(!$){let D=this.main;if(D&&this.now()<D.refreshAfter)return D.quota;throw Error("Quota refresh is already in progress")}try{let D=this.now(),C=await Ff({accessToken:f,fetchImpl:this.fetchImpl,now:this.now}),E=this.now();return this.mainTokenFp=I(f),this.main={quota:C,refreshAfter:af(C,this.storage,E),checkedAt:E},this.mainLastApiError=void 0,this.onMainQuotaFetched?.(C,E,this.mainTokenFp,D),C}catch(D){throw this._handleMainFetchError(D),D}finally{await $.release()}}finally{if(this.inflightMainFp===_)this.inflightMain=null,this.inflightMainFp=null}})}async _fetchFallback(f,_){return this._enqueueApiFetch(async()=>{try{if(this.isFallbackBackedOff(f,_)){let D=this.getFallback(f,_);if(D)return D.quota;throw Error("Quota API rate-limited — try again later")}let $=await Zf({name:v.quotaLockName(f),ttlMs:30000});if(!$){let D=this.getFallback(f,_);if(D&&this.now()<D.refreshAfter)return D.quota;throw Error("Quota refresh is already in progress")}try{let D=await Ff({accessToken:_,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();return this.setFallback(f,{quota:D,refreshAfter:C+h(this.storage),checkedAt:C},_),this.fallbackApiErrors.delete(f),this.fallbackErrorTokenFps.delete(f),D}finally{await $.release()}}catch($){throw this._handleFallbackFetchError(f,_,$),$}finally{this.inflightFallbacks.delete(v.fallbackInflightKey(f,_))}})}static isAuthError(f){if(f.status===401||tf(f))return!0;let $=f instanceof Error?f.message:String(f);return/quota check failed: 401\b/.test($)}_handleMainFetchError(f){if(v.isAuthError(f))return;this.mainLastApiError=Xf({error:f,now:this.now(),previous:this.mainLastApiError}),this.onApiError?.(this.mainLastApiError)}_handleFallbackFetchError(f,_,$){if(v.isAuthError($))return;let D=I(_),C=this.fallbackErrorTokenFps.get(f)===D?this.fallbackApiErrors.get(f):void 0;this.fallbackApiErrors.set(f,Xf({error:$,now:this.now(),previous:C})),this.fallbackErrorTokenFps.set(f,D)}}var aE="claude-quota",q_={five_hour:"5h",seven_day:"1w"};function Tf(f){return`${Math.round(f*10)/10}%`}function hf(f,_){let $=Math.max(0,_-f),D=Math.floor($/60000);if(D<1)return"just now";if(D===1)return"1m ago";if(D<60)return`${D}m ago`;let C=Math.floor(D/60),E=D%60;if(E===0)return`${C}h ago`;return`${C}h ${E}m ago`}function JD(f,_){let $=Date.parse(f);if(!Number.isFinite($))return f;let D=$-_;if(D<=0)return"now";let C=Math.max(1,Math.ceil(D/60000));if(C<60)return`in ${C}m`;let E=Math.floor(C/60),N=C%60;if(N===0)return`in ${E}h`;return`in ${E}h ${N}m`}function x_(f,_){if(!f)return"";return`, resets ${JD(f,_)}`}function I_(f,_,$){if(!_)return` - ${q_[f]}: unknown`;return[` - ${q_[f]}: ${Tf(_.remainingPercent)} remaining`,` (${Tf(_.usedPercent)} used`,`${x_(_.resetsAt,$)}, checked ${hf(_.checkedAt,$)})`].join("")}function WD(f,_){return[` - ${f.title}: ${Tf(f.remainingPercent)} remaining`,` (${Tf(f.usedPercent)} used`,`${x_(f.resetsAt,_)}, checked ${hf(f.checkedAt,_)})`].join("")}function YD(f){return f.label?.trim()||f.id}function ZD(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function eE(f,_=new Map){if(!f?.accounts.length)return[];return f.accounts.filter(T).map(($)=>{let D=_.get($.id)??ZD($);return{name:YD($),role:"fallback",enabled:$.enabled!==!1,quota:$.quota,lastRefreshedAt:$.lastRefreshedAt,...D&&{error:D}}})}function fN(f){let _=f.now??Date.now(),$=["## Claude Quotas",""];if(f.refreshedAt)$.push(`Refreshed: ${hf(f.refreshedAt,_)}`,"");if(!f.accounts.length)return $.push("No Claude OAuth accounts found yet."),$.join(`
|
|
46
|
-
`);for(let D of f.accounts){let C=D.role==="main"?"main":"fallback",E=D.enabled===!1?" disabled":"";if($.push(`### ${D.name} (${C}${E})`),D.lastRefreshedAt)$.push(` - Last token refresh: ${hf(D.lastRefreshedAt,_)}`);if(D.error)$.push(` - Error: ${D.error}`);$.push(I_("five_hour",D.quota?.five_hour,_)),$.push(I_("seven_day",D.quota?.seven_day,_));for(let N of D.quota?.scoped??[])$.push(WD(N,_));$.push("")}return $.join(`
|
|
47
|
-
`).trimEnd()}import{Buffer as v_}from"node:buffer";import{createHash as XD,randomBytes as FD}from"node:crypto";class j0 extends Error{}class B0 extends Error{code="ECONNRESET";syscall="websocket";closeCode;closeReason;wasClean;constructor(f,_){super(f);this.name="RelayWebSocketConnectionResetError",this.closeCode=_?.code,this.closeReason=_?.reason,this.wasClean=_?.wasClean}}var k=new Map,c=new Map,T_=new Set,VD=7200000,mD=1800000,AD=128,QD=32,h_=0;function G0(){return h_+=1,`req_${Date.now().toString(36)}_${h_.toString(36)}`}function wf(f){if(T_.has(f))return;T_.add(f),L(f)}function NN(f){let _=f?.relay;if(!_)return wf("disabled: no relay config found"),null;if(_.enabled!==!0)return wf("disabled: relay.enabled is not true"),null;if(!_.url?.trim()||!_.token?.trim())return wf("disabled: missing relay url or token"),null;let $=_.transport==="http"?"http":"websocket";return wf(`configured transport=${$} protocol=${$==="websocket"?2:1} url=${_.url.trim()} fallbackToDirect=${_.fallbackToDirect!==!1}`),{enabled:!0,url:_.url.trim(),token:_.token.trim(),fallbackToDirect:_.fallbackToDirect!==!1,transport:$}}function bN(){return FD(32).toString("base64url")}function RD(f){return`sha256:${XD("sha256").update(f).digest("hex")}`}function w_(f,_){let $=0,D=Math.min(f.length,_.length);while($<D&&f.charCodeAt($)===_.charCodeAt($))$++;let C=f.length,E=_.length;while(C>$&&E>$&&f.charCodeAt(C-1)===_.charCodeAt(E-1))C--,E--;return{start:$,deleteCount:C-$,insert:_.slice($,E)}}function PD(f){return f.deleteCount===0&&f.insert.length===0}function y_(f){let _=f.match(/\bcch=([0-9a-f]{5});/),$=_?.[1];if(!$||_.index==null)return null;let D=_.index+4;return{start:D,end:D+$.length,token:$}}function qD(f,_,$,D){return`${f.slice(0,_)}${D}${f.slice($)}`}function d_(f,_){let $=y_(f),D=y_(_);if($&&D&&$.start===D.start&&$.end-$.start===D.end-D.start&&$.token!==D.token){let C={start:$.start,deleteCount:$.end-$.start,insert:D.token},E=qD(f,$.start,$.end,D.token),N=w_(E,_);return PD(N)?C:[C,N]}return w_(f,_)}function ID(f,_){if(typeof _!=="string")return!1;try{let $=f instanceof Request?new URL(f.url):new URL(f.toString());return $.pathname==="/v1/messages"||$.pathname==="/messages"}catch{return!1}}function xD(f){let _={};for(let[$,D]of f.entries()){if($==="x-session-affinity"||$==="x-opencode-session")continue;_[$]=D}return _}async function k_(f,_,$){let D=z(),C=JSON.stringify(_);return $f("http_payload_stringify",{session:J(_.affinity),ms:R(z()-D),relayBytes:C.length,mode:_.mode}),fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:C,signal:$??void 0})}function J(f){return f.length>12?`${f.slice(0,12)}…`:f}function z(){return performance.now()}function R(f){return Math.round(f*10)/10}function TD(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function $f(f,_){if(!TD())return;L(`[perf] relay ${f} ${JSON.stringify(_)}`)}function hD(f){let{input:_,init:$,headers:D,bodyText:C,affinity:E,previous:N,nextHash:b}=f,K=_ instanceof Request?_.url:_.toString(),U={protocol:1,type:"request",affinity:E,upstream:{url:K,method:$?.method||(_ instanceof Request?_.method:"POST"),headers:xD(D)},next_hash:b};return N?{...U,mode:"patch",base_hash:N.hash,revision:N.revision+1,patch:d_(N.body,C)}:{...U,mode:"full_sync",revision:1,body:C}}function M0(f,_){return{protocol:f.protocol,type:"request",affinity:f.affinity,upstream:f.upstream,next_hash:f.next_hash,mode:"full_sync",revision:1,body:_}}function i_(f,_,$,D){let C=Date.now();k.delete(f),k.set(f,{body:_,hash:$,revision:D,updatedAt:C}),H0(C)}async function l_(f){let{config:_,payload:$,bodyText:D,fallback:C,signal:E}=f,N=$,b=await k_(_,N,E);if(b.status===409&&N.mode==="patch")L(`state mismatch from relay session=${J(N.affinity)}; retrying full_sync`),await b.body?.cancel().catch(()=>{}),N=M0(N,D),b=await k_(_,N,E);if(!b.ok&&b.status>=500&&_.fallbackToDirect)return L(`relay returned ${b.status}; falling back direct session=${J(N.affinity)}`),await b.body?.cancel().catch(()=>{}),{response:await C(),payload:N,transport:"http",protocol:N.protocol,usedRelay:!1};return{response:b,payload:N,transport:"http",protocol:N.protocol,usedRelay:!0}}function wD(f,_){let $=new URL(f);return $.protocol=$.protocol==="http:"?"ws:":"wss:",$.pathname="/ws",$.searchParams.set("token",_),$.toString()}function yD(f){return new Uint8Array(v_.from(f,"base64"))}function kD(f){if(f instanceof Uint8Array)return f;if(f instanceof ArrayBuffer)return new Uint8Array(f);if(ArrayBuffer.isView(f))return new Uint8Array(f.buffer,f.byteOffset,f.byteLength);return new Uint8Array(v_.from(String(f)))}function lD(f){return JSON.parse(f)}function p_(f){let _=f,$=[`code=${_.code??"unknown"}`,`wasClean=${_.wasClean??"unknown"}`];if(_.reason)$.push(`reason=${JSON.stringify(_.reason)}`);return $.join(" ")}function pD(f){let _=f.message||"relay websocket error";return f.status?`relay websocket error ${f.status}: ${_}`:_}class u_{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;lastUsedAt=Date.now();constructor(f,_){this.config=f,this.affinity=_}touch(f=Date.now()){this.lastUsedAt=f}canEvict(f=Date.now()){return!this.pending&&!this.connecting&&f-this.lastUsedAt>mD}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send(f,_,$=!1){this.touch();let D=z(),C=this.queue.catch(()=>{}).then(()=>this.startQueued(f,_,D,$)),E=C.then(async({response:N,getPayload:b})=>({response:await N,payload:b(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=C.then(({done:N})=>N.catch(()=>{}),()=>{}),E}async startQueued(f,_,$,D){let C=z();await this.ensureConnected();let E=z(),N=k.get(this.affinity),b=this.serverState?.hash,K={...f,protocol:2,id:G0()};if(K.mode==="patch"&&(!b||b!==K.base_hash))K.mode="full_sync",K.revision=(this.serverState?.revision??0)+1,delete K.base_hash,delete K.patch,K.body=_;if(K.mode==="patch"&&N)K.patch=d_(N.body,_);L(`perf websocket send_start session=${J(this.affinity)} request=${K.id} mode=${K.mode} queueMs=${R(E-$)} connectMs=${R(E-C)} bodyBytes=${_.length} relayBytes=${JSON.stringify(K).length}`);let U=K,G=this.sendPayload(K,_,D);G.done.catch(()=>{});let O=G.done,Z=G.response.catch((X)=>{if(!(X instanceof j0)||K.mode!=="patch")throw X;let W=M0(K,_);W.protocol=2,W.id=G0(),W.revision=(this.serverState?.revision??0)+1,U=W;let B=this.sendPayload(W,_,D);return B.done.catch(()=>{}),O=B.done,B.response}),H=Z.then(()=>O,()=>O.catch(()=>{}));return{response:Z,done:H,getPayload:()=>U}}async ensureConnected(){if(this.socket?.readyState===WebSocket.OPEN&&this.serverState!==void 0)return;if(this.connecting)return await this.connecting;this.connecting=new Promise((f,_)=>{let $=wD(this.config.url,this.config.token),D=new URL($);D.searchParams.set("affinity",this.affinity);let C=new WebSocket(D.toString());this.socket=C,this.serverState=void 0;let E=setTimeout(()=>{C.close(),_(Error("relay websocket ready timed out"))},15000);C.addEventListener("message",(N)=>{try{if(typeof N.data!=="string"){this.handleBinaryChunk(N.data);return}let b=lD(N.data);if(b.type==="ready"){clearTimeout(E),this.serverState=b.state,f();return}this.handleMessage(b)}catch(b){clearTimeout(E),_(b),this.failPending(b),C.close()}}),C.addEventListener("error",()=>{clearTimeout(E);let N=new B0("relay websocket error");_(N),this.failPending(N)}),C.addEventListener("close",(N)=>{if(clearTimeout(E),this.socket===C)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let b=this.pending.responseStartedAt!=null,K=b?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,K,N))return;let U=b?new B0("relay websocket closed during response stream",N):Error("relay websocket closed before response");L(`websocket ${b?"closed during response stream":"closed before response without retry"} session=${J(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${p_(N)}`),this.failPending(U)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,_,$){let D=this.socket;if(!D||D.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let C=z(),E,N,b=new Promise((U,G)=>{E=U,N=G});return{response:new Promise((U,G)=>{let O={payload:f,bodyText:_,resolve:U,reject:G,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:E,rejectDone:N,sentAt:C,optimisticResponse:$,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=O,this.resetPendingTimeout(O),D.send(JSON.stringify(f)),$)this.resolvePendingResponse(O,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:b}}resetPendingTimeout(f){clearTimeout(f.timeout),f.timeout=setTimeout(()=>{if(this.pending!==f)return;if(this.retryPendingBeforeResponse(f,"response timed out"))return;this.failPending(Error("relay websocket response timed out")),this.socket?.close()},45000)}retryPendingBeforeResponse(f,_,$){if(f.responseStartedAt!=null&&f.streamByteCount>0)return!1;if(f.streamDone)return!1;if(f.retryAttempts>=1)return!1;f.retryAttempts+=1,f.retryingBeforeResponse=!0,clearTimeout(f.timeout);let D=f.retryAttempts,C=f.payload.id;return L(`websocket ${_}; reconnecting and retrying full_sync session=${J(this.affinity)} request=${C} retry=${D} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}${$?` ${p_($)}`:""}`),this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0,(async()=>{try{if(await this.ensureConnected(),this.pending!==f)return;let E=M0(f.payload,f.bodyText);E.protocol=2,E.id=G0(),E.revision=(this.serverState?.revision??0)+1,f.payload=E,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=z(),f.retryingBeforeResponse=!1;let N=this.socket;if(!N||N.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),L(`perf websocket retry_send session=${J(this.affinity)} request=${E.id} previous=${C} mode=full_sync retry=${D} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify(E).length}`),N.send(JSON.stringify(E))}catch(E){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending(E)}})(),!0}enqueueStreamChunk(f,_){f.streamChunkCount+=1,f.streamByteCount+=_.byteLength,f.streamController?.enqueue(_)}handleBinaryChunk(f){let _=this.pending;if(!_?.responseStarted)return;this.enqueueStreamChunk(_,kD(f))}resolvePendingResponse(f,_,$,D){if(f.responseStarted)return;f.responseStarted=!0;let C=new ReadableStream({start:(E)=>{f.streamController=E},cancel:()=>{this.socket?.close()}});f.resolve(new Response(C,{status:_,statusText:$,headers:D}))}handleMessage(f){if(f.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let _=this.pending;if(!_)return;if("id"in f&&f.id&&f.id!==_.payload.id)return;if(f.type==="accepted"){let $=z();_.accepted=!0,_.acceptedAt=$,L(`perf websocket accepted session=${J(this.affinity)} request=${_.payload.id} sentMs=${R($-_.sentAt)} mode=${_.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},i_(this.affinity,_.bodyText,f.hash,f.revision),this.resetPendingTimeout(_);return}if(f.type==="response_start"){let $=z();if(_.responseStartedAt=$,L(`perf websocket response_start session=${J(this.affinity)} request=${_.payload.id} sentMs=${R($-_.sentAt)} upstreamMs=${_.acceptedAt==null?"unknown":R($-_.acceptedAt)} status=${f.status}`),clearTimeout(_.timeout),this.resolvePendingResponse(_,f.status,f.statusText,f.headers),_.optimisticResponse&&f.status>=400)_.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
48
|
-
data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${f.status}`}})}
|
|
49
|
-
|
|
50
|
-
`)),this.finishPending();return}if(f.type==="chunk"){this.enqueueStreamChunk(_,yD(f.base64));return}if(f.type==="done"){this.finishPending(f);return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){L(`websocket relay error during optimistic response session=${J(this.affinity)} request=${_.payload.id} status=${f.status} message=${f.message||"unknown"} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}`),_.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
51
|
-
data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:f.message||"relay error"}})}
|
|
52
|
-
|
|
53
|
-
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse(_,f.message||"state mismatch"))return;let $=f.status===409?new j0(f.message||"state mismatch"):Error(pD(f));this.failPending($)}}finishPending(f){let _=this.pending;if(!_)return;let $=z(),D=f&&"frames"in f?` upstreamChunks=${f.upstreamChunks??"unknown"} upstreamBytes=${f.upstreamBytes??"unknown"} frames=${f.frames} frameBytes=${f.frameBytes??"unknown"}`:"";if(L(`perf websocket done session=${J(this.affinity)} request=${_.payload.id} sentMs=${R($-_.sentAt)} streamMs=${_.responseStartedAt==null?"unknown":R($-_.responseStartedAt)} chunks=${_.streamChunkCount} bytes=${_.streamByteCount}${D}`),clearTimeout(_.timeout),!_.streamDone)_.streamDone=!0,_.streamController?.close();_.resolveDone(),this.pending=void 0}failPending(f){let _=this.pending;if(!_)return;if(clearTimeout(_.timeout),this.pending=void 0,_.responseStarted)_.streamController?.error(f);else _.reject(f);_.rejectDone(f)}}function H0(f=Date.now()){for(let[_,$]of k)if(f-$.updatedAt>VD)k.delete(_);while(k.size>AD){let _=k.keys().next().value;if(_===void 0)break;k.delete(_)}for(let[_,$]of c)if($.canEvict(f))$.dispose(),c.delete(_);while(c.size>QD){let _=!1;for(let[$,D]of c){if(!D.canEvict(f))continue;D.dispose(),c.delete($),_=!0;break}if(!_)break}}function vD(f,_){H0();let $=c.get(_);if($)return $.touch(),$;let D=new u_(f,_);return c.set(_,D),H0(),D}async function KN(f){let{config:_,input:$,init:D,headers:C,body:E,fallback:N,affinity:b,optimisticResponse:K}=f;if(!_||!ID($,E))return N();let U=b||C.get("x-session-affinity")||C.get("x-opencode-session");if(!U)return L("skipping relay: missing x-session-affinity header"),N();let G=E,O=z(),Z=RD(G);$f("hash_body",{session:J(U),ms:R(z()-O),bodyBytes:G.length});let H=k.get(U),X=z(),W=hD({input:$,init:D,headers:C,bodyText:G,affinity:U,previous:H,nextHash:Z});$f("create_payload",{session:J(U),ms:R(z()-X),mode:W.mode,bodyBytes:G.length,previousBytes:H?.body.length});try{let B,d=z();if(_.transport==="websocket")try{B=await vD(_,U).send(W,G,K===!0)}catch(j){L(`websocket relay failed session=${J(U)}; trying http relay: ${j instanceof Error?j.message:String(j)}`),B=await l_({config:_,payload:W,bodyText:G,fallback:N,signal:D?.signal})}else B=await l_({config:_,payload:W,bodyText:G,fallback:N,signal:D?.signal});if($f("send",{session:J(U),ms:R(z()-d),transport:B.transport,protocol:B.protocol,mode:B.payload.mode,status:B.response.status,usedRelay:B.usedRelay}),!B.usedRelay)return B.response;if(B.transport==="http")i_(U,G,B.payload.next_hash,B.payload.revision);let q=z(),y=JSON.stringify(B.payload).length;$f("payload_stringify",{session:J(U),ms:R(z()-q),relayBytes:y}),L(`used relay transport=${B.transport} protocol=${B.protocol} mode=${B.payload.mode} status=${B.response.status} session=${J(U)} bodyBytes=${G.length} relayBytes=${y}`);let x=z();return await Q_({affinity:U,transport:B.transport,protocol:B.protocol,mode:B.payload.mode,status:B.response.status,bodyText:G,previousBodyText:H?.body,payload:B.payload,relayBytes:y}),$f("dump",{session:J(U),ms:R(z()-x),enabled:!0}),B.response}catch(B){if(!_.fallbackToDirect)throw L(`relay failed session=${J(U)} and fallbackToDirect=false: ${B instanceof Error?B.message:String(B)}`),B;return L(`relay failed; falling back direct session=${J(U)}: ${B instanceof Error?B.message:String(B)}`),N()}}var UN=`
|
|
54
|
-
async function hashBody(body) {
|
|
55
|
-
const bytes = new TextEncoder().encode(body)
|
|
56
|
-
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
|
57
|
-
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
|
|
58
|
-
return 'sha256:' + hex
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function applyPatch(base, patch) {
|
|
62
|
-
return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function applyPatchSet(base, patch) {
|
|
66
|
-
if (!Array.isArray(patch)) return applyPatch(base, patch)
|
|
67
|
-
if (patch.length === 0) return base
|
|
68
|
-
|
|
69
|
-
let result = ''
|
|
70
|
-
let cursor = 0
|
|
71
|
-
for (const item of patch) {
|
|
72
|
-
if (item.start < cursor) return { error: 'overlapping patch', status: 400 }
|
|
73
|
-
result += base.slice(cursor, item.start)
|
|
74
|
-
result += item.insert
|
|
75
|
-
cursor = item.start + item.deleteCount
|
|
76
|
-
}
|
|
77
|
-
return result + base.slice(cursor)
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async function readState(env, affinity) {
|
|
81
|
-
const raw = await env.RELAY_STATE.get('session:' + affinity)
|
|
82
|
-
return raw ? JSON.parse(raw) : null
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
async function writeState(env, affinity, state) {
|
|
86
|
-
await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
async function resolveBody(env, payload) {
|
|
90
|
-
if (payload.mode === 'full_sync') return payload.body
|
|
91
|
-
if (payload.mode === 'patch') {
|
|
92
|
-
const state = await readState(env, payload.affinity)
|
|
93
|
-
if (!state || state.hash !== payload.base_hash) {
|
|
94
|
-
return { error: 'state mismatch', status: 409 }
|
|
95
|
-
}
|
|
96
|
-
return applyPatchSet(state.body, payload.patch)
|
|
97
|
-
}
|
|
98
|
-
return { error: 'unknown mode', status: 400 }
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
async function prepareUpstream(env, payload) {
|
|
102
|
-
if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
103
|
-
return { error: 'invalid payload', status: 400 }
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const body = await resolveBody(env, payload)
|
|
107
|
-
if (body && typeof body === 'object' && 'error' in body) return body
|
|
108
|
-
|
|
109
|
-
if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {
|
|
110
|
-
return { error: 'hash mismatch', status: 409 }
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})
|
|
114
|
-
console.log(JSON.stringify({
|
|
115
|
-
relay: 'opencode-anthropic-auth',
|
|
116
|
-
transport: 'relay',
|
|
117
|
-
mode: payload.mode,
|
|
118
|
-
revision: payload.revision,
|
|
119
|
-
affinity: String(payload.affinity).slice(0, 12),
|
|
120
|
-
bodyBytes: body.length,
|
|
121
|
-
}))
|
|
122
|
-
|
|
123
|
-
return { body, stateWrite }
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
function resolveBodyFromState(state, payload) {
|
|
127
|
-
if (payload.mode === 'full_sync') return payload.body
|
|
128
|
-
if (payload.mode === 'patch') {
|
|
129
|
-
if (!state || state.hash !== payload.base_hash) {
|
|
130
|
-
return { error: 'state mismatch', status: 409 }
|
|
131
|
-
}
|
|
132
|
-
return applyPatchSet(state.body, payload.patch)
|
|
133
|
-
}
|
|
134
|
-
return { error: 'unknown mode', status: 400 }
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function deferWorkerTask(task) {
|
|
138
|
-
return new Promise((resolve) => setTimeout(resolve, 0)).then(task)
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
const WEBSOCKET_STREAM_FLUSH_BYTES = 1024
|
|
142
|
-
const WEBSOCKET_STREAM_FLUSH_MS = 20
|
|
143
|
-
|
|
144
|
-
function createWebSocketStreamCoalescer(socket, options = {}) {
|
|
145
|
-
const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES
|
|
146
|
-
const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS
|
|
147
|
-
let chunks = []
|
|
148
|
-
let byteLength = 0
|
|
149
|
-
let flushTimer = null
|
|
150
|
-
const stats = {
|
|
151
|
-
upstreamChunks: 0,
|
|
152
|
-
upstreamBytes: 0,
|
|
153
|
-
frames: 0,
|
|
154
|
-
frameBytes: 0,
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
const clearFlushTimer = () => {
|
|
158
|
-
if (flushTimer === null) return
|
|
159
|
-
clearTimeout(flushTimer)
|
|
160
|
-
flushTimer = null
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
const mergeChunks = () => {
|
|
164
|
-
if (chunks.length === 1) return chunks[0]
|
|
165
|
-
const frame = new Uint8Array(byteLength)
|
|
166
|
-
let offset = 0
|
|
167
|
-
for (const chunk of chunks) {
|
|
168
|
-
frame.set(chunk, offset)
|
|
169
|
-
offset += chunk.byteLength
|
|
170
|
-
}
|
|
171
|
-
return frame
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
const flush = () => {
|
|
175
|
-
clearFlushTimer()
|
|
176
|
-
if (byteLength === 0) return
|
|
177
|
-
const frame = mergeChunks()
|
|
178
|
-
chunks = []
|
|
179
|
-
byteLength = 0
|
|
180
|
-
socket.send(frame)
|
|
181
|
-
stats.frames += 1
|
|
182
|
-
stats.frameBytes += frame.byteLength
|
|
183
|
-
}
|
|
184
|
-
|
|
185
|
-
const scheduleFlush = () => {
|
|
186
|
-
if (flushTimer !== null) return
|
|
187
|
-
flushTimer = setTimeout(flush, flushMs)
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
return {
|
|
191
|
-
push(value) {
|
|
192
|
-
const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)
|
|
193
|
-
if (chunk.byteLength === 0) return
|
|
194
|
-
stats.upstreamChunks += 1
|
|
195
|
-
stats.upstreamBytes += chunk.byteLength
|
|
196
|
-
chunks.push(chunk)
|
|
197
|
-
byteLength += chunk.byteLength
|
|
198
|
-
if (byteLength >= flushBytes) flush()
|
|
199
|
-
else scheduleFlush()
|
|
200
|
-
},
|
|
201
|
-
flush,
|
|
202
|
-
stats() {
|
|
203
|
-
return { ...stats, pendingBytes: byteLength }
|
|
204
|
-
},
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
function checkpointWebSocketState(env, payload, body, nextState) {
|
|
209
|
-
return deferWorkerTask(async () => {
|
|
210
|
-
try {
|
|
211
|
-
if ((await hashBody(body)) !== payload.next_hash) {
|
|
212
|
-
throw new Error('hash mismatch')
|
|
213
|
-
}
|
|
214
|
-
await writeState(env, payload.affinity, nextState)
|
|
215
|
-
} catch (error) {
|
|
216
|
-
console.log(JSON.stringify({
|
|
217
|
-
relay: 'opencode-anthropic-auth',
|
|
218
|
-
transport: 'websocket',
|
|
219
|
-
event: 'checkpoint_write_failed',
|
|
220
|
-
affinity: String(payload.affinity).slice(0, 12),
|
|
221
|
-
message: error instanceof Error ? error.message : String(error),
|
|
222
|
-
}))
|
|
223
|
-
}
|
|
224
|
-
})
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
async function prepareWebSocketUpstream(env, state, payload) {
|
|
228
|
-
if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {
|
|
229
|
-
return { error: 'invalid payload', status: 400 }
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
const body = resolveBodyFromState(state, payload)
|
|
233
|
-
if (body && typeof body === 'object' && 'error' in body) return body
|
|
234
|
-
if (typeof body !== 'string') return { error: 'invalid body', status: 400 }
|
|
235
|
-
if ((await hashBody(body)) !== payload.next_hash) {
|
|
236
|
-
return { error: 'hash mismatch', status: 409 }
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
const nextState = { body, hash: payload.next_hash, revision: payload.revision }
|
|
240
|
-
const checkpoint = checkpointWebSocketState(env, payload, body, nextState)
|
|
241
|
-
const logAccepted = () => console.log(JSON.stringify({
|
|
242
|
-
relay: 'opencode-anthropic-auth',
|
|
243
|
-
transport: 'websocket',
|
|
244
|
-
mode: payload.mode,
|
|
245
|
-
revision: payload.revision,
|
|
246
|
-
affinity: String(payload.affinity).slice(0, 12),
|
|
247
|
-
bodyBytes: body.length,
|
|
248
|
-
}))
|
|
249
|
-
|
|
250
|
-
return { body, state: nextState, checkpoint, logAccepted }
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
function headersToObject(headers) {
|
|
254
|
-
const result = {}
|
|
255
|
-
for (const [key, value] of headers.entries()) result[key] = value
|
|
256
|
-
return result
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
async function handleRelayPayload(env, payload) {
|
|
260
|
-
const prepared = await prepareUpstream(env, payload)
|
|
261
|
-
if (prepared.error) return prepared
|
|
262
|
-
const upstream = await fetch(payload.upstream.url, {
|
|
263
|
-
method: payload.upstream.method || 'POST',
|
|
264
|
-
headers: payload.upstream.headers,
|
|
265
|
-
body: prepared.body,
|
|
266
|
-
})
|
|
267
|
-
return { upstream, stateWrite: prepared.stateWrite }
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
async function handleWebSocket(socket, env, ctx, payload, getState, setState) {
|
|
271
|
-
const heartbeat = setInterval(() => {
|
|
272
|
-
try {
|
|
273
|
-
socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))
|
|
274
|
-
} catch {
|
|
275
|
-
clearInterval(heartbeat)
|
|
276
|
-
}
|
|
277
|
-
}, 15000)
|
|
278
|
-
let streamCoalescer = null
|
|
279
|
-
try {
|
|
280
|
-
const result = await prepareWebSocketUpstream(env, getState(), payload)
|
|
281
|
-
if (result.error) {
|
|
282
|
-
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))
|
|
283
|
-
return
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
setState(result.state)
|
|
287
|
-
socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))
|
|
288
|
-
ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))
|
|
289
|
-
|
|
290
|
-
const upstreamPromise = fetch(payload.upstream.url, {
|
|
291
|
-
method: payload.upstream.method || 'POST',
|
|
292
|
-
headers: payload.upstream.headers,
|
|
293
|
-
body: result.body,
|
|
294
|
-
})
|
|
295
|
-
ctx?.waitUntil?.(result.checkpoint)
|
|
296
|
-
const upstream = await upstreamPromise
|
|
297
|
-
socket.send(JSON.stringify({
|
|
298
|
-
protocol: 2,
|
|
299
|
-
type: 'response_start',
|
|
300
|
-
id: payload.id,
|
|
301
|
-
status: upstream.status,
|
|
302
|
-
statusText: upstream.statusText,
|
|
303
|
-
headers: headersToObject(upstream.headers),
|
|
304
|
-
}))
|
|
305
|
-
|
|
306
|
-
const reader = upstream.body?.getReader()
|
|
307
|
-
if (reader) {
|
|
308
|
-
streamCoalescer = createWebSocketStreamCoalescer(socket)
|
|
309
|
-
while (true) {
|
|
310
|
-
const { done, value } = await reader.read()
|
|
311
|
-
if (done) break
|
|
312
|
-
streamCoalescer.push(value)
|
|
313
|
-
}
|
|
314
|
-
streamCoalescer.flush()
|
|
315
|
-
}
|
|
316
|
-
const stats = streamCoalescer?.stats?.() || {}
|
|
317
|
-
socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))
|
|
318
|
-
} catch (error) {
|
|
319
|
-
try {
|
|
320
|
-
streamCoalescer?.flush?.()
|
|
321
|
-
} catch {}
|
|
322
|
-
socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
323
|
-
} finally {
|
|
324
|
-
clearInterval(heartbeat)
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
export default {
|
|
329
|
-
async fetch(request, env, ctx) {
|
|
330
|
-
if (request.headers.get('Upgrade') === 'websocket') {
|
|
331
|
-
const url = new URL(request.url)
|
|
332
|
-
const token = url.searchParams.get('token')
|
|
333
|
-
const affinity = url.searchParams.get('affinity')
|
|
334
|
-
if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })
|
|
335
|
-
if (!affinity) return new Response('missing affinity', { status: 400 })
|
|
336
|
-
const pair = new WebSocketPair()
|
|
337
|
-
const client = pair[0]
|
|
338
|
-
const server = pair[1]
|
|
339
|
-
server.binaryType = 'arraybuffer'
|
|
340
|
-
let state = null
|
|
341
|
-
let ready = false
|
|
342
|
-
server.accept()
|
|
343
|
-
const loadState = readState(env, affinity).then((loadedState) => {
|
|
344
|
-
state = loadedState
|
|
345
|
-
ready = true
|
|
346
|
-
server.send(JSON.stringify({
|
|
347
|
-
protocol: 2,
|
|
348
|
-
type: 'ready',
|
|
349
|
-
state: state ? { hash: state.hash, revision: state.revision } : null,
|
|
350
|
-
}))
|
|
351
|
-
}).catch((error) => {
|
|
352
|
-
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))
|
|
353
|
-
server.close(1011, 'state load failed')
|
|
354
|
-
})
|
|
355
|
-
ctx?.waitUntil?.(loadState)
|
|
356
|
-
if (!ctx?.waitUntil) void loadState
|
|
357
|
-
let busy = false
|
|
358
|
-
server.addEventListener('message', (event) => {
|
|
359
|
-
if (!ready) {
|
|
360
|
-
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))
|
|
361
|
-
return
|
|
362
|
-
}
|
|
363
|
-
if (busy) {
|
|
364
|
-
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))
|
|
365
|
-
return
|
|
366
|
-
}
|
|
367
|
-
let payload
|
|
368
|
-
try {
|
|
369
|
-
payload = JSON.parse(event.data)
|
|
370
|
-
} catch {
|
|
371
|
-
server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))
|
|
372
|
-
return
|
|
373
|
-
}
|
|
374
|
-
payload.affinity = affinity
|
|
375
|
-
busy = true
|
|
376
|
-
const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })
|
|
377
|
-
ctx?.waitUntil?.(run)
|
|
378
|
-
if (!ctx?.waitUntil) void run
|
|
379
|
-
})
|
|
380
|
-
return new Response(null, { status: 101, webSocket: client })
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
if (request.method === 'GET') {
|
|
384
|
-
return Response.json({ status: 'ok', transports: ['http', 'websocket'] })
|
|
385
|
-
}
|
|
386
|
-
if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })
|
|
387
|
-
if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {
|
|
388
|
-
return new Response('unauthorized', { status: 401 })
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
try {
|
|
392
|
-
const payload = await request.json()
|
|
393
|
-
const result = await handleRelayPayload(env, payload)
|
|
394
|
-
if (result.error) return Response.json({ error: result.error }, { status: result.status })
|
|
395
|
-
|
|
396
|
-
if (result.stateWrite) ctx.waitUntil(result.stateWrite)
|
|
397
|
-
|
|
398
|
-
const upstream = result.upstream
|
|
399
|
-
return new Response(upstream.body, {
|
|
400
|
-
status: upstream.status,
|
|
401
|
-
statusText: upstream.statusText,
|
|
402
|
-
headers: upstream.headers,
|
|
403
|
-
})
|
|
404
|
-
} catch (error) {
|
|
405
|
-
return Response.json(
|
|
406
|
-
{ error: error instanceof Error ? error.message : 'internal relay error' },
|
|
407
|
-
{ status: 502 },
|
|
408
|
-
)
|
|
409
|
-
}
|
|
410
|
-
},
|
|
411
|
-
}
|
|
412
|
-
`;var BN="claude-routing",L0=["main-first","fallback-first"],S0="main-first",g_="Usage: `/claude-routing`, `/claude-routing main-first`, or `/claude-routing fallback-first`.";function dD(f){return typeof f==="string"&&L0.includes(f)?f:S0}function MN(f){return dD(f?.routing?.mode)}async function HN(f,_=S()){let $=await F(_)??Q();return $.routing={...$.routing??{},mode:f},await m($,_),$}function iD(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&L0.includes(_[0]))return{type:"mode",mode:_[0]};if(_.length===2&&_[0]==="mode"&&L0.includes(_[1]))return{type:"mode",mode:_[1]};return{type:"usage"}}function uD(f){if(f==="fallback-first")return"Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";return"Try the main account first. Use fallback accounts only when quota policy or fallback errors require it."}function O0(f){let _=f?.mode??S0;return["## Claude Routing Status","",`- Mode: \`${_}\``,`- Behavior: ${uD(_)}`,"",g_].join(`
|
|
413
|
-
`)}function ON(f){let _=iD(f.argumentsText),$=f.mode??S0;if(_.type==="status")return O0({mode:$});if(_.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${_.mode}\`.`,"",...O0({mode:_.mode}).split(`
|
|
414
|
-
`).slice(2)].join(`
|
|
415
|
-
`);return["## Claude Routing Usage","",g_,"",...O0({mode:$}).split(`
|
|
416
|
-
`).slice(2)].join(`
|
|
417
|
-
`)}export{gD as a,Z0 as b,sD as c,rD as d,nD as e,cD as f,tD as g,X0 as h,oD as i,aD as j,P0 as k,DC as l,CC as m,T as n,MC as o,$1 as p,HC as q,S as r,Q as s,F as t,m as u,x1 as v,Zf as w,OC as x,h1 as y,LC as z,SC as A,zC as B,JC as C,WC as D,YC as E,ZC as F,XC as G,FC as H,VC as I,mC as J,a0 as K,v1 as L,AC as M,Df as N,gf as O,QC as P,RC as Q,PC as R,e0 as S,of as T,i1 as U,y0 as V,__ as W,u1 as X,g1 as Y,qC as Z,IC as _,xC as $,TC as aa,hC as ba,wC as ca,yC as da,kC as ea,af as fa,o1 as ga,$$ as ha,vC as ia,dC as ja,iC as ka,uC as la,b$ as ma,gC as na,H_ as oa,DE as pa,cC as qa,tC as ra,oC as sa,G_ as ta,KE as ua,UE as va,l$ as wa,E0 as xa,J_ as ya,p$ as za,GE as Aa,d$ as Ba,BE as Ca,i$ as Da,u$ as Ea,ME as Fa,YE as Ga,ZE as Ha,$D as Ia,XE as Ja,FE as Ka,mE as La,AE as Ma,QE as Na,jD as Oa,RE as Pa,_f as Qa,IE as Ra,TE as Sa,HD as Ta,hE as Ua,yE as Va,LD as Wa,kE as Xa,lE as Ya,pE as Za,vE as _a,dE as $a,iE as ab,uE as bb,gE as cb,sE as db,v as eb,aE as fb,eE as gb,fN as hb,NN as ib,bN as jb,KN as kb,UN as lb,BN as mb,MN as nb,HN as ob,iD as pb,ON as qb};
|