@cortexkit/opencode-anthropic-auth 1.2.0 → 1.2.2
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/dist/cli.js +1 -1
- package/dist/{index-sebye7nt.js → index-z4vzznkk.js} +27 -27
- package/dist/index.js +3 -3
- package/package.json +2 -2
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{l as y,m as w,o as l,p as u,q as m,ra as b,ta as k}from"./index-
|
|
2
|
+
import{l as y,m as w,o as l,p as u,q as m,ra as b,ta as k}from"./index-z4vzznkk.js";import{stdin as A,stdout as $}from"node:process";import{createInterface as R}from"node:readline/promises";function v(){return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:[401,403,429],refresh:{enabled:!0,intervalMinutes:10,refreshBeforeExpiryMinutes:240},quota:{enabled:!0,checkIntervalMinutes:5,minimumRemaining:{five_hour:10,seven_day:20},failClosedOnUnknownQuota:!0},accounts:[]}}function h(){console.log(`Usage:
|
|
3
3
|
opencode-anthropic-auth login [label]
|
|
4
4
|
opencode-anthropic-auth list
|
|
5
5
|
opencode-anthropic-auth relay setup
|
|
@@ -1,36 +1,36 @@
|
|
|
1
|
-
var y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Of={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Ef="https://platform.claude.com/oauth/code/callback",Ff="https://
|
|
2
|
-
${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function A(f,$){if(vf)return;try{if(P.push(`[${new Date().toISOString()}] ${f}${
|
|
3
|
-
`),P.length>=
|
|
4
|
-
`,{encoding:"utf8",mode:384}),await a0(D,$)}async function
|
|
5
|
-
`,{encoding:"utf8",mode:384}),!0}catch(F){if(F.code!=="EEXIST")throw F;return!1}}if(!await E()){try{let F=JSON.parse(await d(m,"utf8"));if(Number(F?.expiresAt)>H())return null}catch{}if(await df(_,{recursive:!0,force:!0}).catch(()=>{}),!await E())return null}return{release:async()=>{try{if(JSON.parse(await d(m,"utf8"))?.ownerId!==D)return}catch{return}await df(_,{recursive:!0,force:!0}).catch(()=>{})}}}function H_(f){return f?.claudeCache?.enabled===!0}function S1(f){return typeof f==="string"&&Rf.includes(f)?f:p}function W1(f){return S1(f?.claudeCache?.mode)}async function E_(f,$,_=B()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.claudeCache={...m.claudeCache??{},enabled:f,mode:$??W1(m)},await Y(m,_),m}async function F_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeCache={..._.claudeCache??{},enabled:_.claudeCache?.enabled===!0,mode:f},await Y(_,$),_}function M_(f){return f?.dump?.enabled===!0}async function C_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.dump={..._.dump??{},enabled:f},await Y(_,$),_}function K_(f){return f?.claudeFast?.enabled===!0}async function j_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeFast={..._.claudeFast??{},enabled:f},await Y(_,$),_}async function N_(f,$,_=B()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.cacheKeep={enabled:!0,startHour:f,endHour:$},await Y(m,_),m}async function J_(f,$=B()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.cacheKeep={..._.cacheKeep??{},enabled:f},await Y(_,$),_}function L1(f){return f?.fallbackOn?.length?f.fallbackOn:m1}function b_(f,$){return L1($).includes(f)}function D0(f){let $=f?.quota?.minimumRemaining||{};return{five_hour:$.five_hour??$["5h"]??tf.five_hour,seven_day:$.seven_day??$["1w"]??tf.seven_day}}function i(f){return f?.quota?.enabled!==!1}function B1(f){return f?.refresh?.enabled!==!1}function Q1(f){let $=f?.refresh?.refreshBeforeExpiryMinutes??D1;return Math.max(m0,$)*60000}function H0(f){return o0("sha256").update(f).digest("hex")}function U1(f){if(f instanceof h)return f.status===429||f.status>=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 Z1(f){let $=H0(f.refreshToken),m=(f.previous?.tokenHash===$?f.previous.retryCount??0:0)+1,D=U1(f.error)?Math.min(E1,H1*2**Math.min(m-1,6)):F1;return{message:jf(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:m,tokenHash:$}}function v(f,$,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;if(!$)return!0;return f.tokenHash===H0($)}function sf(f,$){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??$)-$)/1000))}s after: ${f.message}`}function R(f){let $=f?.quota?.checkIntervalMinutes??M1;return Math.max(1,$)*60000}function E0(f){return f?.quota?.failClosedOnUnknownQuota??C1}function X1(f,$){if(!i($))return!0;let _=D0($);for(let m of["five_hour","seven_day"]){let D=f?.[m];if(!D)return!E0($);if(D.remainingPercent<_[m])return!1}return!0}function I_(f,$,_){if(!i($))return _+R($);let m=D0($),D=[];for(let H of["five_hour","seven_day"]){let E=f?.[H];if(!E)return _+R($);if(E.remainingPercent>=m[H])continue;let F=E.resetsAt?Date.parse(E.resetsAt):Number.NaN;if(!Number.isFinite(F)||F<=_)return _+R($);D.push(F)}if(!D.length)return _+R($);return Math.min(...D)+60000}function k(f,$,_){return!f.access||!f.expires||f.expires-_<=Q1($)}function rf(f,$,_){if(!i($))return!1;let m=R($);return["five_hour","seven_day"].some((D)=>{let H=f.quota?.[D];return!H||_-H.checkedAt>=m})}function of(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function af(f,$){if(typeof f?.utilization!=="number")return;let _=of(f.utilization);return{usedPercent:_,remainingPercent:of(100-_),resetsAt:f.resets_at,checkedAt:$}}async function ef(f){let _=await(f.fetchImpl??fetch)(_1,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${Z}`}});if(!_.ok){let H=await _.text().catch(()=>"");throw Error(`Claude quota check failed: ${_.status} — ${H}`)}let m=f.now?.()??Date.now(),D=await _.json();return{five_hour:af(D.five_hour,m),seven_day:af(D.seven_day,m)}}function X(f,$){let _=f.accounts.findIndex((m)=>m.id===$.id);if(_>=0)f.accounts[_]=$}function jf(f){return f instanceof Error?f.message:String(f)}function F0(f,$,_){f.lastRefreshError=Z1({error:$,now:_,refreshToken:f.refresh,previous:f.lastRefreshError})}function f0(f,$,_){if(f.lastQuotaRefreshError={message:jf($),checkedAt:_},$ instanceof h)F0(f,$,_)}class z1{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??B()}async load(){return V(this.configPath)}async save(f){await Y(f,this.configPath)}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},K1),"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 _=[],m=!1;for(let D of $.accounts){if(D.enabled===!1)continue;try{let H=D;if(k(H,$,this.now())){let E=H.lastRefreshError;if(E&&v(E,H.refresh,this.now()))throw Error(sf(E,this.now()));H=await this.refreshAccount(H,$),m=!0}if(rf(H,$,this.now()))H=await this.refreshAccountQuota(H,$),m=!0;if(this.accountPassesQuotaPolicy(H,$))_.push(H)}catch{if(!E0($))_.push(D)}}if(m)await this.save($);return _}async markUsed(f){let $=await this.load();if(!$)return;let _=$.accounts.find((m)=>m.id===f.id);if(!_)return;_.lastUsed=this.now(),await this.save($)}accountPassesQuotaPolicy(f,$){return X1(f.quota,$)}async refreshDueAccounts(){let f=await this.load();if(!f||!B1(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;if(!k(_,f,this.now()))continue;if(v(_.lastRefreshError,_.refresh,this.now())){A("[refresh] fallback oauth skipped backoff",{accountId:_.id,nextRetryAt:_.lastRefreshError?.nextRetryAt,retryCount:_.lastRefreshError?.retryCount});continue}try{A("[refresh] fallback oauth background due",{accountId:_.id,expiresInMs:_.expires?_.expires-this.now():void 0}),await this.refreshAccount(_,f),$=!0}catch(m){A("[refresh] fallback oauth background failed",{accountId:_.id,error:m instanceof Error?m.message:String(m)}),F0(_,m,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!i(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;let m=_;try{if(k(m,f,this.now())){if(v(m.lastRefreshError,m.refresh,this.now()))continue;m=await this.refreshAccount(m,f),$=!0}if(!rf(m,f,this.now()))continue;await this.refreshAccountQuota(m,f),$=!0}catch(D){f0(_,D,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForAllAccounts(){let f=await this.load(),$=[];if(!f||!i(f))return{storage:f,errors:$};let _=!1;for(let m of f.accounts){if(m.enabled===!1)continue;let D=m;try{if(k(D,f,this.now())){let H=D.lastRefreshError;if(H&&v(H,D.refresh,this.now()))throw Error(sf(H,this.now()));D=await this.refreshAccount(D,f),_=!0}await this.refreshAccountQuota(D,f),_=!0}catch(H){f0(m,H,this.now()),X(f,m),_=!0,$.push({accountId:m.id,message:jf(H)})}}if(_)await this.save(f);return{storage:f,errors:$}}async refreshAccount(f,$,_={}){let m=this.refreshPromises.get(f.id);if(m){let E=await m;return X($,E),E}let D=this.refreshAccountNow(f,$,_).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,D);let H=await D;return X($,H),H}async refreshAccountNow(f,$,_){let m=await this.load(),D=m?.accounts.find((C)=>C.id===f.id);if(D&&!_.force&&!k(D,m,this.now()))return X($,D),D;let H=D??f,E=H.refresh;A("[refresh] fallback oauth refresh request start",{accountId:H.id,force:_.force===!0,expiresInMs:H.expires?H.expires-this.now():void 0});let F=await nf({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return H.access=F.access,H.refresh=F.refresh,H.expires=F.expires,H.lastRefreshedAt=F.expires-F.expiresIn*1000,H.lastRefreshError=void 0,X($,H),A("[refresh] fallback oauth refresh succeeded",{accountId:H.id,expiresInMs:H.expires?H.expires-this.now():void 0}),H}async refreshAccountQuota(f,$){let _=f;if(!_.access)throw Error(`Fallback account ${f.id} has no access token`);try{_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}catch(m){if(!(m instanceof Error?m.message:String(m)).includes("Claude quota check failed: 401"))throw m;if(_=await this.refreshAccount(f,$,{force:!0}),!_.access)throw m;_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}return _.lastQuotaRefreshError=void 0,X($,_),_}}var W_="claude-cache",M0="## Claude Cache Status",A1="## Claude Cache Enabled",V1="## Claude Cache Disabled",Y1="## Claude Cache Usage",T1="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",g=!1,s=p;function L_(){return g}function B_(){return s}function Q_(f){g=f.enabled,s=f.mode}function O1(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 c(f){let $=f?.enabled??g,_=f?.mode??s;return[M0,"",`- 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(`
|
|
6
|
-
`)}function
|
|
7
|
-
`);if($.type==="disable")return[
|
|
8
|
-
`);if($.type==="mode")return[
|
|
9
|
-
`);return[
|
|
10
|
-
`)}import{randomBytes as q1,randomUUID as K0}from"node:crypto";var h1=1000,u=new Map;function Jf(f,$,_){if(!f.has($)&&f.size>=h1){let m=f.keys().next().value;if(m!==void 0)f.delete(m)}f.set($,_)}function j0(f){let $=f||"anonymous",_=u.get($);if(_)return _;let m={deviceId:q1(32).toString("hex"),sessionId:K0()};return Jf(u,$,m),m}var Nf=new Map;async function w1(f,$){if(!f.startsWith("sk-ant-oat"))return null;let _=new AbortController,m=setTimeout(()=>_.abort(),5000);try{let D=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(D.searchParams.set("entrypoint",wf),$)D.searchParams.set("model",$);let H=await fetch(D,{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/${Z}`},signal:_.signal});if(!H.ok)return null;let F=(await H.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof F==="string"&&F?F:null}catch{return null}finally{clearTimeout(m)}}async function A_(f,$){let _=j0(f);if(!f.startsWith("sk-ant-oat"))return _;let m=Nf.get(f);if(!m)m=w1(f,$),Nf.set(f,m);let D=await m;if(!D)return Nf.delete(f),_;let H=`account:${D}`,E=u.get(H);if(E)return Jf(u,f,E),E;return _.accountUuid=D,Jf(u,H,_),_}function T(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function x1(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function V_(f,$){let _=x1($);if(!_){if(T(f.metadata))delete f.metadata.user_id;return!1}if(!T(f.metadata))f.metadata={};let m=f.metadata;if(T(m))m.user_id=_;return!0}var P1=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","context-1m-2025-08-07","effort-2025-11-24","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],k1=["oauth-2025-04-20","interleaved-thinking-2025-05-14","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"],C0=["oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","cache-diagnosis-2026-04-07"];function R1(f){return f.output_config?.format?.type==="json_schema"}function i1(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&T(f.thinking)&&T(f.context_management)&&T(f.output_config)&&T(f.diagnostics)}function c1(f,$=[]){let _=f?i1(f)?[...P1]:R1(f)?[...k1]:[...C0]:[...C0];if(f?.speed==="fast")_.push(hf);for(let m of $){let D=m.trim();if(D)_.push(D)}return[...new Set(_)].join(",")}function u1(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function n1(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function Y_(f,$,_={}){let m=_.identity??j0($),H=[...(f.get("anthropic-beta")??"").split(",").map((E)=>E.trim()).filter(Boolean),..._.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${$}`),f.set("content-type","application/json"),f.set("user-agent",kf),f.set("anthropic-beta",c1(_.body,H)),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",K0()),f.set("x-claude-code-session-id",m.sessionId),f.set("x-stainless-arch",n1()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",u1()),f.set("x-stainless-package-version",xf),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",Pf),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var l1=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function N0(f){let $={};for(let _ of l1)if(Object.hasOwn(f,_))$[_]=f[_];for(let[_,m]of Object.entries(f))if(!Object.hasOwn($,_))$[_]=m;return $}import{createHash as p1}from"node:crypto";var y1=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 J0(){return function(f){let{exports:{mem:$,xxh32:_,xxh64:m,init32:D,update32:H,digest32:E,init64:F,update64:C,digest64:N}}=f,j=new Uint8Array($.buffer);function b(M,I){if($.buffer.byteLength<M+I){let Df=Math.ceil((M+I-$.buffer.byteLength)/65536);$.grow(Df),j=new Uint8Array($.buffer)}}function U(M,I,Df,c0,u0,n0){b(M);let x=new Uint8Array(M);return j.set(x),Df(0,I),x.set(j.subarray(0,M)),{update(q){let Hf;return j.set(x),typeof q=="string"?(b(3*q.length,M),Hf=L.encodeInto(q,j.subarray(M)).written):(b(q.byteLength,M),j.set(q,M),Hf=q.byteLength),c0(0,M,Hf),x.set(j.subarray(0,M)),this},digest:()=>(j.set(x),n0(u0(0)))}}function Q(M){return M>>>0}let K=2n**64n-1n;function W(M){return M&K}let L=new TextEncoder,n=0,l=0n;function Yf(M,I=n){return b(3*M.length,0),Q(_(0,L.encodeInto(M,j).written,I))}function Tf(M,I=l){return b(3*M.length,0),W(m(0,L.encodeInto(M,j).written,I))}return{h32:Yf,h32ToString:(M,I=n)=>Yf(M,I).toString(16).padStart(8,"0"),h32Raw:(M,I=n)=>(b(M.byteLength,0),j.set(M),Q(_(0,M.byteLength,I))),create32:(M=n)=>U(48,M,D,H,E,Q),h64:Tf,h64ToString:(M,I=l)=>Tf(M,I).toString(16).padStart(16,"0"),h64Raw:(M,I=l)=>(b(M.byteLength,0),j.set(M),W(m(0,M.byteLength,I))),create64:(M=l)=>U(88,M,F,C,N,W)}}((await WebAssembly.instantiate(y1)).instance)}var v1=0x6e52736ac806831en,r=/\bcch=([0-9a-f]{5});/,b0=null,bf=null;async function d1(){if(bf)return;b0??=(async()=>{bf=(await J0()).h64Raw})(),await b0}async function t1(f){return await d1(),((bf?.(f,v1)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function I0(f){if(!r.test(f))return f;let $=await t1(new TextEncoder().encode(f));return f.replace(r,`cch=${$};`)}function g1(f=Z,$=new Date){if(f===Z)return Mf;let _=$.toISOString().slice(0,10);return p1("sha256").update(`${_}${f}`).digest("hex").slice(0,3)}function x_(f,$=Z,_,m=new Date){let D=g1($,m);return`x-anthropic-billing-header: cc_version=${$}.${D}; cc_entrypoint=${_}; cch=00000;`}var i_="claude-cachekeep",G0=3600000,If=300000,s1=60000,c_="extended-cache-ttl-2025-04-11",r1="## Claude Cache Keep Status",o1="## Claude Cache Keep Enabled",a1="## Claude Cache Keep Disabled",e1="## Claude Cache Keep Usage",f$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function a(f){return String(f).padStart(2,"0")}function $$(f){let $=f.trim();if(!$)return{type:"status"};if($==="off")return{type:"disable"};let _=/^(\d{1,2})-(\d{1,2})$/.exec($);if(!_)return{type:"usage"};let m=Number(_[1]),D=Number(_[2]);if(!Number.isInteger(m)||!Number.isInteger(D)||m<0||m>23||D<0||D>23||m===D)return{type:"usage"};return{type:"window",startHour:m,endHour:D}}function Sf(f){let $=Number(f?.cacheKeep?.startHour),_=Number(f?.cacheKeep?.endHour);if(!Number.isInteger($)||!Number.isInteger(_)||$<0||$>23||_<0||_>23||$===_)return;return{startHour:$,endHour:_}}function L0(f){return f?.cacheKeep?.enabled===!0&&!!Sf(f)}function _$(f){return L0(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function S0(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 W0(f=new Date){return`${f.getFullYear()}-${a(f.getMonth()+1)}-${a(f.getDate())}`}function Gf(f,$=new Date){if(f&&f.startHour>f.endHour&&$.getHours()<f.endHour){let _=new Date($);return _.setDate(_.getDate()-1),W0(_)}return W0($)}function o(f){let $=f.window?`${a(f.window.startHour)}-${a(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(`
|
|
11
|
-
`)}function
|
|
12
|
-
`);if($.type==="disable")return[
|
|
13
|
-
`);if($.type==="window")return[
|
|
14
|
-
`);return[
|
|
15
|
-
`)}function
|
|
16
|
-
`)}function
|
|
17
|
-
`);if($.type==="disable")return[
|
|
18
|
-
`);return[
|
|
19
|
-
`)}function Q0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function
|
|
1
|
+
var y="9d1c250a-e61b-44d9-88ed-5944d1962f5e",Of={console:"https://platform.claude.com/oauth/authorize",max:"https://claude.ai/oauth/authorize"},Ef="https://platform.claude.com/oauth/code/callback",Ff="https://api.anthropic.com/v1/oauth/token",qf=["org:create_api_key","user:profile","user:inference","user:sessions:claude_code","user:mcp_servers","user:file_upload"],c$="mcp_";var wf="fast-mode-2026-02-01";function u$(f,$){let _=(f??"").split(",").map((m)=>m.trim()).filter(Boolean);return[...new Set([..._,...$])].join(",")}function n$(f){return typeof f==="string"&&(f.startsWith("claude-opus-4-6")||f.startsWith("claude-opus-4-7"))}var l$="You are OpenCode",y$="You are a Claude agent, built on Anthropic's Claude Agent SDK.";var Z="2.1.141",Mf="67b",hf="sdk-cli",xf="0.94.0",Pf="v24.3.0",kf="claude-cli/2.1.141 (external, sdk-cli)",Rf=["explicit","automatic","hybrid"],p="explicit",p$=["github.com/anomalyco/opencode","opencode.ai/docs"],v$=[{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 cf(f){let $="";for(let _ of f)$+=String.fromCharCode(_);return btoa($).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function uf(){let f=new Uint8Array(64);crypto.getRandomValues(f);let $=cf(f),_=await crypto.subtle.digest("SHA-256",new TextEncoder().encode($));return{verifier:$,challenge:cf(new Uint8Array(_)),method:"S256"}}class w extends Error{status;body;constructor(f,$){super(`Claude OAuth refresh failed: ${f} — ${$}`);this.status=f,this.body=$,this.name="ClaudeOAuthRefreshError"}}function n0(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 nf(f){let $=f.fetchImpl??fetch,_=f.maxRetries??2,m=f.baseDelayMs??500;for(let D=0;D<=_;D++)try{if(D>0){let M=m*2**(D-1);await new Promise((N)=>setTimeout(N,M))}let H=await $(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({grant_type:"refresh_token",refresh_token:f.refreshToken,client_id:y})});if(!H.ok){if(H.status>=500&&D<_){await H.body?.cancel().catch(()=>{});continue}let M=await H.text().catch(()=>"");throw new w(H.status,M)}let E=await H.json(),F=f.now?.()??Date.now();return{access:E.access_token,refresh:E.refresh_token??f.refreshToken,expires:F+E.expires_in*1000,expiresIn:E.expires_in}}catch(H){if(H instanceof w)throw H;if(D<_&&n0(H))continue;throw H}throw Error("Token refresh exhausted all retries")}function l0(){return crypto.randomUUID().replace(/-/g,"")}function y0(f){let $=f.trim();try{let E=new URL($),F=E.searchParams.get("code"),M=E.searchParams.get("state");if(F&&M)return{code:F,state:M}}catch{}let _=$.split("#");if(_.length===2&&_[0]&&_[1])return{code:_[0],state:_[1]};let m=new URLSearchParams($),D=m.get("code"),H=m.get("state");if(D&&H)return{code:D,state:H};return null}async function p0(f,$,_){let m=await fetch(Ff,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json, text/plain, */*","User-Agent":"axios/1.13.6"},body:JSON.stringify({code:f.code,state:f.state,grant_type:"authorization_code",client_id:y,redirect_uri:_,code_verifier:$})});if(!m.ok)return{type:"failed"};let D=await m.json();return{type:"success",refresh:D.refresh_token,access:D.access_token,expires:Date.now()+D.expires_in*1000}}async function r$(f){let $=await uf(),_=l0(),m=new URL(Of[f],import.meta.url);return m.searchParams.set("code","true"),m.searchParams.set("client_id",y),m.searchParams.set("response_type","code"),m.searchParams.set("redirect_uri",Ef),m.searchParams.set("scope",qf.join(" ")),m.searchParams.set("code_challenge",$.challenge),m.searchParams.set("code_challenge_method","S256"),m.searchParams.set("state",_),{url:m.toString(),redirectUri:Ef,state:_,verifier:$.verifier}}async function o$(f,$,_,m){let D=y0(f);if(!D)return{type:"failed"};if(m&&D.state!==m)return{type:"failed"};return p0(D,$,_)}import*as lf from"node:fs";import*as yf from"node:os";import*as pf from"node:path";var v0=pf.join(yf.tmpdir(),"opencode-anthropic-auth.log"),vf=!1,d0=500,t0=50,P=[],h=null;function Cf(){if(h)clearTimeout(h),h=null;if(P.length===0)return;let f=P.join("");P=[];try{lf.appendFileSync(v0,f)}catch{}}function g0(){if(h)return;h=setTimeout(()=>{h=null,Cf()},d0)}function s0(f){if(f===void 0)return"";if(f instanceof Error)return` ${f.message}${f.stack?`
|
|
2
|
+
${f.stack}`:""}`;return` ${JSON.stringify(f)}`}function A(f,$){if(vf)return;try{if(P.push(`[${new Date().toISOString()}] ${f}${s0($)}
|
|
3
|
+
`),P.length>=t0)Cf();else g0()}catch{}}function b(f,$){A(`[relay] ${f}`,$)}if(!vf)process.on("exit",Cf);import{createHash as r0,randomUUID as Kf}from"node:crypto";import{mkdir as o0,readFile as d,rename as a0,rm as df,stat as e0,writeFile as $0}from"node:fs/promises";import{homedir as f1}from"node:os";import{dirname as $1,join as t}from"node:path";var _1="anthropic-auth.json",m1="https://api.anthropic.com/api/oauth/usage",D1=[401,403,429],_0=240,H1=_0;var E1=300000,F1=3600000,M1=86400000,C1=5,tf={five_hour:0,seven_day:0},K1=!0,j1=60000,N1=60000;function b1(){if(process.env.OPENCODE_CONFIG_DIR?.trim())return process.env.OPENCODE_CONFIG_DIR.trim();return t(process.env.XDG_CONFIG_HOME||t(f1(),".config"),"opencode")}function Q(){return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim()||t(b1(),_1)}function I(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function J1(f){if(!I(f))return null;if(f.type!=="oauth")return null;if(typeof f.refresh!=="string"||!f.refresh.trim())return null;return{id:typeof f.id==="string"&&f.id.trim()?f.id.trim():Kf(),label:typeof f.label==="string"?f.label:void 0,type:"oauth",access:typeof f.access==="string"?f.access:void 0,refresh:f.refresh,expires:typeof f.expires==="number"?f.expires: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,lastRefreshedAt:typeof f.lastRefreshedAt==="number"?f.lastRefreshedAt:void 0,lastRefreshError:gf(f.lastRefreshError),lastQuotaRefreshError:gf(f.lastQuotaRefreshError),quota:G1(f.quota)}}function gf(f){if(!I(f))return;if(typeof f.message!=="string")return;let $=Number(f.checkedAt);if(!Number.isFinite($))return;let _=Number(f.nextRetryAt),m=Number(f.retryCount);return{message:f.message,checkedAt:$,nextRetryAt:Number.isFinite(_)?_:void 0,retryCount:Number.isFinite(m)?m:void 0,tokenHash:typeof f.tokenHash==="string"?f.tokenHash:void 0}}function G1(f){if(!I(f))return;let $={};for(let _ of["five_hour","seven_day"]){let m=f[_];if(!I(m))continue;let D=Number(m.usedPercent),H=Number(m.remainingPercent),E=Number(m.checkedAt);if(!Number.isFinite(D)||!Number.isFinite(H)||!Number.isFinite(E))continue;$[_]={usedPercent:D,remainingPercent:H,checkedAt:E,resetsAt:typeof m.resetsAt==="string"?m.resetsAt:void 0}}return Object.keys($).length?$:void 0}function I1(f){if(!I(f)||!Array.isArray(f.accounts))return null;return{version:1,main:{type:"opencode",provider:"anthropic"},fallbackOn:Array.isArray(f.fallbackOn)?f.fallbackOn.filter(($)=>Number.isInteger($)):void 0,refresh:I(f.refresh)?f.refresh:void 0,quota:I(f.quota)?f.quota:void 0,claudeCache:I(f.claudeCache)?f.claudeCache:void 0,dump:I(f.dump)?f.dump:void 0,claudeFast:I(f.claudeFast)?f.claudeFast:void 0,cacheKeep:I(f.cacheKeep)?f.cacheKeep:void 0,relay:I(f.relay)?f.relay:void 0,accounts:f.accounts.map(J1).filter(($)=>$!=null)}}async function V(f=Q()){try{let $=await d(f,"utf8");return I1(JSON.parse($))}catch($){if($.code==="ENOENT")return null;return null}}async function W1(f){try{let $=await d(f,"utf8"),_=JSON.parse($);return I(_)?_:{}}catch{return{}}}function S1(f){return Object.fromEntries(Object.entries(f).filter(([,$])=>$!==void 0))}async function Y(f,$=Q()){await o0($1($),{recursive:!0});let m={...await W1($),...S1(f)},D=`${$}.${Kf()}.tmp`;await $0(D,`${JSON.stringify(m,null,2)}
|
|
4
|
+
`,{encoding:"utf8",mode:384}),await a0(D,$)}async function F_(f){let _=`${f.path??Q()}.${f.name}.lock`,m=t(_,"owner.json"),D=Kf(),H=f.now??Date.now;async function E(){try{return JSON.parse(await d(_,"utf8"))}catch(M){if(M.code!=="EISDIR")throw M;return JSON.parse(await d(m,"utf8"))}}async function F(){try{return await $0(_,`${JSON.stringify({ownerId:D,expiresAt:H()+f.ttlMs})}
|
|
5
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(M){let N=M.code;if(N==="EEXIST"||N==="EISDIR")return!1;throw M}}if(!await F()){try{let M=await E();if(Number(M?.expiresAt)>H())return null}catch{try{if((await e0(_)).mtimeMs+f.ttlMs>Date.now())return null}catch{return null}}if(await df(_,{recursive:!0,force:!0}).catch(()=>{}),!await F())return null}return{release:async()=>{try{if((await E())?.ownerId!==D)return}catch{return}await df(_,{recursive:!0,force:!0}).catch(()=>{})}}}function M_(f){return f?.claudeCache?.enabled===!0}function L1(f){return typeof f==="string"&&Rf.includes(f)?f:p}function Q1(f){return L1(f?.claudeCache?.mode)}async function C_(f,$,_=Q()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.claudeCache={...m.claudeCache??{},enabled:f,mode:$??Q1(m)},await Y(m,_),m}async function K_(f,$=Q()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeCache={..._.claudeCache??{},enabled:_.claudeCache?.enabled===!0,mode:f},await Y(_,$),_}function j_(f){return f?.dump?.enabled===!0}async function N_(f,$=Q()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.dump={..._.dump??{},enabled:f},await Y(_,$),_}function b_(f){return f?.claudeFast?.enabled===!0}async function J_(f,$=Q()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.claudeFast={..._.claudeFast??{},enabled:f},await Y(_,$),_}async function G_(f,$,_=Q()){let m=await V(_)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return m.cacheKeep={enabled:!0,startHour:f,endHour:$},await Y(m,_),m}async function I_(f,$=Q()){let _=await V($)??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};return _.cacheKeep={..._.cacheKeep??{},enabled:f},await Y(_,$),_}function B1(f){return f?.fallbackOn?.length?f.fallbackOn:D1}function W_(f,$){return B1($).includes(f)}function m0(f){let $=f?.quota?.minimumRemaining||{};return{five_hour:$.five_hour??$["5h"]??tf.five_hour,seven_day:$.seven_day??$["1w"]??tf.seven_day}}function i(f){return f?.quota?.enabled!==!1}function U1(f){return f?.refresh?.enabled!==!1}function Z1(f){return Math.floor(Math.random()*Math.max(0,f))}function X1(f){let $=f?.refresh?.refreshBeforeExpiryMinutes??H1;return Math.max(_0,$)*60000}function D0(f){return r0("sha256").update(f).digest("hex")}function z1(f){if(f instanceof w)return f.status===429||f.status>=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 A1(f){let $=D0(f.refreshToken),m=(f.previous?.tokenHash===$?f.previous.retryCount??0:0)+1,D=z1(f.error)?Math.min(F1,E1*2**Math.min(m-1,6)):M1;return{message:jf(f.error),checkedAt:f.now,nextRetryAt:f.now+D,retryCount:m,tokenHash:$}}function v(f,$,_){if(!f?.nextRetryAt||f.nextRetryAt<=_)return!1;if(!$)return!0;return f.tokenHash===D0($)}function sf(f,$){return`Claude OAuth refresh is backed off for ${Math.max(1,Math.ceil(((f.nextRetryAt??$)-$)/1000))}s after: ${f.message}`}function R(f){let $=f?.quota?.checkIntervalMinutes??C1;return Math.max(1,$)*60000}function H0(f){return f?.quota?.failClosedOnUnknownQuota??K1}function V1(f,$){if(!i($))return!0;let _=m0($);for(let m of["five_hour","seven_day"]){let D=f?.[m];if(!D)return!H0($);if(D.remainingPercent<_[m])return!1}return!0}function S_(f,$,_){if(!i($))return _+R($);let m=m0($),D=[];for(let H of["five_hour","seven_day"]){let E=f?.[H];if(!E)return _+R($);if(E.remainingPercent>=m[H])continue;let F=E.resetsAt?Date.parse(E.resetsAt):Number.NaN;if(!Number.isFinite(F)||F<=_)return _+R($);D.push(F)}if(!D.length)return _+R($);return Math.min(...D)+60000}function k(f,$,_){return!f.access||!f.expires||f.expires-_<=X1($)}function rf(f,$,_){if(!i($))return!1;let m=R($);return["five_hour","seven_day"].some((D)=>{let H=f.quota?.[D];return!H||_-H.checkedAt>=m})}function of(f){if(!Number.isFinite(f))return 0;if(f<0)return 0;if(f>100)return 100;return f}function af(f,$){if(typeof f?.utilization!=="number")return;let _=of(f.utilization);return{usedPercent:_,remainingPercent:of(100-_),resetsAt:f.resets_at,checkedAt:$}}async function ef(f){let _=await(f.fetchImpl??fetch)(m1,{method:"GET",headers:{Authorization:`Bearer ${f.accessToken}`,Accept:"application/json","Content-Type":"application/json","anthropic-beta":"oauth-2025-04-20","User-Agent":`claude-code/${Z}`}});if(!_.ok){let H=await _.text().catch(()=>"");throw Error(`Claude quota check failed: ${_.status} — ${H}`)}let m=f.now?.()??Date.now(),D=await _.json();return{five_hour:af(D.five_hour,m),seven_day:af(D.seven_day,m)}}function X(f,$){let _=f.accounts.findIndex((m)=>m.id===$.id);if(_>=0)f.accounts[_]=$}function jf(f){return f instanceof Error?f.message:String(f)}function E0(f,$,_){f.lastRefreshError=A1({error:$,now:_,refreshToken:f.refresh,previous:f.lastRefreshError})}function f0(f,$,_){if(f.lastQuotaRefreshError={message:jf($),checkedAt:_},$ instanceof w)E0(f,$,_)}class Y1{now;fetchImpl;configPath;refreshPromises=new Map;refreshTimer=null;quotaTimer=null;constructor(f={}){this.now=f.now??Date.now,this.fetchImpl=f.fetchImpl??fetch,this.configPath=f.configPath??Q()}async load(){return V(this.configPath)}async save(f){await Y(f,this.configPath)}startBackgroundRefresh(){let f=async()=>{await this.refreshDueAccounts(),await this.refreshQuotaForDueAccounts()};if(f().catch(()=>{}),!this.refreshTimer){if(this.refreshTimer=setInterval(()=>{f().catch(()=>{})},j1+Z1(N1)),"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 _=[],m=!1;for(let D of $.accounts){if(D.enabled===!1)continue;try{let H=D;if(k(H,$,this.now())){let E=H.lastRefreshError;if(E&&v(E,H.refresh,this.now()))throw Error(sf(E,this.now()));H=await this.refreshAccount(H,$),m=!0}if(rf(H,$,this.now()))H=await this.refreshAccountQuota(H,$),m=!0;if(this.accountPassesQuotaPolicy(H,$))_.push(H)}catch{if(!H0($))_.push(D)}}if(m)await this.save($);return _}async markUsed(f){let $=await this.load();if(!$)return;let _=$.accounts.find((m)=>m.id===f.id);if(!_)return;_.lastUsed=this.now(),await this.save($)}accountPassesQuotaPolicy(f,$){return V1(f.quota,$)}async refreshDueAccounts(){let f=await this.load();if(!f||!U1(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;if(!k(_,f,this.now()))continue;if(v(_.lastRefreshError,_.refresh,this.now())){A("[refresh] fallback oauth skipped backoff",{accountId:_.id,nextRetryAt:_.lastRefreshError?.nextRetryAt,retryCount:_.lastRefreshError?.retryCount});continue}try{A("[refresh] fallback oauth background due",{accountId:_.id,expiresInMs:_.expires?_.expires-this.now():void 0}),await this.refreshAccount(_,f),$=!0}catch(m){A("[refresh] fallback oauth background failed",{accountId:_.id,error:m instanceof Error?m.message:String(m)}),E0(_,m,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForDueAccounts(){let f=await this.load();if(!f||!i(f))return;let $=!1;for(let _ of f.accounts){if(_.enabled===!1)continue;let m=_;try{if(k(m,f,this.now())){if(v(m.lastRefreshError,m.refresh,this.now()))continue;m=await this.refreshAccount(m,f),$=!0}if(!rf(m,f,this.now()))continue;await this.refreshAccountQuota(m,f),$=!0}catch(D){f0(_,D,this.now()),X(f,_),$=!0}}if($)await this.save(f)}async refreshQuotaForAllAccounts(){let f=await this.load(),$=[];if(!f||!i(f))return{storage:f,errors:$};let _=!1;for(let m of f.accounts){if(m.enabled===!1)continue;let D=m;try{if(k(D,f,this.now())){let H=D.lastRefreshError;if(H&&v(H,D.refresh,this.now()))throw Error(sf(H,this.now()));D=await this.refreshAccount(D,f),_=!0}await this.refreshAccountQuota(D,f),_=!0}catch(H){f0(m,H,this.now()),X(f,m),_=!0,$.push({accountId:m.id,message:jf(H)})}}if(_)await this.save(f);return{storage:f,errors:$}}async refreshAccount(f,$,_={}){let m=this.refreshPromises.get(f.id);if(m){let E=await m;return X($,E),E}let D=this.refreshAccountNow(f,$,_).finally(()=>{this.refreshPromises.delete(f.id)});this.refreshPromises.set(f.id,D);let H=await D;return X($,H),H}async refreshAccountNow(f,$,_){let m=await this.load(),D=m?.accounts.find((M)=>M.id===f.id);if(D&&!_.force&&!k(D,m,this.now()))return X($,D),D;let H=D??f,E=H.refresh;A("[refresh] fallback oauth refresh request start",{accountId:H.id,force:_.force===!0,expiresInMs:H.expires?H.expires-this.now():void 0});let F=await nf({refreshToken:E,fetchImpl:this.fetchImpl,now:this.now});return H.access=F.access,H.refresh=F.refresh,H.expires=F.expires,H.lastRefreshedAt=F.expires-F.expiresIn*1000,H.lastRefreshError=void 0,X($,H),A("[refresh] fallback oauth refresh succeeded",{accountId:H.id,expiresInMs:H.expires?H.expires-this.now():void 0}),H}async refreshAccountQuota(f,$){let _=f;if(!_.access)throw Error(`Fallback account ${f.id} has no access token`);try{_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}catch(m){if(!(m instanceof Error?m.message:String(m)).includes("Claude quota check failed: 401"))throw m;if(_=await this.refreshAccount(f,$,{force:!0}),!_.access)throw m;_.quota=await ef({accessToken:_.access,fetchImpl:this.fetchImpl,now:this.now})}return _.lastQuotaRefreshError=void 0,X($,_),_}}var B_="claude-cache",F0="## Claude Cache Status",T1="## Claude Cache Enabled",O1="## Claude Cache Disabled",q1="## Claude Cache Usage",w1="Usage: `/claude-cache`, `/claude-cache on`, `/claude-cache off`, or `/claude-cache mode explicit|automatic|hybrid`.",g=!1,s=p;function U_(){return g}function Z_(){return s}function X_(f){g=f.enabled,s=f.mode}function h1(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 c(f){let $=f?.enabled??g,_=f?.mode??s;return[F0,"",`- 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(`
|
|
6
|
+
`)}function z_(f){let $=h1(f.argumentsText),_=f.enabled??g,m=f.mode??s;if($.type==="status")return c({enabled:_,mode:m});if($.type==="enable")return[T1,"",c({enabled:!0,mode:m})].join(`
|
|
7
|
+
`);if($.type==="disable")return[O1,"",c({enabled:!1,mode:m})].join(`
|
|
8
|
+
`);if($.type==="mode")return[F0,"",`Mode updated to \`${$.mode}\`.`,"",c({enabled:_,mode:$.mode})].join(`
|
|
9
|
+
`);return[q1,"",w1,"",c({enabled:_,mode:m})].join(`
|
|
10
|
+
`)}import{randomBytes as x1,randomUUID as C0}from"node:crypto";var P1=1000,u=new Map;function bf(f,$,_){if(!f.has($)&&f.size>=P1){let m=f.keys().next().value;if(m!==void 0)f.delete(m)}f.set($,_)}function K0(f){let $=f||"anonymous",_=u.get($);if(_)return _;let m={deviceId:x1(32).toString("hex"),sessionId:C0()};return bf(u,$,m),m}var Nf=new Map;async function k1(f,$){if(!f.startsWith("sk-ant-oat"))return null;let _=new AbortController,m=setTimeout(()=>_.abort(),5000);try{let D=new URL("https://api.anthropic.com/api/claude_cli/bootstrap");if(D.searchParams.set("entrypoint",hf),$)D.searchParams.set("model",$);let H=await fetch(D,{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/${Z}`},signal:_.signal});if(!H.ok)return null;let F=(await H.json().catch(()=>null))?.oauth_account?.account_uuid;return typeof F==="string"&&F?F:null}catch{return null}finally{clearTimeout(m)}}async function T_(f,$){let _=K0(f);if(!f.startsWith("sk-ant-oat"))return _;let m=Nf.get(f);if(!m)m=k1(f,$),Nf.set(f,m);let D=await m;if(!D)return Nf.delete(f),_;let H=`account:${D}`,E=u.get(H);if(E)return bf(u,f,E),E;return _.accountUuid=D,bf(u,H,_),_}function T(f){return f!=null&&typeof f==="object"&&!Array.isArray(f)}function R1(f){if(!f.accountUuid)return null;return JSON.stringify({device_id:f.deviceId,account_uuid:f.accountUuid,session_id:f.sessionId})}function O_(f,$){let _=R1($);if(!_){if(T(f.metadata))delete f.metadata.user_id;return!1}if(!T(f.metadata))f.metadata={};let m=f.metadata;if(T(m))m.user_id=_;return!0}var i1=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","advanced-tool-use-2025-11-20","context-1m-2025-08-07","effort-2025-11-24","extended-cache-ttl-2025-04-11","cache-diagnosis-2026-04-07"],c1=["oauth-2025-04-20","interleaved-thinking-2025-05-14","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"],M0=["oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","advisor-tool-2026-03-01","cache-diagnosis-2026-04-07"];function u1(f){return f.output_config?.format?.type==="json_schema"}function n1(f){return Array.isArray(f.tools)&&f.tools.length>0&&Array.isArray(f.system)&&T(f.thinking)&&T(f.context_management)&&T(f.output_config)&&T(f.diagnostics)}function l1(f,$=[]){let _=f?n1(f)?[...i1]:u1(f)?[...c1]:[...M0]:[...M0];if(f?.speed==="fast")_.push(wf);for(let m of $){let D=m.trim();if(D)_.push(D)}return[...new Set(_)].join(",")}function y1(){switch(process.platform){case"darwin":return"MacOS";case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return"Unknown"}}function p1(){switch(process.arch){case"arm64":return"arm64";case"x64":return"x64";case"ia32":return"x32";default:return process.arch}}function q_(f,$,_={}){let m=_.identity??K0($),H=[...(f.get("anthropic-beta")??"").split(",").map((E)=>E.trim()).filter(Boolean),..._.extraBetas??[]];return f.set("accept","application/json"),f.set("authorization",`Bearer ${$}`),f.set("content-type","application/json"),f.set("user-agent",kf),f.set("anthropic-beta",l1(_.body,H)),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",C0()),f.set("x-claude-code-session-id",m.sessionId),f.set("x-stainless-arch",p1()),f.set("x-stainless-lang","js"),f.set("x-stainless-os",y1()),f.set("x-stainless-package-version",xf),f.set("x-stainless-retry-count","0"),f.set("x-stainless-runtime","node"),f.set("x-stainless-runtime-version",Pf),f.set("x-stainless-timeout","600"),f.delete("x-api-key"),f}var v1=["model","messages","system","tools","tool_choice","metadata","max_tokens","temperature","thinking","context_management","output_config","diagnostics","stream","speed"];function j0(f){let $={};for(let _ of v1)if(Object.hasOwn(f,_))$[_]=f[_];for(let[_,m]of Object.entries(f))if(!Object.hasOwn($,_))$[_]=m;return $}import{createHash as t1}from"node:crypto";var d1=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 N0(){return function(f){let{exports:{mem:$,xxh32:_,xxh64:m,init32:D,update32:H,digest32:E,init64:F,update64:M,digest64:N}}=f,j=new Uint8Array($.buffer);function J(C,G){if($.buffer.byteLength<C+G){let Df=Math.ceil((C+G-$.buffer.byteLength)/65536);$.grow(Df),j=new Uint8Array($.buffer)}}function U(C,G,Df,i0,c0,u0){J(C);let x=new Uint8Array(C);return j.set(x),Df(0,G),x.set(j.subarray(0,C)),{update(q){let Hf;return j.set(x),typeof q=="string"?(J(3*q.length,C),Hf=L.encodeInto(q,j.subarray(C)).written):(J(q.byteLength,C),j.set(q,C),Hf=q.byteLength),i0(0,C,Hf),x.set(j.subarray(0,C)),this},digest:()=>(j.set(x),u0(c0(0)))}}function B(C){return C>>>0}let K=2n**64n-1n;function S(C){return C&K}let L=new TextEncoder,n=0,l=0n;function Yf(C,G=n){return J(3*C.length,0),B(_(0,L.encodeInto(C,j).written,G))}function Tf(C,G=l){return J(3*C.length,0),S(m(0,L.encodeInto(C,j).written,G))}return{h32:Yf,h32ToString:(C,G=n)=>Yf(C,G).toString(16).padStart(8,"0"),h32Raw:(C,G=n)=>(J(C.byteLength,0),j.set(C),B(_(0,C.byteLength,G))),create32:(C=n)=>U(48,C,D,H,E,B),h64:Tf,h64ToString:(C,G=l)=>Tf(C,G).toString(16).padStart(16,"0"),h64Raw:(C,G=l)=>(J(C.byteLength,0),j.set(C),S(m(0,C.byteLength,G))),create64:(C=l)=>U(88,C,F,M,N,S)}}((await WebAssembly.instantiate(d1)).instance)}var g1=0x6e52736ac806831en,r=/\bcch=([0-9a-f]{5});/,b0=null,Jf=null;async function s1(){if(Jf)return;b0??=(async()=>{Jf=(await N0()).h64Raw})(),await b0}async function r1(f){return await s1(),((Jf?.(f,g1)??0n)&0xfffffn).toString(16).padStart(5,"0")}async function J0(f){if(!r.test(f))return f;let $=await r1(new TextEncoder().encode(f));return f.replace(r,`cch=${$};`)}function o1(f=Z,$=new Date){if(f===Z)return Mf;let _=$.toISOString().slice(0,10);return t1("sha256").update(`${_}${f}`).digest("hex").slice(0,3)}function R_(f,$=Z,_,m=new Date){let D=o1($,m);return`x-anthropic-billing-header: cc_version=${$}.${D}; cc_entrypoint=${_}; cch=00000;`}var n_="claude-cachekeep",G0=3600000,Gf=300000,a1=60000,l_="extended-cache-ttl-2025-04-11",e1="## Claude Cache Keep Status",f$="## Claude Cache Keep Enabled",$$="## Claude Cache Keep Disabled",_$="## Claude Cache Keep Usage",m$="Usage: `/claude-cachekeep`, `/claude-cachekeep off`, or `/claude-cachekeep HH-HH`.";function a(f){return String(f).padStart(2,"0")}function D$(f){let $=f.trim();if(!$)return{type:"status"};if($==="off")return{type:"disable"};let _=/^(\d{1,2})-(\d{1,2})$/.exec($);if(!_)return{type:"usage"};let m=Number(_[1]),D=Number(_[2]);if(!Number.isInteger(m)||!Number.isInteger(D)||m<0||m>23||D<0||D>23||m===D)return{type:"usage"};return{type:"window",startHour:m,endHour:D}}function Wf(f){let $=Number(f?.cacheKeep?.startHour),_=Number(f?.cacheKeep?.endHour);if(!Number.isInteger($)||!Number.isInteger(_)||$<0||$>23||_<0||_>23||$===_)return;return{startHour:$,endHour:_}}function S0(f){return f?.cacheKeep?.enabled===!0&&!!Wf(f)}function H$(f){return S0(f)&&f?.claudeCache?.enabled===!0&&f.claudeCache.mode==="hybrid"}function I0(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 W0(f=new Date){return`${f.getFullYear()}-${a(f.getMonth()+1)}-${a(f.getDate())}`}function If(f,$=new Date){if(f&&f.startHour>f.endHour&&$.getHours()<f.endHour){let _=new Date($);return _.setDate(_.getDate()-1),W0(_)}return W0($)}function o(f){let $=f.window?`${a(f.window.startHour)}-${a(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(`
|
|
11
|
+
`)}function y_(f){let $=D$(f.argumentsText),_={enabled:f.enabled??!1,window:f.window,trackedSessions:f.trackedSessions,nextPrewarmAt:f.nextPrewarmAt,hybridActive:f.hybridActive};if($.type==="status")return[e1,"",o(_)].join(`
|
|
12
|
+
`);if($.type==="disable")return[$$,"",o({..._,enabled:!1})].join(`
|
|
13
|
+
`);if($.type==="window")return[f$,"",o({..._,enabled:!0,window:{startHour:$.startHour,endHour:$.endHour}})].join(`
|
|
14
|
+
`);return[_$,"",m$,"",o(_)].join(`
|
|
15
|
+
`)}function Sf(f){if(!f||typeof f!=="object")return!1;if(Array.isArray(f))return f.some(Sf);let $=f,_=$.cache_control;if(_&&typeof _==="object"&&_.type==="ephemeral")return!0;return Object.values($).some(Sf)}async function E$(f){let $;try{$=JSON.parse(f)}catch{return{ok:!1,reason:"body is not valid JSON"}}if(!Sf($))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 H=_.tool_choice;if(H?.type==="tool"||H?.type==="any")delete _.tool_choice;let E=JSON.stringify(j0(_)).replace(r,"cch=00000;");return{ok:!0,bodyText:await J0(E)}}class F${options;targets=new Map;timer=null;constructor(f){this.options=f}start(){if(this.timer)return;if(this.timer=setInterval(()=>{this.tick().catch((f)=>{this.options.log?.("[cachekeep] tick failed",{error:f instanceof Error?f.message:String(f)})})},a1),"unref"in this.timer)this.timer.unref()}stop(){if(this.timer)clearInterval(this.timer);this.timer=null}stats(f,$=this.options.now?.()??Date.now()){let _=If(f,new Date($)),m=[...this.targets.values()].filter((H)=>H.dayKey===_),D=m.length?Math.min(...m.map((H)=>H.cacheExpiresAt-Gf)):void 0;return{trackedSessions:m.length,nextPrewarmAt:D}}track(f){if(!f.sessionId)return{tracked:!1,reason:"missing session id"};if(!S0(f.storage))return{tracked:!1,reason:"cachekeep disabled"};if(f.cacheMode!=="hybrid")return{tracked:!1,reason:"cache mode is not hybrid"};let $=this.options.now?.()??Date.now(),_=Wf(f.storage);if(!I0(_,new Date($)))return{tracked:!1,reason:"outside configured window"};let m={};return f.headers.forEach((D,H)=>{m[H]=D}),this.targets.set(f.sessionId,{id:f.sessionId,url:f.url,headers:m,bodyText:f.bodyText,cacheExpiresAt:$+G0,dayKey:If(_,new Date($))}),this.start(),{tracked:!0}}async tick(){let f=await this.options.loadStorage(),$=Wf(f),_=this.options.now?.()??Date.now(),m=If($,new Date(_));for(let[H,E]of this.targets)if(E.dayKey!==m)this.targets.delete(H);if(!this.targets.size){this.stop();return}if(!H$(f))return;if(!I0($,new Date(_)))return;let D=_+Gf;for(let H of this.targets.values()){if(H.cacheExpiresAt>D)continue;await this.prewarm(H,_)}}async prewarm(f,$){let _=await E$(f.bodyText);if(!_.ok){this.options.log?.("[cachekeep] prewarm skipped",{session:f.id,reason:_.reason}),this.targets.delete(f.id);return}let m=this.options.fetchImpl??fetch,D={...f,bodyText:_.bodyText},H=this.options.prepareHeaders?await this.options.prepareHeaders(new Headers(f.headers),D):new Headers(f.headers);H.delete("content-length"),H.delete("transfer-encoding");let E=await m(f.url,{method:"POST",headers:H,body:_.bodyText});if(!E.ok){this.options.log?.("[cachekeep] prewarm failed",{session:f.id,status:E.status,body:await E.text().catch(()=>"")}),f.cacheExpiresAt=$+Gf+300000;return}await E.body?.cancel().catch(()=>{}),f.cacheExpiresAt=$+G0,this.options.log?.("[cachekeep] prewarm succeeded",{session:f.id})}}import{createHash as M$}from"node:crypto";import{mkdir as C$,writeFile as Lf}from"node:fs/promises";import{tmpdir as K$}from"node:os";import{join as B0}from"node:path";var r_="claude-dump",j$="## Claude Dump Status",N$="## Claude Dump Enabled",b$="## Claude Dump Disabled",J$="## Claude Dump Usage",G$="Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.",Bf=B0(K$(),"opencode-anthropic-auth-dumps"),ff=!1,L0=0;function o_(f){ff=f}function I$(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 e(f){let $=f?.enabled??ff;return[j$,"",`- Enabled: ${$?"enabled":"disabled"}`,`- Directory: ${Bf}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Captures: final rewritten Anthropic body plus redacted relay payload metadata","- Warning: body dumps may contain prompt/session content; turn this off after debugging"].join(`
|
|
16
|
+
`)}function a_(f){let $=I$(f.argumentsText),_=f.enabled??ff;if($.type==="status")return e({enabled:_});if($.type==="enable")return[N$,"",e({enabled:!0})].join(`
|
|
17
|
+
`);if($.type==="disable")return[b$,"",e({enabled:!1})].join(`
|
|
18
|
+
`);return[J$,"",G$,"",e({enabled:_})].join(`
|
|
19
|
+
`)}function Q0(f){return f.length<=16?f:`${f.slice(0,12)}…`}function U0(f){return M$("sha256").update(f).digest("hex")}function W$(f){return f.match(/\bcch=([0-9a-f]{5});/)?.[1]??null}function S$(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 m=f.length-1,D=$.length-1;while(m>=_&&D>=_&&f[m]===$[D])m-=1,D-=1;return{changed:!0,firstByte:_,lastPreviousByte:m,lastCurrentByte:D,changedPreviousBytes:m-_+1,changedCurrentBytes:D-_+1,previousBytes:f.length,currentBytes:$.length}}function L$(f){try{let $=JSON.parse(f);return $!=null&&typeof $==="object"&&!Array.isArray($)?$:null}catch($){return b(`dump body parse failed: ${$ instanceof Error?$.message:String($)}`),null}}function Qf(f){return U0(JSON.stringify(f))}function Q$(f){let $=L$(f);if(!$)return{parseable:!1};let _=Array.isArray($.messages)?$.messages:[],m=Array.isArray($.system)?$.system:[],D=_[0],H=_.slice(1);return{parseable:!0,model:typeof $.model==="string"?$.model:void 0,stream:$.stream,systemCount:m.length,messagesCount:_.length,systemHash:Qf(m),message0Hash:D===void 0?null:Qf(D),message0Bytes:D===void 0?0:JSON.stringify(D).length,messagesAfter0Hash:Qf(H),messagesAfter0Bytes:JSON.stringify(H).length,cch:W$(f)}}function Uf(f){if(Array.isArray(f))return f.map(Uf);if(f==null||typeof f!=="object")return f;let $={};for(let[_,m]of Object.entries(f)){let D=_.toLowerCase();if(D==="authorization"||D==="x-api-key"||D==="cookie"||D==="set-cookie"){$[_]="[redacted]";continue}$[_]=Uf(m)}return $}async function Z0(f){if(!ff)return;L0+=1;let $=`${new Date().toISOString().replace(/[:.]/g,"-")}-${String(L0).padStart(5,"0")}-${f.transport}-p${f.protocol}-${f.mode}`,_=B0(Bf,$);try{await C$(Bf,{recursive:!0});let m={id:$,createdAt:new Date().toISOString(),session:Q0(f.affinity),transport:f.transport,protocol:f.protocol,mode:f.mode,status:f.status,bodyBytes:f.bodyText.length,relayBytes:f.relayBytes,bodyHash:U0(f.bodyText),diff:S$(f.previousBodyText,f.bodyText),body:Q$(f.bodyText),files:{body:`${_}.body.json`,relay:`${_}.relay.json`,metadata:`${_}.meta.json`}};await Promise.all([Lf(`${_}.body.json`,f.bodyText,"utf8"),Lf(`${_}.relay.json`,`${JSON.stringify(Uf(f.payload),null,2)}
|
|
20
20
|
`,"utf8"),Lf(`${_}.meta.json`,`${JSON.stringify(m,null,2)}
|
|
21
|
-
`,"utf8")]),
|
|
22
|
-
`)}function
|
|
21
|
+
`,"utf8")]),b(`dumped request id=${$} session=${Q0(f.affinity)} body=${_}.body.json meta=${_}.meta.json`)}catch(m){b(`dump failed: ${m instanceof Error?m.message:String(m)}`)}}var fm="claude-fast";var _f=!1;function $m(){return _f}function _m(f){_f=f}function B$(f){let $=f.trim().split(/\s+/).filter(Boolean);if($.length===0)return{type:"status"};if($.length===1&&$[0]==="on")return{type:"enable"};if($.length===1&&$[0]==="off")return{type:"disable"};return{type:"usage"}}function $f(f){return["## Claude Fast Mode Status","",`- Enabled: ${f?.enabled??_f?"enabled":"disabled"}`,"- Persisted: ~/.config/opencode/anthropic-auth.json","- Scope: adds Anthropic fast mode to supported Opus requests","- Supported models: claude-opus-4-6 and claude-opus-4-7",'- 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(`
|
|
22
|
+
`)}function mm(f){let $=B$(f.argumentsText),_=f.enabled??_f;if($.type==="status")return $f({enabled:_});if($.type==="enable")return["## Claude Fast Mode Enabled","",$f({enabled:!0})].join(`
|
|
23
23
|
`);if($.type==="disable")return["## Claude Fast Mode Disabled","",$f({enabled:!1})].join(`
|
|
24
24
|
`);return["## Claude Fast Mode Usage","","Usage: `/claude-fast`, `/claude-fast on`, or `/claude-fast off`.","",$f({enabled:_})].join(`
|
|
25
|
-
`)}var
|
|
26
|
-
`);for(let m of f.accounts){let D=m.role==="main"?"main":"fallback",H=m.enabled===!1?" disabled":"";if(_.push(`### ${m.name} (${D}${H})`),m.lastRefreshedAt)_.push(` - Last token refresh: ${Zf(m.lastRefreshedAt,$)}`);if(m.error)_.push(` - Error: ${m.error}`);_.push(
|
|
27
|
-
`).trimEnd()}import{Buffer as
|
|
25
|
+
`)}var Hm="claude-quota",X0={five_hour:"5h",seven_day:"1w"};function z0(f){return`${Math.round(f*10)/10}%`}function Zf(f,$){let _=Math.max(0,$-f),m=Math.floor(_/60000);if(m<1)return"just now";if(m===1)return"1m ago";if(m<60)return`${m}m ago`;let D=Math.floor(m/60),H=m%60;if(H===0)return`${D}h ago`;return`${D}h ${H}m ago`}function U$(f,$){let _=Date.parse(f);if(!Number.isFinite(_))return f;let m=_-$;if(m<=0)return"now";let D=Math.max(1,Math.ceil(m/60000));if(D<60)return`in ${D}m`;let H=Math.floor(D/60),E=D%60;if(E===0)return`in ${H}h`;return`in ${H}h ${E}m`}function Z$(f,$){if(!f)return"";return`, resets ${U$(f,$)}`}function A0(f,$,_){if(!$)return` - ${X0[f]}: unknown`;return[` - ${X0[f]}: ${z0($.remainingPercent)} remaining`,` (${z0($.usedPercent)} used`,`${Z$($.resetsAt,_)}, checked ${Zf($.checkedAt,_)})`].join("")}function X$(f){return f.label?.trim()||f.id}function z$(f){return f.lastQuotaRefreshError?.message??f.lastRefreshError?.message}function Em(f,$=new Map){if(!f?.accounts.length)return[];return f.accounts.map((_)=>{let m=$.get(_.id)??z$(_);return{name:X$(_),role:"fallback",enabled:_.enabled!==!1,quota:_.quota,lastRefreshedAt:_.lastRefreshedAt,...m&&{error:m}}})}function Fm(f){let $=f.now??Date.now(),_=["## Claude Quotas",""];if(f.refreshedAt)_.push(`Refreshed: ${Zf(f.refreshedAt,$)}`,"");if(!f.accounts.length)return _.push("No Claude OAuth accounts found yet."),_.join(`
|
|
26
|
+
`);for(let m of f.accounts){let D=m.role==="main"?"main":"fallback",H=m.enabled===!1?" disabled":"";if(_.push(`### ${m.name} (${D}${H})`),m.lastRefreshedAt)_.push(` - Last token refresh: ${Zf(m.lastRefreshedAt,$)}`);if(m.error)_.push(` - Error: ${m.error}`);_.push(A0("five_hour",m.quota?.five_hour,$)),_.push(A0("seven_day",m.quota?.seven_day,$)),_.push("")}return _.join(`
|
|
27
|
+
`).trimEnd()}import{Buffer as x0}from"node:buffer";import{createHash as A$,randomBytes as V$}from"node:crypto";class zf extends Error{}var Vf=new Map,V0=new Map,Y0=new Set,T0=0;function Xf(){return T0+=1,`req_${Date.now().toString(36)}_${T0.toString(36)}`}function mf(f){if(Y0.has(f))return;Y0.add(f),b(f)}function bm(f){let $=f?.relay;if(!$)return mf("disabled: no relay config found"),null;if($.enabled!==!0)return mf("disabled: relay.enabled is not true"),null;if(!$.url?.trim()||!$.token?.trim())return mf("disabled: missing relay url or token"),null;let _=$.transport==="http"?"http":"websocket";return mf(`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 Jm(){return V$(32).toString("base64url")}function Y$(f){return`sha256:${A$("sha256").update(f).digest("hex")}`}function O0(f,$){let _=0,m=Math.min(f.length,$.length);while(_<m&&f.charCodeAt(_)===$.charCodeAt(_))_++;let D=f.length,H=$.length;while(D>_&&H>_&&f.charCodeAt(D-1)===$.charCodeAt(H-1))D--,H--;return{start:_,deleteCount:D-_,insert:$.slice(_,H)}}function T$(f){return f.deleteCount===0&&f.insert.length===0}function q0(f){let $=f.match(/\bcch=([0-9a-f]{5});/),_=$?.[1];if(!_||$.index==null)return null;let m=$.index+4;return{start:m,end:m+_.length,token:_}}function O$(f,$,_,m){return`${f.slice(0,$)}${m}${f.slice(_)}`}function P0(f,$){let _=q0(f),m=q0($);if(_&&m&&_.start===m.start&&_.end-_.start===m.end-m.start&&_.token!==m.token){let D={start:_.start,deleteCount:_.end-_.start,insert:m.token},H=O$(f,_.start,_.end,m.token),E=O0(H,$);return T$(E)?D:[D,E]}return O0(f,$)}function q$(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 w$(f){let $={};for(let[_,m]of f.entries()){if(_==="x-session-affinity"||_==="x-opencode-session")continue;$[_]=m}return $}async function w0(f,$){return fetch(f.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":f.token},body:JSON.stringify($)})}function W(f){return f.length>12?`${f.slice(0,12)}…`:f}function z(){return performance.now()}function O(f){return Math.round(f*10)/10}function h$(f){let{input:$,init:_,headers:m,bodyText:D,affinity:H,previous:E,nextHash:F}=f,M=$ instanceof Request?$.url:$.toString(),N={protocol:1,type:"request",affinity:H,upstream:{url:M,method:_?.method||($ instanceof Request?$.method:"POST"),headers:w$(m)},next_hash:F};return E?{...N,mode:"patch",base_hash:E.hash,revision:E.revision+1,patch:P0(E.body,D)}:{...N,mode:"full_sync",revision:1,body:D}}function Af(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 k0(f,$,_,m){Vf.set(f,{body:$,hash:_,revision:m})}async function h0(f){let{config:$,payload:_,bodyText:m,fallback:D}=f,H=_,E=await w0($,H);if(E.status===409&&H.mode==="patch")b(`state mismatch from relay session=${W(H.affinity)}; retrying full_sync`),await E.body?.cancel().catch(()=>{}),H=Af(H,m),E=await w0($,H);if(!E.ok&&E.status>=500&&$.fallbackToDirect)return b(`relay returned ${E.status}; falling back direct session=${W(H.affinity)}`),await E.body?.cancel().catch(()=>{}),{response:await D(),payload:H,transport:"http",protocol:H.protocol,usedRelay:!1};return{response:E,payload:H,transport:"http",protocol:H.protocol,usedRelay:!0}}function x$(f,$){let _=new URL(f);return _.protocol=_.protocol==="http:"?"ws:":"wss:",_.pathname="/ws",_.searchParams.set("token",$),_.toString()}function P$(f){return new Uint8Array(x0.from(f,"base64"))}function k$(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(x0.from(String(f)))}function R$(f){return JSON.parse(f)}class R0{config;affinity;socket;connecting;queue=Promise.resolve();pending;serverState;constructor(f,$){this.config=f,this.affinity=$}send(f,$,_=!1){let m=z(),D=this.queue.catch(()=>{}).then(()=>this.startQueued(f,$,m,_)),H=D.then(async({response:E,getPayload:F})=>({response:await E,payload:F(),transport:"websocket",protocol:2,usedRelay:!0}));return this.queue=D.then(({done:E})=>E.catch(()=>{}),()=>{}),H}async startQueued(f,$,_,m){let D=z();await this.ensureConnected();let H=z(),E=Vf.get(this.affinity),F=this.serverState?.hash,M={...f,protocol:2,id:Xf()};if(M.mode==="patch"&&(!F||F!==M.base_hash))M.mode="full_sync",M.revision=(this.serverState?.revision??0)+1,delete M.base_hash,delete M.patch,M.body=$;if(M.mode==="patch"&&E)M.patch=P0(E.body,$);b(`perf websocket send_start session=${W(this.affinity)} request=${M.id} mode=${M.mode} queueMs=${O(H-_)} connectMs=${O(H-D)} bodyBytes=${$.length} relayBytes=${JSON.stringify(M).length}`);let N=M,j=this.sendPayload(M,$,m);j.done.catch(()=>{});let J=j.done,U=j.response.catch((K)=>{if(!(K instanceof zf)||M.mode!=="patch")throw K;let S=Af(M,$);S.protocol=2,S.id=Xf(),S.revision=(this.serverState?.revision??0)+1,N=S;let L=this.sendPayload(S,$,m);return L.done.catch(()=>{}),J=L.done,L.response}),B=U.then(()=>J,()=>J.catch(()=>{}));return{response:U,done:B,getPayload:()=>N}}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 _=x$(this.config.url,this.config.token),m=new URL(_);m.searchParams.set("affinity",this.affinity);let D=new WebSocket(m.toString());this.socket=D,this.serverState=void 0;let H=setTimeout(()=>{D.close(),$(Error("relay websocket ready timed out"))},15000);D.addEventListener("message",(E)=>{try{if(typeof E.data!=="string"){this.handleBinaryChunk(E.data);return}let F=R$(E.data);if(F.type==="ready"){clearTimeout(H),this.serverState=F.state,f();return}this.handleMessage(F)}catch(F){clearTimeout(H),$(F),this.failPending(F),D.close()}}),D.addEventListener("error",()=>{clearTimeout(H);let E=Error("relay websocket error");$(E),this.failPending(E)}),D.addEventListener("close",()=>{if(clearTimeout(H),this.socket===D)this.socket=void 0,this.serverState=void 0,this.connecting=void 0;if(this.pending){if(this.pending.retryingBeforeResponse)return;if(this.retryPendingBeforeResponse(this.pending,"closed before response"))return;let E=Error("relay websocket closed before response");this.failPending(E)}})}).finally(()=>{this.connecting=void 0}),await this.connecting}sendPayload(f,$,_){let m=this.socket;if(!m||m.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");let D=z(),H,E,F=new Promise((N,j)=>{H=N,E=j});return{response:new Promise((N,j)=>{let J={payload:f,bodyText:$,resolve:N,reject:j,streamDone:!1,accepted:!1,responseStarted:!1,resolveDone:H,rejectDone:E,sentAt:D,optimisticResponse:_,retryAttempts:0,retryingBeforeResponse:!1};if(this.pending=J,this.resetPendingTimeout(J),m.send(JSON.stringify(f)),_)this.resolvePendingResponse(J,200,"OK",{"content-type":"text/event-stream","x-cortexkit-relay-optimistic":"true"})}),done:F}}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)return!1;if(f.streamDone)return!1;if(f.retryAttempts>=1)return!1;f.retryAttempts+=1,f.retryingBeforeResponse=!0,clearTimeout(f.timeout);let _=f.retryAttempts,m=f.payload.id;return b(`websocket ${$}; reconnecting and retrying full_sync session=${W(this.affinity)} request=${m} retry=${_}`),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 D=Af(f.payload,f.bodyText);D.protocol=2,D.id=Xf(),D.revision=(this.serverState?.revision??0)+1,f.payload=D,f.accepted=!1,f.acceptedAt=void 0,f.responseStartedAt=void 0,f.sentAt=z(),f.retryingBeforeResponse=!1;let H=this.socket;if(!H||H.readyState!==WebSocket.OPEN)throw Error("relay websocket is not connected");this.resetPendingTimeout(f),b(`perf websocket retry_send session=${W(this.affinity)} request=${D.id} previous=${m} mode=full_sync retry=${_} bodyBytes=${f.bodyText.length} relayBytes=${JSON.stringify(D).length}`),H.send(JSON.stringify(D))}catch(D){if(f.retryingBeforeResponse=!1,this.pending===f)this.failPending(D)}})(),!0}handleBinaryChunk(f){let $=this.pending;if(!$?.responseStarted)return;$.streamController?.enqueue(k$(f))}resolvePendingResponse(f,$,_,m){if(f.responseStarted)return;f.responseStarted=!0;let D=new ReadableStream({start:(H)=>{f.streamController=H},cancel:()=>{this.socket?.close()}});f.resolve(new Response(D,{status:$,statusText:_,headers:m}))}handleMessage(f){if(f.type==="keepalive"){if(this.pending)this.resetPendingTimeout(this.pending);return}let $=this.pending;if(!$)return;if("id"in f&&f.id&&f.id!==$.payload.id)return;if(f.type==="accepted"){let _=z();$.accepted=!0,$.acceptedAt=_,b(`perf websocket accepted session=${W(this.affinity)} request=${$.payload.id} sentMs=${O(_-$.sentAt)} mode=${$.payload.mode}`),this.serverState={hash:f.hash,revision:f.revision},k0(this.affinity,$.bodyText,f.hash,f.revision),this.resetPendingTimeout($);return}if(f.type==="response_start"){let _=z();if($.responseStartedAt=_,b(`perf websocket response_start session=${W(this.affinity)} request=${$.payload.id} sentMs=${O(_-$.sentAt)} upstreamMs=${$.acceptedAt==null?"unknown":O(_-$.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
|
|
28
28
|
data: ${JSON.stringify({type:"error",error:{type:"relay_upstream_error",message:`Relay upstream returned HTTP ${f.status}`}})}
|
|
29
29
|
|
|
30
|
-
`)),this.finishPending();return}if(f.type==="chunk"){$.streamController?.enqueue(
|
|
30
|
+
`)),this.finishPending();return}if(f.type==="chunk"){$.streamController?.enqueue(P$(f.base64));return}if(f.type==="done"){this.finishPending();return}if(f.type==="error"){if($.optimisticResponse&&$.responseStartedAt!=null){b(`websocket relay error during optimistic response session=${W(this.affinity)} request=${$.payload.id} status=${f.status} message=${f.message||"unknown"}`),$.streamController?.enqueue(new TextEncoder().encode(`event: error
|
|
31
31
|
data: ${JSON.stringify({type:"error",error:{type:"relay_error",message:f.message||"relay error"}})}
|
|
32
32
|
|
|
33
|
-
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse($,f.message||"state mismatch"))return;let _=f.status===409?new zf(f.message||"state mismatch"):Error(f.message||"relay websocket error");this.failPending(_)}}finishPending(){let f=this.pending;if(!f)return;let $=z();if(
|
|
33
|
+
`)),this.finishPending(),this.socket?.close();return}if(f.status===409&&this.retryPendingBeforeResponse($,f.message||"state mismatch"))return;let _=f.status===409?new zf(f.message||"state mismatch"):Error(f.message||"relay websocket error");this.failPending(_)}}finishPending(){let f=this.pending;if(!f)return;let $=z();if(b(`perf websocket done session=${W(this.affinity)} request=${f.payload.id} sentMs=${O($-f.sentAt)} streamMs=${f.responseStartedAt==null?"unknown":O($-f.responseStartedAt)}`),clearTimeout(f.timeout),!f.streamDone)f.streamDone=!0,f.streamController?.close();f.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 i$(f,$){let _=V0.get($);if(_)return _;let m=new R0(f,$);return V0.set($,m),m}async function Gm(f){let{config:$,input:_,init:m,headers:D,body:H,fallback:E,affinity:F,optimisticResponse:M}=f;if(!$||!q$(_,H))return E();let N=F||D.get("x-session-affinity")||D.get("x-opencode-session");if(!N)return b("skipping relay: missing x-session-affinity header"),E();let j=H,J=Y$(j),U=Vf.get(N),B=h$({input:_,init:m,headers:D,bodyText:j,affinity:N,previous:U,nextHash:J});try{let K;if($.transport==="websocket")try{K=await i$($,N).send(B,j,M===!0)}catch(L){b(`websocket relay failed session=${W(N)}; trying http relay: ${L instanceof Error?L.message:String(L)}`),K=await h0({config:$,payload:B,bodyText:j,fallback:E})}else K=await h0({config:$,payload:B,bodyText:j,fallback:E});if(!K.usedRelay)return K.response;if(K.transport==="http")k0(N,j,K.payload.next_hash,K.payload.revision);let S=JSON.stringify(K.payload).length;return b(`used relay transport=${K.transport} protocol=${K.protocol} mode=${K.payload.mode} status=${K.response.status} session=${W(N)} bodyBytes=${j.length} relayBytes=${S}`),await Z0({affinity:N,transport:K.transport,protocol:K.protocol,mode:K.payload.mode,status:K.response.status,bodyText:j,previousBodyText:U?.body,payload:K.payload,relayBytes:S}),K.response}catch(K){if(!$.fallbackToDirect)throw b(`relay failed session=${W(N)} and fallbackToDirect=false: ${K instanceof Error?K.message:String(K)}`),K;return b(`relay failed; falling back direct session=${W(N)}: ${K instanceof Error?K.message:String(K)}`),E()}}var Im=`
|
|
34
34
|
async function hashBody(body) {
|
|
35
35
|
const bytes = new TextEncoder().encode(body)
|
|
36
36
|
const digest = await crypto.subtle.digest('SHA-256', bytes)
|
|
@@ -315,4 +315,4 @@ export default {
|
|
|
315
315
|
}
|
|
316
316
|
},
|
|
317
317
|
}
|
|
318
|
-
`;export{
|
|
318
|
+
`;export{c$ as a,wf as b,u$ as c,n$ as d,l$ as e,y$ as f,hf as g,p$ as h,v$ as i,w as j,nf as k,r$ as l,o$ as m,A as n,Q as o,V as p,Y as q,F_ as r,M_ as s,Q1 as t,C_ as u,K_ as v,j_ as w,N_ as x,b_ as y,J_ as z,G_ as A,I_ as B,W_ as C,D0 as D,A1 as E,v as F,sf as G,R as H,V1 as I,S_ as J,ef as K,Y1 as L,B_ as M,U_ as N,Z_ as O,X_ as P,h1 as Q,z_ as R,J0 as S,R_ as T,T_ as U,O_ as V,q_ as W,j0 as X,n_ as Y,l_ as Z,D$ as _,Wf as $,S0 as aa,H$ as ba,y_ as ca,F$ as da,r_ as ea,o_ as fa,I$ as ga,a_ as ha,fm as ia,$m as ja,_m as ka,B$ as la,mm as ma,Hm as na,Em as oa,Fm as pa,bm as qa,Jm as ra,Gm as sa,Im as ta};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as S1,A as N1,B as _1,C as H0,D as K0,E as F1,F as Z0,G as M1,H as B1,I as q0,J as v1,K as S0,L as U1,M as $0,N as G0,O as D0,P as p,Q as x1,R as V0,S as s0,T as e0,U as E0,V as j1,W as J1,X as K1,Y as P0,Z as H1,_ as q1,a as p0,aa as E1,b as c0,ba as A1,c as s,ca as R1,d as e,da as C1,e as o0,ea as X0,f as d,fa as W0,g as t0,ga as f1,h as a0,ha as A0,i as r0,ia as Y0,j as F0,ja as T1,k as w1,ka as w0,l as M0,la as y1,m as B0,ma as R0,n as H,na as z0,oa as k1,p as E,pa as g1,q as v0,qa as m1,r as z1,s as j0,sa as b1,t as J0,u as I1,v as O1,w as U0,x as Q1,y as x0,z as L1}from"./index-z4vzznkk.js";import{randomUUID as Wj}from"node:crypto";function b(j){return typeof j==="object"&&j!==null}function s1(j){if(Array.isArray(j))return j;if(b(j)&&Array.isArray(j.data))return j.data;return[]}function e1(j){if(!b(j)||!b(j.info))return;return typeof j.info.role==="string"?j.info.role:void 0}function m0(j){if(!b(j)||!b(j.info))return null;let J=j.info,K=b(J.model)?J.model:void 0,Z=typeof J.agent==="string"?J.agent:void 0,D=typeof K?.providerID==="string"?K.providerID:typeof J.providerID==="string"?J.providerID:void 0,V=typeof K?.modelID==="string"?K.modelID:typeof J.modelID==="string"?J.modelID:void 0,M=typeof K?.variant==="string"?K.variant:typeof J.variant==="string"?J.variant:void 0;if(!Z&&(!D||!V)&&!M)return null;let A={};if(Z)A.agent=Z;if(D&&V)A.model={providerID:D,modelID:V};if(M)A.variant=M;return A}function b0(j,J){return{agent:j.agent??J.agent,model:j.model??J.model,variant:j.variant??J.variant}}function h0(j){return Boolean(j.agent&&j.model&&j.variant)}async function u0(j,J){if(!j||!J)return null;let K=j;if(typeof K.session?.messages!=="function")return null;let Z=[];try{Z=s1(await Promise.resolve(K.session.messages({path:{id:J},query:{limit:100}})))}catch{return null}if(Z.length===0)return null;let D={};for(let V=Z.length-1;V>=0;V--){if(e1(Z[V])!=="assistant")continue;let M=m0(Z[V]);if(!M)continue;if(D=b0(D,M),h0(D))return D}for(let V=Z.length-1;V>=0;V--){let M=m0(Z[V]);if(!M)continue;if(D=b0(D,M),h0(D))return D}if(!D.agent&&!D.model&&!D.variant)return null;return D}function d0(j){return`${p0}${j.charAt(0).toUpperCase()}${j.slice(1)}`}function jj(j){if(j==="StructuredOutput")return j;return`${j.charAt(0).toLowerCase()}${j.slice(1)}`}function Z1(j,J){let K=new Headers;if(j instanceof Request)j.headers.forEach((D,V)=>{K.set(V,D)});let Z=J?.headers;if(Z){if(Z instanceof Headers)Z.forEach((D,V)=>{K.set(V,D)});else if(Array.isArray(Z))for(let D of Z){let[V,M]=D;if(typeof M<"u")K.set(V,String(M))}else for(let[D,V]of Object.entries(Z))if(typeof V<"u")K.set(D,String(V))}return K}function N0(j){return j.set("anthropic-beta",s(j.get("anthropic-beta"),[c0])),j}function i(j,J,K={}){return J1(j,J,K)}function Jj(j){if(j.tools&&Array.isArray(j.tools))j.tools=j.tools.map((J)=>({...J,name:J.name?d0(J.name):J.name}));if(j.messages&&Array.isArray(j.messages))j.messages=j.messages.map((J)=>{if(J.content&&Array.isArray(J.content))J.content=J.content.map((K)=>{if(K.type==="tool_use"&&K.name)return{...K,name:d0(K.name)};return K});return J});return JSON.stringify(K1(j))}function Q0(j){return j.replace(/"name"\s*:\s*"mcp_([^"]+)"/g,(J,K)=>`"name": "${jj(K)}"`)}function i0(j,J=!1){if(J)return{ready:Q0(j),pending:""};let K=j.length,Z='"name"',D=Math.max(0,j.length-Z.length+1);for(let M=D;M<j.length;M++)if(Z.startsWith(j.slice(M))){K=Math.min(K,M);break}let V=j.lastIndexOf(Z);if(V!==-1){let M=j.slice(V);if(/^"name"\s*(?::\s*(?:"[^"]*)?)?$/.test(M))K=Math.min(K,V)}if(K<j.length)return{ready:Q0(j.slice(0,K)),pending:j.slice(K)};return{ready:Q0(j),pending:""}}function $1(){if(!process.env.ANTHROPIC_BASE_URL?.trim())return!1;let j=process.env.ANTHROPIC_INSECURE?.trim();return j==="1"||j==="true"}function Kj(){let j=process.env.ANTHROPIC_BASE_URL?.trim();if(!j)return null;try{let J=new URL(j);if(J.protocol!=="http:"&&J.protocol!=="https:"||J.username||J.password)return null;return J}catch{return null}}function G1(j){let J=null;try{if(typeof j==="string"||j instanceof URL)J=new URL(j.toString());else if(j instanceof Request)J=new URL(j.url)}catch{J=null}if(!J)return{input:j,url:null};let K=J.href,Z=Kj();if(Z)J.protocol=Z.protocol,J.host=Z.host;if(J.pathname==="/v1/messages"&&!J.searchParams.has("beta"))J.searchParams.set("beta","true");if(J.href===K)return{input:j,url:J};return{input:j instanceof Request?new Request(J.toString(),j):J,url:J}}function t(j){let Z=j.split(/\n\n+/).filter((D)=>{if(D.includes(o0))return!1;for(let V of a0)if(D.includes(V))return!1;return!0}).join(`
|
|
2
2
|
|
|
3
|
-
`);for(let G of r0)Z=Z.replace(G.match,G.replacement);return Z.trim()}function E(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Jj(j){let J={type:"text",text:u};if(j==null)return[J];if(typeof j==="string"){let Z=c(j);if(Z===u)return[J];return[J,{type:"text",text:Z}]}if(E(j)){let Z=typeof j.type==="string"?j.type:"text",G=typeof j.text==="string"?j.text:"";return[J,{...j,type:Z,text:c(G)}]}if(!Array.isArray(j))return[J];let K=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:c(Z)};if(E(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:c(Z.text)};return{type:"text",text:String(Z)}});if(K[0]?.text===u)return K;return[J,...K]}var D1={type:"ephemeral",ttl:"1h"};function Kj(j){if(E(j.cache_control))return j.cache_control;if(E(j.cacheControl))return j.cacheControl;return null}function t(j,J){if(!E(j))return!1;return delete j.cacheControl,j.cache_control=J?{...D1}:{type:"ephemeral"},!0}function i0(j){if(!E(j))return;delete j.cache_control,delete j.cacheControl}function Zj(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function o(j,J){if(!E(j))return;let K=Kj(j);if(!K||K.type!=="ephemeral")return;if(J)K.ttl="1h";else delete K.ttl}function l0(j,J){if(Array.isArray(j.system))for(let K of j.system)o(K,J);else o(j.system,J);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(o(K,J),E(K)&&Array.isArray(K.content))for(let Z of K.content)o(Z,J)}function $j(j,J){if(Array.isArray(j.system))for(let K of j.system)J(K);else J(j.system);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(J(K),E(K)&&Array.isArray(K.content))for(let Z of K.content)J(Z)}function V1(j){i0(j),$j(j,i0)}function Gj(j){V1(j),j.cache_control={...D1}}function Q0(j){if(!E(j))return!1;let J=Zj(j.content);if(!J?.length)return t(j,!0);j.content=J;let K=[...J].reverse().find((Z)=>E(Z)&&Z.type!=="thinking");return t(K??j,!0)}function Dj(j){if(V1(j),Array.isArray(j.system)){let K=j.system.findIndex((D)=>E(D)&&D.text===u),Z=j.system.slice(K>=0?K+1:0).filter(E),G=Z[Z.length-1];t(G,!0)}else t(j.system,!0);if(!Array.isArray(j.messages))return;Q0(j.messages[0]),Q0(j.messages[1]);let J=j.messages.length-2;if(J>1)Q0(j.messages[J])}function Vj(j,J){if(!J.enabled){l0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Gj(j);return}if(J.mode==="hybrid"){Dj(j);return}l0(j,!0),delete j.cacheControl}async function P1(j,J={}){try{let K=JSON.parse(j),Z=Array.isArray(K.messages)&&K.messages.some((G)=>G.role==="user")?e0(K.messages,void 0,t0):null;if(K.system=Jj(K.system),Z&&Array.isArray(K.system))K.system.unshift({type:"text",text:Z});if(Vj(K,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&r(K.model))K.speed="fast";else if(K.speed==="fast")delete K.speed;if(J.identity)j1(K,J.identity);return await s0(e1(K))}catch{return j}}function v0(j){if(!j.body)return j;let J=j.body.getReader(),K=new TextDecoder,Z=new TextEncoder,G="",D=new ReadableStream({async pull(F){let{done:A,value:T}=await J.read();if(A){let h=n0(`${G}${K.decode()}`,!0);if(h.ready)F.enqueue(Z.encode(h.ready));F.close();return}let z0=G+K.decode(T,{stream:!0}),b=n0(z0);if(G=b.pending,b.ready)F.enqueue(Z.encode(b.ready))}});return new Response(D,{status:j.status,statusText:j.statusText,headers:j.headers})}var Xj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",Wj=60000,m1=240,Yj=m1,wj=1,X1=!1;function w0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function M(){return performance.now()}function q(j){return Math.round(j*10)/10}function zj(){if(X1||!1||!w0())return;X1=!0;let j=100,J=250,K=M()+j;setInterval(()=>{let Z=M(),G=Z-K;if(K=Z+j,G<J)return;H("[perf] opencode event_loop_lag",{lagMs:q(G),thresholdMs:J})},j).unref?.()}function Ij(j){let J=M(),K={requestId:String(wj++),start:J,last:J,mark(Z,G){let D=M();if(w0())H("[perf] opencode request stage",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D},done(Z,G){let D=M();if(w0())H("[perf] opencode request done",{requestId:K.requestId,stage:Z,deltaMs:q(D-K.last),totalMs:q(D-K.start),...G});K.last=D}};if(w0())H("[perf] opencode request start",{requestId:K.requestId,...j});return K}async function n(j,J,K){let Z=j.client.session,G=await u0(j.client,J),D={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:K,ignored:!0}]}};if(G?.agent)D.body.agent=G.agent;if(G?.model)D.body.model=G.model;if(G?.variant)D.body.variant=G.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(D);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(D));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function i(){throw Error(Xj)}var Bj=async(j)=>{zj();let{client:J}=j,K=new M1;K.startBackgroundRefresh();let Z=null,G=new E1({loadStorage:()=>S(),prepareHeaders:async($,O)=>{if(!A)return $;let L=await A();if(L.type!=="oauth")return $;if(!L.access||L.expires&&L.expires<Date.now()){if(!Z)return $;L.access=await Z()}if(!L.access)return $;try{let Q=JSON.parse(O.bodyText),U=await S0(L.access,typeof Q.model==="string"?Q.model:void 0);if($.delete("anthropic-beta"),d($,L.access,{body:Q,identity:U}),$.set("anthropic-beta",a($.get("anthropic-beta"),[U1])),Q.speed==="fast")L0($)}catch{d($,L.access)}return $},log:H}),D=await S(),F=k1(D);l({enabled:s(D),mode:e(D)}),P0(B0(D)),W0(U0(D));let A=null,T=null;function z0($){let O=$?.refresh?.refreshBeforeExpiryMinutes??Yj;return Math.max(m1,O)*60000}function b($){return $?.refresh?.enabled!==!1}async function h($){if(!$)return;let O=await S(),L=O?.refresh?.mainLastRefreshError;if(!O?.refresh||!L?.tokenHash)return;let Q=j0($);if(L.tokenHash===Q)return;O.refresh.mainLastRefreshError=void 0,await M0(O),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:L.checkedAt,previousNextRetryAt:L.nextRetryAt,previousRetryCount:L.retryCount})}async function b1(){let $=[];if(A)try{let Q=await A();if(Q.type==="oauth"&&Q.access)$.push({name:"OpenCode anthropic",role:"main",quota:await q0({accessToken:Q.access})});else if(Q.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(Q){$.push({name:"OpenCode anthropic",role:"main",error:Q instanceof Error?Q.message:String(Q)})}let{storage:O,errors:L}=await K.refreshQuotaForAllAccounts();if($.push(...T1(O,new Map(L.map((Q)=>[Q.accountId,Q.message])))),!A)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return y1({accounts:$,refreshedAt:Date.now()})}async function h1($){let O=B1($);if(O.type==="enable"||O.type==="disable"){let f=O.type==="enable",y=await w1(f),k=e(y);return l({enabled:f,mode:k}),G0({argumentsText:$,enabled:f,mode:k})}if(O.type==="mode"){let f=await z1(O.mode),y=s(f);return l({enabled:y,mode:O.mode}),G0({argumentsText:$,enabled:y,mode:O.mode})}let L=await S(),Q=s(L),U=e(L);return l({enabled:Q,mode:U}),G0({argumentsText:$,enabled:Q,mode:U})}async function u1($){let O=x1($),L=await S();if(O.type==="window")L=await Q1(O.startHour,O.endHour);else if(O.type==="disable")L=await L1(!1);let Q=H1(L),U=G.stats(Q);return A1({argumentsText:$,enabled:q1(L),window:Q,hybridActive:S1(L),trackedSessions:U.trackedSessions,nextPrewarmAt:U.nextPrewarmAt})}async function d1($){let O=R1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await I1(U),P0(U),A0({argumentsText:$,enabled:U})}let L=await S(),Q=B0(L);return P0(Q),A0({argumentsText:$,enabled:Q})}async function n1($){let O=C1($);if(O.type==="enable"||O.type==="disable"){let U=O.type==="enable";return await O1(U),W0(U),E0({argumentsText:$,enabled:U})}let L=await S(),Q=U0(L);return W0(Q),E0({argumentsText:$,enabled:Q})}return{config:async($)=>{$.command={...$.command??{},[K0]:{template:K0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[D0]:{template:D0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[Y0]:{template:Y0,description:"Show current Claude OAuth quota usage for all accounts."},[V0]:{template:V0,description:"Show or toggle Anthropic request dump capture for debugging."},[X0]:{template:X0,description:"Show or toggle Anthropic fast mode for supported Opus models."}}},"command.execute.before":async($)=>{if($.command===K0)await n(j,$.sessionID,await h1($.arguments)),i();if($.command===D0)await n(j,$.sessionID,await u1($.arguments)),i();if($.command===Y0)await n(j,$.sessionID,await b1()),i();if($.command===V0)await n(j,$.sessionID,await d1($.arguments)),i();if($.command===X0)await n(j,$.sessionID,await n1($.arguments)),i()},auth:{provider:"anthropic",async loader($,O){if(A=$,(await $()).type==="oauth"){let i1=function(){if(T)clearInterval(T),T=null;let V=async()=>{try{let X=await S();if(!b(X))return;let Y=await $();if(Y.type!=="oauth")return;if(await h(Y.refresh),!Y.expires)return;let I=Y.expires-Date.now(),B=z0(X);if(I>B)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:I,refreshBeforeMs:B}),Y.refresh&&J0(X?.refresh?.mainLastRefreshError,Y.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:X?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:X?.refresh?.mainLastRefreshError?.retryCount});return}if(Y.refresh&&X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===j0(Y.refresh))return;await k(),H("[refresh] opencode main oauth refreshed in background",{expires:Y.expires})}catch(X){H("[refresh] opencode main oauth refresh failed",{message:X instanceof Error?X.message:String(X)})}};if(T=setInterval(()=>{V()},Wj),"unref"in T)T.unref()},R0=function(V,X){if(V instanceof Request&&V.body)return!1;return X==null||typeof X==="string"},l1=function(V){return V.has("x-parent-session-id")},f0=function(V){return V.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(V)},p1=function(V){return V?.quota?.enabled===!0},c1=function(V,X){let Y=Date.now();if(f||Y<y)return;f=y0(V,X).catch((I)=>{throw y=Y+_1(X),I}).finally(()=>{f=null}),f.catch(()=>{})};for(let V of Object.values(O.models))V.cost={input:0,output:0,cache:{read:0,write:0}};let Q=null,U=null,f=null,y=0;async function k(){if(!Q)Q=(async()=>{let Y=null,I=null,B=null;async function _(z){let v=await S()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};v.refresh=v.refresh??{},z(v),await M0(v)}for(let z=0;z<=2;z++){let v=null;try{if(z>0){let x=500*2**(z-1);await new Promise((I0)=>setTimeout(I0,x))}if(v=await $(),!v.refresh)throw Error("Token refresh failed: missing refresh token");let P=await S(),W=j0(v.refresh),w=P?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:z,expiresInMs:v.expires?v.expires-Date.now():void 0,hasBackoff:Boolean(w),backoffActive:w?J0(w,v.refresh,Date.now()):!1,retryCount:w?.retryCount,nextRetryAt:w?.nextRetryAt}),w&&J0(w,v.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:w.nextRetryAt,retryCount:w.retryCount}),Error(N1(w,Date.now()));if(P?.refresh?.mainRefreshLeaseUntil&&P.refresh.mainRefreshLeaseUntil>Date.now()&&P.refresh.mainRefreshLeaseTokenHash===W)throw H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:P.refresh.mainRefreshLeaseUntil}),Error("Claude OAuth refresh is already in progress");let N=await Y1({name:"opencode-main-oauth-refresh",ttlMs:120000});if(!N)throw H("[refresh] opencode main oauth refresh skipped file lock"),Error("Claude OAuth refresh is already in progress");B=N.release,Y=Pj(),I=W,await _((x)=>{x.refresh=x.refresh??{},x.refresh.mainRefreshLeaseId=Y??void 0,x.refresh.mainRefreshLeaseUntil=Date.now()+120000,x.refresh.mainRefreshLeaseTokenHash=W});let C=await S();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:z,leaseUntil:Date.now()+120000}),C?.refresh?.mainRefreshLeaseId!==Y||C.refresh.mainRefreshLeaseTokenHash!==W)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:z});let R=await W1({refreshToken:v.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:R.refresh,access:R.access,expires:R.expires}}),await _((x)=>{if(!x?.refresh)return;if(x.refresh.mainLastRefreshError=void 0,x.refresh.mainRefreshLeaseId===Y)x.refresh.mainRefreshLeaseId=void 0,x.refresh.mainRefreshLeaseUntil=void 0,x.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:z,expiresInMs:R.expires-Date.now()}),R.access}catch(P){let W=P instanceof Error&&(P.message.includes("fetch failed")||("code"in P)&&(P.code==="ECONNRESET"||P.code==="ECONNREFUSED"||P.code==="ETIMEDOUT"||P.code==="UND_ERR_CONNECT_TIMEOUT"));if(z<2&&(W||P instanceof N0&&P.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:z,error:P instanceof Error?P.message:String(P),transient:W});let w=v?.refresh;if(w&&P instanceof N0)await _((N)=>{N.refresh=N.refresh??{},N.refresh.mainLastRefreshError=v1({error:P,now:Date.now(),refreshToken:w,previous:N.refresh.mainLastRefreshError})});throw P}finally{if(Y)await _((P)=>{if(!P?.refresh)return;if(P.refresh.mainRefreshLeaseId===Y&&P.refresh.mainRefreshLeaseTokenHash===I)P.refresh.mainRefreshLeaseId=void 0,P.refresh.mainRefreshLeaseUntil=void 0,P.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await B?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{Q=null});return Q}Z=k,i1();async function C0(V,X){if(!V.body||V.status!==200)return X?.mark("inspect_stream_skip",{status:V.status}),{response:V,rateLimited:!1};if(V.headers.get("x-cortexkit-relay-optimistic")==="true")return X?.mark("inspect_stream_skip",{status:V.status,reason:"optimistic_relay"}),{response:V,rateLimited:!1};let Y=M(),I=V.body.getReader(),B=[],_=new TextDecoder,z="",v=0;while(!z.includes(`
|
|
3
|
+
`);for(let D of r0)Z=Z.replace(D.match,D.replacement);return Z.trim()}function R(j){return j!=null&&typeof j==="object"&&!Array.isArray(j)}function Zj(j){let J={type:"text",text:d};if(j==null)return[J];if(typeof j==="string"){let Z=t(j);if(Z===d)return[J];return[J,{type:"text",text:Z}]}if(R(j)){let Z=typeof j.type==="string"?j.type:"text",D=typeof j.text==="string"?j.text:"";return[J,{...j,type:Z,text:t(D)}]}if(!Array.isArray(j))return[J];let K=j.map((Z)=>{if(typeof Z==="string")return{type:"text",text:t(Z)};if(R(Z)&&Z.type==="text"&&typeof Z.text==="string")return{...Z,type:"text",text:t(Z.text)};return{type:"text",text:String(Z)}});if(K[0]?.text===d)return K;return[J,...K]}var D1={type:"ephemeral",ttl:"1h"};function $j(j){if(R(j.cache_control))return j.cache_control;if(R(j.cacheControl))return j.cacheControl;return null}function r(j,J){if(!R(j))return!1;return delete j.cacheControl,j.cache_control=J?{...D1}:{type:"ephemeral"},!0}function n0(j){if(!R(j))return;delete j.cache_control,delete j.cacheControl}function Gj(j){if(Array.isArray(j))return j;if(typeof j==="string")return[{type:"text",text:j}];return null}function a(j,J){if(!R(j))return;let K=$j(j);if(!K||K.type!=="ephemeral")return;if(J)K.ttl="1h";else delete K.ttl}function l0(j,J){if(Array.isArray(j.system))for(let K of j.system)a(K,J);else a(j.system,J);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(a(K,J),R(K)&&Array.isArray(K.content))for(let Z of K.content)a(Z,J)}function Dj(j,J){if(Array.isArray(j.system))for(let K of j.system)J(K);else J(j.system);if(!Array.isArray(j.messages))return;for(let K of j.messages)if(J(K),R(K)&&Array.isArray(K.content))for(let Z of K.content)J(Z)}function V1(j){n0(j),Dj(j,n0)}function Vj(j){V1(j),j.cache_control={...D1}}function L0(j){if(!R(j))return!1;let J=Gj(j.content);if(!J?.length)return r(j,!0);j.content=J;let K=[...J].reverse().find((Z)=>R(Z)&&Z.type!=="thinking");return r(K??j,!0)}function Pj(j){if(V1(j),Array.isArray(j.system)){let K=j.system.findIndex((V)=>R(V)&&V.text===d),Z=j.system.slice(K>=0?K+1:0).filter(R),D=Z[Z.length-1];r(D,!0)}else r(j.system,!0);if(!Array.isArray(j.messages))return;L0(j.messages[0]),L0(j.messages[1]);let J=j.messages.length-2;if(J>1)L0(j.messages[J])}function Xj(j,J){if(!J.enabled){l0(j,!1),delete j.cache_control,delete j.cacheControl;return}if(J.mode==="automatic"){Vj(j);return}if(J.mode==="hybrid"){Pj(j);return}l0(j,!0),delete j.cacheControl}async function P1(j,J={}){try{let K=JSON.parse(j),Z=Array.isArray(K.messages)&&K.messages.some((D)=>D.role==="user")?e0(K.messages,void 0,t0):null;if(K.system=Zj(K.system),Z&&Array.isArray(K.system))K.system.unshift({type:"text",text:Z});if(Xj(K,{enabled:J.cache1hEnabled??!1,mode:J.cache1hMode??"explicit"}),J.fastModeEnabled&&e(K.model))K.speed="fast";else if(K.speed==="fast")delete K.speed;if(J.identity)j1(K,J.identity);return await s0(Jj(K))}catch{return j}}function _0(j){if(!j.body)return j;let J=j.body.getReader(),K=new TextDecoder,Z=new TextEncoder,D="",V=new ReadableStream({async pull(M){let{done:A,value:y}=await J.read();if(A){let u=i0(`${D}${K.decode()}`,!0);if(u.ready)M.enqueue(Z.encode(u.ready));M.close();return}let O0=D+K.decode(y,{stream:!0}),h=i0(O0);if(D=h.pending,h.ready)M.enqueue(Z.encode(h.ready))}});return new Response(V,{status:j.status,statusText:j.statusText,headers:j.headers})}var Yj="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",wj=60000,zj=60000,Ij=5000,X1=200,h1=240,Oj=h1,Qj=1,W1=!1;function I0(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function B(){return performance.now()}function q(j){return Math.round(j*10)/10}function Y1(j){return Math.floor(Math.random()*Math.max(0,j))}function Lj(){if(W1||!1||!I0())return;W1=!0;let j=100,J=250,K=B()+j;setInterval(()=>{let Z=B(),D=Z-K;if(K=Z+j,D<J)return;H("[perf] opencode event_loop_lag",{lagMs:q(D),thresholdMs:J})},j).unref?.()}function Nj(j){let J=B(),K={requestId:String(Qj++),start:J,last:J,mark(Z,D){let V=B();if(I0())H("[perf] opencode request stage",{requestId:K.requestId,stage:Z,deltaMs:q(V-K.last),totalMs:q(V-K.start),...D});K.last=V},done(Z,D){let V=B();if(I0())H("[perf] opencode request done",{requestId:K.requestId,stage:Z,deltaMs:q(V-K.last),totalMs:q(V-K.start),...D});K.last=V}};if(I0())H("[perf] opencode request start",{requestId:K.requestId,...j});return K}async function n(j,J,K){let Z=j.client.session,D=await u0(j.client,J),V={path:{id:J},body:{noReply:!0,parts:[{type:"text",text:K,ignored:!0}]}};if(D?.agent)V.body.agent=D.agent;if(D?.model)V.body.model=D.model;if(D?.variant)V.body.variant=D.variant;if(typeof Z?.promptAsync==="function"){await Z.promptAsync(V);return}if(typeof Z?.prompt==="function"){await Promise.resolve(Z.prompt(V));return}throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function l(){throw Error(Yj)}var qj=async(j)=>{Lj();let{client:J}=j,K=new U1;K.startBackgroundRefresh();let Z=null,D=new C1({loadStorage:()=>E(),prepareHeaders:async($,I)=>{if(!A)return $;let L=await A();if(L.type!=="oauth")return $;if(!L.access||L.expires&&L.expires<Date.now()){if(!Z)return $;L.access=await Z()}if(!L.access)return $;try{let Q=JSON.parse(I.bodyText),U=await E0(L.access,typeof Q.model==="string"?Q.model:void 0);if($.delete("anthropic-beta"),i($,L.access,{body:Q,identity:U}),$.set("anthropic-beta",s($.get("anthropic-beta"),[H1])),Q.speed==="fast")N0($)}catch{i($,L.access)}return $},log:H}),V=await E(),M=m1(V);p({enabled:j0(V),mode:J0(V)}),W0(U0(V)),w0(x0(V));let A=null,y=null;function O0($){let I=$?.refresh?.refreshBeforeExpiryMinutes??Oj;return Math.max(h1,I)*60000}function h($){return $?.refresh?.enabled!==!1}async function u($){if(!$)return;let I=await E(),L=I?.refresh?.mainLastRefreshError;if(!I?.refresh||!L?.tokenHash)return;let Q=K0($);if(L.tokenHash===Q)return;I.refresh.mainLastRefreshError=void 0,await v0(I),H("[refresh] opencode main oauth cleared stale backoff after token rotation",{previousCheckedAt:L.checkedAt,previousNextRetryAt:L.nextRetryAt,previousRetryCount:L.retryCount})}async function u1(){let $=[];if(A)try{let Q=await A();if(Q.type==="oauth"&&Q.access)$.push({name:"OpenCode anthropic",role:"main",quota:await S0({accessToken:Q.access})});else if(Q.type==="oauth")$.push({name:"OpenCode anthropic",role:"main",error:"missing access token; send a request first or reconnect auth"})}catch(Q){$.push({name:"OpenCode anthropic",role:"main",error:Q instanceof Error?Q.message:String(Q)})}let{storage:I,errors:L}=await K.refreshQuotaForAllAccounts();if($.push(...k1(I,new Map(L.map((Q)=>[Q.accountId,Q.message])))),!A)$.unshift({name:"OpenCode anthropic",role:"main",error:"auth loader has not run yet; send a request first"});return g1({accounts:$,refreshedAt:Date.now()})}async function d1($){let I=x1($);if(I.type==="enable"||I.type==="disable"){let f=I.type==="enable",k=await I1(f),g=J0(k);return p({enabled:f,mode:g}),V0({argumentsText:$,enabled:f,mode:g})}if(I.type==="mode"){let f=await O1(I.mode),k=j0(f);return p({enabled:k,mode:I.mode}),V0({argumentsText:$,enabled:k,mode:I.mode})}let L=await E(),Q=j0(L),U=J0(L);return p({enabled:Q,mode:U}),V0({argumentsText:$,enabled:Q,mode:U})}async function i1($){let I=q1($),L=await E();if(I.type==="window")L=await N1(I.startHour,I.endHour);else if(I.type==="disable")L=await _1(!1);let Q=S1(L),U=D.stats(Q);return R1({argumentsText:$,enabled:E1(L),window:Q,hybridActive:A1(L),trackedSessions:U.trackedSessions,nextPrewarmAt:U.nextPrewarmAt})}async function n1($){let I=f1($);if(I.type==="enable"||I.type==="disable"){let U=I.type==="enable";return await Q1(U),W0(U),A0({argumentsText:$,enabled:U})}let L=await E(),Q=U0(L);return W0(Q),A0({argumentsText:$,enabled:Q})}async function l1($){let I=y1($);if(I.type==="enable"||I.type==="disable"){let U=I.type==="enable";return await L1(U),w0(U),R0({argumentsText:$,enabled:U})}let L=await E(),Q=x0(L);return w0(Q),R0({argumentsText:$,enabled:Q})}return{config:async($)=>{$.command={...$.command??{},[$0]:{template:$0,description:"Show or toggle 1-hour Anthropic ephemeral prompt cache TTL."},[P0]:{template:P0,description:"Keep hybrid Claude cache warm for recently used sessions during a local time window."},[z0]:{template:z0,description:"Show current Claude OAuth quota usage for all accounts."},[X0]:{template:X0,description:"Show or toggle Anthropic request dump capture for debugging."},[Y0]:{template:Y0,description:"Show or toggle Anthropic fast mode for supported Opus models."}}},"command.execute.before":async($)=>{if($.command===$0)await n(j,$.sessionID,await d1($.arguments)),l();if($.command===P0)await n(j,$.sessionID,await i1($.arguments)),l();if($.command===z0)await n(j,$.sessionID,await u1()),l();if($.command===X0)await n(j,$.sessionID,await n1($.arguments)),l();if($.command===Y0)await n(j,$.sessionID,await l1($.arguments)),l()},auth:{provider:"anthropic",async loader($,I){if(A=$,(await $()).type==="oauth"){let p1=function(){if(y)clearInterval(y),y=null;let P=async()=>{try{let X=await E();if(!h(X))return;let Y=await $();if(Y.type!=="oauth")return;if(await u(Y.refresh),!Y.expires)return;let z=Y.expires-Date.now(),v=O0(X);if(z>v)return;if(H("[refresh] opencode main oauth background due",{expiresInMs:z,refreshBeforeMs:v}),Y.refresh&&Z0(X?.refresh?.mainLastRefreshError,Y.refresh,Date.now())){H("[refresh] opencode main oauth background skipped backoff",{nextRetryAt:X?.refresh?.mainLastRefreshError?.nextRetryAt,retryCount:X?.refresh?.mainLastRefreshError?.retryCount});return}if(Y.refresh&&X?.refresh?.mainRefreshLeaseUntil&&X.refresh.mainRefreshLeaseUntil>Date.now()&&X.refresh.mainRefreshLeaseTokenHash===K0(Y.refresh))return;await g(),H("[refresh] opencode main oauth refreshed in background",{expires:Y.expires})}catch(X){H("[refresh] opencode main oauth refresh failed",{message:X instanceof Error?X.message:String(X)})}};if(y=setInterval(()=>{P()},wj+Y1(zj)),"unref"in y)y.unref()},C0=function(P,X){if(P instanceof Request&&P.body)return!1;return X==null||typeof X==="string"},c1=function(P){return P.has("x-parent-session-id")},f0=function(P){return P.includes("rate_limit_error")||/exceed your account'?s rate limit/i.test(P)},o1=function(P){return P?.quota?.enabled===!0},t1=function(P,X){let Y=Date.now();if(f||Y<k)return;f=k0(P,X).catch((z)=>{throw k=Y+B1(X),z}).finally(()=>{f=null}),f.catch(()=>{})};for(let P of Object.values(I.models))P.cost={input:0,output:0,cache:{read:0,write:0}};let Q=null,U=null,f=null,k=0;async function g(){if(!Q)Q=(async()=>{let Y=null,z=null,v=null;async function _(O){let w=await E()??{version:1,main:{type:"opencode",provider:"anthropic"},accounts:[]};w.refresh=w.refresh??{},O(w),await v0(w)}async function F(O){let w=Date.now()+Ij;while(Date.now()<w){await new Promise((W)=>setTimeout(W,X1+Y1(X1)));let G=await $();if(G.type!=="oauth"||!G.access)continue;if((G.access!==O.access||G.refresh!==O.refresh||(G.expires??0)>(O.expires??0)+60000)&&(!G.expires||G.expires>Date.now()))return H("[refresh] opencode main oauth joined concurrent refresh",{expiresInMs:G.expires?G.expires-Date.now():void 0}),G.access}return null}for(let O=0;O<=2;O++){let w=null;try{if(O>0){let x=500*2**(O-1);await new Promise((c)=>setTimeout(c,x))}if(w=await $(),!w.refresh)throw Error("Token refresh failed: missing refresh token");let G=await E(),N=K0(w.refresh),W=G?.refresh?.mainLastRefreshError;if(H("[refresh] opencode main oauth refresh check",{attempt:O,expiresInMs:w.expires?w.expires-Date.now():void 0,hasBackoff:Boolean(W),backoffActive:W?Z0(W,w.refresh,Date.now()):!1,retryCount:W?.retryCount,nextRetryAt:W?.nextRetryAt}),W&&Z0(W,w.refresh,Date.now()))throw H("[refresh] opencode main oauth refresh skipped backoff",{nextRetryAt:W.nextRetryAt,retryCount:W.retryCount}),Error(M1(W,Date.now()));if(G?.refresh?.mainRefreshLeaseUntil&&G.refresh.mainRefreshLeaseUntil>Date.now()&&G.refresh.mainRefreshLeaseTokenHash===N){H("[refresh] opencode main oauth refresh skipped lease",{leaseUntil:G.refresh.mainRefreshLeaseUntil});let x=await F(w);if(x)return x;throw Error("Claude OAuth refresh is already in progress")}let S=await z1({name:"opencode-main-oauth-refresh",ttlMs:120000});if(!S){H("[refresh] opencode main oauth refresh skipped file lock");let x=await F(w);if(x)return x;throw Error("Claude OAuth refresh is already in progress")}v=S.release,Y=Wj(),z=N,await _((x)=>{x.refresh=x.refresh??{},x.refresh.mainRefreshLeaseId=Y??void 0,x.refresh.mainRefreshLeaseUntil=Date.now()+120000,x.refresh.mainRefreshLeaseTokenHash=N});let T=await E();if(H("[refresh] opencode main oauth refresh lease acquired",{attempt:O,leaseUntil:Date.now()+120000}),T?.refresh?.mainRefreshLeaseId!==Y||T.refresh.mainRefreshLeaseTokenHash!==N)throw Error("Claude OAuth refresh is already in progress");H("[refresh] opencode main oauth refresh request start",{attempt:O});let C=await w1({refreshToken:w.refresh,maxRetries:0});return await J.auth.set({path:{id:"anthropic"},body:{type:"oauth",refresh:C.refresh,access:C.access,expires:C.expires}}),await _((x)=>{if(!x?.refresh)return;if(x.refresh.mainLastRefreshError=void 0,x.refresh.mainRefreshLeaseId===Y)x.refresh.mainRefreshLeaseId=void 0,x.refresh.mainRefreshLeaseUntil=void 0,x.refresh.mainRefreshLeaseTokenHash=void 0}),H("[refresh] opencode main oauth refresh succeeded",{attempt:O,expiresInMs:C.expires-Date.now()}),C.access}catch(G){let N=G instanceof Error&&(G.message.includes("fetch failed")||("code"in G)&&(G.code==="ECONNRESET"||G.code==="ECONNREFUSED"||G.code==="ETIMEDOUT"||G.code==="UND_ERR_CONNECT_TIMEOUT"));if(O<2&&(N||G instanceof F0&&G.status>=500))continue;H("[refresh] opencode main oauth refresh attempt failed",{attempt:O,error:G instanceof Error?G.message:String(G),transient:N});let W=w?.refresh;if(W&&G instanceof F0)await _((S)=>{S.refresh=S.refresh??{},S.refresh.mainLastRefreshError=F1({error:G,now:Date.now(),refreshToken:W,previous:S.refresh.mainLastRefreshError})});throw G}finally{if(Y)await _((G)=>{if(!G?.refresh)return;if(G.refresh.mainRefreshLeaseId===Y&&G.refresh.mainRefreshLeaseTokenHash===z)G.refresh.mainRefreshLeaseId=void 0,G.refresh.mainRefreshLeaseUntil=void 0,G.refresh.mainRefreshLeaseTokenHash=void 0}).catch(()=>{});await v?.().catch(()=>{})}}throw Error("Token refresh exhausted all retries")})().finally(()=>{Q=null});return Q}Z=g,p1();async function T0(P,X){if(!P.body||P.status!==200)return X?.mark("inspect_stream_skip",{status:P.status}),{response:P,rateLimited:!1};if(P.headers.get("x-cortexkit-relay-optimistic")==="true")return X?.mark("inspect_stream_skip",{status:P.status,reason:"optimistic_relay"}),{response:P,rateLimited:!1};let Y=B(),z=P.body.getReader(),v=[],_=new TextDecoder,F="",O=0;while(!F.includes(`
|
|
4
4
|
|
|
5
|
-
`)&&
|
|
5
|
+
`)&&F.length<65536){let{done:G,value:N}=await z.read();if(G)break;if(v.push(N),O+=N.byteLength,F+=_.decode(N,{stream:!0}),f0(F))break}if(f0(F))return await z.cancel().catch(()=>{}),X?.mark("inspect_stream_first_event",{ms:q(B()-Y),bytes:O,rateLimited:!0}),{response:P,rateLimited:!0};let w=new ReadableStream({start(G){for(let N of v)G.enqueue(N)},async pull(G){let{done:N,value:W}=await z.read();if(N){G.close();return}G.enqueue(W)},cancel(G){return z.cancel(G)}});return X?.mark("inspect_stream_first_event",{ms:q(B()-Y),bytes:O,rateLimited:!1}),{response:new Response(w,{status:P.status,statusText:P.statusText,headers:P.headers}),rateLimited:!1}}async function y0(P,X,Y,z,v="unknown"){let _=B(),F=Z1(P,X),O=F.get("x-session-affinity")||F.get("x-opencode-session"),w=c1(F);F.delete("x-parent-session-id"),F.delete("x-session-affinity"),F.delete("x-opencode-session");let G=X?.body,N;if(G&&typeof G==="string")try{let m=JSON.parse(G);if(typeof m.model==="string")N=m.model}catch{}let W=await E0(Y,N),S=typeof G==="string"?G.length:void 0;if(G&&typeof G==="string"){let m=B(),o=(()=>{if(!T1())return!1;try{return e(JSON.parse(G).model)}catch{return!1}})();G=await P1(G,{cache1hEnabled:!w&&G0(),cache1hMode:D0(),fastModeEnabled:o,identity:W});try{i(F,Y,{body:JSON.parse(G),identity:W})}catch{i(F,Y,{identity:W})}if(o)N0(F);z?.mark("rewrite_body",{route:v,ms:q(B()-m),originalBytes:S,rewrittenBytes:G.length,cacheEnabled:!w&&G0(),cacheMode:D0(),fastModeEnabled:o,subagent:w})}let T=G1(P);if(v==="main"&&typeof G==="string"&&!w&&G0()&&D0()==="hybrid"){let m=await E();if((await D.track({sessionId:O,url:T.url?.toString()??T.input.toString(),headers:F,bodyText:G,storage:m,cacheMode:"hybrid"})).tracked)z?.mark("cachekeep_track",{session:O})}let C=()=>fetch(T.input,{...X,body:G,headers:F,...$1()&&{tls:{rejectUnauthorized:!1}}}),x=B(),c=await b1({config:M,input:T.input,init:X,headers:F,body:G,fallback:C,affinity:O,optimisticResponse:M?.transport==="websocket"});return z?.mark("send_headers_received",{route:v,ms:q(B()-x),status:c.status,relayConfigured:M!=null,totalSendWithAccessMs:q(B()-_)}),c}async function k0(P,X){let Y=Date.now(),z=await S0({accessToken:P});return U={accessToken:P,refreshAfter:v1(z,X,Y),quota:z},z}async function a1(P,X){let Y=Date.now();if(U?.accessToken!==P)return await k0(P,X);if(Y>=U.refreshAfter)t1(P,X);return U.quota}async function g0(P,X,Y,z,v,_){if(!Y.length)return v??null;await v?.body?.cancel().catch(()=>{});let F=v??null;for(let[O,w]of Y.entries()){let G=w.access;if(!G)continue;let N=await y0(P,X,G,_,`fallback_${O}`);F=N;let W=H0(N.status,z);if(!W){let S=await T0(N,_);N=S.response,F=N,W=S.rateLimited}if(!W)return await K.markUsed(w),N;if(O<Y.length-1)await N.body?.cancel().catch(()=>{})}return F}async function r1(P,X,Y,z,v,_){if(!C0(P,X?.body))return Y;let F=B(),O=_??await E();v?.mark("fallback_load_storage",{ms:q(B()-F),cached:!!_});let w=Y,G=H0(w.status,O);if(!G){let W=await T0(w,v);w=W.response,G=W.rateLimited}if(!G)return w;let N=z;if(!N){let W=B();N=await K.getUsableFallbackAccounts(),v?.mark("fallback_get_accounts",{ms:q(B()-W),accounts:N.length})}return await g0(P,X,N,O,w,v)??w}return{apiKey:"",async fetch(P,X){let Y=X?.body,z=Nj({bodyBytes:typeof Y==="string"?Y.length:void 0,relayConfigured:M!=null}),v=B(),_=await $();if(z.mark("get_auth",{ms:q(B()-v),authType:_.type,hasAccess:Boolean(_.access)}),_.type!=="oauth"){let W=await fetch(P,X);return z.done("non_oauth_passthrough",{status:W.status}),W}if(await u(_.refresh),!_.access||!_.expires||_.expires<Date.now()){H("[refresh] opencode main oauth refresh required for request",{hasAccess:Boolean(_.access),expiresInMs:_.expires?_.expires-Date.now():void 0});let W=B();_.access=await g(),z.mark("refresh_main_access",{ms:q(B()-W)})}if(!_.access)throw z.done("missing_access_error"),Error("OAuth access token is missing after refresh");let F=B(),O=await E();z.mark("load_storage",{ms:q(B()-F)});let w;if(C0(P,X?.body)&&o1(O))try{let W=B(),S=await a1(_.access,O);if(z.mark("main_quota_for_routing",{ms:q(B()-W),passes:q0(S,O)}),!q0(S,O)){let T=B();w=await K.getUsableFallbackAccounts(),z.mark("preselect_fallback_accounts",{ms:q(B()-T),accounts:w.length});let C=await g0(P,X,w,O,void 0,z);if(C)return z.done("return_preselected_fallback",{status:C.status}),_0(C)}}catch(W){z.mark("main_quota_for_routing_error",{error:W instanceof Error?W.message:String(W)})}let G=await y0(P,X,_.access,z,"main"),N=await r1(P,X,G,w,z,O);return z.done("return_response",{status:N.status}),_0(N)}}}return{}},methods:[{label:"Claude Pro/Max",type:"oauth",authorize:async()=>{let $=await M0("max");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(I)=>{return B0(I,$.verifier,$.redirectUri,$.state)}}}},{label:"Create an API Key",type:"oauth",authorize:async()=>{let $=await M0("console");return{url:$.url,instructions:"Paste the authorization code here:",method:"code",callback:async(I)=>{let L=await B0(I,$.verifier,$.redirectUri,$.state);if(L.type==="failed")return L;return{type:"success",key:(await fetch("https://api.anthropic.com/api/oauth/claude_cli/create_api_key",{method:"POST",headers:{"Content-Type":"application/json",authorization:`Bearer ${L.access}`}}).then((U)=>U.json())).raw_key}}}}},{provider:"anthropic",label:"Manually enter API Key",type:"api"}]}}};export{qj as AnthropicAuthPlugin};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "1.2.
|
|
3
|
+
"version": "1.2.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -41,6 +41,6 @@
|
|
|
41
41
|
"@opencode-ai/plugin": "*"
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@cortexkit/anthropic-auth-core": "1.2.
|
|
44
|
+
"@cortexkit/anthropic-auth-core": "1.2.2"
|
|
45
45
|
}
|
|
46
46
|
}
|