@cortexkit/opencode-anthropic-auth 1.14.0 → 1.15.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/cli.js +1 -1
- package/dist/fable-fallback.d.ts +34 -0
- package/dist/{index-se4sd5kz.js → index-6gdd6e4s.js} +1 -1
- package/dist/index-bxs26mw4.js +2 -0
- package/dist/{index-ha0gz07d.js → index-jkbar3k3.js} +1 -1
- package/dist/{index-97vmbv5w.js → index-qejbx8c9.js} +1 -1
- package/dist/{index-1gc9eney.js → index-qsaph2g4.js} +1 -1
- package/dist/index-z03wayzs.js +417 -0
- package/dist/index.js +12 -12
- package/dist/{logger-sg9wxpvj.js → logger-vxnb5hjr.js} +1 -1
- package/dist/prompt-context.d.ts +5 -2
- 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 +8 -0
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +16 -0
- package/dist/tui-preferences.js +1 -1
- package/package.json +13 -10
- package/src/sidebar-state.ts +47 -0
- package/src/tui/entry.mjs +37 -0
- package/src/tui-compiled/rpc/port-file.ts +70 -0
- package/src/tui-compiled/rpc/protocol.ts +34 -0
- package/src/tui-compiled/rpc/rpc-client.ts +62 -0
- package/src/tui-compiled/rpc/rpc-dir.ts +19 -0
- package/src/tui-compiled/sidebar-state.ts +410 -0
- package/src/tui-compiled/tui/command-dialogs.tsx +615 -0
- package/src/tui-compiled/tui-preferences.ts +370 -0
- package/src/tui-compiled/tui.tsx +1102 -0
- package/src/tui.tsx +54 -15
- package/dist/index-8meqn6xw.js +0 -2
- package/dist/index-fwjqfkj2.js +0 -417
package/dist/index-fwjqfkj2.js
DELETED
|
@@ -1,417 +0,0 @@
|
|
|
1
|
-
import{Ab as I,Bb as u,Cb as O,wb as Z1}from"./index-se4sd5kz.js";import{Vb as t1}from"./index-1gc9eney.js";var Mf="9d1c250a-e61b-44d9-88ed-5944d1962f5e",S0={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",uD="mcp_";var Z0="fast-mode-2026-02-01";function gD(f,_){let $=(f??"").split(",").map((D)=>D.trim()).filter(Boolean);return[...new Set([...$,..._])].join(",")}function sD(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7")||f.startsWith("claude-opus-4-8"))}var rD="You are OpenCode",nD="You are Claude Code, Anthropic's official CLI for Claude.",cD=["<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)",Q0=["explicit","automatic","hybrid"],Lf="explicit",tD=["github.com/anomalyco/opencode","opencode.ai/docs"],oD=[{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 A0(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 _=A0(f),$=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(_));return{verifier:_,challenge:A0(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 s1(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((G)=>setTimeout(G,K))}let N=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:Mf,scope:Y0})});if(!N.ok){if(N.status>=500&&C<$){await N.body?.cancel().catch(()=>{});continue}let K=await N.text().catch(()=>"");throw new df(N.status,K,N.headers.get("retry-after"))}let b=await N.json(),E=f.now?.()??Date.now();return{access:b.access_token,refresh:b.refresh_token??f.refreshToken,expires:E+b.expires_in*1000,expiresIn:b.expires_in}}catch(N){if(N instanceof df)throw N;if(C<$&&s1(N))continue;throw N}throw Error("Token refresh exhausted all retries")}function r1(){return crypto.randomUUID().replace(/-/g,"")}function n1(f){let _=f.trim();try{let b=new URL(_),E=b.searchParams.get("code"),K=b.searchParams.get("state");if(E&&K)return{code:E,state:K}}catch{}let $=_.split("#");if($.length===2&&$[0]&&$[1])return{code:$[0],state:$[1]};let D=new URLSearchParams(_),C=D.get("code"),N=D.get("state");if(C&&N)return{code:C,state:N};return null}async function c1(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:Mf,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 $C(f){let _=await R0(),$=r1(),D=new URL(S0[f],import.meta.url);return D.searchParams.set("code","true"),D.searchParams.set("client_id",Mf),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 DC(f,_,$,D){let C=n1(f);if(!C)return{type:"failed"};if(D&&C.state!==D)return{type:"failed"};return c1(C,_,$)}import{createHash as p0,randomUUID as Cf}from"node:crypto";import{mkdir as v0,readFile as Of,rename as d0,rm as t,stat as q0,writeFile as zf}from"node:fs/promises";import{homedir as o1}from"node:os";import{dirname as i0,join as o}from"node:path";var a1=globalThis.setTimeout.bind(globalThis),e1=globalThis.clearTimeout.bind(globalThis),u0="anthropic-auth.json",f_="anthropic-auth-state.json",__="https://api.anthropic.com/api/oauth/usage";function h(f){return f.type==="oauth"}function BC(f){return f.type==="api"}function $_(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 D_=[401,403,429],g0=240,C_=g0;var N_=300000,b_=3600000,s0=86400000,E_=60000,K_=900000,G_=300000,U_=5,I0={five_hour:0,seven_day:0},j_=!0,B_=60000,H_=60000,M_=600000,L_=1e4,O_=100;function z_(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return o(process.env.XDG_CONFIG_HOME||o(o1(),".config"),"opencode")}function z(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||o(z_(),u0)}function r0(f=z()){let _=process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();if(_)return _;return f.endsWith(u0)?o(i0(f),f_):`${f}.state.json`}function H(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 J_(f){if(!H(f))return null;if(f.type==="api"){let _=typeof f.baseURL==="string"?f.baseURL.trim():"",$=typeof f.apiKey==="string"?f.apiKey.trim():"";if(!$_(_))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:S_(f.quota)}}function T0(f){if(!H(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(!H(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 S_(f){if(!H(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(!H(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 N=typeof D.modelId==="string"&&D.modelId.trim()?D.modelId.trim():void 0;return{...C,id:D.id.trim(),title:D.title.trim(),...N&&{modelId:N},modelName:D.modelName.trim()}}).filter((D)=>D!=null);_.scoped=$}return Object.keys(_).length?_:void 0}function A(){return{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]}}function W_(f){if(!H(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},routing:H(f.routing)?f.routing:void 0,fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter((_)=>Number.isInteger(_)):void 0,refresh:H(f.refresh)?f.refresh:void 0,quota:H(f.quota)?f.quota:void 0,claudeCache:H(f.claudeCache)?f.claudeCache:void 0,dump:H(f.dump)?f.dump:void 0,claudeFast:H(f.claudeFast)?f.claudeFast:void 0,costZeroing:H(f.costZeroing)?f.costZeroing:void 0,cacheKeep:H(f.cacheKeep)?f.cacheKeep:void 0,relay:H(f.relay)?f.relay:void 0,logging:H(f.logging)?f.logging:void 0,killswitch:H(f.killswitch)?f.killswitch:void 0,accounts:f.accounts.map(J_).filter((_)=>_!=null)}}async function Sf(f){try{return{exists:!0,value:JSON.parse(await Of(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 Jf(f){return typeof f==="number"&&Number.isFinite(f)?f:0}function nf(f){return Math.max(Jf(f.lastRefreshedAt),Jf(f.lastUsed),Jf(f.addedAt))}function Y_(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 Z_(f,_){if(Y_(f,_)){let $={..._,...f},D=nf(f);if(D>Jf($.lastRefreshedAt))$.lastRefreshedAt=D;return delete $.quota,delete $.lastRefreshError,delete $.lastQuotaRefreshError,$}return{...f,..._}}function X_(f,_){if(!H(f))return f;let $=H(_)?_:{},D=H($.main)?$.main:void 0,C=H($.accounts)?$.accounts:{},N=H(f.quota)?f.quota:{},b=H(f.refresh)?f.refresh:{},E=D??N,K=D??b,G=Array.isArray(f.accounts)?f.accounts.map((U)=>{if(!H(U))return U;let L=typeof U.id==="string"&&H(C[U.id])?C[U.id]:{};return Z_(U,L)}):[];return{...f,refresh:s({...b,mainLastRefreshError:K.lastRefreshError,mainRefreshLeaseId:K.refreshLeaseId,mainRefreshLeaseUntil:K.refreshLeaseUntil,mainRefreshLeaseTokenHash:K.refreshLeaseTokenHash}),quota:s({...N,mainQuota:E.quota,mainQuotaCheckedAt:E.quotaCheckedAt,mainQuotaToken:E.quotaToken,mainLastQuotaApiError:E.lastQuotaApiError}),accounts:G}}async function F(f=z()){let _=await Sf(f),$=await Sf(r0(f));if(!_.exists&&!$.exists)return null;let D=_.exists?_.value:A();return W_(X_(D,$.value))}async function F_(f){let _=await Sf(f);return H(_.value)?_.value:{}}function V_(f){return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0))}function m_(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 Q_(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 Nf(f){return Math.max(f?.five_hour?.checkedAt??0,f?.seven_day?.checkedAt??0,...f?.scoped?.map((_)=>_.checkedAt)??[],f?.checkedAt??0)}function A_(f,_){if(!H(f))return _;let $=f,D=Nf($.quota),C=Nf(_.quota),N=Boolean($.access&&_.access&&$.access!==_.access||$.refresh&&_.refresh&&$.refresh!==_.refresh);if(D>C){let E=$.lastRefreshedAt??0,K=_.lastRefreshedAt??0;if(N&&K<=E){let U={...$};if(typeof _.lastUsed==="number"&&(typeof $.lastUsed!=="number"||_.lastUsed>$.lastUsed))U.lastUsed=_.lastUsed;return U}let G={...$,..._};if(N){if("quota"in _)if(G.quota=$.quota,"lastQuotaRefreshError"in $)G.lastQuotaRefreshError=$.lastQuotaRefreshError;else delete G.lastQuotaRefreshError;else delete G.quota,delete G.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete G.lastRefreshError;return G}return{...G,quota:$.quota,lastQuotaRefreshError:$.lastQuotaRefreshError}}let b={...$,..._};if(!("lastQuotaRefreshError"in _))delete b.lastQuotaRefreshError;if(!("lastRefreshError"in _))delete b.lastRefreshError;return b}function R_(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 V_({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(m_)})}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 zf($,`${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,_=z()){let $=_;return n0(()=>P_(f,$))}async function P_(f,_){let D={...await F_(_),...R_(f)};await c0(_,D),await t0(f,_,{mainQuota:!0,mainRefresh:!0,accounts:!0})}function q_(f,_){f.main=f.main??{};let $=typeof f.main.quotaCheckedAt==="number"?f.main.quotaCheckedAt:Nf(f.main.quota),D=typeof _.quota?.mainQuotaCheckedAt==="number"?_.quota.mainQuotaCheckedAt:Nf(_.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 I_(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(!H(f))return f;return Object.fromEntries(Object.entries(f).filter(([,_])=>_!==void 0).map(([_,$])=>[_,cf($)]))}function x_(f,_=z(),$={mainQuota:!0,mainRefresh:!0,accounts:!0}){let D=_;return n0(()=>t0(f,D,$))}async function t0(f,_,$){let D=r0(_),C=(await Sf(D)).value,N=H(C)?{...C,version:1}:{version:1};if($.mainQuota)q_(N,f);if($.mainRefresh)I_(N,f);if($.accounts){let b=$.accounts===!0?null:new Set($.accounts);N.accounts={...H(N.accounts)?N.accounts:{}};for(let E of f.accounts){if(b&&!b.has(E.id))continue;N.accounts[E.id]=A_(N.accounts[E.id],Q_(E))}if(b){for(let E of b)if(!f.accounts.some((K)=>K.id===E))delete N.accounts[E]}else{let E=new Set(f.accounts.map((K)=>K.id));for(let K of Object.keys(N.accounts))if(!E.has(K))delete N.accounts[K]}}await c0(D,cf(N))}async function Zf(f){let $=`${f.path??z()}.${f.name}.lock`,D=o($,"owner.json"),C=Cf(),N=f.now??Date.now,b=null,E=!1;async function K(){try{return JSON.parse(await Of($,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await Of(D,"utf8"))}}async function G(){await zf($,`${JSON.stringify({ownerId:C,expiresAt:N()+f.ttlMs})}
|
|
4
|
-
`,{encoding:"utf8",mode:384})}async function U(){try{return await zf($,`${JSON.stringify({ownerId:C,expiresAt:N()+f.ttlMs})}
|
|
5
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(M){let X=M.code;if(X==="EEXIST"||X==="EISDIR")return!1;throw M}}function L(){if(!f.renew||E)return;let M=f.renewIntervalMs??Math.max(1000,Math.floor(f.ttlMs/3));if(b=a1(()=>{(async()=>{try{let X=await K(),W=N();if(E||X?.ownerId!==C||Number(X?.expiresAt)<=W)return;await G(),L()}catch{}})()},M),"unref"in b)b.unref()}let Z=await U();if(!Z){let M=`${$}.evicting`,X=o(M,"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)>N()}catch{try{return(await q0($)).mtimeMs+f.ttlMs>N()}catch{return!1}}}async function T(){try{return JSON.parse(await Of(X,"utf8"))?.ownerId===W}catch{return!1}}async function j(){await v0(M);try{await zf(X,`${JSON.stringify({ownerId:W,createdAt:N()})}
|
|
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 T())await t(M,{recursive:!0,force:!0}).catch(()=>{})}for(let V=0;V<8;V++){if(Z=await U(),Z)break;if(await y())return null;try{if(!await j()){await q();continue}}catch(Bf){if(Bf.code!=="EEXIST")throw Bf;let Hf;try{Hf=await q0(M)}catch(P){if(P.code==="ENOENT"){await q();continue}throw P}if(Hf.mtimeMs+5000>N())return null;await f.onStep?.("stale-marker-stat");let l=`${M}.${Cf()}`;try{await d0(M,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 T())return null;if(await f.onStep?.("stale-lock-confirmed"),!await T())return null;if(await t($,{recursive:!0,force:!0}).catch(()=>{}),!await T())return null;if(Z=await U(),!Z)return null;if(!await T())return await t($,{recursive:!0,force:!0}).catch(()=>{}),Z=!1,null;break}finally{await Y()}}}if(!Z)return null;return L(),{release:async()=>{if(E=!0,b)e1(b),b=null;try{if((await K())?.ownerId!==C)return}catch{return}await t($,{recursive:!0,force:!0}).catch(()=>{})}}}function MC(f){return f?.claudeCache?.enabled===!0}function T_(f){return typeof f==="string"&&Q0.includes(f)?f:Lf}function h_(f){return T_(f?.claudeCache?.mode)}async function LC(f,_,$=z()){let D=await F($)??A();return D.claudeCache={...D.claudeCache??{},enabled:f,mode:_??h_(D)},await m(D,$),D}async function OC(f,_=z()){let $=await F(_)??A();return $.claudeCache={...$.claudeCache??{},enabled:$.claudeCache?.enabled===!0,mode:f},await m($,_),$}function zC(f){return f?.dump?.enabled===!0}async function JC(f,_=z()){let $=await F(_)??A();return $.dump={...$.dump??{},enabled:f},await m($,_),$}function SC(f){return f?.claudeFast?.enabled===!0}async function WC(f,_=z()){let $=await F(_)??A();return $.claudeFast={...$.claudeFast??{},enabled:f},await m($,_),$}async function YC(f,_,$=z()){let D=await F($)??A();return D.cacheKeep={enabled:!0,startHour:f,endHour:_},await m(D,$),D}async function ZC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},enabled:f},await m($,_),$}function XC(f){return f?.cacheKeep?.subagents===!0}async function FC(f,_=z()){let $=await F(_)??A();return $.cacheKeep={...$.cacheKeep??{},subagents:f},await m($,_),$}function w_(f){return f?.fallbackOn?.length?f.fallbackOn:D_}function VC(f,_){return w_(_).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 bf(f){return f?.quota?.enabled!==!1}function y_(f){return f?.refresh?.enabled!==!1}function k_(f){return Math.floor(Math.random()*Math.max(0,f))}function l_(f){let _=f?.refresh?.refreshBeforeExpiryMinutes??C_;return Math.max(g0,_)*60000}function a0(f){return p0("sha256").update(f).digest("hex")}function p_(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 v_(f){let _=a0(f.refreshToken),D=(f.previous?.tokenHash===_?f.previous.retryCount??0:0)+1,C=f.error.retryAfter,N;if(typeof C==="number"&&C>0)N=C*1000;else if(p_(f.error))N=Math.min(b_,N_*2**Math.min(D-1,6));else N=s0;let b=f.error.status,E=typeof b==="number"&&Number.isFinite(b)?b:void 0,K=e(f.error),U=(typeof f.error.body==="string"?f.error.body:"").includes("invalid_grant")||K.includes("invalid_grant");return{message:K,checkedAt:f.now,nextRetryAt:f.now+N,retryCount:D,tokenHash:_,status:E,permanent:E===400&&U}}function mC(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=D1(f.error)?Math.min(K_,E_*2**Math.min($-1,6)):G_;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 w(f){let _=f?.quota?.checkIntervalMinutes??U_;return Math.max(1,_)*60000}function AC(f){return f?.logging?.level}async function RC(f,_=z()){let{setLogLevel:$}=await import("./logger-sg9wxpvj.js"),D=await F(_)??A();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 f1(f){let _=f?.quota?.refreshEveryNRequests;return typeof _==="number"&&Number.isFinite(_)&&_>0?Math.floor(_):0}function Wf(f){return f?.quota?.failClosedOnUnknownQuota??j_}function d_(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 $=d_(_);if(!$)return;return f?.scoped?.find((D)=>{return[D.modelId,D.modelName,D.title].filter((N)=>typeof N==="string").join(" ").toLowerCase().includes($)})}function i_(f,_){let $=of(f,_);return Boolean($&&Number.isFinite($.remainingPercent)&&$.remainingPercent<=0)}function y0(f,_){return!i_(f,_)}function _1(f,_){if(!bf(_))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 Ef(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 u_(f){return f?.killswitch?.enabled===!0}function g_(f,_){if(!f?.killswitch)return g;if(_&&f.killswitch.accounts?.[_])return Ef(f.killswitch.accounts[_]);return Ef(f.killswitch.main)}function PC(f,_,$,D){if(!u_(_))return!0;let C=g_(_,$),N=!1;for(let b of["five_hour","seven_day"]){let E=f?.[b];if(!E){N=!0;continue}if(!Number.isFinite(E.remainingPercent)){N=!0;continue}if(E.remainingPercent<C[b])return!1}if(D){let b=of(f,D);if(b&&Number.isFinite(b.remainingPercent)&&b.remainingPercent<=C.scoped)return!1}if(N)return!Wf(_);return!0}function qC(f,_,$,D){let C=[],N=[f,..._.map((b)=>b.quota)];for(let b of N)if(D){let K=of(b,D)?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}else for(let E of["five_hour","seven_day"]){let K=b?.[E]?.resetsAt;if(!K)continue;let G=Date.parse(K);if(Number.isFinite(G)&&G>$)C.push(G)}if(!C.length)return 300;return Math.max(1,Math.ceil((Math.min(...C)-$)/1000))+60}function IC(f){return f?.killswitch??{enabled:!1}}async function xC(f,_=z()){let $=await F(_)??A();return $.killswitch=f,await m($,_),$}async function TC(f,_=z()){let $=await F(_);if(!$)return!1;let D=a_($,f);if(D)await m($,_);return D}async function hC(f,_=z()){let $=await F(_);if(!$)return;e_($,f),await m($,_)}async function wC(f,_,$=z()){let D=await F($);if(!D)return!1;let C=f$(D,f,_);if(C)await m(D,$);return C}async function yC(f,_=z()){let $=await F(_)??A();o_($,f),await m($,_)}function af(f,_,$){if(!bf(_))return $+w(_);let D=o0(_),C=[];for(let N of["five_hour","seven_day"]){let b=f?.[N];if(!b)return $+w(_);if(b.remainingPercent>=D[N])continue;let E=b.resetsAt?Date.parse(b.resetsAt):Number.NaN;if(!Number.isFinite(E)||E<=$)return $+w(_);C.push(E)}if(!C.length)return $+w(_);return Math.min(...C)+60000}function i(f,_,$){return!f.access||!f.expires||f.expires-$<=l_(_)}function $1(f,_,$){if(!bf(_))return!0;let D=w(_);return["five_hour","seven_day"].every((C)=>{let N=f?.[C];return Boolean(N&&$-N.checkedAt<D)})}function sf(f,_,$){return!$1(f.quota,_,$)}function s_(f,_){if(!f)return!1;if(!f.resetsAt)return!0;let $=Date.parse(f.resetsAt);return!Number.isFinite($)||$>_}function r_(f,_){return["five_hour","seven_day"].every(($)=>s_(f?.[$],_))}function D1(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 n_(f,_,$,D){return D1($)&&_1(f.quota,_)&&r_(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 c_(f){return f.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function t_(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 N=rf(C.scope?.model?.display_name);if(!N)continue;let b=rf(C.scope?.model?.id)??N,E=c_(b);if(!E)continue;let K=`claude-weekly-scoped-${E}`;if($.has(K))continue;$.add(K);let G=Yf(C.percent),U=rf(C.scope?.model?.id);D.push({id:K,title:`${N} only`,...U&&{modelId:U},modelName:N,usedPercent:G,remainingPercent:Yf(100-G),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)(__,{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 N=await $.text().catch(()=>"");throw Object.assign(Error(`Claude quota check failed: ${$.status} — ${N}`),{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:t_(C.limits,D),checkedAt:D}}function Q(f,_){let $=f.accounts.findIndex((D)=>D.id===_.id);if($>=0)f.accounts[$]=_}function o_(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 a_(f,_){let $=f.accounts.findIndex((D)=>D.id===_);if($<0)return!1;return f.accounts.splice($,1),!0}function e_(f,_){let $=new Map(_.map((N,b)=>[N,b])),D=f.accounts.filter((N)=>$.has(N.id)),C=f.accounts.filter((N)=>!$.has(N.id));D.sort((N,b)=>($.get(N.id)??0)-($.get(b.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 C1(f,_,$){f.lastRefreshError=v_({error:_,now:$,refreshToken:f.refresh,previous:f.lastRefreshError})}function l0(f,_,$){if(tf(_))return;if(f.lastQuotaRefreshError=Xf({error:_,now:$,previous:f.lastQuotaRefreshError}),_.isRefreshError)C1(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??z(),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=w(_);this.quotaManager.setFallback(f.id,{quota:f.quota,refreshAfter:$+C,checkedAt:$},f.access)}async load(){return F(this.configPath)}async save(f,_){await x_(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(()=>{})},B_+k_(H_)),"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 N of $.accounts){if(N.enabled===!1||!h(N))continue;try{let b=N;if(i(b,$,this.now())){let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Error(gf(K,this.now()));b=await this.refreshAccount(b,$),C=!0}if(this.seedFallbackQuota(b,$),(this.quotaManager?this.quotaManager.isFallbackStale(b.id,b.access):sf(b,$,this.now()))&&!a(b.lastQuotaRefreshError,this.now()))b=await this.refreshAccountQuota(b,$),C=!0;if(this.accountPassesQuotaPolicy(this.quotaPolicyAccount(b),$,{modelId:_.modelId}))D.push(b)}catch(b){if(n_(N,$,b,this.now())){if(u("[refresh] fallback quota using cached quota after refresh error",{accountId:N.id,error:e(b)}),this.accountPassesQuotaPolicy(this.quotaPolicyAccount(N),$,{modelId:_.modelId}))D.push(N)}else if(!Wf($)&&y0(N.quota,_.modelId))D.push(N)}}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 _1(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||!y_(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))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){I.warn("refresh","fallback oauth background failed",{accountId:$.id,error:D instanceof Error?D.message:String(D)}),C1($,D,this.now()),Q(f,$),_=!0}}if(_)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!bf(f))return;let _=!1;for(let $ of f.accounts){if($.enabled===!1||!h($))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()),Q(f,$),_=!0}}if(_)await this.save(f),this.onFallbackStorageChanged?.()}async refreshQuotaForAllAccounts(f={}){let _=await this.load(),$=[];if(!_||!bf(_))return{storage:_,errors:$};let D=f.force??!1,C=!1;for(let N of _.accounts){if(N.enabled===!1||!h(N))continue;let b=N;try{if(i(b,_,this.now())){let E=b.lastRefreshError;if(E&&Df(E,b.refresh,this.now()))throw Error(gf(E,this.now()));b=await this.refreshAccount(b,_),C=!0}if(!D&&!sf(b,_,this.now())){if(b.lastQuotaRefreshError)b.lastQuotaRefreshError=void 0,Q(_,b),C=!0;continue}await this.refreshAccountQuota(b,_),C=!0}catch(E){l0(N,E,this.now()),Q(_,N),C=!0,$.push({accountId:N.id,message:e(E)})}}if(C)await this.save(_);return{storage:_,errors:$}}async refreshAccount(f,_,$={}){let D=this.refreshPromises.get(f.id);if(D){let b=await D;return Q(_,b),b}let C=this.refreshAccountNow(f,_,$).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,C);let N=await C;return Q(_,N),N}async waitForConcurrentFallbackRefresh(f,_,$,D){let C=Date.now()+L_;while(Date.now()<C){await new Promise((G)=>setTimeout(G,O_));let N=await this.load(),b=N?.accounts.find((G)=>G.id===f.id&&h(G));if(!b)continue;if((b.access!==$.access||b.refresh!==$.refresh||(b.expires??0)>($.expires??0)+60000)&&(D.force||!i(b,N,this.now())))return Q(_,b),u("[refresh] fallback oauth joined concurrent refresh",{accountId:b.id,expiresInMs:b.expires?b.expires-this.now():void 0}),b;let K=b.lastRefreshError;if(K&&Df(K,b.refresh,this.now()))throw Q(_,b),Error(gf(K,this.now()))}return null}async refreshAccountNow(f,_,$){let D=await this.load(),C=D?.accounts.find((E)=>E.id===f.id&&h(E));if(C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;let N=C??f,b=await Zf({name:_$(N.id),ttlMs:M_,path:this.configPath,now:this.now,renew:!0});if(!b){u("[refresh] fallback oauth refresh skipped file lock",{accountId:N.id});let E=await this.waitForConcurrentFallbackRefresh(f,_,N,$);if(E)return E;throw Error("Fallback OAuth refresh is already in progress")}try{if(D=await this.load(),C=D?.accounts.find((G)=>G.id===f.id&&h(G)),C&&!$.force&&!i(C,D,this.now()))return Q(_,C),C;N=C??N;let E=N.refresh;u("[refresh] fallback oauth refresh request start",{accountId:N.id,force:$.force===!0,expiresInMs:N.expires?N.expires-this.now():void 0});let K=await P0({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return N.access=K.access,N.refresh=K.refresh,N.expires=K.expires,N.lastRefreshedAt=K.expires-K.expiresIn*1000,N.lastRefreshError=void 0,Q(_,N),await this.save(_),u("[refresh] fallback oauth refresh succeeded",{accountId:N.id,expiresInMs:N.expires?N.expires-this.now():void 0}),N}finally{await b.release()}}async refreshAccountQuota(f,_){let $=f;if(!$.access)throw Error(`Fallback account ${f.id} has no access token`);let D=(E)=>this.quotaManager?this.quotaManager.refreshFallback($.id,E):Ff({accessToken:E,fetchImpl:this.fetchImpl,now:this.now}),C=this.now();try{$.quota=await D($.access)}catch(E){if(!(E instanceof Error?E.message:String(E)).includes("Claude quota check failed: 401"))throw E;if($=await this.refreshAccount(f,_,{force:!0}),!$.access)throw E;$.quota=await D($.access)}let N=await this.load(),b=N?.accounts.find((E)=>E.id===$.id&&h(E));if(N&&b&&b.access!==$.access)return this.seedFallbackQuota(b,N),Q(_,b),b;if(N&&b?.access===$.access&&b.quota&&Nf(b.quota)>=C&&$1(b.quota,N,this.now()))return this.seedFallbackQuota(b,N),Q(_,b),b;if($.lastQuotaRefreshError=void 0,Q(_,$),this.quotaManager&&$.quota){let E=this.now();this.quotaManager.setFallback($.id,{quota:$.quota,refreshAfter:E+w(_),checkedAt:E},$.access)}return $}}var pC="claude-cache",N1="## Claude Cache Status",D$="## Claude Cache Enabled",C$="## Claude Cache Disabled",N$="## Claude Cache Usage",b$="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",Vf=!1,mf=Lf;function vC(){return Vf}function dC(){return mf}function iC(f){Vf=f.enabled,mf=f.mode}function E$(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[N1,"",`- 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 uC(f){let _=E$(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[N1,"",`Mode updated to \`${_.mode}\`.`,"",Kf({enabled:$,mode:_.mode})].join(`
|
|
10
|
-
`);return[N$,"",b$,"",Kf({enabled:$,mode:D})].join(`
|
|
11
|
-
`)}import{randomBytes as K$,randomUUID as K1}from"node:crypto";var G$=1000,r=new Map;function Gf(f,_,$){if(!f.has(_)&&f.size>=G$){let D=f.keys().next().value;if(D!==void 0)f.delete(D)}f.set(_,$)}function G1(f){let _=f||"anonymous",$=r.get(_);if($)return $;let D={deviceId:K$(32).toString("hex"),sessionId:K1()};return Gf(r,_,D),D}var U$=86400000,j$=300000,ef=new Map,b1=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 N=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(!N.ok)return null;let E=(await N.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof E==="string"&&E?E:null}catch{return null}finally{clearTimeout(D)}}async function nC(f,_){let $=G1(f);if(!f.startsWith("sk-ant-oat"))return $;let D=Date.now(),C=b1.get(f);if(C&&C.expiresAt>D){if(!C.accountUuid)return $;let G=`account:${C.accountUuid}`,U=r.get(G);if(U)return Gf(r,f,U),U}let N=ef.get(f);if(!N)N=B$(f,_),ef.set(f,N);let b=await N.finally(()=>{ef.delete(f)});if(Gf(b1,f,{accountUuid:b,expiresAt:D+(b?U$:j$)}),!b)return $;let E=`account:${b}`,K=r.get(E);if(K)return Gf(r,f,K),K;return $.accountUuid=b,Gf(r,E,$),$}function n(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function H$(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function cC(f,_){let $=H$(_);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 M$=["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"],L$=["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"],E1=["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 O$(f){return f.output_config?.format?.type==="json_schema"}function z$(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 J$(f,_=[]){let $=f?z$(f)?[...M$]:O$(f)?[...L$]:[...E1]:[...E1];if(f?.speed==="fast")$.push(Z0);for(let D of _){let C=D.trim();if(C)$.push(C)}return[...new Set($)].join(",")}function S$(){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 tC(f,_,$={}){let D=$.identity??G1(_),N=[...(f.get("anthropic-beta")??"").split(",").map((b)=>b.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",J$($.body,N)),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",K1()),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",S$()),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 U1(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 j1(){return function(f){let{exports:{mem:_,xxh32:$,xxh64:D,init32:C,update32:N,digest32:b,init64:E,update64:K,digest64:G}}=f,U=new Uint8Array(_.buffer);function L(j,Y){if(_.buffer.byteLength<j+Y){let V=Math.ceil((j+Y-_.buffer.byteLength)/65536);_.grow(V),U=new Uint8Array(_.buffer)}}function Z(j,Y,V,Bf,J0,Hf){L(j);let l=new Uint8Array(j);return U.set(l),V(0,Y),l.set(U.subarray(0,j)),{update(P){let yf;return U.set(l),typeof P=="string"?(L(3*P.length,j),yf=B.encodeInto(P,U.subarray(j)).written):(L(P.byteLength,j),U.set(P,j),yf=P.byteLength),Bf(0,j,yf),l.set(U.subarray(0,j)),this},digest:()=>(U.set(l),Hf(J0(0)))}}function M(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 L(3*j.length,0),M($(0,B.encodeInto(j,U).written,Y))}function T(j,Y=q){return L(3*j.length,0),W(D(0,B.encodeInto(j,U).written,Y))}return{h32:y,h32ToString:(j,Y=d)=>y(j,Y).toString(16).padStart(8,"0"),h32Raw:(j,Y=d)=>(L(j.byteLength,0),U.set(j),M($(0,j.byteLength,Y))),create32:(j=d)=>Z(48,j,C,N,b,M),h64:T,h64ToString:(j,Y=q)=>T(j,Y).toString(16).padStart(16,"0"),h64Raw:(j,Y=q)=>(L(j.byteLength,0),U.set(j),W(D(0,j.byteLength,Y))),create64:(j=q)=>Z(88,j,E,K,G,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;/,B1=null,f0=null;async function Q$(){if(f0)return;B1??=(async()=>{f0=(await j1()).h64Raw})(),await B1}async function A$(f){return await Q$(),((f0?.(f,F$)??0n)&0xfffffn).toString(16).padStart(5,"0")}function R$(f){return f.replace(_0,`$1${V$}`)}function H1(f){return _0.exec(f)?.[2]??null}async function M1(f){if(!_0.test(f))return f;let _=R$(f),$=await A$(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 $N(f,_=p,$,D=new Date){let C=P$(_,D);return`x-anthropic-billing-header: cc_version=${_}.${C}; cc_entrypoint=${$}; cch=00000;`}var EN="claude-cachekeep",C0=3600000,$0=300000,q$=60000,KN="extended-cache-ttl-2025-04-11",I$=32,L1=16777216,x$=2*C0,O1="## Claude Cache Keep Status",T$="## Claude Cache Keep Enabled",h$="## Claude Cache Keep Disabled",w$="## Claude Cache Keep Usage",y$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function Qf(f){return String(f).padStart(2,"0")}function k$(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 N0(f){let _=Number(f?.cacheKeep?.startHour),$=Number(f?.cacheKeep?.endHour);if(!Number.isInteger(_)||!Number.isInteger($)||_<0||_>23||$<0||$>23||_===$)return;return{startHour:_,endHour:$}}function S1(f){return f?.cacheKeep?.enabled===!0&&!!N0(f)}function l$(f){return S1(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function z1(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 J1(f=new Date){return`${f.getFullYear()}-${Qf(f.getMonth()+1)}-${Qf(f.getDate())}`}function D0(f,_=new Date){if(f&&f.startHour>f.endHour&&_.getHours()<f.endHour){let $=new Date(_);return $.setDate($.getDate()-1),J1($)}return J1(_)}function Uf(f){let _=f.window?`${Qf(f.window.startHour)}-${Qf(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 GN(f){let _=k$(f.argumentsText),$={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if(_.type==="status")return[O1,"",Uf($)].join(`
|
|
13
|
-
`);if(_.type==="disable")return[h$,"",Uf({...$,enabled:!1})].join(`
|
|
14
|
-
`);if(_.type==="window")return[T$,"",Uf({...$,enabled:!0,window:{startHour:_.startHour,endHour:_.endHour}})].join(`
|
|
15
|
-
`);if(_.type==="subagents")return[O1,"",Uf($),"",`Subagent tracking: ${_.enabled?"enabled":"disabled"}`].join(`
|
|
16
|
-
`);return[w$,"",y$,"",Uf($)].join(`
|
|
17
|
-
`)}function b0(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(b0);let _=f,$=_.cache_control;if($&&typeof $==="object"&&$.type==="ephemeral")return!0;return Object.values(_).some(b0)}async function p$(f){let _;try{_=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!b0(_))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 N=$.tool_choice;if(N?.type==="tool"||N?.type==="any")delete $.tool_choice;return{ok:!0,bodyText:await M1(JSON.stringify(U1($)))}}class v${options;targets=new Map;timer=null;constructor(f){this.options=f}start(){if(this.timer)return;if(I.debug("cachekeep","started"),this.timer=setInterval(()=>{this.tick().catch((f)=>{I.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;I.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((N)=>N.dayKey===$),C=D.length?Math.min(...D.map((N)=>N.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()>L1){let $=this.targets.size;if(this.evictOldestTarget(),this.targets.size===$)break}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!S1(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>L1)return{tracked:!1,reason:"body exceeds cachekeep memory budget"};let _=this.options.now?.()??Date.now(),$=N0(f.storage);if(!z1($,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((N,b)=>{C[b]=N}),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 tick(){let f=await this.options.loadStorage(),_=N0(f),$=this.options.now?.()??Date.now(),D=D0(_,new Date($));if(this.pruneTargets($,D),!this.targets.size){this.stop();return}if(!l$(f))return;if(!z1(_,new Date($)))return;I.debug("cachekeep","fired",{targets:this.targets.size});let C=$+$0;for(let N of this.targets.values()){if(N.cacheExpiresAt>C)continue;await this.prewarm(N,$)}}async prewarm(f,_){let $=await p$(f.bodyText);if(!$.ok){I.debug("cachekeep","prewarm skipped",{session:f.id,reason:$.reason}),this.targets.delete(f.id);return}let D=this.options.fetchImpl??fetch,C={...f,bodyText:$.bodyText},N=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),C):new Headers(f.headers);N.delete("content-length"),N.delete("transfer-encoding");let b=await D(f.url,{method:"POST",headers:N,body:$.bodyText});if(!b.ok){I.warn("cachekeep","prewarm failed",{session:f.id,status:b.status,body:await b.text().catch(()=>"")}),f.cacheExpiresAt=_+$0+300000;return}let K=(await b.json().catch(()=>null))?.usage;if(f.cacheExpiresAt=_+C0,K)I.debug("cachekeep","prewarm succeeded",{session:f.id,usage:K});else I.debug("cachekeep","prewarm succeeded",{session:f.id})}}var jN="claude-account";function d$(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,N,b,E=C.match(/--base-url\s+(\S+)/);if(E)N=E[1],C=C.replace(E[0],"").trim();let K=C.match(/--auth-header\s+(authorization-bearer|x-api-key)/);if(K)b=K[1],C=C.replace(K[0],"").trim();let G,U=C.match(/--label\s+(.+)/);if(U)G=U[1]?.trim()||void 0,C=C.replace(U[0],"").trim();let L=C.indexOf(" ");if(L===-1){if(!C)return{type:"usage"};return{type:"add-apikey",apiKey:C,baseURL:N,authHeader:b,label:G}}let Z=C.slice(0,L),M=C.slice(L+1).trim();return{type:"add-apikey",apiKey:Z,label:G??(M||void 0),baseURL:N,authHeader:b}}if($==="add-oauth-start")return{type:"add-oauth-start"};if($==="add-oauth-finish"&&D){let C=D,N,b=C.match(/--label\s+(.+)/);if(b)N=b[1]?.trim()||void 0,C=C.replace(b[0],"").trim();if(!C)return{type:"usage"};return{type:"add-oauth-finish",code:C,label:N}}return{type:"usage"}}function i$(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 E0=["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 BN(f){let _=d$(f.argumentsText),$=f.storage.accounts,D="main";if(_.type==="status"){let N=i$(f.storage),b=["## Claude Accounts",""];for(let E of N){let K=E.quotaPercent!=null?` ${Math.round(E.quotaPercent)}%`:"",G=!E.enabled?" (disabled)":"";b.push(`- **${E.label}** [${E.role}]${G}${K}`)}return b.push("",E0),{text:b.join(`
|
|
19
|
-
`)}}if(_.type==="usage")return{text:E0};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 N=$.find((b)=>b.id===C);if(!N)return{text:`Account "${C}" not found.`};return{text:`Account "${N.label??C}" ${_.type}d.`,updated:{id:C,action:_.type,enabled:_.type==="enable"}}}if(_.type==="remove"){let N=$.find((b)=>b.id===C);if(!N)return{text:`Account "${C}" not found.`};return{text:`Account "${N.label??C}" removed.`,updated:{id:C,action:"remove"}}}if(_.type==="move-up"){let N=$.findIndex((G)=>G.id===C);if(N<0)return{text:`Account "${C}" not found.`};if(N===0)return{text:`Account "${$[N]?.label??C}" is already first.`};let b=$.map((G)=>G.id),E=[...$];[E[N-1],E[N]]=[E[N],E[N-1]];let K=E.map((G)=>G.id);return{text:`Account "${$[N]?.label??C}" moved up.`,updated:{id:C,action:"reorder",previousOrder:b,newOrder:K}}}if(_.type==="move-down"){let N=$.findIndex((G)=>G.id===C);if(N<0)return{text:`Account "${C}" not found.`};if(N===$.length-1)return{text:`Account "${$[N]?.label??C}" is already last.`};let b=$.map((G)=>G.id),E=[...$];[E[N],E[N+1]]=[E[N+1],E[N]];let K=E.map((G)=>G.id);return{text:`Account "${$[N]?.label??C}" moved down.`,updated:{id:C,action:"reorder",previousOrder:b,newOrder:K}}}return{text:E0}}import{createHash as u$}from"node:crypto";import{mkdir as g$,writeFile as Af}from"node:fs/promises";import{tmpdir as s$}from"node:os";import{join as X1}from"node:path";var WN="claude-dump",r$="## Claude Dump Status",n$="## Claude Dump Enabled",c$="## Claude Dump Disabled",t$="## Claude Dump Usage",o$="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",a$="OPENCODE_ANTHROPIC_AUTH_DUMP_DIR",e$=X1(s$(),"opencode-anthropic-auth-dumps"),jf=!1,W1=0,fD=100,ff=new Map;function YN(f){jf=f}function F1(){return process.env[a$]||e$}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[r$,"",`- Enabled: ${_?"enabled":"disabled"}`,`- Directory: ${F1()}`,"- 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 ZN(f){let _=_D(f.argumentsText),$=f.enabled??jf;if(_.type==="status")return Rf({enabled:$});if(_.type==="enable")return[n$,"",Rf({enabled:!0})].join(`
|
|
21
|
-
`);if(_.type==="disable")return[c$,"",Rf({enabled:!1})].join(`
|
|
22
|
-
`);return[t$,"",o$,"",Rf({enabled:$})].join(`
|
|
23
|
-
`)}function Y1(f){return f.length<=16?f:`${f.slice(0,12)}…`}function V1(f){let _=f.trim().replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"");if(!_)return"session-unknown";return _.length<=80?_:_.slice(0,80)}function $D(f){if(f.transport!=="direct")return`${f.transport}-p${f.protocol}-${f.mode}`;return`direct${f.route?`-${V1(f.route)}`:""}`}function DD(f){let _=f.affinity?.trim();if(_)return`session:${_}`;return`request:${f.route??"direct"}:${f.url??""}`}function CD(f,_){if(!ff.has(f))while(ff.size>=fD){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 m1(f){return u$("sha256").update(f).digest("hex")}function bD(f){return H1(f)}function ED(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 KD(f){try{let _=JSON.parse(f);return _!=null&&typeof _==="object"&&!Array.isArray(_)?_:null}catch(_){return O(`dump body parse failed: ${_ instanceof Error?_.message:String(_)}`),null}}function K0(f){return m1(JSON.stringify(f))}function GD(f){let _=KD(f);if(!_)return{parseable:!1};let $=Array.isArray(_.messages)?_.messages:[],D=Array.isArray(_.system)?_.system:[],C=$[0],N=$.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(N),messagesAfter0Bytes:JSON.stringify(N).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"||Z1($)){_[$]="[redacted]";continue}_[$]=Pf(D)}return _}async function Q1(f){if(!jf)return;W1+=1;let _=f.affinity?.trim()||"session-unknown",$=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(W1).padStart(5,"0")}-${V1(_)}-${$D(f)}`,D=F1(),C=X1(D,$),N={body:`${C}.body.json`,metadata:`${C}.meta.json`};if(f.payload!==void 0)N.relay=`${C}.relay.json`;if(f.request!==void 0)N.request=`${C}.request.json`;try{await g$(D,{recursive:!0});let b={id:$,createdAt:new Date().toISOString(),session:Y1(_),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:m1(f.bodyText),diff:ED(f.previousBodyText,f.bodyText),body:GD(f.bodyText),files:N},E=[Af(N.body,f.bodyText,"utf8"),Af(N.metadata,`${JSON.stringify(b,null,2)}
|
|
24
|
-
`,"utf8")];if(f.payload!==void 0&&N.relay)E.push(Af(N.relay,`${JSON.stringify(Pf(f.payload),null,2)}
|
|
25
|
-
`,"utf8"));if(f.request!==void 0&&N.request)E.push(Af(N.request,`${JSON.stringify(Pf({...f.request,headers:ND(f.request.headers)}),null,2)}
|
|
26
|
-
`,"utf8"));await Promise.all(E),O(`dumped request id=${$} session=${Y1(_)} body=${N.body} meta=${N.metadata}`)}catch(b){O(`dump failed: ${b instanceof Error?b.message:String(b)}`)}}async function XN(f){if(!jf)return;let _=DD(f),$=ff.get(_);await Q1({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}}),CD(_,f.bodyText)}async function A1(f){await Q1({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 VN="claude-fast";var If=!1;function mN(){return If}function QN(f){If=f}function UD(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 AN(f){let _=UD(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 jD(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[,N,b,E,K]=C,G=typeof K==="string"&&K.length>0?Number.parseInt(K,10):void 0,U={account:N,fh:Number.parseInt(b,10),sd:Number.parseInt(E,10)};if(G!==void 0)U.scoped=G;$.push(U)}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=Ef(f.main);D.push(`| main | ≥ ${C.five_hour}% | ≥ ${C.seven_day}% | ≤ ${C.scoped}% |`);for(let N of _){let b=Ef(f.accounts?.[N]??f.main);D.push(`| ${N} | ≥ ${b.five_hour}% | ≥ ${b.seven_day}% | ≤ ${b.scoped}% |`)}}return D.join(`
|
|
31
|
-
`)}var R1=["## 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 qN(f){let _=jD(f.argumentsText);if(_.type==="status")return{text:`${xf(f.config,f.accountIds)}
|
|
33
|
-
|
|
34
|
-
${R1}`};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 b of _.entries){let E={five_hour:b.fh,seven_day:b.sd};if(b.scoped!==void 0)E.scoped=b.scoped;if(b.account==="main")C.main=E;else if(b.account==="all"){C.main=E;for(let K of f.accountIds)D[K]=E}else D[b.account]=E}return{text:`## Killswitch Updated
|
|
37
|
-
|
|
38
|
-
${xf(C,f.accountIds)}`,updatedConfig:C}}return{text:`${xf(f.config,f.accountIds)}
|
|
39
|
-
|
|
40
|
-
${R1}`}}var xN="claude-logging",BD=["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&&BD.includes(_[0]))return{type:"level",level:_[0]};return{type:"usage"}}function G0(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 TN(f){let _=HD(f.argumentsText),$=f.level??"info";if(_.type==="status")return G0({level:$});if(_.type==="level")return["## Claude Log Level Updated","",`Level set to \`${_.level}\`.`,"",...G0({level:_.level}).split(`
|
|
42
|
-
`).slice(2)].join(`
|
|
43
|
-
`);return["## Claude Log Level Usage","","Usage: `/claude-logging`, `/claude-logging error|warn|info|debug|trace`.","",...G0({level:$}).split(`
|
|
44
|
-
`).slice(2)].join(`
|
|
45
|
-
`)}var MD=["claude-fable-5","claude-mythos-5"],LD={type:"adaptive",display:"summarized"},wN={input:10,output:50,cacheRead:1,cacheWrite5m:12.5,cacheWrite1h:20},yN=1e6,kN=128000,lN="2026-06-09",pN={["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 vN(f){return typeof f==="string"&&MD.some((_)=>f===_||f.startsWith(`${_}-`))}var P1="claude-sonnet-5",dN=LD;function iN(f){return typeof f==="string"&&(f===P1||f.startsWith(`${P1}-`))}function uN(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 OD}from"node:crypto";var zD=globalThis.setTimeout;function x(f){return OD("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!==x(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)!==x(_))return this.fallbacks.delete(f),this.fallbackTokenFps.delete(f),null;return $}getAllFallbacks(){return this.fallbacks}setMain(f,_){this.mainTokenFp=x(f),this.main=_}setFallback(f,_,$){if(this.fallbacks.set(f,_),$)this.fallbackTokenFps.set(f,x($));else this.fallbackTokenFps.delete(f)}async refreshMain(f){let _=x(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 N=this.getFallback(f,_);if(N)return N.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 _=f1(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=_?x(_):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 _=w(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)!==x(_))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,x(_)])}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 N=zD(C,v.API_CALL_GAP_MS-D);if(typeof N==="object"&&"unref"in N)N.unref()});return this.lastApiCallAt=this.now(),f()},$=this.apiGate.then(_,_);return this.apiGate=$.catch(()=>{}),$}async _fetchMain(f){let _=x(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}),N=this.now();return this.mainTokenFp=x(f),this.main={quota:C,refreshAfter:af(C,this.storage,N),checkedAt:N},this.mainLastApiError=void 0,this.onMainQuotaFetched?.(C,N,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+w(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=x(_),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 tN="claude-quota",q1={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),N=D%60;if(N===0)return`${C}h ago`;return`${C}h ${N}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 N=Math.floor(C/60),b=C%60;if(b===0)return`in ${N}h`;return`in ${N}h ${b}m`}function x1(f,_){if(!f)return"";return`, resets ${JD(f,_)}`}function I1(f,_,$){if(!_)return` - ${q1[f]}: unknown`;return[` - ${q1[f]}: ${Tf(_.remainingPercent)} remaining`,` (${Tf(_.usedPercent)} used`,`${x1(_.resetsAt,$)}, checked ${hf(_.checkedAt,$)})`].join("")}function SD(f,_){return[` - ${f.title}: ${Tf(f.remainingPercent)} remaining`,` (${Tf(f.usedPercent)} used`,`${x1(f.resetsAt,_)}, checked ${hf(f.checkedAt,_)})`].join("")}function WD(f){return f.label?.trim()||f.id}function YD(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function oN(f,_=new Map){if(!f?.accounts.length)return[];return f.accounts.filter(h).map(($)=>{let D=_.get($.id)??YD($);return{name:WD($),role:"fallback",enabled:$.enabled!==!1,quota:$.quota,lastRefreshedAt:$.lastRefreshedAt,...D&&{error:D}}})}function aN(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",N=D.enabled===!1?" disabled":"";if($.push(`### ${D.name} (${C}${N})`),D.lastRefreshedAt)$.push(` - Last token refresh: ${hf(D.lastRefreshedAt,_)}`);if(D.error)$.push(` - Error: ${D.error}`);$.push(I1("five_hour",D.quota?.five_hour,_)),$.push(I1("seven_day",D.quota?.seven_day,_));for(let b of D.quota?.scoped??[])$.push(SD(b,_));$.push("")}return $.join(`
|
|
47
|
-
`).trimEnd()}import{Buffer as v1}from"node:buffer";import{createHash as ZD,randomBytes as XD}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,T1=new Set,FD=7200000,VD=1800000,mD=128,QD=32,h1=0;function U0(){return h1+=1,`req_${Date.now().toString(36)}_${h1.toString(36)}`}function wf(f){if(T1.has(f))return;T1.add(f),O(f)}function C6(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 N6(){return XD(32).toString("base64url")}function AD(f){return`sha256:${ZD("sha256").update(f).digest("hex")}`}function w1(f,_){let $=0,D=Math.min(f.length,_.length);while($<D&&f.charCodeAt($)===_.charCodeAt($))$++;let C=f.length,N=_.length;while(C>$&&N>$&&f.charCodeAt(C-1)===_.charCodeAt(N-1))C--,N--;return{start:$,deleteCount:C-$,insert:_.slice($,N)}}function RD(f){return f.deleteCount===0&&f.insert.length===0}function y1(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 PD(f,_,$,D){return`${f.slice(0,_)}${D}${f.slice($)}`}function d1(f,_){let $=y1(f),D=y1(_);if($&&D&&$.start===D.start&&$.end-$.start===D.end-D.start&&$.token!==D.token){let C={start:$.start,deleteCount:$.end-$.start,insert:D.token},N=PD(f,$.start,$.end,D.token),b=w1(N,_);return RD(b)?C:[C,b]}return w1(f,_)}function qD(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 ID(f){let _={};for(let[$,D]of f.entries()){if($==="x-session-affinity"||$==="x-opencode-session")continue;_[$]=D}return _}async function k1(f,_,$){let D=J(),C=JSON.stringify(_);return $f("http_payload_stringify",{session:S(_.affinity),ms:R(J()-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 S(f){return f.length>12?`${f.slice(0,12)}…`:f}function J(){return performance.now()}function R(f){return Math.round(f*10)/10}function xD(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function $f(f,_){if(!xD())return;O(`[perf] relay ${f} ${JSON.stringify(_)}`)}function TD(f){let{input:_,init:$,headers:D,bodyText:C,affinity:N,previous:b,nextHash:E}=f,K=_ instanceof Request?_.url:_.toString(),G={protocol:1,type:"request",affinity:N,upstream:{url:K,method:$?.method||(_ instanceof Request?_.method:"POST"),headers:ID(D)},next_hash:E};return b?{...G,mode:"patch",base_hash:b.hash,revision:b.revision+1,patch:d1(b.body,C)}:{...G,mode:"full_sync",revision:1,body:C}}function H0(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 i1(f,_,$,D){let C=Date.now();k.delete(f),k.set(f,{body:_,hash:$,revision:D,updatedAt:C}),M0(C)}async function l1(f){let{config:_,payload:$,bodyText:D,fallback:C,signal:N}=f,b=$,E=await k1(_,b,N);if(E.status===409&&b.mode==="patch")O(`state mismatch from relay session=${S(b.affinity)}; retrying full_sync`),await E.body?.cancel().catch(()=>{}),b=H0(b,D),E=await k1(_,b,N);if(!E.ok&&E.status>=500&&_.fallbackToDirect)return O(`relay returned ${E.status}; falling back direct session=${S(b.affinity)}`),await E.body?.cancel().catch(()=>{}),{response:await C(),payload:b,transport:"http",protocol:b.protocol,usedRelay:!1};return{response:E,payload:b,transport:"http",protocol:b.protocol,usedRelay:!0}}function hD(f,_){let $=new URL(f);return $.protocol=$.protocol==="http:"?"ws:":"wss:",$.pathname="/ws",$.searchParams.set("token",_),$.toString()}function wD(f){return new Uint8Array(v1.from(f,"base64"))}function yD(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(v1.from(String(f)))}function kD(f){return JSON.parse(f)}function p1(f){let _=f,$=[`code=${_.code??"unknown"}`,`wasClean=${_.wasClean??"unknown"}`];if(_.reason)$.push(`reason=${JSON.stringify(_.reason)}`);return $.join(" ")}function lD(f){let _=f.message||"relay websocket error";return f.status?`relay websocket error ${f.status}: ${_}`:_}class u1{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>VD}dispose(){this.socket?.close(),this.socket=void 0,this.serverState=void 0,this.connecting=void 0}send(f,_,$=!1){this.touch();let D=J(),C=this.queue.catch(()=>{}).then(()=>this.startQueued(f,_,D,$)),N=C.then(async({response:b,getPayload:E})=>({response:await b,payload:E(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=C.then(({done:b})=>b.catch(()=>{}),()=>{}),N}async startQueued(f,_,$,D){let C=J();await this.ensureConnected();let N=J(),b=k.get(this.affinity),E=this.serverState?.hash,K={...f,protocol:2,id:U0()};if(K.mode==="patch"&&(!E||E!==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"&&b)K.patch=d1(b.body,_);O(`perf websocket send_start session=${S(this.affinity)} request=${K.id} mode=${K.mode} queueMs=${R(N-$)} connectMs=${R(N-C)} bodyBytes=${_.length} relayBytes=${JSON.stringify(K).length}`);let G=K,U=this.sendPayload(K,_,D);U.done.catch(()=>{});let L=U.done,Z=U.response.catch((X)=>{if(!(X instanceof j0)||K.mode!=="patch")throw X;let W=H0(K,_);W.protocol=2,W.id=U0(),W.revision=(this.serverState?.revision??0)+1,G=W;let B=this.sendPayload(W,_,D);return B.done.catch(()=>{}),L=B.done,B.response}),M=Z.then(()=>L,()=>L.catch(()=>{}));return{response:Z,done:M,getPayload:()=>G}}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 $=hD(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 N=setTimeout(()=>{C.close(),_(Error("relay websocket ready timed out"))},15000);C.addEventListener("message",(b)=>{try{if(typeof b.data!=="string"){this.handleBinaryChunk(b.data);return}let E=kD(b.data);if(E.type==="ready"){clearTimeout(N),this.serverState=E.state,f();return}this.handleMessage(E)}catch(E){clearTimeout(N),_(E),this.failPending(E),C.close()}}),C.addEventListener("error",()=>{clearTimeout(N);let b=new B0("relay websocket error");_(b),this.failPending(b)}),C.addEventListener("close",(b)=>{if(clearTimeout(N),this.socket===C)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;let E=this.pending.responseStartedAt!=null,K=E?"closed after response_start before stream bytes":"closed before response";if(this.retryPendingBeforeResponse(this.pending,K,b))return;let G=E?new B0("relay websocket closed during response stream",b):Error("relay websocket closed before response");O(`websocket ${E?"closed during response stream":"closed before response without retry"} session=${S(this.affinity)} request=${this.pending.payload.id} chunks=${this.pending.streamChunkCount} bytes=${this.pending.streamByteCount} ${p1(b)}`),this.failPending(G)}})}).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=J(),N,b,E=new Promise((G,U)=>{N=G,b=U});return{response:new Promise((G,U)=>{let L={payload:f,bodyText:_,resolve:G,reject:U,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:N,rejectDone:b,sentAt:C,optimisticResponse:$,streamChunkCount:0,streamByteCount:0,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=L,this.resetPendingTimeout(L),D.send(JSON.stringify(f)),$)this.resolvePendingResponse(L,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:E}}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 O(`websocket ${_}; reconnecting and retrying full_sync session=${S(this.affinity)} request=${C} retry=${D} chunks=${f.streamChunkCount} bytes=${f.streamByteCount}${$?` ${p1($)}`:""}`),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 N=H0(f.payload,f.bodyText);N.protocol=2,N.id=U0(),N.revision=(this.serverState?.revision??0)+1,f.payload=N,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=J(),f.retryingBeforeResponse=!1;let b=this.socket;if(!b||b.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),O(`perf websocket retry_send session=${S(this.affinity)} request=${N.id} previous=${C} mode=full_sync retry=${D} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify(N).length}`),b.send(JSON.stringify(N))}catch(N){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending(N)}})(),!0}enqueueStreamChunk(f,_){f.streamChunkCount+=1,f.streamByteCount+=_.byteLength,f.streamController?.enqueue(_)}handleBinaryChunk(f){let _=this.pending;if(!_?.responseStarted)return;this.enqueueStreamChunk(_,yD(f))}resolvePendingResponse(f,_,$,D){if(f.responseStarted)return;f.responseStarted=!0;let C=new ReadableStream({start:(N)=>{f.streamController=N},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 $=J();_.accepted=!0,_.acceptedAt=$,O(`perf websocket accepted session=${S(this.affinity)} request=${_.payload.id} sentMs=${R($-_.sentAt)} mode=${_.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},i1(this.affinity,_.bodyText,f.hash,f.revision),this.resetPendingTimeout(_);return}if(f.type==="response_start"){let $=J();if(_.responseStartedAt=$,O(`perf websocket response_start session=${S(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(_,wD(f.base64));return}if(f.type==="done"){this.finishPending(f);return}if(f.type==="error"){if(_.optimisticResponse&&_.responseStartedAt!=null){O(`websocket relay error during optimistic response session=${S(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(lD(f));this.failPending($)}}finishPending(f){let _=this.pending;if(!_)return;let $=J(),D=f&&"frames"in f?` upstreamChunks=${f.upstreamChunks??"unknown"} upstreamBytes=${f.upstreamBytes??"unknown"} frames=${f.frames} frameBytes=${f.frameBytes??"unknown"}`:"";if(O(`perf websocket done session=${S(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 M0(f=Date.now()){for(let[_,$]of k)if(f-$.updatedAt>FD)k.delete(_);while(k.size>mD){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 pD(f,_){M0();let $=c.get(_);if($)return $.touch(),$;let D=new u1(f,_);return c.set(_,D),M0(),D}async function b6(f){let{config:_,input:$,init:D,headers:C,body:N,fallback:b,affinity:E,optimisticResponse:K}=f;if(!_||!qD($,N))return b();let G=E||C.get("x-session-affinity")||C.get("x-opencode-session");if(!G)return O("skipping relay: missing x-session-affinity header"),b();let U=N,L=J(),Z=AD(U);$f("hash_body",{session:S(G),ms:R(J()-L),bodyBytes:U.length});let M=k.get(G),X=J(),W=TD({input:$,init:D,headers:C,bodyText:U,affinity:G,previous:M,nextHash:Z});$f("create_payload",{session:S(G),ms:R(J()-X),mode:W.mode,bodyBytes:U.length,previousBytes:M?.body.length});try{let B,d=J();if(_.transport==="websocket")try{B=await pD(_,G).send(W,U,K===!0)}catch(j){O(`websocket relay failed session=${S(G)}; trying http relay: ${j instanceof Error?j.message:String(j)}`),B=await l1({config:_,payload:W,bodyText:U,fallback:b,signal:D?.signal})}else B=await l1({config:_,payload:W,bodyText:U,fallback:b,signal:D?.signal});if($f("send",{session:S(G),ms:R(J()-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")i1(G,U,B.payload.next_hash,B.payload.revision);let q=J(),y=JSON.stringify(B.payload).length;$f("payload_stringify",{session:S(G),ms:R(J()-q),relayBytes:y}),O(`used relay transport=${B.transport} protocol=${B.protocol} mode=${B.payload.mode} status=${B.response.status} session=${S(G)} bodyBytes=${U.length} relayBytes=${y}`);let T=J();return await A1({affinity:G,transport:B.transport,protocol:B.protocol,mode:B.payload.mode,status:B.response.status,bodyText:U,previousBodyText:M?.body,payload:B.payload,relayBytes:y}),$f("dump",{session:S(G),ms:R(J()-T),enabled:!0}),B.response}catch(B){if(!_.fallbackToDirect)throw O(`relay failed session=${S(G)} and fallbackToDirect=false: ${B instanceof Error?B.message:String(B)}`),B;return O(`relay failed; falling back direct session=${S(G)}: ${B instanceof Error?B.message:String(B)}`),b()}}var E6=`
|
|
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 U6="claude-routing",O0=["main-first","fallback-first"],z0="main-first",g1="Usage: `/claude-routing`, `/claude-routing main-first`, or `/claude-routing fallback-first`.";function vD(f){return typeof f==="string"&&O0.includes(f)?f:z0}function j6(f){return vD(f?.routing?.mode)}async function B6(f,_=z()){let $=await F(_)??A();return $.routing={...$.routing??{},mode:f},await m($,_),$}function dD(f){let _=f.trim().toLowerCase().split(/\s+/).filter(Boolean);if(_.length===0)return{type:"status"};if(_.length===1&&O0.includes(_[0]))return{type:"mode",mode:_[0]};if(_.length===2&&_[0]==="mode"&&O0.includes(_[1]))return{type:"mode",mode:_[1]};return{type:"usage"}}function iD(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 L0(f){let _=f?.mode??z0;return["## Claude Routing Status","",`- Mode: \`${_}\``,`- Behavior: ${iD(_)}`,"",g1].join(`
|
|
413
|
-
`)}function H6(f){let _=dD(f.argumentsText),$=f.mode??z0;if(_.type==="status")return L0({mode:$});if(_.type==="mode")return["## Claude Routing Updated","",`Mode updated to \`${_.mode}\`.`,"",...L0({mode:_.mode}).split(`
|
|
414
|
-
`).slice(2)].join(`
|
|
415
|
-
`);return["## Claude Routing Usage","",g1,"",...L0({mode:$}).split(`
|
|
416
|
-
`).slice(2)].join(`
|
|
417
|
-
`)}export{uD as a,Z0 as b,gD as c,sD as d,rD as e,nD as f,cD as g,X0 as h,tD as i,oD as j,P0 as k,$C as l,DC as m,h as n,BC as o,$_ as p,HC as q,z as r,A as s,F as t,m as u,x_ as v,Zf as w,MC as x,h_ as y,LC as z,OC as A,zC as B,JC as C,SC as D,WC as E,YC as F,ZC as G,XC as H,FC as I,VC as J,a0 as K,v_ as L,mC as M,Df as N,gf as O,QC as P,AC as Q,RC as R,e0 as S,of as T,i_ as U,y0 as V,_1 as W,u_ as X,g_ as Y,PC as Z,qC as _,IC as $,xC as aa,TC as ba,hC as ca,wC as da,yC as ea,af as fa,o_ as ga,$$ as ha,pC as ia,vC as ja,dC as ka,iC as la,E$ as ma,uC as na,M1 as oa,$N as pa,nC as qa,cC as ra,tC as sa,U1 as ta,EN as ua,KN as va,k$ as wa,N0 as xa,S1 as ya,l$ as za,GN as Aa,v$ as Ba,jN as Ca,d$ as Da,i$ as Ea,BN as Fa,WN as Ga,YN as Ha,_D as Ia,ZN as Ja,XN as Ka,VN as La,mN as Ma,QN as Na,UD as Oa,AN as Pa,_f as Qa,qN as Ra,xN as Sa,HD as Ta,TN as Ua,LD as Va,wN as Wa,yN as Xa,kN as Ya,lN as Za,pN as _a,vN as $a,dN as ab,iN as bb,uN as cb,v as db,tN as eb,oN as fb,aN as gb,C6 as hb,N6 as ib,b6 as jb,E6 as kb,U6 as lb,j6 as mb,B6 as nb,dD as ob,H6 as pb};
|