@cortexkit/opencode-anthropic-auth 2.4.7 → 2.4.8
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 +43 -43
- package/dist/tui/claude-sidebar.d.ts +1 -1
- package/dist/v2/server.js +5 -5
- package/package.json +2 -2
- package/src/tui/claude-sidebar.tsx +321 -274
- package/src/tui/quota-sidebar.d.ts +11 -0
- package/src/tui/quota-sidebar.js +879 -0
- package/src/tui-compiled/quota-sidebar.js +879 -0
- package/src/tui-compiled/tui/claude-sidebar.tsx +431 -539
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** @jsxImportSource @opentui/solid */
|
|
2
|
-
import {
|
|
2
|
+
import type { RGBA } from '@opentui/core';
|
|
3
3
|
import { type JSX } from 'solid-js';
|
|
4
4
|
import { type AccountQuota, type SidebarState } from '../sidebar-state.js';
|
|
5
5
|
import { type AnthropicAuthTuiPrefs, type AppearancePrefs } from '../tui-preferences.js';
|
package/dist/v2/server.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import{a as e2,b as f1,c as l1,d as m0,e as l0,f as Y0,g as y2,h as d0,i as u0,j as v1,k as g1,l as h1,m as p0,n as d1,o as c0,p as i0,q as o0,r as n0,s as P0,t as o1}from"../index-61yvrgwy.js";import"../index-2ra790fx.js";import"../index-jc8zwxvw.js";import{y as c1}from"../index-eq1kbq5z.js";import{A as Q0,C as p1,z as V0}from"../index-qqs4ec18.js";import"../index-a0jxsmac.js";import{M as G0}from"../index-d4e8qj37.js";import"../index-crx0xd9j.js";import"../index-n8xr16kr.js";import{acquireNativeAccountRuntime as V$,assertUnmanagedInjectedPaths as Q$,authorize as W$,createNativeUi as U$,decideOpenCodeStateLayoutOnce as B$,disconnectNativeVaultForHost as z$,exchange as K$,getPersistedLogLevel as M$,isDumpPersistentlyEnabled as H$,logger as S0,openCodeHolderKind as N$,readNativeEnrollmentMode as _$,registerNativePoolHolder as L$,resolveNativePoolPaths as F$,setDumpEnabled as P$,setLogLevel as T$,stateLayoutIoFailure as C$,unmovedRegistrationPolicy as O$}from"@cortexkit/anthropic-auth-core";class f2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function R2($){return`common-auth-placeholder.${$}`}function R0($){let Z=R2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function M0($,Z){if($?.type!=="oauth")return!1;let Q=Z===void 0?void 0:R2(Z),V=(M)=>Q===void 0?M.startsWith("common-auth-placeholder."):M===Q;return V($.access)&&V($.refresh)}var b0="No browser sign-in: this connects the plugin to the accounts in its vault.";async function H0($,Z){let Q=Z.now??Date.now,{integrationID:V}=Z,M=(T)=>R0({integrationID:V,methodID:T,now:Q()}),C=async(T,H)=>{return await Z.onLogin(T,{integrationID:V,methodID:H}),M(H)},q=(T)=>async(H)=>{let G=T.method.id,z=await T.authorize(H),K={url:z.url,instructions:z.instructions,...z.expiresAt===void 0?{}:{expiresAt:z.expiresAt}};if(z.mode==="auto")return{...K,mode:"auto",callback:z.callback.then((L)=>C(L,G))};let _=z.callback;return{...K,mode:"code",callback:async(L)=>C(await _(L),G)}};return $.integration.transform((T)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let K of Z.methods)T.method.update({integrationID:V,method:K.method,authorize:q(K),refresh:async(_)=>{if(!M0(_,V))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return M(_.methodID)},...H});let G=Z.vault;if(G===void 0)return;let z=G.method.id;T.method.update({integrationID:V,method:G.method,authorize:async()=>({url:"",instructions:G.instructions??b0,mode:"auto",callback:Promise.resolve().then(()=>G.activate({integrationID:V,methodID:z})).then(()=>M(z))}),refresh:async(K)=>{if(!M0(K,V)||K.methodID!==z)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return M(z)},...H})})}function n1($){let Z=[],Q;for(let V of $.split(/\r?\n/))if(V.startsWith("data:"))Z.push(V.slice(5).replace(/^ /,""));else if(V.startsWith("event:"))Q=V.slice(6).trim();if(Z.length===0)return;return Q===void 0?{data:Z.join(`
|
|
2
2
|
`)}:{event:Q,data:Z.join(`
|
|
3
|
-
`)}}function N0($,Z){let Q=new TextDecoder,V="",M=(q)=>{let T=n1(q);if(!T)return;try{$(T)}catch(H){Z(H)}},C=()=>{for(;;){let q=/\r?\n\r?\n/.exec(V);if(!q)return;let T=V.slice(0,q.index);V=V.slice(q.index+q[0].length),M(T)}};return new TransformStream({transform(q,T){T.enqueue(q),V+=Q.decode(q,{stream:!0}),C()},flush(){if(V+=Q.decode(),C(),V.trim()!=="")M(V);V=""}})}var A0=512,w0=1200000,v2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),x2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function r1($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function s1($,Z){let Q=$.getReader();return new ReadableStream({async pull(V){let M;try{M=await Q.read()}catch(C){Z({reason:"failed",message:C instanceof Error?C.message:String(C)}),V.error(C);return}if(M.done)Z(),V.close();else V.enqueue(M.value)},async cancel(V){Z({reason:"cancelled",...V===void 0?{}:{message:String(V)}}),await Q.cancel(V)}})}function s2($,Z){for(let[Q,V]of Object.entries(Z)){let M=Q.toLowerCase();for(let C of Object.keys($))if(C.toLowerCase()===M)delete $[C];if(V!==null)$[Q]=V}}function a1($,Z){for(let[Q,V]of Object.entries(Z))if(V===null)$.delete(Q);else $.set(Q,V)}async function _0($,Z,Q={}){let{providerID:V}=Z,M=Q.gateOnPlaceholder,C=(j)=>M===void 0||M.credential(j)===R2(V),q=Q.logger,T=Math.max(1,Q.maxRecords??A0),H=[...Q.hostCredentials??[R2(V)],...M?[R2(V)]:[]].filter((j)=>j!==""),G=new Map,z=new WeakMap,K=new Map,_=0,L=new Set,S=new Map,O=new Map,b=(j)=>{let W=O.get(j);return W?.ownedSeen===!0&&W.foreignSeen},w=(j,W)=>{S.set(j,W);let F=O.get(j)??{ownedSeen:!1,foreignSeen:!1};if(W)F.ownedSeen=!0;else F.foreignSeen=!0;O.set(j,F)},f=(j,W)=>{let F=M?.refuseMisplaced,k=F?[...W].filter(([,p])=>p.includes(R2(V))):[],P=C(W)&&(!F||k.length>0);if(F){if(k.length>0&&(k.length!==1||!P))throw w(j.sessionID,!1),new f2({kind:"placement-refused",providerID:V,sessionID:j.sessionID,requestKind:j.kind,message:F(k[0]?.[0]??"")})}return w(j.sessionID,P),P},y=!1,n=!1,e=new Map,V2=0,j2=!1,$2=new Map,c=(j,W)=>{try{q?.warn(j,W)}catch{}},l=(j)=>j instanceof Error?j.message:String(j),s=new Map,Z2=(j,W)=>{let F=(s.get(j)??Promise.resolve()).then(W),k=F.then(()=>{},()=>{});return s.set(j,k),k.then(()=>{if(s.get(j)===k)s.delete(j)}),F},J=(j,W)=>{let F=s.get(j);return F?F.then(()=>J(j,W)):W()},X=async(j)=>{try{await Z.dropChoice?.({...j.input,accountId:j.accountId})}catch(W){c("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},B=async(j)=>{try{await Z.dropSameAccountRetry?.({...j.input,accountId:j.accountId})}catch(W){c("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},R=async(j)=>{if(j.next)await X(j.next);if(j.sameAccount)await B(j.sameAccount)},I=(j)=>{let W=K.get(j);if(K.delete(j),W)Z2(W.sessionID,()=>R(W))},A=async(j,W)=>{let F=e.get(j);if(!F||F.size===0)return;await Promise.all([...F].map(async(k)=>{try{await k(W)}catch(P){c("opencode2 auth listener threw; the request is unaffected",{event:j,error:l(P)})}}))},h=async(j,W)=>{try{await Z.onAttemptEnd?.(j,W)}catch(F){c("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:j.attemptId,error:l(F)})}},r=(j,W)=>{if(j.ended||!j.attempt)return;let F={...j.status===void 0?{}:{status:j.status},outputStarted:j.outputStarted,...j.limit?{limit:j.limit.signal}:{},...W?{error:W}:{}};if(W)j.endError=W;j.ended=h(j.attempt,F)},m=(j,W)=>r(j,{reason:"abandoned",message:W}),a=(j)=>[...G.values()].filter((W)=>W.key===j),W2=(j)=>a(j).at(-1),d=(j)=>{if(G.delete(j.id),K.get(j.key)?.attemptId===j.id||!a(j.key).length)I(j.key)},J2=(j)=>{G.set(j.id,j);while(G.size>T){let W=G.values().next().value;if(W===void 0)break;m(W,"dropped to keep the record bound"),d(W)}},u=(j)=>j.accountId===void 0?void 0:{...j.scope,accountId:j.accountId},Y=(j,W)=>new f2({kind:"no-account",providerID:V,sessionID:j.sessionID,requestKind:j.kind,...W===void 0?{}:{message:W}}),N=(j)=>{$2.get(j)?.clear(),$2.delete(j)},U=async(j,W)=>{let F=()=>Y(j,`${V} ${j.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw F();let k=$2.get(j.sessionID);if(!k)k=new Set,$2.set(j.sessionID,k);let P={};k.add(P);let p=()=>{if(!k.has(P))throw F()};try{return await W(p)}finally{if(k.delete(P),k.size===0&&$2.get(j.sessionID)===k)$2.delete(j.sessionID)}},E=(j,W)=>{for(let[F,k]of W)if(H.some((P)=>k.includes(P)))throw new f2({kind:"host-credential-on-wire",providerID:V,sessionID:j.sessionID,requestKind:j.kind,message:`${V} ${j.kind} request still carries the host's placeholder credential in ${F}; the adapter's account headers must replace it`})},x=(j)=>{for(let W of a(j))if(W.ended||!W.attempt)d(W);else if(W.transport==="ws"||W.judged)m(W,"a newer attempt of its session and kind began"),d(W)},v=async(j,W,F,k)=>{let P=D2(j.sessionID,j.kind),{input:p,accountId:D,sameAccountRetry:i}=await J(j.sessionID,async()=>{F();let M2=K.get(P);K.delete(P);let L2=M2?.accountId??W2(P)?.accountId;x(P);let H2=M2?.next,P2=M2?.sameAccount,U2=P2!==void 0&&P2.input.modelID===j.modelID&&P2.input.agent===j.agent,O2=H2!==void 0&&H2.input.modelID===j.modelID&&H2.input.agent===j.agent,E2={...j,phase:"request",...L2===void 0?{}:{previousAccountId:L2},...M2?.rerouteFrom?{rerouteFrom:M2.rerouteFrom}:{}};if(H2&&!O2)await Z2(j.sessionID,()=>X(H2)),F();if(P2&&!U2)await Z2(j.sessionID,()=>B(P2)),F();let q2=U2?P2.accountId:O2?H2.accountId:await Z.chooseAccount(E2);return{input:E2,accountId:typeof q2==="string"?q2:void 0,sameAccountRetry:U2}});F();let Q2={},C2;if(D!==void 0){let M2=await Z.accountHeaders({...j,accountId:D});if(F(),r1(M2))Q2=M2.headers,C2=M2.attempt;else Q2=M2}let n2=`attempt-${++V2}`,w2={id:n2,key:P,scope:j,accountId:D,headers:Q2,attempt:D===void 0?void 0:{...j,accountId:D,attemptId:n2,transport:k,data:C2},...k===void 0?{}:{transport:k},outputStarted:!1,sameAccountRetry:i};if(J2(w2),w2.attempt)A("select",{...j,accountId:w2.attempt.accountId,hook:W,...p.previousAccountId===void 0?{}:{previousAccountId:p.previousAccountId},...p.rerouteFrom===void 0?{}:{rerouteFrom:p.rerouteFrom},handle:w2.attempt});return w2},g=async(j,W,F,k,P)=>{let p=D2(j.sessionID,j.kind),D=k===void 0?void 0:G.get(k);if(D?.key!==p)D=void 0;if(!D){if(D=W2(p),a(p).filter((Q2)=>Q2.transport===void 0&&!Q2.ended).length>1&&!n)n=!0,c("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:j.sessionID,kind:j.kind})}if(!D||D.transport!==void 0||D.ended)D=await v(j,W,P,F);else if(D.transport=F,D.attempt)D.attempt.transport=F;if(F==="ws"){for(let i of a(p))if(i!==D&&i.transport==="ws")m(i,"a newer attempt of its session and kind went out over WebSocket")}return D},X2=async(j,W)=>{try{return await W()}catch(F){throw r(j,{reason:"failed",message:l(F)}),F}},o=(j,W)=>{let F=a(D2(j,W)).filter((k)=>k.transport==="ws").at(-1);return F?.attempt!==void 0&&!F.ended?F:void 0},B2=(j,W,F)=>{let k=u(j);if(!k||!j.attempt||j.limit)return;j.limit={signal:W,delivered:A("limit",{...k,via:F,limit:W,outputStarted:j.outputStarted,handle:j.attempt})}},N2=(j,W,F,k)=>{let P=u(j);if(!P||!j.attempt)return;A("quota",{...P,transport:W,...k===void 0?{}:{status:k},quota:F,handle:j.attempt})},_2=(j,W,F,k)=>{let P=j.attempt;if(!P)return;let p=Z.inspectEvent?.(k===void 0?{transport:W,data:F,attempt:P}:{transport:W,data:F,event:k,attempt:P});if(!p)return;if(p.quota!==void 0)N2(j,W,p.quota);if(p.outputStarted)j.outputStarted=!0;if(p.limit)B2(j,p.limit,W);if(p.error!==void 0)r(j,{reason:"failed",message:p.error});else if(p.done)r(j)},S2=(j,W)=>{let F=j.attempt;if(!F||W.accountId===j.accountId)return;if(F.reboundFrom??=F.accountId,F.accountId=W.accountId,"data"in W)F.data=W.data;j.accountId=W.accountId},Y2=(j)=>!j.attempt||j.endError!==void 0||j.status!==void 0&&j.status>=400,G2=(j)=>{let W=[...G.values()].filter((i)=>i.scope.sessionID===j),F=W.filter((i)=>i.limit&&!i.rerouted).at(-1);if(F)return F;let k=W.filter((i)=>i.scope.kind==="primary"),P=k.length>0?k:W;if(P.length<=1)return P[0];let p=P.filter((i)=>!i.judged&&Y2(i)).at(-1);if(p)return p;let D=P.filter((i)=>i.attempt&&!i.ended);if(D.length>1)return"ambiguous";return D[0]??P.at(-1)},z2={providerID:V},K2=[];K2.push(await $.session.hook("model.request",(j)=>{if(M)return;return U(x2(j),async(W)=>{let F=await v(x2(j),"model.request",W);if(W(),F.accountId===void 0)throw Y(F.scope);s2(j.headers,{...F.headers,[v2]:F.id})})},z2)),K2.push(await $.session.hook("http.request",(j)=>{if(M){if(!f(x2(j),j.request.headers))return}return U(x2(j),async(W)=>{let F=j.request.headers.get(v2)??void 0,k=M?await v(x2(j),"http.request",W,"http"):await g(x2(j),"http.request","http",F,W);W();let P=u(k),p=k.attempt;if(!P||!p)throw Y(k.scope);await X2(k,async()=>{let D=j.request;if(Z.rewriteRequest){if(F!==void 0){let C2=new Headers(D.headers);C2.delete(v2),D=new Request(D,{headers:C2})}D=await Z.rewriteRequest({...P,request:D,attempt:p})??D,W()}let i=new Headers(D.headers);i.delete(v2),a1(i,k.headers),E(k.scope,i.entries());let Q2=new Request(D,{headers:i});z.set(Q2,k),j.request=Q2})})},z2)),K2.push(await $.session.hook("http.response",async(j)=>{let W=z.get(j.request);if(!W){if(M)return;if(!y)y=!0,c("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:j.sessionID,kind:j.kind});return}let F=j.response;if(Z.answeredBy&&W.attempt){let i=W.attempt,Q2=await X2(W,async()=>Z.answeredBy?.({request:j.request,response:F,attempt:i}));if(Q2)S2(W,Q2)}let k=u(W),P=W.attempt;if(!k||!P)return;W.status=F.status;let p=Z.quotaFromHeaders?.(F.headers,F.status,P);if(p!==void 0)N2(W,"http",p,F.status);if(!F.ok&&Z.limitFromResponse){let i=await Z.limitFromResponse({status:F.status,headers:F.headers,body:()=>F.clone().text(),attempt:P});if(i)B2(W,i,"http")}if(!F.ok||!F.body)r(W);let D=F;if(F.body&&(Z.inspectEvent||Z.onAttemptEnd)){let i=F.body;if(Z.inspectEvent)i=i.pipeThrough(N0((Q2)=>_2(W,"http",Q2.data,Q2.event),(Q2)=>c("opencode2 auth event inspection threw",{error:l(Q2)})));D=new Response(s1(i,(Q2)=>r(W,Q2)),{status:F.status,statusText:F.statusText,headers:F.headers})}if(Z.rewriteResponse)D=await Z.rewriteResponse({...k,request:j.request,response:D,attempt:P})??D;if(D!==F)j.response=D},z2)),K2.push(await $.session.hook("experimental.ws.handshake",(j)=>{if(M){let W=D2(j.sessionID,j.kind);if(L.delete(W),!f(x2(j),new Headers(j.headers)))return}return U(x2(j),async(W)=>{let F;for(let D of Object.keys(j.headers)){if(D.toLowerCase()!==v2)continue;F??=j.headers[D],delete j.headers[D]}let k=M?await v(x2(j),"experimental.ws.handshake",W,"ws"):await g(x2(j),"experimental.ws.handshake","ws",F,W);W();let P=u(k),p=k.attempt;if(!P||!p)throw Y(k.scope);await X2(k,async()=>{if(!M?.refuseMisplaced)s2(j.headers,k.headers);let D=Z.rewriteHandshakeURL?.({...P,url:j.url,attempt:p});if(D!==void 0)j.url=D;if(M?.refuseMisplaced)s2(j.headers,k.headers);if(E(k.scope,Object.entries(j.headers)),M)L.add(k.key)})})},z2));let t=Z.rewriteWebSocketFrame?.bind(Z);if(t)K2.push(await $.session.hook("experimental.ws.send",async(j)=>{let W=x2(j);if(M&&!L.has(D2(W.sessionID,W.kind)))return;let F=o(W.sessionID,W.kind),k=await t({...W,attempt:F?.attempt,frame:j.frame});if(k!==void 0)j.frame=k},z2));K2.push(await $.session.hook("experimental.ws.receive",(j)=>{if(M&&!L.has(D2(j.sessionID,j.kind)))return;let W=o(j.sessionID,j.kind);if(!W)return;try{_2(W,"ws",j.frame)}catch(F){c("opencode2 auth frame inspection threw",{error:l(F)})}},z2)),K2.push(await $.session.hook("retry",async(j)=>{if(M&&S.get(j.sessionID)!==!0)return;let W=j.decision,F=()=>A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});if(b(j.sessionID)&&!Z.retrySameAccount){await F();return}let k=G2(j.sessionID);if(!k)return;if(k==="ambiguous"){await A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});return}let P=k;await U(P.scope,async(p)=>{let D=p,i=Z.retrySameAccount?.bind(Z),Q2=P.attempt;if(i&&Q2&&!P.outputStarted&&!P.sameAccountRetry){if(P.ended)await P.ended;if(P.limit)await P.limit.delivered;let M2=await Z2(P.scope.sessionID,async()=>{D();let L2=Q2.accountId,H2=()=>G.has(P.id)&&P.accountId===L2&&G2(j.sessionID)===P&&!P.outputStarted&&(!M||S.get(j.sessionID)===!0);if(!H2()||P.sameAccountRetry)return!1;P.sameAccountRetry=!0;let P2={...P.scope,accountId:L2,error:j.error,attempt:j.attempt,...P.limit?{limit:P.limit.signal}:{}},U2;try{U2=await i(P2)}catch(q2){c("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:j.sessionID,error:l(q2)})}if(!U2)return D(),!1;let O2={accountId:U2.accountId,input:P2};try{D()}catch(q2){throw await B(O2),q2}if(!H2()||U2.accountId!==L2)return await B(O2),!1;let E2=K.get(P.key);if(K.delete(P.key),E2)await R(E2);try{D()}catch(q2){throw await B(O2),q2}if(!H2())return await B(O2),!1;return K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:L2,sameAccount:O2}),P.judged=!0,j.decision={retry:!0,delay:0},!0});if(D(),M2){await A("retry",{sessionID:j.sessionID,accountId:P.accountId,kind:P.scope.kind,attempt:j.attempt,reason:"same-account",hostDecision:W,decision:j.decision,handle:P.attempt});return}}if(b(j.sessionID)){await F();return}P.judged=!0;let C2=P.attempt;if(C2&&!P.outputStarted){if(!P.limit){let M2=Z.limitFromError?.(j.error,C2);if(M2)B2(P,M2,"error")}if(P.ended)await P.ended;if(P.limit)await P.limit.delivered}D();let{decision:n2,reason:w2}=await Z2(P.scope.sessionID,async()=>{if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let M2=K.get(P.key);if(K.delete(P.key),M2)await R(M2);if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let L2=W,H2,P2,U2;if(P.accountId===void 0||!C2)L2={retry:!1},H2="no-account";else if(P.outputStarted)L2={retry:!1},H2="output-started";else if(P.limit){let O2={accountId:P.accountId,limit:P.limit.signal},E2,q2={...P.scope,phase:"retry",previousAccountId:P.accountId,rerouteFrom:O2};try{E2=await Z.chooseAccount(q2)}catch(K0){c("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:P.scope.sessionID,error:l(K0)})}let k2=typeof E2==="object"?E2.hold:void 0,r2=typeof E2==="string"?E2:k2?P.accountId:void 0;if(r2!==void 0)U2={accountId:r2,input:q2};try{D()}catch(K0){if(U2)await X(U2);throw K0}if(b(j.sessionID)){if(U2)await X(U2);return{decision:W,reason:"host-decides"}}if(k2&&Number.isFinite(k2.delayMs)&&k2.delayMs>=0)L2={retry:!0,delay:Math.min(k2.delayMs,w0)},H2="hold";else if(!k2&&r2!==void 0&&r2!==P.accountId)P.rerouted=!0,P2=O2,L2={retry:!0,delay:0},H2="reroute";else{if(k2&&U2)await X(U2),U2=void 0;H2="host-decides-last-account"}}else H2="host-decides";if(j.decision=L2,L2.retry&&P.accountId!==void 0&&G.has(P.id))K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:P.accountId,...P2===void 0?{}:{rerouteFrom:P2},...U2===void 0?{}:{next:U2}});else if(U2)await X(U2);return{decision:L2,reason:H2}});D(),await A("retry",{sessionID:j.sessionID,...P.accountId===void 0?{}:{accountId:P.accountId},kind:P.scope.kind,attempt:j.attempt,reason:w2,hostDecision:W,decision:n2,...C2===void 0?{}:{handle:C2}})})},z2));let T2=(j)=>{if(N(j),S.delete(j),!O.get(j)?.foreignSeen)O.delete(j);for(let W of L)if(JSON.parse(W)[0]===j)L.delete(W);for(let W of[...G.values()]){if(W.scope.sessionID!==j)continue;m(W,"its session was forgotten"),G.delete(W.id)}for(let[W,F]of K)if(F.sessionID===j)I(W)},F2=new AbortController,o2=$.event;if(o2)(async()=>{try{for await(let j of o2.subscribe({signal:F2.signal}))if(j.type==="session.deleted")T2(j.data.sessionID);else if(j.type==="session.status"&&j.data.status.type==="idle"){let W=j.data.sessionID,F=++_;Z2(W,async()=>{for(let[k,P]of K)if(P.sessionID===W&&P.order<F)K.delete(k),await R(P)})}}catch(j){if(!F2.signal.aborted)c("opencode2 auth stopped listening for session deletion",{error:l(j)})}})();return{on(j,W){let F=e.get(j);if(!F)F=new Set,e.set(j,F);let k=W;return F.add(k),()=>{F.delete(k)}},accountFor(j,W){return W2(D2(j,W))?.accountId},forgetSession:T2,get size(){return G.size},async dispose(){if(j2)return;j2=!0;for(let j of $2.keys())N(j);F2.abort();for(let j of G.values())m(j,"the installation was disposed");G.clear();for(let j of K.keys())I(j);L.clear(),S.clear(),O.clear(),e.clear(),await Promise.all(s.values()),await Promise.all(K2.map(async(j)=>{try{await j.dispose()}catch(W){c("opencode2 auth hook did not dispose cleanly",{error:l(W)})}}))}}}import{createHash as t1}from"node:crypto";import{AnthropicOAuthOriginError as e1,applyCustomHeaders as $4,assertNotCustodyTombstone as Z4,classifyGzipRejection as j4,createProviderErrorRedactor as D0,createProviderErrorResponseScope as I0,decideRequestGzip as J4,dumpDirectRequest as y0,dumpRelayRequest as f0,dumpResponseArtifact as a2,encodeGzipRequestBody as X4,getAccountStoragePath as G4,getRequestGzipLatch as Y4,getRequestGzipLatchPath as V4,isDumpEnabled as Q4,mergeAnthropicBetas as W4,remapModelId as v0,remapRequestBodyModel as U4,setDumpEnabled as g0,stateRefusalCause as B4,stateRefusalPublicMessage as z4,stripEmptyTrailingAssistantMessages as K4,TrailingAssistantHistoryError as M4}from"@cortexkit/anthropic-auth-core";var g2="anthropic",r0="x-common-auth-attempt",H4=["x-session-affinity","x-opencode-session","x-parent-session-id",m0,e2,y2,r0],t2=new Set(["authorization","x-api-key"]),N4="physical send before a response",_4="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",L4=512,F4=5000,P4=500,s0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),L0=($,Z="provider request failed")=>({type:s0.has($.type)?$.type:"provider_error",message:Z,...$.status!==void 0?{status:$.status}:{}});class a0 extends Error{sessionID;requestKind;kind="no-account";providerID=g2;constructor($,Z){super(_4);this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicNoAccountError"}}class T0 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=g2;constructor($,Z){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicRevokedError"}}class b2 extends Error{kind="unsupported-transport";providerID=g2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class t0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class e0 extends Error{kind="state-relocated";providerID=g2;constructor($){super(z4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function $0($){let Z=B4($);return Z?new e0(Z):void 0}var I2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function d2($){try{return JSON.parse($)}catch{return}}function F0($){let Z={};for(let[Q,V]of Object.entries($??{}))Z[Q.toLowerCase()]=V;return Z}function h0($){let Z={};for(let Q of H4){let V=$.get(Q);if(V!==null&&Q!==r0)Z[Q]=V;$.delete(Q)}return Z}function T4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function C4($){return $ instanceof M4||$ instanceof l0||$ instanceof e1?new t0($):void 0}function O4($,Z){let Q=[];if($.oauth)Q.push($.oauth.accessToken);for(let[V,M]of Object.entries($.apiHeaders??{})){if(M===null||!t2.has(V))continue;Q.push(M.replace(/^Bearer\s+/i,""))}for(let V of t2){let M=Z.get(V);if(M!==null)Q.push(M.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")Q.push($.dispatch.token);return[...new Set(Q.filter(Boolean))]}var E4=new Set(["oauth-2025-04-20","claude-code-20250219",p0]);function q4($){let Z=$.split(",").map((Q)=>Q.trim()).filter((Q)=>Q&&!E4.has(Q));return W4(null,Z)}function x4($){let Z=d2($);if(!I2(Z))return $;let Q=K4(Z.messages),V=Object.hasOwn(Z,"fallbacks"),{droppedMarkers:M}=c0(Z,!1),C=V&&!Object.hasOwn(Z,"fallbacks"),q=U4(Z);return Q>0||M>0||C||q?JSON.stringify(Z):$}async function S4($,Z){if(!($ instanceof Promise))return"settled";let Q;try{return await Promise.race([$.then(()=>"settled"),new Promise((V)=>{Q=setTimeout(()=>V("timed-out"),Z)})])}finally{if(Q!==void 0)clearTimeout(Q)}}function h2($){let{source:Z,log:Q}=$,V=Math.max(1,$.maxPendingSends??L4),M=$.attemptEndTimeoutMs??F4,C=$.requestGzipLatch??Y4(V4(G4())),q=new WeakSet,T=new Map,H=new WeakMap,G=new WeakMap,z=(Y)=>JSON.stringify([Y.providerID,Y.sessionID,Y.kind,Y.modelID,Y.agent,Y.accountId]),K=new Map,_=new WeakMap,L=new Map,S=new WeakMap,O=D0([]);O.dispose();let b=(Y)=>(Y&&L.get(Y)?.redactor)??O,w=(Y)=>{let N=L.get(Y);if(!N)return;L.delete(Y),N.redactor.dispose(),N.scope.dispose()},f=(Y,N,U,E)=>{let x=O4(N,E),v=I0(x,U);y.set(Y,U),L.set(Y,{sessionID:N.sessionID,redactor:D0(x),scope:v}),v.settled.then(()=>w(Y));while(L.size>V){let g=L.keys().next().value;if(g===void 0)break;w(g)}},y=new WeakMap,n=(Y,N)=>{let U=Y?y.get(Y):void 0;if(!U||!N.ok)return O.redactResponse(N);let E=I0([],U),x=E.redactResponse(N);return E.dispose(),x},e=(Y,N)=>{let U=Y?L.get(Y)?.scope:void 0;if(!U)return n(Y,N);try{return U.redactResponse(N)}catch{return n(Y,N)}},V2=!1,j2=new Map,$2=new WeakMap,c=new WeakMap,l=new WeakMap,s=(Y)=>Y.agent==="cachekeep"||Y.agent==="prime",Z2=async()=>{try{if(Z.isDumpEnabled)return await Z.isDumpEnabled()}catch{return!1}try{return Q4()}catch{return!1}},J=(Y)=>{j2.delete(Y)},X=new WeakMap,B=(Y,N)=>{if(Y&&!N.ok)X.set(N.headers,Y);return N},R=(Y,N)=>{if(N.dispatch!=="http-relay")return!0;let U=/^req_[A-Za-z0-9_-]+$/.test(Y.get("request-id")??"");return G.set(N,U),U},I=(Y)=>new a0(Y.sessionID,Y.kind),A=new Map,h=async(Y,N)=>{if(V2)throw new T0(Y.sessionID,Y.kind);let U={revoked:!1},E=A.get(Y.sessionID);if(!E)E=new Set,A.set(Y.sessionID,E);E.add(U);let x=()=>{if(V2||U.revoked)throw new T0(Y.sessionID,Y.kind)};try{let v=await N(x);return x(),v}finally{let v=A.get(Y.sessionID);if(v?.delete(U)&&v.size===0)A.delete(Y.sessionID)}},r=(Y,N)=>{T.set(Y,N);while(T.size>V){let U=T.keys().next().value;if(U===void 0)break;T.delete(U),Q?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:V})}},m=(Y,N)=>({providerID:Y.providerID,modelID:Y.modelID,sessionID:Y.sessionID,agent:Y.agent,kind:Y.kind,accountId:Y.accountId,attemptId:Y.attemptId,transport:Y.transport,route:N.route,provenance:N.provenance,dispatch:N.dispatch}),a=(Y)=>h(Y,async(N)=>{let{accountId:U,...E}=Y,x;try{x=await Z.authorizeAccount(E,U)}catch(v){let g=$0(v);if(g)throw Q?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:g.cause instanceof Error?g.cause.name:""}),g;throw v}return N(),W2(E,x)}),W2=(Y,N)=>{if(!N)throw I(Y);if(N.dispatch?.kind==="websocket-relay")throw new b2;let U=N.dispatch?.kind==="http-relay"?"http-relay":"direct",E=N.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":N.dispatch.token}:void 0;if(N.route==="oauth"){if(!N.accessToken)throw I(Y);Z4(N.accessToken,g2);let g=Object.freeze({route:"oauth",provenance:N.provenance,dispatch:U});r(g,{sessionID:Y.sessionID,oauth:{accessToken:N.accessToken,...N.identity?{identity:N.identity}:{}},dispatch:N.dispatch,oauthHeaders:N.headers});let X2=F0(N.headers);for(let o of t2)delete X2[o];return delete X2["anthropic-beta"],{headers:E??{...X2,"x-api-key":null,authorization:`Bearer ${N.accessToken}`},attempt:g}}let x={authorization:null,"x-api-key":null,...F0(N.headers)};if(!x.authorization&&!x["x-api-key"])throw I(Y);let v=Object.freeze({route:"api",provenance:N.provenance,dispatch:U});return r(v,{sessionID:Y.sessionID,...N.baseURL?{baseURL:N.baseURL}:{},dispatch:N.dispatch,apiHeaders:x}),{headers:E??x,attempt:v}},d=(Y)=>h(Y,(N)=>J2(Y,N)),J2=async(Y,N)=>{let{request:U,attempt:E}=Y,x=E.data;K.set(z(Y),E);while(K.size>V){let Y2=K.keys().next();if(!Y2.done)K.delete(Y2.value)}let v=x?T.get(x):void 0;if(x)T.delete(x);if(!x||!v||x.route==="oauth"&&!v.oauth)throw I(Y);let g=new Headers(U.headers);$4(g);let X2=h0(g),o=U.body===null?void 0:await U.text();N();let B2=o!==void 0&&T4(U.url),N2=o0(U.url,v.baseURL!==void 0?{baseURL:v.baseURL}:{}).url?.toString()??U.url;try{if(x.route==="oauth"&&v.oauth){d0(N2);let{accessToken:Y2,identity:G2}=v.oauth;for(let[K2,t]of Object.entries(F0(v.oauthHeaders))){if(t2.has(K2))continue;if(t===null)g.delete(K2);else g.set(K2,t)}let z2=null;if(o!==void 0&&B2){let K2={...m(E,x),modelID:(()=>{let F2=d2(o);return v0(I2(F2)&&typeof F2.model==="string"?F2.model:Y.modelID)})(),route:"oauth",correlation:X2},t=await Z.requestOptions?.(K2)??{};if(N(),E.agent!=="cachekeep")o=await n0(o,{...t,...G2?{identity:G2}:{},sessionId:Y.sessionID,onToolNameMap:(F2)=>_.set(x,F2)});let T2=d2(o);z2=I2(T2)?T2:null}i0(g,Y2,{body:z2,...G2?{identity:G2}:{},requestClass:u0(E.agent)?"auxiliary":"main"})}else{if(o!==void 0&&B2)o=x4(o);g.delete("authorization"),g.delete("x-api-key");for(let[G2,z2]of Object.entries(v.apiHeaders??{}))if(z2===null)g.delete(G2);else g.set(G2,z2);if(o!==void 0&&B2&&!g.has("content-type"))g.set("content-type","application/json");let Y2=g.get("anthropic-beta");if(Y2!==null){let G2=q4(Y2);if(G2)g.set("anthropic-beta",G2);else g.delete("anthropic-beta")}}}catch(Y2){let G2=C4(Y2);if(!G2)throw Y2;throw H.set(x,G2.check),Q?.warn("refused an Anthropic request locally; nothing was sent",{check:G2.check}),G2}let _2=o!==void 0?d2(o):void 0;if(await Z.admitRequest?.({...m(E,x),modelID:v0(I2(_2)&&typeof _2.model==="string"?_2.model:Y.modelID)}),h0(g),o!==void 0)g.delete("content-length");if(N(),f(x,v,I2(_2)&&_2.stream===!0?"event-stream":"http",g),x.route==="oauth"&&B2&&o!==void 0)await Z.onRequestPrepared?.({...m(E,x),url:N2,bodyText:o}),N();if(v.dispatch?.kind==="http-relay"){let Y2=o??"";g.delete("x-relay-token");let G2={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:N2,method:U.method,headers:Object.fromEntries(g)},mode:"full_sync",revision:1,body:Y2,next_hash:`sha256:${t1("sha256").update(Y2).digest("hex")}`};if(B2&&o!==void 0&&!s(E)){let z2=X2[y2]==="1"?"start":void 0,K2=JSON.stringify(G2);j2.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:Y2,url:N2,method:U.method,headers:new Headers(g),dispatch:"http-relay",relayUrl:v.dispatch.url,envelope:G2,relayBytes:K2.length,...z2?{tag:z2}:{}})}else J(x);return new Request(v.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":v.dispatch.token},redirect:"error",signal:U.signal,body:JSON.stringify(G2)})}let S2=o;if(x.route==="oauth"&&B2&&o!==void 0){let Y2=await J4({url:N2,body:o,latch:C});if(N(),Y2.gzip)S2=await X4(o),g.set("content-encoding","gzip"),q.add(x),N()}if(B2&&o!==void 0&&!s(E)){let Y2=X2[y2]==="1"?"start":void 0;j2.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:o,url:N2,method:U.method,headers:new Headers(g),dispatch:"direct",...Y2?{tag:Y2}:{}})}else J(x);return new Request(N2,{method:U.method,headers:g,redirect:x.route==="oauth"?"error":U.redirect,signal:U.signal,...S2!==void 0?{body:S2}:{}})},u={providerID:g2,chooseAccount:(Y)=>h(Y,async()=>{let N=await Z.chooseAccount(Y);if(typeof N==="object"&&Y.phase==="retry")return N;if(typeof N!=="string"||!N)throw I(Y);return N}),dropChoice:(Y)=>Z.dropChoice?.(Y),async retrySameAccount(Y){if(!Z.retrySameAccount)return;let N=z(Y),U=K.get(N);K.delete(N);let E=Y.limit??(U?u.limitFromError?.(Y.error,U):void 0);return Z.retrySameAccount({...Y,error:L0(Y.error),...E?{limit:E}:{}})},dropSameAccountRetry:(Y)=>Z.dropSameAccountRetry?.({...Y,error:L0(Y.error)}),accountHeaders:a,rewriteRequest:d,rewriteHandshakeURL(){throw new b2},async rewriteResponse({response:Y,attempt:N}){let U=N.data;if(U&&!R(Y.headers,U)){if(U)J(U);if(Y.status===401)return w(U),Y.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return e(U,Y)}if(U&&q.has(U))q.delete(U),j4(Y).then((t)=>{if(!t)return;C.latchProcess(),Q?.warn("gzipped request body rejected; later requests go uncompressed",{kind:t,status:Y.status})},()=>{});let E=null,x=U?j2.get(U):void 0;if(U&&x){let t=!1;try{t=await Z2()}catch{t=!1}if(!t)J(U);else{try{g0(!0)}catch{}try{if(x.dispatch==="http-relay")E=await f0({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:Y.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}});else E=await y0({affinity:x.affinity,route:x.route,status:Y.status,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{E=null}if(J(U),E){$2.set(U,E);try{await a2(E,{status:Y.status,message:null,complete:!1})}catch{}l.set(U,Promise.resolve())}}}let v=e(U,Y);if(U?.route!=="oauth"||!v.body)return B(U,v);let g={...m(N,U),status:Y.status},X2=Z.responseOptions?.(g)??{},o=(Y.headers.get("content-type")??"").includes("application/json"),B2={...X2,toolNameMap:U?_.get(U):void 0,onToolNameRefusal:()=>{if(!U)return;H.set(U,"response_tool_names"),w(U)},laneStartOAuthServed:!0,...o?{responseMode:"json"}:{}};if(!U||!E)return B(U,P0(v,B2));let N2=E,_2=Y.status,S2=(t)=>{let F2=(l.get(U)??Promise.resolve()).then(()=>t().then(()=>{return})).catch(()=>{return});l.set(U,F2)},Y2=X2.onMessageStart,G2=X2.onMessageDelta,z2=X2.onMessageResponse,K2=X2.onStreamEnd;return B(U,P0(v,{...B2,onMessageStart:(t)=>{try{Y2?.(t)}catch{}try{c.set(U,{...t}),S2(()=>a2(N2,{status:_2,message:t,complete:!1}))}catch{}},onMessageDelta:(t)=>{try{G2?.(t)}catch{}try{let T2=c.get(U)??{},F2=T2.usage&&typeof T2.usage==="object"&&!Array.isArray(T2.usage)?T2.usage:{},o2={...T2,...t.usage?{usage:{...F2,...t.usage}}:{},...t.stopReason?{stop_reason:t.stopReason}:{}};S2(()=>a2(N2,{status:_2,message:o2,complete:!0}))}catch{}},onMessageResponse:(t)=>{try{z2?.(t)}catch{}try{S2(()=>a2(N2,{status:_2,message:t,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await K2?.()}catch{}try{await(l.get(U)??Promise.resolve())}catch{}}}))},quotaFromHeaders(Y,N,U){let E=U.data;if(!E||!R(Y,E))return;return Z.quotaFromHeaders?.(Y,{...m(U,E),status:N})},async limitFromResponse({status:Y,headers:N,body:U,attempt:E}){let x=E.data;if(!x||H.get(x)==="response_tool_names")return;if(!R(N,x))return Z.limitFromRelayFailure?.({...m(E,x),status:Y});if(S.set(x,`provider responded with HTTP ${Y}`),!Z.limitFromResponse)return;let v=X.get(N)===x,g=b(x);return Z.limitFromResponse({...m(E,x),status:Y,headers:N,body:async()=>v?await U():g.redactText(await U())})},inspectEvent({data:Y,event:N,attempt:U}){if(U.data&&H.get(U.data)==="response_tool_names")return;let E=d2(Y);if(!I2(E))return;let x=typeof E.type==="string"?E.type:N;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let v=U.data,g=b(v),X2=I2(E.error)?E.error:{},o=typeof X2.type!=="string"?void 0:s0.has(X2.type)?X2.type:g.redactText(X2.type),B2=typeof X2.message==="string"?g.redactText(X2.message):void 0;if(v?.dispatch==="http-relay"&&G.get(v)===!1)return;let N2=v?Z.limitFromStreamError?.({...m(U,v),errorType:o,message:B2}):void 0,_2={error:[o??"error",B2].filter(Boolean).join(": ").slice(0,P4),...N2?{limit:N2}:{}};if(v&&_2.error)S.set(v,_2.error);return _2},limitFromError(Y,N){let U=N.data;if(!U||H.has(U))return;let E=L0(Y,S.get(U));if(w(U),U.dispatch==="http-relay"&&G.get(U)===!1)return;return Z.limitFromHostError?.(E,m(N,U))},async onAttemptEnd(Y,N){let U=Y.data;if(!U)return;T.delete(U);let E=j2.get(U);if(E){J(U);try{if(await Z2()){try{g0(!0)}catch{}try{if(E.dispatch==="http-relay"){if(N.status!==void 0)await f0({affinity:E.affinity,transport:"http",protocol:1,mode:"full_sync",status:N.status,bodyText:E.bodyText,payload:E.envelope??{},relayBytes:E.relayBytes??0,...E.tag?{tag:E.tag}:{}})}else await y0({affinity:E.affinity,route:E.route,status:N.status,error:N.status===void 0?N4:void 0,bodyText:E.bodyText,url:E.url,method:E.method,headers:E.headers,...E.tag?{tag:E.tag}:{}})}catch{}}}catch{}}let x=N.error?.reason;if(x==="cancelled"||x==="abandoned"||x===void 0&&(N.status===void 0||N.status<400))w(U);let v=H.get(U),{status:g,...X2}=N,o=Z.onAttemptEnd?.(m(Y,U),{...X2,...g!==void 0&&(U.dispatch!=="http-relay"||G.get(U)===!0)?{status:g}:{},...v!==void 0?{localRefusal:{check:v}}:{}});if(await S4(o,M)==="timed-out")Q?.warn("the account source did not finish recording a send",{timeoutMs:M})}};return{adapter:u,dispose(){V2=!0;for(let[Y,N]of A){for(let U of N)U.revoked=!0;Z.forgetSession?.(Y)}A.clear(),T.clear(),K.clear(),j2.clear();for(let Y of[...L.keys()])w(Y)},forgetSession(Y){for(let N of A.get(Y)??[])N.revoked=!0;A.delete(Y);for(let[N,U]of K)if(U.sessionID===Y)K.delete(N);for(let[N,U]of T)if(U.sessionID===Y)T.delete(N);for(let[N,U]of[...L])if(U.sessionID===Y)w(N);for(let[N,U]of[...j2])if(U.affinity===Y)j2.delete(N);Z.forgetSession?.(Y)},get pendingSendCount(){return T.size},get heldCredentialCount(){let Y=0;for(let N of T.values())if(N.oauth)Y++;return Y},get heldRedactorCount(){return L.size},get operationsInProgress(){let Y=0;for(let N of A.values())Y+=N.size;return Y}}}import{setTimeout as o4}from"node:timers/promises";import{CacheKeepManager as n4,CacheKeepSessionRegistry as r4,getDefaultCacheKeepRegistryDirectory as s4,isCacheKeepActiveNow as W1,isCacheKeepHybridActive as p2,isCacheKeepSubagentsEnabled as J0,logger as X0,NativeAccountRefusal as A2,nativeAccountCanServe as B1,nativeAccountRefusal as a4}from"@cortexkit/anthropic-auth-core";import{createHash as R4,randomUUID as b4}from"node:crypto";import{constants as $1}from"node:fs";import{lstat as Z1,mkdir as A4,open as w4,readdir as j1,rm as Z0,writeFile as D4}from"node:fs/promises";import{tmpdir as I4}from"node:os";import{join as u2}from"node:path";import{promisify as Y1}from"node:util";import{gunzip as y4,gzip as f4}from"node:zlib";import{CACHE_KEEP_MAX_BODY_BYTES as V1,createWindowsOwnerOnly as v4,ensureWindowsOwnerOnlyDirectory as g4,isOwnerOnly as J1,logger as h4,readWindowsOwnerOnly as m4,renameWithWindowsSharingRetry as l4}from"@cortexkit/anthropic-auth-core";var C0="2.4.7";var d4=Y1(f4),u4=Y1(y4),j0=($)=>R4("sha256").update($).digest("hex"),X1=/^[a-f0-9]{64}\.json\.gz$/,O0=/^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/,G1=2*V1+65536;function p4($,Z=I4()){return u2(Z,`cortexkit-anthropic-auth-cachekeep-${j0($).slice(0,16)}`)}function c4($){return{v:1,pluginVersion:C0,id:$.id,bodyText:$.bodyText,url:$.url,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt,oauthAccountIdentity:$.oauthAccountIdentity,isSubagent:$.isSubagent}}function Q1($){let Z=JSON.parse($);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid restart body");let Q=!1;for(let V of Object.keys(Z))if(/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(V))delete Z[V],Q=!0;return Q?JSON.stringify(Z):$}function i4($,Z,Q){if(!$||typeof $!=="object"||Array.isArray($))return!1;if($.v!==1||$.pluginVersion!==C0||typeof $.id!=="string"||!$.id||`${j0($.id)}.json.gz`!==Z||typeof $.bodyText!=="string"||Buffer.byteLength($.bodyText)>V1||typeof $.url!=="string"||typeof $.oauthAccountIdentity!=="string"||!$.oauthAccountIdentity||typeof $.isSubagent!=="boolean"||!Number.isFinite($.cacheExpiresAt)||$.cacheExpiresAt<=Q||!Number.isFinite($.nextPrewarmAt))return!1;return Q1($.bodyText)===$.bodyText}class E0{options;directory;disabled=!1;chain=Promise.resolve();pending=new Map;timers=new Map;lastWrite=new Map;latest=new Map;constructor($){this.options=$;this.directory=p4($.storageId,$.root)}refuse(){if(this.disabled)return;this.disabled=!0;for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),h4.warn("cachekeep","restart storage unavailable; retaining sessions in memory only")}async directoryReady(){if(this.disabled)return!1;try{if(!await g4(this.directory,this.options.ownerOnly))try{await A4(this.directory,{mode:448})}catch(Z){if(Z.code!=="EEXIST")throw Z}let $=await Z1(this.directory);if(!$.isDirectory()||$.isSymbolicLink()||!await J1(this.directory,()=>$.uid===process.getuid?.()&&($.mode&511)===448,this.options.ownerOnly))throw Error("Unsafe restart directory");return!0}catch{return this.refuse(),!1}}enqueue($){this.chain=this.chain.then(async()=>{if(await this.directoryReady())await $()}).catch(()=>this.refuse())}async load($,Z){if(!await this.directoryReady())return;try{for(let Q of(await j1(this.directory)).sort()){if(!X1.test(Q)&&!O0.test(Q))continue;let V=u2(this.directory,Q);try{if(O0.test(Q))throw Error("Unfinished write");let M=await Z1(V);if(!M.isFile()||M.isSymbolicLink()||M.size>G1||!await J1(V,()=>M.uid===process.getuid?.()&&(M.mode&511)===384,this.options.ownerOnly))throw Error("Unsafe restart file");let C=await m4(V,this.options.ownerOnly);if(!C){let H=await w4(V,$1.O_RDONLY|$1.O_NOFOLLOW);try{C=await H.readFile()}finally{await H.close()}}let q=await u4(C,{maxOutputLength:G1}),T=JSON.parse(q.toString("utf8"));if(!i4(T,Q,$)||!Z(T))throw Error("Stale restart file")}catch{await Z0(V,{force:!0})}}}catch{this.refuse()}}changed($){if(this.disabled)return;let Z=c4($),Q=this.latest.get(Z.id);if(Q&&Q.bodyText===Z.bodyText&&Q.url===Z.url&&Q.oauthAccountIdentity===Z.oauthAccountIdentity&&Q.cacheExpiresAt===Z.cacheExpiresAt&&Q.nextPrewarmAt===Z.nextPrewarmAt&&Q.isSubagent===Z.isSubagent)return;if(this.latest.set(Z.id,Z),this.pending.set(Z.id,Z),this.timers.has(Z.id))return;let V=Math.max(250,(this.lastWrite.get(Z.id)??0)+5000-(this.options.now?.()??Date.now())),M=(this.options.setTimeoutImpl??setTimeout)(()=>this.flush(Z.id),V);M.unref?.(),this.timers.set(Z.id,M)}flush($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($);let Q=this.pending.get($);if(this.pending.delete($),!Q)return this.chain;return this.lastWrite.set($,this.options.now?.()??Date.now()),this.enqueue(async()=>{let V=u2(this.directory,`${j0($)}.json.gz`),M=`${V}.${b4()}.tmp`;try{let C={...Q,bodyText:Q1(Q.bodyText)},q=await d4(JSON.stringify(C));if(!await v4(M,q,this.options.ownerOnly))await D4(M,q,{flag:"wx",mode:384});await l4(M,V,{platform:this.options.ownerOnly?.platform})}finally{await Z0(M,{force:!0})}}),this.chain}removed($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($),this.pending.delete($),this.latest.delete($),this.lastWrite.delete($),this.enqueue(()=>Z0(u2(this.directory,`${j0($)}.json.gz`),{force:!0}))}clear(){for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),this.enqueue(async()=>{for(let $ of await j1(this.directory))if(X1.test($)||O0.test($))await Z0(u2(this.directory,$),{force:!0})})}async drain(){for(let $ of this.pending.keys())this.flush($);await this.chain}}function m2($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}var U1=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function z1(){let $=globalThis;return $[U1]??=new Map,$[U1]}function t4($,Z){let Q=new Map,V=new Map,M=new E0({storageId:$,...Z.persistence}),C=new Set,q=0,T=new r4({directory:Z.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||s4("opencode"),now:Z.now}),H=()=>{let O;for(let b of V.values())O=b;return O},G=Z.setIntervalImpl??globalThis.setInterval,z=new n4({loadStorage:async()=>{let O=H(),b=O?await O.loadStorage():null;if(O&&!p2(b)){for(let w of z.trackedSessions())z.untrack(w.id);M.clear()}return b},now:Z.now,setIntervalImpl:(O,b)=>G(()=>{let w=z.tick();return S.ticking=w.catch(()=>{X0.warn("cachekeep","tick failed")}),S.ticking},b),clearIntervalImpl:Z.clearIntervalImpl,onTargetChanged:(O)=>M.changed(O),onTargetRemoved:(O)=>{C.delete(O),M.removed(O)},onTrackedSessionsChanged:(O)=>T.publish(V.size===0?[]:O),prepareHeaders(O,b,w){let f=H();if(!f)return;return Q.set(w.id,{target:b,attempt:w,lease:f}),new Headers({"x-native-cachekeep-attempt":String(w.id)})},fetchImpl:async(O,b)=>{let w=new Request(O,b),f=Number(w.headers.get("x-native-cachekeep-attempt")),y=Q.get(f);if(Q.delete(f),!y||y.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(C.delete(y.target.id))await o4(Math.max(0,q+3000-Date.now()),void 0,{signal:y.attempt.signal}),q=Date.now();let n=y.lease.send(y.target,w,y.attempt.signal),e=n.then(()=>{},()=>{});return y.lease.inflight.add(e),e.then(()=>y.lease.inflight.delete(e)),n},onComplete:({attempt:O})=>{Q.delete(O.id)}}),K,_=()=>{if(K!==void 0)clearTimeout(K);K=void 0},L=()=>{if(_(),V.size>0)return;let O=z.dropExpiredTargets();if(O===void 0){let w=z1();if(w.get($)===S)w.delete($);return}let b=Z.now?.()??Date.now();if(K=setTimeout(L,Math.max(0,O-b)),typeof K==="object"&&"unref"in K)K.unref()},S={manager:z,registry:T,persistence:M,prepared:Q,leases:V,nextGeneration:0,retain(){z.stop(),Q.clear(),L()},async adopt(){if(_(),S.loading??=(async()=>{let O=H();if(!O)return;let b=await O.read();if(!p2(b.policyStorage)){M.clear();return}let w=Z.now?.()??Date.now(),f=0;await M.load(w,(y)=>{if(!V.size||z.trackedRequest(y.id))return!0;let n=b.accounts.find((j2)=>m2(j2)===y.oauthAccountIdentity);if(n?.type!=="oauth"||!B1(n)||y.isSubagent&&!J0(b.policyStorage))return!1;let e=y.nextPrewarmAt<=w?w+f++*3000:y.nextPrewarmAt,V2=z.track({sessionId:y.id,url:y.url,headers:new Headers,bodyText:y.bodyText,storage:b.policyStorage,cacheMode:"hybrid",oauthAccountId:n.id,oauthAccountIdentity:y.oauthAccountIdentity,isSubagent:y.isSubagent,retained:{cacheExpiresAt:y.cacheExpiresAt,nextPrewarmAt:e}});if(V2.tracked)C.add(y.id);return V2.tracked})})().catch(()=>{X0.warn("cachekeep","failed to restore tracked sessions")}),await S.loading,!V.size)return;if(z.dropExpiredTargets()===void 0)return;z.start(),T.publish(z.trackedSessions()).catch(()=>{X0.warn("cachekeep","failed to publish tracked sessions")})}};return S}function K1($){let{runtime:Z,source:Q}=$,V=new AbortController,M=z1(),C=M.get($.storageId)??t4($.storageId,$);M.set($.storageId,C);let{manager:q,registry:T}=C,H=async(L,S,O)=>{let b=O?AbortSignal.any([V.signal,O]):V.signal;b.throwIfAborted();let w=JSON.parse(await S.text()),f={providerID:"anthropic",modelID:w.model,sessionID:`oc2-cachekeep:${L.id}`,agent:"cachekeep",kind:"generate"},y=(c)=>{throw new A2(c)},n=h2({source:{...Q,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(c){return{...await Q.requestOptions?.(c,y),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(c,l){let s=await Z.read();b.throwIfAborted();let Z2=s.accounts.find((X)=>X.id===l);if(Z2?.type!=="oauth"||!B1(Z2))throw new A2("account-unavailable");if(m2(Z2)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!J0(s.policyStorage)||!p2(s.policyStorage)||!W1(s.policyStorage,new Date($.now?.()??Date.now())))return;let J=await Q.authorizeAccount(c,l,y);if(J?.provenance.kind==="local"&&m2({...Z2,binding:J.provenance.subject.binding,accountIdentity:J.provenance.subject.binding.identity})!==L.oauthAccountIdentity)throw new A2("credential-changed");if(J?.provenance.kind==="vault"&&J.provenance.credentialId!==Z2.credentialId)throw new A2("credential-changed");return J},async admitRequest(c){await Q.admitRequest?.(c,y);let l=await Z.read(),s=l.accounts.find((Z2)=>Z2.id===c.accountId);if(b.throwIfAborted(),!s)throw new A2("account-unavailable");if(m2(s)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!J0(l.policyStorage)||!p2(l.policyStorage)||!W1(l.policyStorage,new Date($.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),e,V2,j2=!1,$2=()=>n.forgetSession(f.sessionID);b.addEventListener("abort",$2,{once:!0});try{let c=await Z.read(),l=c.accounts.find((R)=>m2(R)===L.oauthAccountIdentity)?.id;if(!l)throw new A2(c.accounts.some((R)=>R.id===L.oauthAccountId)?"credential-changed":"account-unavailable");let s=await n.adapter.accountHeaders({...f,accountId:l});if(!("headers"in s)||typeof s.headers!=="object"||s.headers===null||typeof s.attempt!=="object"||s.attempt===null||s.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");e={...f,accountId:l,attemptId:crypto.randomUUID(),transport:"http",data:s.attempt};let Z2=await n.adapter.rewriteRequest?.({...f,accountId:l,attempt:e,request:new Request(L.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w),signal:b})});if(!Z2)throw Error("CacheKeep rewrite refused");b.throwIfAborted();let J=await($.fetch??fetch)(Z2),X=await n.adapter.rewriteResponse?.({...f,accountId:l,attempt:e,request:Z2,response:J});if(!X)throw Error("CacheKeep response rewrite refused");if(V2=X.status,n.adapter.quotaFromHeaders?.(X.headers,X.status,e),!X.ok)await n.adapter.limitFromResponse?.({status:V2,headers:X.headers,body:()=>X.clone().text(),attempt:e});let B=await X.arrayBuffer();return j2=!0,new Response(B,{status:V2,headers:X.headers})}catch(c){let l=a4(c);if(l)throw l;throw Error("Native CacheKeep was not completed")}finally{b.removeEventListener("abort",$2);try{if(e)await n.adapter.onAttemptEnd?.(e,{status:V2,outputStarted:!1,...j2?{}:{error:{reason:"cancelled"}}})}finally{n.dispose(),Q.forgetSession?.(f.sessionID)}}},G={generation:C.nextGeneration++,stopped:!1,loadStorage:async()=>(await Z.read()).policyStorage,send:H,inflight:new Set,read:()=>Z.read()},z=C.leases.size===0;C.leases.set(G.generation,G);let K=z?C.adopt():C.loading??Promise.resolve(),_;return{ready:K,async track(L){let S=(y)=>{X0.debug("cachekeep","tracking skipped",{session:L.sessionID,reason:y})};if(G.stopped)return S("lease-stopped");if(L.route!=="oauth")return S("not-oauth");if(L.agent==="cachekeep"||L.agent==="prime")return S("background-agent");if(L.kind!=="primary")return S("not-primary");let O=await Z.read();if(G.stopped)return S("lease-stopped");if(!p2(O.policyStorage)){for(let y of q.trackedSessions())q.untrack(y.id);return C.persistence.clear(),S("hybrid-inactive")}let b=!1;try{b=await $.isSubagent?.(L.sessionID)??!1}catch{return S("session-lookup-failed")}if(G.stopped)return S("lease-stopped");if(b&&!J0(O.policyStorage))return S("subagents-disabled");let w=O.accounts.find((y)=>y.id===L.accountId);if(!w?.accountIdentity)return S("account-identity-missing");if(L.provenance.kind==="local"&&JSON.stringify(w.binding)!==JSON.stringify(L.provenance.subject.binding))return S("local-binding-changed");if(L.provenance.kind==="vault"&&w.credentialId!==L.provenance.credentialId)return S("vault-credential-changed");let f=q.track({sessionId:L.sessionID,url:L.url,headers:new Headers,bodyText:L.bodyText,storage:O.policyStorage,cacheMode:"hybrid",oauthAccountId:L.accountId,oauthAccountIdentity:m2(w),isSubagent:b});return await T.publish(q.trackedSessions()),f},registry:T,dispose(){if(_)return _;G.stopped=!0,V.abort();for(let[S,O]of C.prepared)if(O.lease===G)C.prepared.delete(S);let L=C.leases.delete(G.generation)&&C.leases.size===0;if(L)C.retain();return _=(async()=>{try{if(L)await C.ticking;await K,await Promise.all(G.inflight),await C.persistence.drain()}finally{if(L&&C.leases.size===0)await T.dispose()}})(),_}}}async function M1($,Z,Q){let V=h2(Z),M=[],C=async(_,L,S)=>{let O=await $.session.hook(_,L,S);return M.push(O),O},q=new AbortController,T;try{T=await _0({session:{hook:C},event:$.event},V.adapter,{logger:Z.log,gateOnPlaceholder:Q})}catch(_){throw V.dispose(),await Promise.allSettled(M.map((L)=>L.dispose())),_}let H=(_)=>{V.forgetSession(_),T.forgetSession(_)},G=$.event,z=G?(async()=>{try{for await(let _ of G.subscribe({signal:q.signal}))if(_.type==="session.deleted")H(_.data.sessionID)}catch(_){if(!q.signal.aborted)Z.log?.warn("stopped listening for session deletion",{error:_ instanceof Error?_.name:"unknown"})}})():Promise.resolve(),K;return{installation:T,forgetSession:H,dispose(){if(K)return K;return V.dispose(),q.abort(),K=(async()=>{await T.dispose(),await z})(),K}}}import{effectiveRelayTransport as H1,getQuotaCheckIntervalMs as e4,logger as $7,nativeAccountCanServe as Z7,oauthProfileIsFresh as j7,quotaSnapshotCheckedAt as J7}from"@cortexkit/anthropic-auth-core";function N1($,Z){let Q=new AbortController,V,M=!1,C=async()=>{let H=await $.read();if(Q.signal.throwIfAborted(),H.policyStorage.relay?.enabled===!0&&H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="websocket")return;let G=H,z=e4(G.policyStorage);for(let K of G.accounts){if(Q.signal.aborted)return;if(!Z7(K)||K.type!=="oauth")continue;if(G.policyStorage.quota?.enabled!==!1&&Date.now()-J7(K.quota)>=z)await $.fetchQuota(K.id,Z,Q.signal,void 0,"background").catch(()=>{});if(!j7(K.profile)&&!Q.signal.aborted)await $.fetchProfile(K.id,Z,Q.signal).catch(()=>{})}},q=()=>{if(M||V)return V;return V=C().catch(()=>{if(!Q.signal.aborted)$7.debug("opencode2","native background readings did not complete")}).finally(()=>{V=void 0}),V},T=$.vault.watch({intervalMs:60000,onRefresh:q,shouldRefresh:async()=>{let H=await $.read();return H.policyStorage.relay?.enabled!==!0||H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){M=!0,T.close(),Q.abort(),await V}}}import{authorize as H7,buildCacheKeepStatusSummary as N7,buildClaudeQuotaSummary as _7,buildPrimeAccountStatuses as L7,buildPrimeStatusSummary as F7,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P7,effectiveRelayTransport as T7,exchange as C7,formatNativeAccountState as O7,formatOAuthAccountTier as E7,getCacheKeepWindow as q7,getHostClaustrumEnrollmentPaths as x7,isCacheKeepAlways as S7,isCacheKeepHybridActive as k7,isCacheKeepPersistentlyEnabled as R7,nativeAccountCanServe as b7,parseLogLevel as A7,resetClaustrumEnrollmentState as w7,setDumpEnabled as D7}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as X7,effectiveRelayStatus as G7,formatNativeAccountState as Y7,formatOAuthAccountTier as _1,getCacheKeepWindow as V7,getRoutingMode as Q7,isCacheKeepAlways as W7,isCacheKeepHybridActive as U7,isPermanentRefreshError as B7,isPrimePersistentlyEnabled as z7,nativeAccountCanServe as P1,refreshBackoffActive as L1}from"@cortexkit/anthropic-auth-core";var F1=($)=>P1($)&&$.state!=="unsupported-access"?void 0:Y7($)||void 0,K7=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return P1($)?"on-vault-served":"on-cold"},M7=($,Z)=>typeof $==="number"&&$>Z;function T1($,Z){let{now:Q}=Z,V=$.policyStorage,M=$.accounts.filter((z)=>z.type==="oauth"),C=M.find((z)=>z.id==="main"),q=C?F1(C):void 0,T=C?.lastQuotaRefreshError?.nextRetryAt,H=C?.lastRefreshError,G=V7(V);return G0({main:{quota:C?.quota??null,enabled:C?.enabled,tierLabel:_1(C?.profile),quotaBackedOff:M7(T,Q),quotaBackoffUntil:T,refreshBackedOff:L1(H,C?.accountIdentity,Q,void 0),refreshBackoffUntil:H?.nextRetryAt,stateLine:q,quotaDated:Boolean(q)},fallbacks:M.filter((z)=>z.id!=="main"&&(z.enabled||z.source==="vault")).map((z)=>{let K=F1(z),_=K7(z);return{id:z.id,label:z.label,quota:z.quota??null,enabled:z.enabled,tierLabel:_1(z.profile),needsReauth:B7(z.lastRefreshError)&&L1(z.lastRefreshError,z.accountIdentity,Q,void 0),..._==="on-vault-reauth"?{vaultReauth:!0}:{},..._==="on-vault-served"?{vaultServed:!0}:{},..._!=="off"?{custodyState:_}:{},stateLine:K,quotaDated:Boolean(K)}}),...Z.activeId!==void 0&&{activeId:Z.activeId},route:Q7(V),relay:G7(V.relay),fastMode:V.claudeFast?.enabled===!0,cacheKeep:{enabled:U7(V),...W7(V)?{window:"always"}:G&&{window:`${G.startHour}-${G.endHour}`},trackedSessions:Z.trackedSessions},prime:z7(V)?{enabled:!0,accounts:X7(V,{now:Q})}:void 0,lastUpdated:Q})}var q0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},C1=`For first-time model access, connect Anthropic with "${Q0}".
|
|
4
|
-
Run: opencode auth login anthropic --method ${V0}`,
|
|
5
|
-
Route: ${$.id}`;return`${Z==="main"?"Main account":`Fallback ${$.id}`}: ${Q}`};function q1($){let{runtime:Z,source:Q}=$,V=new Map,M=!1,C=async(G,z)=>{await Z.updateSettings((K)=>({...K,[G]:{...q0(K[G]),...z}}))},q=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(G,z)=>{if(M)throw Error("Native menu is closed");switch(z.signal?.throwIfAborted(),G.action){case"enable":case"disable":return await Z.setEnabled(G.values.id,G.action==="enable"),q();case"remove":return await Z.remove(G.values.id),q();case"move-up":case"move-down":{let _=(await Z.read()).accounts.map((w)=>w.id),L=_.indexOf(G.values.id),S=L+(G.action==="move-up"?-1:1);if(L<0||S<0||S>=_.length)return{ok:!1,text:"Account cannot move in that direction."};let O=_[L],b=_[S];if(O===void 0||b===void 0)return{ok:!1,text:"Account order changed."};return _[L]=b,_[S]=O,await Z.reorder(_),q()}case"add-apikey":return await Z.addApi(G.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let K=new AbortController;V.get(G.sessionId)?.active.abort();let _={active:K,auth:void 0};V.set(G.sessionId,_);let L=await
|
|
3
|
+
`)}}function N0($,Z){let Q=new TextDecoder,V="",M=(q)=>{let T=n1(q);if(!T)return;try{$(T)}catch(H){Z(H)}},C=()=>{for(;;){let q=/\r?\n\r?\n/.exec(V);if(!q)return;let T=V.slice(0,q.index);V=V.slice(q.index+q[0].length),M(T)}};return new TransformStream({transform(q,T){T.enqueue(q),V+=Q.decode(q,{stream:!0}),C()},flush(){if(V+=Q.decode(),C(),V.trim()!=="")M(V);V=""}})}var A0=512,w0=1200000,v2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),x2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function r1($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function s1($,Z){let Q=$.getReader();return new ReadableStream({async pull(V){let M;try{M=await Q.read()}catch(C){Z({reason:"failed",message:C instanceof Error?C.message:String(C)}),V.error(C);return}if(M.done)Z(),V.close();else V.enqueue(M.value)},async cancel(V){Z({reason:"cancelled",...V===void 0?{}:{message:String(V)}}),await Q.cancel(V)}})}function s2($,Z){for(let[Q,V]of Object.entries(Z)){let M=Q.toLowerCase();for(let C of Object.keys($))if(C.toLowerCase()===M)delete $[C];if(V!==null)$[Q]=V}}function a1($,Z){for(let[Q,V]of Object.entries(Z))if(V===null)$.delete(Q);else $.set(Q,V)}async function _0($,Z,Q={}){let{providerID:V}=Z,M=Q.gateOnPlaceholder,C=(j)=>M===void 0||M.credential(j)===R2(V),q=Q.logger,T=Math.max(1,Q.maxRecords??A0),H=[...Q.hostCredentials??[R2(V)],...M?[R2(V)]:[]].filter((j)=>j!==""),G=new Map,z=new WeakMap,K=new Map,_=0,L=new Set,S=new Map,O=new Map,b=(j)=>{let W=O.get(j);return W?.ownedSeen===!0&&W.foreignSeen},w=(j,W)=>{S.set(j,W);let F=O.get(j)??{ownedSeen:!1,foreignSeen:!1};if(W)F.ownedSeen=!0;else F.foreignSeen=!0;O.set(j,F)},f=(j,W)=>{let F=M?.refuseMisplaced,k=F?[...W].filter(([,p])=>p.includes(R2(V))):[],P=C(W)&&(!F||k.length>0);if(F){if(k.length>0&&(k.length!==1||!P))throw w(j.sessionID,!1),new f2({kind:"placement-refused",providerID:V,sessionID:j.sessionID,requestKind:j.kind,message:F(k[0]?.[0]??"")})}return w(j.sessionID,P),P},y=!1,n=!1,e=new Map,V2=0,j2=!1,$2=new Map,c=(j,W)=>{try{q?.warn(j,W)}catch{}},l=(j)=>j instanceof Error?j.message:String(j),s=new Map,Z2=(j,W)=>{let F=(s.get(j)??Promise.resolve()).then(W),k=F.then(()=>{},()=>{});return s.set(j,k),k.then(()=>{if(s.get(j)===k)s.delete(j)}),F},J=(j,W)=>{let F=s.get(j);return F?F.then(()=>J(j,W)):W()},X=async(j)=>{try{await Z.dropChoice?.({...j.input,accountId:j.accountId})}catch(W){c("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},B=async(j)=>{try{await Z.dropSameAccountRetry?.({...j.input,accountId:j.accountId})}catch(W){c("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},R=async(j)=>{if(j.next)await X(j.next);if(j.sameAccount)await B(j.sameAccount)},I=(j)=>{let W=K.get(j);if(K.delete(j),W)Z2(W.sessionID,()=>R(W))},A=async(j,W)=>{let F=e.get(j);if(!F||F.size===0)return;await Promise.all([...F].map(async(k)=>{try{await k(W)}catch(P){c("opencode2 auth listener threw; the request is unaffected",{event:j,error:l(P)})}}))},h=async(j,W)=>{try{await Z.onAttemptEnd?.(j,W)}catch(F){c("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:j.attemptId,error:l(F)})}},r=(j,W)=>{if(j.ended||!j.attempt)return;let F={...j.status===void 0?{}:{status:j.status},outputStarted:j.outputStarted,...j.limit?{limit:j.limit.signal}:{},...W?{error:W}:{}};if(W)j.endError=W;j.ended=h(j.attempt,F)},m=(j,W)=>r(j,{reason:"abandoned",message:W}),a=(j)=>[...G.values()].filter((W)=>W.key===j),W2=(j)=>a(j).at(-1),d=(j)=>{if(G.delete(j.id),K.get(j.key)?.attemptId===j.id||!a(j.key).length)I(j.key)},J2=(j)=>{G.set(j.id,j);while(G.size>T){let W=G.values().next().value;if(W===void 0)break;m(W,"dropped to keep the record bound"),d(W)}},u=(j)=>j.accountId===void 0?void 0:{...j.scope,accountId:j.accountId},Y=(j,W)=>new f2({kind:"no-account",providerID:V,sessionID:j.sessionID,requestKind:j.kind,...W===void 0?{}:{message:W}}),N=(j)=>{$2.get(j)?.clear(),$2.delete(j)},U=async(j,W)=>{let F=()=>Y(j,`${V} ${j.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw F();let k=$2.get(j.sessionID);if(!k)k=new Set,$2.set(j.sessionID,k);let P={};k.add(P);let p=()=>{if(!k.has(P))throw F()};try{return await W(p)}finally{if(k.delete(P),k.size===0&&$2.get(j.sessionID)===k)$2.delete(j.sessionID)}},E=(j,W)=>{for(let[F,k]of W)if(H.some((P)=>k.includes(P)))throw new f2({kind:"host-credential-on-wire",providerID:V,sessionID:j.sessionID,requestKind:j.kind,message:`${V} ${j.kind} request still carries the host's placeholder credential in ${F}; the adapter's account headers must replace it`})},x=(j)=>{for(let W of a(j))if(W.ended||!W.attempt)d(W);else if(W.transport==="ws"||W.judged)m(W,"a newer attempt of its session and kind began"),d(W)},v=async(j,W,F,k)=>{let P=D2(j.sessionID,j.kind),{input:p,accountId:D,sameAccountRetry:i}=await J(j.sessionID,async()=>{F();let M2=K.get(P);K.delete(P);let L2=M2?.accountId??W2(P)?.accountId;x(P);let H2=M2?.next,P2=M2?.sameAccount,U2=P2!==void 0&&P2.input.modelID===j.modelID&&P2.input.agent===j.agent,O2=H2!==void 0&&H2.input.modelID===j.modelID&&H2.input.agent===j.agent,E2={...j,phase:"request",...L2===void 0?{}:{previousAccountId:L2},...M2?.rerouteFrom?{rerouteFrom:M2.rerouteFrom}:{}};if(H2&&!O2)await Z2(j.sessionID,()=>X(H2)),F();if(P2&&!U2)await Z2(j.sessionID,()=>B(P2)),F();let q2=U2?P2.accountId:O2?H2.accountId:await Z.chooseAccount(E2);return{input:E2,accountId:typeof q2==="string"?q2:void 0,sameAccountRetry:U2}});F();let Q2={},C2;if(D!==void 0){let M2=await Z.accountHeaders({...j,accountId:D});if(F(),r1(M2))Q2=M2.headers,C2=M2.attempt;else Q2=M2}let n2=`attempt-${++V2}`,w2={id:n2,key:P,scope:j,accountId:D,headers:Q2,attempt:D===void 0?void 0:{...j,accountId:D,attemptId:n2,transport:k,data:C2},...k===void 0?{}:{transport:k},outputStarted:!1,sameAccountRetry:i};if(J2(w2),w2.attempt)A("select",{...j,accountId:w2.attempt.accountId,hook:W,...p.previousAccountId===void 0?{}:{previousAccountId:p.previousAccountId},...p.rerouteFrom===void 0?{}:{rerouteFrom:p.rerouteFrom},handle:w2.attempt});return w2},g=async(j,W,F,k,P)=>{let p=D2(j.sessionID,j.kind),D=k===void 0?void 0:G.get(k);if(D?.key!==p)D=void 0;if(!D){if(D=W2(p),a(p).filter((Q2)=>Q2.transport===void 0&&!Q2.ended).length>1&&!n)n=!0,c("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:j.sessionID,kind:j.kind})}if(!D||D.transport!==void 0||D.ended)D=await v(j,W,P,F);else if(D.transport=F,D.attempt)D.attempt.transport=F;if(F==="ws"){for(let i of a(p))if(i!==D&&i.transport==="ws")m(i,"a newer attempt of its session and kind went out over WebSocket")}return D},X2=async(j,W)=>{try{return await W()}catch(F){throw r(j,{reason:"failed",message:l(F)}),F}},o=(j,W)=>{let F=a(D2(j,W)).filter((k)=>k.transport==="ws").at(-1);return F?.attempt!==void 0&&!F.ended?F:void 0},B2=(j,W,F)=>{let k=u(j);if(!k||!j.attempt||j.limit)return;j.limit={signal:W,delivered:A("limit",{...k,via:F,limit:W,outputStarted:j.outputStarted,handle:j.attempt})}},N2=(j,W,F,k)=>{let P=u(j);if(!P||!j.attempt)return;A("quota",{...P,transport:W,...k===void 0?{}:{status:k},quota:F,handle:j.attempt})},_2=(j,W,F,k)=>{let P=j.attempt;if(!P)return;let p=Z.inspectEvent?.(k===void 0?{transport:W,data:F,attempt:P}:{transport:W,data:F,event:k,attempt:P});if(!p)return;if(p.quota!==void 0)N2(j,W,p.quota);if(p.outputStarted)j.outputStarted=!0;if(p.limit)B2(j,p.limit,W);if(p.error!==void 0)r(j,{reason:"failed",message:p.error});else if(p.done)r(j)},S2=(j,W)=>{let F=j.attempt;if(!F||W.accountId===j.accountId)return;if(F.reboundFrom??=F.accountId,F.accountId=W.accountId,"data"in W)F.data=W.data;j.accountId=W.accountId},Y2=(j)=>!j.attempt||j.endError!==void 0||j.status!==void 0&&j.status>=400,G2=(j)=>{let W=[...G.values()].filter((i)=>i.scope.sessionID===j),F=W.filter((i)=>i.limit&&!i.rerouted).at(-1);if(F)return F;let k=W.filter((i)=>i.scope.kind==="primary"),P=k.length>0?k:W;if(P.length<=1)return P[0];let p=P.filter((i)=>!i.judged&&Y2(i)).at(-1);if(p)return p;let D=P.filter((i)=>i.attempt&&!i.ended);if(D.length>1)return"ambiguous";return D[0]??P.at(-1)},z2={providerID:V},K2=[];K2.push(await $.session.hook("model.request",(j)=>{if(M)return;return U(x2(j),async(W)=>{let F=await v(x2(j),"model.request",W);if(W(),F.accountId===void 0)throw Y(F.scope);s2(j.headers,{...F.headers,[v2]:F.id})})},z2)),K2.push(await $.session.hook("http.request",(j)=>{if(M){if(!f(x2(j),j.request.headers))return}return U(x2(j),async(W)=>{let F=j.request.headers.get(v2)??void 0,k=M?await v(x2(j),"http.request",W,"http"):await g(x2(j),"http.request","http",F,W);W();let P=u(k),p=k.attempt;if(!P||!p)throw Y(k.scope);await X2(k,async()=>{let D=j.request;if(Z.rewriteRequest){if(F!==void 0){let C2=new Headers(D.headers);C2.delete(v2),D=new Request(D,{headers:C2})}D=await Z.rewriteRequest({...P,request:D,attempt:p})??D,W()}let i=new Headers(D.headers);i.delete(v2),a1(i,k.headers),E(k.scope,i.entries());let Q2=new Request(D,{headers:i});z.set(Q2,k),j.request=Q2})})},z2)),K2.push(await $.session.hook("http.response",async(j)=>{let W=z.get(j.request);if(!W){if(M)return;if(!y)y=!0,c("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:j.sessionID,kind:j.kind});return}let F=j.response;if(Z.answeredBy&&W.attempt){let i=W.attempt,Q2=await X2(W,async()=>Z.answeredBy?.({request:j.request,response:F,attempt:i}));if(Q2)S2(W,Q2)}let k=u(W),P=W.attempt;if(!k||!P)return;W.status=F.status;let p=Z.quotaFromHeaders?.(F.headers,F.status,P);if(p!==void 0)N2(W,"http",p,F.status);if(!F.ok&&Z.limitFromResponse){let i=await Z.limitFromResponse({status:F.status,headers:F.headers,body:()=>F.clone().text(),attempt:P});if(i)B2(W,i,"http")}if(!F.ok||!F.body)r(W);let D=F;if(F.body&&(Z.inspectEvent||Z.onAttemptEnd)){let i=F.body;if(Z.inspectEvent)i=i.pipeThrough(N0((Q2)=>_2(W,"http",Q2.data,Q2.event),(Q2)=>c("opencode2 auth event inspection threw",{error:l(Q2)})));D=new Response(s1(i,(Q2)=>r(W,Q2)),{status:F.status,statusText:F.statusText,headers:F.headers})}if(Z.rewriteResponse)D=await Z.rewriteResponse({...k,request:j.request,response:D,attempt:P})??D;if(D!==F)j.response=D},z2)),K2.push(await $.session.hook("experimental.ws.handshake",(j)=>{if(M){let W=D2(j.sessionID,j.kind);if(L.delete(W),!f(x2(j),new Headers(j.headers)))return}return U(x2(j),async(W)=>{let F;for(let D of Object.keys(j.headers)){if(D.toLowerCase()!==v2)continue;F??=j.headers[D],delete j.headers[D]}let k=M?await v(x2(j),"experimental.ws.handshake",W,"ws"):await g(x2(j),"experimental.ws.handshake","ws",F,W);W();let P=u(k),p=k.attempt;if(!P||!p)throw Y(k.scope);await X2(k,async()=>{if(!M?.refuseMisplaced)s2(j.headers,k.headers);let D=Z.rewriteHandshakeURL?.({...P,url:j.url,attempt:p});if(D!==void 0)j.url=D;if(M?.refuseMisplaced)s2(j.headers,k.headers);if(E(k.scope,Object.entries(j.headers)),M)L.add(k.key)})})},z2));let t=Z.rewriteWebSocketFrame?.bind(Z);if(t)K2.push(await $.session.hook("experimental.ws.send",async(j)=>{let W=x2(j);if(M&&!L.has(D2(W.sessionID,W.kind)))return;let F=o(W.sessionID,W.kind),k=await t({...W,attempt:F?.attempt,frame:j.frame});if(k!==void 0)j.frame=k},z2));K2.push(await $.session.hook("experimental.ws.receive",(j)=>{if(M&&!L.has(D2(j.sessionID,j.kind)))return;let W=o(j.sessionID,j.kind);if(!W)return;try{_2(W,"ws",j.frame)}catch(F){c("opencode2 auth frame inspection threw",{error:l(F)})}},z2)),K2.push(await $.session.hook("retry",async(j)=>{if(M&&S.get(j.sessionID)!==!0)return;let W=j.decision,F=()=>A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});if(b(j.sessionID)&&!Z.retrySameAccount){await F();return}let k=G2(j.sessionID);if(!k)return;if(k==="ambiguous"){await A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});return}let P=k;await U(P.scope,async(p)=>{let D=p,i=Z.retrySameAccount?.bind(Z),Q2=P.attempt;if(i&&Q2&&!P.outputStarted&&!P.sameAccountRetry){if(P.ended)await P.ended;if(P.limit)await P.limit.delivered;let M2=await Z2(P.scope.sessionID,async()=>{D();let L2=Q2.accountId,H2=()=>G.has(P.id)&&P.accountId===L2&&G2(j.sessionID)===P&&!P.outputStarted&&(!M||S.get(j.sessionID)===!0);if(!H2()||P.sameAccountRetry)return!1;P.sameAccountRetry=!0;let P2={...P.scope,accountId:L2,error:j.error,attempt:j.attempt,...P.limit?{limit:P.limit.signal}:{}},U2;try{U2=await i(P2)}catch(q2){c("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:j.sessionID,error:l(q2)})}if(!U2)return D(),!1;let O2={accountId:U2.accountId,input:P2};try{D()}catch(q2){throw await B(O2),q2}if(!H2()||U2.accountId!==L2)return await B(O2),!1;let E2=K.get(P.key);if(K.delete(P.key),E2)await R(E2);try{D()}catch(q2){throw await B(O2),q2}if(!H2())return await B(O2),!1;return K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:L2,sameAccount:O2}),P.judged=!0,j.decision={retry:!0,delay:0},!0});if(D(),M2){await A("retry",{sessionID:j.sessionID,accountId:P.accountId,kind:P.scope.kind,attempt:j.attempt,reason:"same-account",hostDecision:W,decision:j.decision,handle:P.attempt});return}}if(b(j.sessionID)){await F();return}P.judged=!0;let C2=P.attempt;if(C2&&!P.outputStarted){if(!P.limit){let M2=Z.limitFromError?.(j.error,C2);if(M2)B2(P,M2,"error")}if(P.ended)await P.ended;if(P.limit)await P.limit.delivered}D();let{decision:n2,reason:w2}=await Z2(P.scope.sessionID,async()=>{if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let M2=K.get(P.key);if(K.delete(P.key),M2)await R(M2);if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let L2=W,H2,P2,U2;if(P.accountId===void 0||!C2)L2={retry:!1},H2="no-account";else if(P.outputStarted)L2={retry:!1},H2="output-started";else if(P.limit){let O2={accountId:P.accountId,limit:P.limit.signal},E2,q2={...P.scope,phase:"retry",previousAccountId:P.accountId,rerouteFrom:O2};try{E2=await Z.chooseAccount(q2)}catch(K0){c("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:P.scope.sessionID,error:l(K0)})}let k2=typeof E2==="object"?E2.hold:void 0,r2=typeof E2==="string"?E2:k2?P.accountId:void 0;if(r2!==void 0)U2={accountId:r2,input:q2};try{D()}catch(K0){if(U2)await X(U2);throw K0}if(b(j.sessionID)){if(U2)await X(U2);return{decision:W,reason:"host-decides"}}if(k2&&Number.isFinite(k2.delayMs)&&k2.delayMs>=0)L2={retry:!0,delay:Math.min(k2.delayMs,w0)},H2="hold";else if(!k2&&r2!==void 0&&r2!==P.accountId)P.rerouted=!0,P2=O2,L2={retry:!0,delay:0},H2="reroute";else{if(k2&&U2)await X(U2),U2=void 0;H2="host-decides-last-account"}}else H2="host-decides";if(j.decision=L2,L2.retry&&P.accountId!==void 0&&G.has(P.id))K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:P.accountId,...P2===void 0?{}:{rerouteFrom:P2},...U2===void 0?{}:{next:U2}});else if(U2)await X(U2);return{decision:L2,reason:H2}});D(),await A("retry",{sessionID:j.sessionID,...P.accountId===void 0?{}:{accountId:P.accountId},kind:P.scope.kind,attempt:j.attempt,reason:w2,hostDecision:W,decision:n2,...C2===void 0?{}:{handle:C2}})})},z2));let T2=(j)=>{if(N(j),S.delete(j),!O.get(j)?.foreignSeen)O.delete(j);for(let W of L)if(JSON.parse(W)[0]===j)L.delete(W);for(let W of[...G.values()]){if(W.scope.sessionID!==j)continue;m(W,"its session was forgotten"),G.delete(W.id)}for(let[W,F]of K)if(F.sessionID===j)I(W)},F2=new AbortController,o2=$.event;if(o2)(async()=>{try{for await(let j of o2.subscribe({signal:F2.signal}))if(j.type==="session.deleted")T2(j.data.sessionID);else if(j.type==="session.status"&&j.data.status.type==="idle"){let W=j.data.sessionID,F=++_;Z2(W,async()=>{for(let[k,P]of K)if(P.sessionID===W&&P.order<F)K.delete(k),await R(P)})}}catch(j){if(!F2.signal.aborted)c("opencode2 auth stopped listening for session deletion",{error:l(j)})}})();return{on(j,W){let F=e.get(j);if(!F)F=new Set,e.set(j,F);let k=W;return F.add(k),()=>{F.delete(k)}},accountFor(j,W){return W2(D2(j,W))?.accountId},forgetSession:T2,get size(){return G.size},async dispose(){if(j2)return;j2=!0;for(let j of $2.keys())N(j);F2.abort();for(let j of G.values())m(j,"the installation was disposed");G.clear();for(let j of K.keys())I(j);L.clear(),S.clear(),O.clear(),e.clear(),await Promise.all(s.values()),await Promise.all(K2.map(async(j)=>{try{await j.dispose()}catch(W){c("opencode2 auth hook did not dispose cleanly",{error:l(W)})}}))}}}import{createHash as t1}from"node:crypto";import{AnthropicOAuthOriginError as e1,applyCustomHeaders as $4,assertNotCustodyTombstone as Z4,classifyGzipRejection as j4,createProviderErrorRedactor as D0,createProviderErrorResponseScope as I0,decideRequestGzip as J4,dumpDirectRequest as y0,dumpRelayRequest as f0,dumpResponseArtifact as a2,encodeGzipRequestBody as X4,getAccountStoragePath as G4,getRequestGzipLatch as Y4,getRequestGzipLatchPath as V4,isDumpEnabled as Q4,mergeAnthropicBetas as W4,remapModelId as v0,remapRequestBodyModel as U4,setDumpEnabled as g0,stateRefusalCause as B4,stateRefusalPublicMessage as z4,stripEmptyTrailingAssistantMessages as K4,TrailingAssistantHistoryError as M4}from"@cortexkit/anthropic-auth-core";var g2="anthropic",r0="x-common-auth-attempt",H4=["x-session-affinity","x-opencode-session","x-parent-session-id",m0,e2,y2,r0],t2=new Set(["authorization","x-api-key"]),N4="physical send before a response",_4="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",L4=512,F4=5000,P4=500,s0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),L0=($,Z="provider request failed")=>({type:s0.has($.type)?$.type:"provider_error",message:Z,...$.status!==void 0?{status:$.status}:{}});class a0 extends Error{sessionID;requestKind;kind="no-account";providerID=g2;constructor($,Z){super(_4);this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicNoAccountError"}}class T0 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=g2;constructor($,Z){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicRevokedError"}}class b2 extends Error{kind="unsupported-transport";providerID=g2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class t0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class e0 extends Error{kind="state-relocated";providerID=g2;constructor($){super(z4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function $0($){let Z=B4($);return Z?new e0(Z):void 0}var I2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function d2($){try{return JSON.parse($)}catch{return}}function F0($){let Z={};for(let[Q,V]of Object.entries($??{}))Z[Q.toLowerCase()]=V;return Z}function h0($){let Z={};for(let Q of H4){let V=$.get(Q);if(V!==null&&Q!==r0)Z[Q]=V;$.delete(Q)}return Z}function T4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function C4($){return $ instanceof M4||$ instanceof l0||$ instanceof e1?new t0($):void 0}function O4($,Z){let Q=[];if($.oauth)Q.push($.oauth.accessToken);for(let[V,M]of Object.entries($.apiHeaders??{})){if(M===null||!t2.has(V))continue;Q.push(M.replace(/^Bearer\s+/i,""))}for(let V of t2){let M=Z.get(V);if(M!==null)Q.push(M.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")Q.push($.dispatch.token);return[...new Set(Q.filter(Boolean))]}var E4=new Set(["oauth-2025-04-20","claude-code-20250219",p0]);function q4($){let Z=$.split(",").map((Q)=>Q.trim()).filter((Q)=>Q&&!E4.has(Q));return W4(null,Z)}function x4($){let Z=d2($);if(!I2(Z))return $;let Q=K4(Z.messages),V=Object.hasOwn(Z,"fallbacks"),{droppedMarkers:M}=c0(Z,!1),C=V&&!Object.hasOwn(Z,"fallbacks"),q=U4(Z);return Q>0||M>0||C||q?JSON.stringify(Z):$}async function S4($,Z){if(!($ instanceof Promise))return"settled";let Q;try{return await Promise.race([$.then(()=>"settled"),new Promise((V)=>{Q=setTimeout(()=>V("timed-out"),Z)})])}finally{if(Q!==void 0)clearTimeout(Q)}}function h2($){let{source:Z,log:Q}=$,V=Math.max(1,$.maxPendingSends??L4),M=$.attemptEndTimeoutMs??F4,C=$.requestGzipLatch??Y4(V4(G4())),q=new WeakSet,T=new Map,H=new WeakMap,G=new WeakMap,z=(Y)=>JSON.stringify([Y.providerID,Y.sessionID,Y.kind,Y.modelID,Y.agent,Y.accountId]),K=new Map,_=new WeakMap,L=new Map,S=new WeakMap,O=D0([]);O.dispose();let b=(Y)=>(Y&&L.get(Y)?.redactor)??O,w=(Y)=>{let N=L.get(Y);if(!N)return;L.delete(Y),N.redactor.dispose(),N.scope.dispose()},f=(Y,N,U,E)=>{let x=O4(N,E),v=I0(x,U);y.set(Y,U),L.set(Y,{sessionID:N.sessionID,redactor:D0(x),scope:v}),v.settled.then(()=>w(Y));while(L.size>V){let g=L.keys().next().value;if(g===void 0)break;w(g)}},y=new WeakMap,n=(Y,N)=>{let U=Y?y.get(Y):void 0;if(!U||!N.ok)return O.redactResponse(N);let E=I0([],U),x=E.redactResponse(N);return E.dispose(),x},e=(Y,N)=>{let U=Y?L.get(Y)?.scope:void 0;if(!U)return n(Y,N);try{return U.redactResponse(N)}catch{return n(Y,N)}},V2=!1,j2=new Map,$2=new WeakMap,c=new WeakMap,l=new WeakMap,s=(Y)=>Y.agent==="cachekeep"||Y.agent==="prime",Z2=async()=>{try{if(Z.isDumpEnabled)return await Z.isDumpEnabled()}catch{return!1}try{return Q4()}catch{return!1}},J=(Y)=>{j2.delete(Y)},X=new WeakMap,B=(Y,N)=>{if(Y&&!N.ok)X.set(N.headers,Y);return N},R=(Y,N)=>{if(N.dispatch!=="http-relay")return!0;let U=/^req_[A-Za-z0-9_-]+$/.test(Y.get("request-id")??"");return G.set(N,U),U},I=(Y)=>new a0(Y.sessionID,Y.kind),A=new Map,h=async(Y,N)=>{if(V2)throw new T0(Y.sessionID,Y.kind);let U={revoked:!1},E=A.get(Y.sessionID);if(!E)E=new Set,A.set(Y.sessionID,E);E.add(U);let x=()=>{if(V2||U.revoked)throw new T0(Y.sessionID,Y.kind)};try{let v=await N(x);return x(),v}finally{let v=A.get(Y.sessionID);if(v?.delete(U)&&v.size===0)A.delete(Y.sessionID)}},r=(Y,N)=>{T.set(Y,N);while(T.size>V){let U=T.keys().next().value;if(U===void 0)break;T.delete(U),Q?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:V})}},m=(Y,N)=>({providerID:Y.providerID,modelID:Y.modelID,sessionID:Y.sessionID,agent:Y.agent,kind:Y.kind,accountId:Y.accountId,attemptId:Y.attemptId,transport:Y.transport,route:N.route,provenance:N.provenance,dispatch:N.dispatch}),a=(Y)=>h(Y,async(N)=>{let{accountId:U,...E}=Y,x;try{x=await Z.authorizeAccount(E,U)}catch(v){let g=$0(v);if(g)throw Q?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:g.cause instanceof Error?g.cause.name:""}),g;throw v}return N(),W2(E,x)}),W2=(Y,N)=>{if(!N)throw I(Y);if(N.dispatch?.kind==="websocket-relay")throw new b2;let U=N.dispatch?.kind==="http-relay"?"http-relay":"direct",E=N.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":N.dispatch.token}:void 0;if(N.route==="oauth"){if(!N.accessToken)throw I(Y);Z4(N.accessToken,g2);let g=Object.freeze({route:"oauth",provenance:N.provenance,dispatch:U});r(g,{sessionID:Y.sessionID,oauth:{accessToken:N.accessToken,...N.identity?{identity:N.identity}:{}},dispatch:N.dispatch,oauthHeaders:N.headers});let X2=F0(N.headers);for(let o of t2)delete X2[o];return delete X2["anthropic-beta"],{headers:E??{...X2,"x-api-key":null,authorization:`Bearer ${N.accessToken}`},attempt:g}}let x={authorization:null,"x-api-key":null,...F0(N.headers)};if(!x.authorization&&!x["x-api-key"])throw I(Y);let v=Object.freeze({route:"api",provenance:N.provenance,dispatch:U});return r(v,{sessionID:Y.sessionID,...N.baseURL?{baseURL:N.baseURL}:{},dispatch:N.dispatch,apiHeaders:x}),{headers:E??x,attempt:v}},d=(Y)=>h(Y,(N)=>J2(Y,N)),J2=async(Y,N)=>{let{request:U,attempt:E}=Y,x=E.data;K.set(z(Y),E);while(K.size>V){let Y2=K.keys().next();if(!Y2.done)K.delete(Y2.value)}let v=x?T.get(x):void 0;if(x)T.delete(x);if(!x||!v||x.route==="oauth"&&!v.oauth)throw I(Y);let g=new Headers(U.headers);$4(g);let X2=h0(g),o=U.body===null?void 0:await U.text();N();let B2=o!==void 0&&T4(U.url),N2=o0(U.url,v.baseURL!==void 0?{baseURL:v.baseURL}:{}).url?.toString()??U.url;try{if(x.route==="oauth"&&v.oauth){d0(N2);let{accessToken:Y2,identity:G2}=v.oauth;for(let[K2,t]of Object.entries(F0(v.oauthHeaders))){if(t2.has(K2))continue;if(t===null)g.delete(K2);else g.set(K2,t)}let z2=null;if(o!==void 0&&B2){let K2={...m(E,x),modelID:(()=>{let F2=d2(o);return v0(I2(F2)&&typeof F2.model==="string"?F2.model:Y.modelID)})(),route:"oauth",correlation:X2},t=await Z.requestOptions?.(K2)??{};if(N(),E.agent!=="cachekeep")o=await n0(o,{...t,...G2?{identity:G2}:{},sessionId:Y.sessionID,onToolNameMap:(F2)=>_.set(x,F2)});let T2=d2(o);z2=I2(T2)?T2:null}i0(g,Y2,{body:z2,...G2?{identity:G2}:{},requestClass:u0(E.agent)?"auxiliary":"main"})}else{if(o!==void 0&&B2)o=x4(o);g.delete("authorization"),g.delete("x-api-key");for(let[G2,z2]of Object.entries(v.apiHeaders??{}))if(z2===null)g.delete(G2);else g.set(G2,z2);if(o!==void 0&&B2&&!g.has("content-type"))g.set("content-type","application/json");let Y2=g.get("anthropic-beta");if(Y2!==null){let G2=q4(Y2);if(G2)g.set("anthropic-beta",G2);else g.delete("anthropic-beta")}}}catch(Y2){let G2=C4(Y2);if(!G2)throw Y2;throw H.set(x,G2.check),Q?.warn("refused an Anthropic request locally; nothing was sent",{check:G2.check}),G2}let _2=o!==void 0?d2(o):void 0;if(await Z.admitRequest?.({...m(E,x),modelID:v0(I2(_2)&&typeof _2.model==="string"?_2.model:Y.modelID)}),h0(g),o!==void 0)g.delete("content-length");if(N(),f(x,v,I2(_2)&&_2.stream===!0?"event-stream":"http",g),x.route==="oauth"&&B2&&o!==void 0)await Z.onRequestPrepared?.({...m(E,x),url:N2,bodyText:o}),N();if(v.dispatch?.kind==="http-relay"){let Y2=o??"";g.delete("x-relay-token");let G2={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:N2,method:U.method,headers:Object.fromEntries(g)},mode:"full_sync",revision:1,body:Y2,next_hash:`sha256:${t1("sha256").update(Y2).digest("hex")}`};if(B2&&o!==void 0&&!s(E)){let z2=X2[y2]==="1"?"start":void 0,K2=JSON.stringify(G2);j2.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:Y2,url:N2,method:U.method,headers:new Headers(g),dispatch:"http-relay",relayUrl:v.dispatch.url,envelope:G2,relayBytes:K2.length,...z2?{tag:z2}:{}})}else J(x);return new Request(v.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":v.dispatch.token},redirect:"error",signal:U.signal,body:JSON.stringify(G2)})}let S2=o;if(x.route==="oauth"&&B2&&o!==void 0){let Y2=await J4({url:N2,body:o,latch:C});if(N(),Y2.gzip)S2=await X4(o),g.set("content-encoding","gzip"),q.add(x),N()}if(B2&&o!==void 0&&!s(E)){let Y2=X2[y2]==="1"?"start":void 0;j2.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:o,url:N2,method:U.method,headers:new Headers(g),dispatch:"direct",...Y2?{tag:Y2}:{}})}else J(x);return new Request(N2,{method:U.method,headers:g,redirect:x.route==="oauth"?"error":U.redirect,signal:U.signal,...S2!==void 0?{body:S2}:{}})},u={providerID:g2,chooseAccount:(Y)=>h(Y,async()=>{let N=await Z.chooseAccount(Y);if(typeof N==="object"&&Y.phase==="retry")return N;if(typeof N!=="string"||!N)throw I(Y);return N}),dropChoice:(Y)=>Z.dropChoice?.(Y),async retrySameAccount(Y){if(!Z.retrySameAccount)return;let N=z(Y),U=K.get(N);K.delete(N);let E=Y.limit??(U?u.limitFromError?.(Y.error,U):void 0);return Z.retrySameAccount({...Y,error:L0(Y.error),...E?{limit:E}:{}})},dropSameAccountRetry:(Y)=>Z.dropSameAccountRetry?.({...Y,error:L0(Y.error)}),accountHeaders:a,rewriteRequest:d,rewriteHandshakeURL(){throw new b2},async rewriteResponse({response:Y,attempt:N}){let U=N.data;if(U&&!R(Y.headers,U)){if(U)J(U);if(Y.status===401)return w(U),Y.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return e(U,Y)}if(U&&q.has(U))q.delete(U),j4(Y).then((t)=>{if(!t)return;C.latchProcess(),Q?.warn("gzipped request body rejected; later requests go uncompressed",{kind:t,status:Y.status})},()=>{});let E=null,x=U?j2.get(U):void 0;if(U&&x){let t=!1;try{t=await Z2()}catch{t=!1}if(!t)J(U);else{try{g0(!0)}catch{}try{if(x.dispatch==="http-relay")E=await f0({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:Y.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}});else E=await y0({affinity:x.affinity,route:x.route,status:Y.status,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{E=null}if(J(U),E){$2.set(U,E);try{await a2(E,{status:Y.status,message:null,complete:!1})}catch{}l.set(U,Promise.resolve())}}}let v=e(U,Y);if(U?.route!=="oauth"||!v.body)return B(U,v);let g={...m(N,U),status:Y.status},X2=Z.responseOptions?.(g)??{},o=(Y.headers.get("content-type")??"").includes("application/json"),B2={...X2,toolNameMap:U?_.get(U):void 0,onToolNameRefusal:()=>{if(!U)return;H.set(U,"response_tool_names"),w(U)},laneStartOAuthServed:!0,...o?{responseMode:"json"}:{}};if(!U||!E)return B(U,P0(v,B2));let N2=E,_2=Y.status,S2=(t)=>{let F2=(l.get(U)??Promise.resolve()).then(()=>t().then(()=>{return})).catch(()=>{return});l.set(U,F2)},Y2=X2.onMessageStart,G2=X2.onMessageDelta,z2=X2.onMessageResponse,K2=X2.onStreamEnd;return B(U,P0(v,{...B2,onMessageStart:(t)=>{try{Y2?.(t)}catch{}try{c.set(U,{...t}),S2(()=>a2(N2,{status:_2,message:t,complete:!1}))}catch{}},onMessageDelta:(t)=>{try{G2?.(t)}catch{}try{let T2=c.get(U)??{},F2=T2.usage&&typeof T2.usage==="object"&&!Array.isArray(T2.usage)?T2.usage:{},o2={...T2,...t.usage?{usage:{...F2,...t.usage}}:{},...t.stopReason?{stop_reason:t.stopReason}:{}};S2(()=>a2(N2,{status:_2,message:o2,complete:!0}))}catch{}},onMessageResponse:(t)=>{try{z2?.(t)}catch{}try{S2(()=>a2(N2,{status:_2,message:t,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await K2?.()}catch{}try{await(l.get(U)??Promise.resolve())}catch{}}}))},quotaFromHeaders(Y,N,U){let E=U.data;if(!E||!R(Y,E))return;return Z.quotaFromHeaders?.(Y,{...m(U,E),status:N})},async limitFromResponse({status:Y,headers:N,body:U,attempt:E}){let x=E.data;if(!x||H.get(x)==="response_tool_names")return;if(!R(N,x))return Z.limitFromRelayFailure?.({...m(E,x),status:Y});if(S.set(x,`provider responded with HTTP ${Y}`),!Z.limitFromResponse)return;let v=X.get(N)===x,g=b(x);return Z.limitFromResponse({...m(E,x),status:Y,headers:N,body:async()=>v?await U():g.redactText(await U())})},inspectEvent({data:Y,event:N,attempt:U}){if(U.data&&H.get(U.data)==="response_tool_names")return;let E=d2(Y);if(!I2(E))return;let x=typeof E.type==="string"?E.type:N;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let v=U.data,g=b(v),X2=I2(E.error)?E.error:{},o=typeof X2.type!=="string"?void 0:s0.has(X2.type)?X2.type:g.redactText(X2.type),B2=typeof X2.message==="string"?g.redactText(X2.message):void 0;if(v?.dispatch==="http-relay"&&G.get(v)===!1)return;let N2=v?Z.limitFromStreamError?.({...m(U,v),errorType:o,message:B2}):void 0,_2={error:[o??"error",B2].filter(Boolean).join(": ").slice(0,P4),...N2?{limit:N2}:{}};if(v&&_2.error)S.set(v,_2.error);return _2},limitFromError(Y,N){let U=N.data;if(!U||H.has(U))return;let E=L0(Y,S.get(U));if(w(U),U.dispatch==="http-relay"&&G.get(U)===!1)return;return Z.limitFromHostError?.(E,m(N,U))},async onAttemptEnd(Y,N){let U=Y.data;if(!U)return;T.delete(U);let E=j2.get(U);if(E){J(U);try{if(await Z2()){try{g0(!0)}catch{}try{if(E.dispatch==="http-relay"){if(N.status!==void 0)await f0({affinity:E.affinity,transport:"http",protocol:1,mode:"full_sync",status:N.status,bodyText:E.bodyText,payload:E.envelope??{},relayBytes:E.relayBytes??0,...E.tag?{tag:E.tag}:{}})}else await y0({affinity:E.affinity,route:E.route,status:N.status,error:N.status===void 0?N4:void 0,bodyText:E.bodyText,url:E.url,method:E.method,headers:E.headers,...E.tag?{tag:E.tag}:{}})}catch{}}}catch{}}let x=N.error?.reason;if(x==="cancelled"||x==="abandoned"||x===void 0&&(N.status===void 0||N.status<400))w(U);let v=H.get(U),{status:g,...X2}=N,o=Z.onAttemptEnd?.(m(Y,U),{...X2,...g!==void 0&&(U.dispatch!=="http-relay"||G.get(U)===!0)?{status:g}:{},...v!==void 0?{localRefusal:{check:v}}:{}});if(await S4(o,M)==="timed-out")Q?.warn("the account source did not finish recording a send",{timeoutMs:M})}};return{adapter:u,dispose(){V2=!0;for(let[Y,N]of A){for(let U of N)U.revoked=!0;Z.forgetSession?.(Y)}A.clear(),T.clear(),K.clear(),j2.clear();for(let Y of[...L.keys()])w(Y)},forgetSession(Y){for(let N of A.get(Y)??[])N.revoked=!0;A.delete(Y);for(let[N,U]of K)if(U.sessionID===Y)K.delete(N);for(let[N,U]of T)if(U.sessionID===Y)T.delete(N);for(let[N,U]of[...L])if(U.sessionID===Y)w(N);for(let[N,U]of[...j2])if(U.affinity===Y)j2.delete(N);Z.forgetSession?.(Y)},get pendingSendCount(){return T.size},get heldCredentialCount(){let Y=0;for(let N of T.values())if(N.oauth)Y++;return Y},get heldRedactorCount(){return L.size},get operationsInProgress(){let Y=0;for(let N of A.values())Y+=N.size;return Y}}}import{setTimeout as o4}from"node:timers/promises";import{CacheKeepManager as n4,CacheKeepSessionRegistry as r4,getDefaultCacheKeepRegistryDirectory as s4,isCacheKeepActiveNow as W1,isCacheKeepHybridActive as p2,isCacheKeepSubagentsEnabled as J0,logger as X0,NativeAccountRefusal as A2,nativeAccountCanServe as B1,nativeAccountRefusal as a4}from"@cortexkit/anthropic-auth-core";import{createHash as R4,randomUUID as b4}from"node:crypto";import{constants as $1}from"node:fs";import{lstat as Z1,mkdir as A4,open as w4,readdir as j1,rm as Z0,writeFile as D4}from"node:fs/promises";import{tmpdir as I4}from"node:os";import{join as u2}from"node:path";import{promisify as Y1}from"node:util";import{gunzip as y4,gzip as f4}from"node:zlib";import{CACHE_KEEP_MAX_BODY_BYTES as V1,createWindowsOwnerOnly as v4,ensureWindowsOwnerOnlyDirectory as g4,isOwnerOnly as J1,logger as h4,readWindowsOwnerOnly as m4,renameWithWindowsSharingRetry as l4}from"@cortexkit/anthropic-auth-core";var C0="2.4.8";var d4=Y1(f4),u4=Y1(y4),j0=($)=>R4("sha256").update($).digest("hex"),X1=/^[a-f0-9]{64}\.json\.gz$/,O0=/^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/,G1=2*V1+65536;function p4($,Z=I4()){return u2(Z,`cortexkit-anthropic-auth-cachekeep-${j0($).slice(0,16)}`)}function c4($){return{v:1,pluginVersion:C0,id:$.id,bodyText:$.bodyText,url:$.url,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt,oauthAccountIdentity:$.oauthAccountIdentity,isSubagent:$.isSubagent}}function Q1($){let Z=JSON.parse($);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid restart body");let Q=!1;for(let V of Object.keys(Z))if(/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(V))delete Z[V],Q=!0;return Q?JSON.stringify(Z):$}function i4($,Z,Q){if(!$||typeof $!=="object"||Array.isArray($))return!1;if($.v!==1||$.pluginVersion!==C0||typeof $.id!=="string"||!$.id||`${j0($.id)}.json.gz`!==Z||typeof $.bodyText!=="string"||Buffer.byteLength($.bodyText)>V1||typeof $.url!=="string"||typeof $.oauthAccountIdentity!=="string"||!$.oauthAccountIdentity||typeof $.isSubagent!=="boolean"||!Number.isFinite($.cacheExpiresAt)||$.cacheExpiresAt<=Q||!Number.isFinite($.nextPrewarmAt))return!1;return Q1($.bodyText)===$.bodyText}class E0{options;directory;disabled=!1;chain=Promise.resolve();pending=new Map;timers=new Map;lastWrite=new Map;latest=new Map;constructor($){this.options=$;this.directory=p4($.storageId,$.root)}refuse(){if(this.disabled)return;this.disabled=!0;for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),h4.warn("cachekeep","restart storage unavailable; retaining sessions in memory only")}async directoryReady(){if(this.disabled)return!1;try{if(!await g4(this.directory,this.options.ownerOnly))try{await A4(this.directory,{mode:448})}catch(Z){if(Z.code!=="EEXIST")throw Z}let $=await Z1(this.directory);if(!$.isDirectory()||$.isSymbolicLink()||!await J1(this.directory,()=>$.uid===process.getuid?.()&&($.mode&511)===448,this.options.ownerOnly))throw Error("Unsafe restart directory");return!0}catch{return this.refuse(),!1}}enqueue($){this.chain=this.chain.then(async()=>{if(await this.directoryReady())await $()}).catch(()=>this.refuse())}async load($,Z){if(!await this.directoryReady())return;try{for(let Q of(await j1(this.directory)).sort()){if(!X1.test(Q)&&!O0.test(Q))continue;let V=u2(this.directory,Q);try{if(O0.test(Q))throw Error("Unfinished write");let M=await Z1(V);if(!M.isFile()||M.isSymbolicLink()||M.size>G1||!await J1(V,()=>M.uid===process.getuid?.()&&(M.mode&511)===384,this.options.ownerOnly))throw Error("Unsafe restart file");let C=await m4(V,this.options.ownerOnly);if(!C){let H=await w4(V,$1.O_RDONLY|$1.O_NOFOLLOW);try{C=await H.readFile()}finally{await H.close()}}let q=await u4(C,{maxOutputLength:G1}),T=JSON.parse(q.toString("utf8"));if(!i4(T,Q,$)||!Z(T))throw Error("Stale restart file")}catch{await Z0(V,{force:!0})}}}catch{this.refuse()}}changed($){if(this.disabled)return;let Z=c4($),Q=this.latest.get(Z.id);if(Q&&Q.bodyText===Z.bodyText&&Q.url===Z.url&&Q.oauthAccountIdentity===Z.oauthAccountIdentity&&Q.cacheExpiresAt===Z.cacheExpiresAt&&Q.nextPrewarmAt===Z.nextPrewarmAt&&Q.isSubagent===Z.isSubagent)return;if(this.latest.set(Z.id,Z),this.pending.set(Z.id,Z),this.timers.has(Z.id))return;let V=Math.max(250,(this.lastWrite.get(Z.id)??0)+5000-(this.options.now?.()??Date.now())),M=(this.options.setTimeoutImpl??setTimeout)(()=>this.flush(Z.id),V);M.unref?.(),this.timers.set(Z.id,M)}flush($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($);let Q=this.pending.get($);if(this.pending.delete($),!Q)return this.chain;return this.lastWrite.set($,this.options.now?.()??Date.now()),this.enqueue(async()=>{let V=u2(this.directory,`${j0($)}.json.gz`),M=`${V}.${b4()}.tmp`;try{let C={...Q,bodyText:Q1(Q.bodyText)},q=await d4(JSON.stringify(C));if(!await v4(M,q,this.options.ownerOnly))await D4(M,q,{flag:"wx",mode:384});await l4(M,V,{platform:this.options.ownerOnly?.platform})}finally{await Z0(M,{force:!0})}}),this.chain}removed($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($),this.pending.delete($),this.latest.delete($),this.lastWrite.delete($),this.enqueue(()=>Z0(u2(this.directory,`${j0($)}.json.gz`),{force:!0}))}clear(){for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),this.enqueue(async()=>{for(let $ of await j1(this.directory))if(X1.test($)||O0.test($))await Z0(u2(this.directory,$),{force:!0})})}async drain(){for(let $ of this.pending.keys())this.flush($);await this.chain}}function m2($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}var U1=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function z1(){let $=globalThis;return $[U1]??=new Map,$[U1]}function t4($,Z){let Q=new Map,V=new Map,M=new E0({storageId:$,...Z.persistence}),C=new Set,q=0,T=new r4({directory:Z.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||s4("opencode"),now:Z.now}),H=()=>{let O;for(let b of V.values())O=b;return O},G=Z.setIntervalImpl??globalThis.setInterval,z=new n4({loadStorage:async()=>{let O=H(),b=O?await O.loadStorage():null;if(O&&!p2(b)){for(let w of z.trackedSessions())z.untrack(w.id);M.clear()}return b},now:Z.now,setIntervalImpl:(O,b)=>G(()=>{let w=z.tick();return S.ticking=w.catch(()=>{X0.warn("cachekeep","tick failed")}),S.ticking},b),clearIntervalImpl:Z.clearIntervalImpl,onTargetChanged:(O)=>M.changed(O),onTargetRemoved:(O)=>{C.delete(O),M.removed(O)},onTrackedSessionsChanged:(O)=>T.publish(V.size===0?[]:O),prepareHeaders(O,b,w){let f=H();if(!f)return;return Q.set(w.id,{target:b,attempt:w,lease:f}),new Headers({"x-native-cachekeep-attempt":String(w.id)})},fetchImpl:async(O,b)=>{let w=new Request(O,b),f=Number(w.headers.get("x-native-cachekeep-attempt")),y=Q.get(f);if(Q.delete(f),!y||y.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(C.delete(y.target.id))await o4(Math.max(0,q+3000-Date.now()),void 0,{signal:y.attempt.signal}),q=Date.now();let n=y.lease.send(y.target,w,y.attempt.signal),e=n.then(()=>{},()=>{});return y.lease.inflight.add(e),e.then(()=>y.lease.inflight.delete(e)),n},onComplete:({attempt:O})=>{Q.delete(O.id)}}),K,_=()=>{if(K!==void 0)clearTimeout(K);K=void 0},L=()=>{if(_(),V.size>0)return;let O=z.dropExpiredTargets();if(O===void 0){let w=z1();if(w.get($)===S)w.delete($);return}let b=Z.now?.()??Date.now();if(K=setTimeout(L,Math.max(0,O-b)),typeof K==="object"&&"unref"in K)K.unref()},S={manager:z,registry:T,persistence:M,prepared:Q,leases:V,nextGeneration:0,retain(){z.stop(),Q.clear(),L()},async adopt(){if(_(),S.loading??=(async()=>{let O=H();if(!O)return;let b=await O.read();if(!p2(b.policyStorage)){M.clear();return}let w=Z.now?.()??Date.now(),f=0;await M.load(w,(y)=>{if(!V.size||z.trackedRequest(y.id))return!0;let n=b.accounts.find((j2)=>m2(j2)===y.oauthAccountIdentity);if(n?.type!=="oauth"||!B1(n)||y.isSubagent&&!J0(b.policyStorage))return!1;let e=y.nextPrewarmAt<=w?w+f++*3000:y.nextPrewarmAt,V2=z.track({sessionId:y.id,url:y.url,headers:new Headers,bodyText:y.bodyText,storage:b.policyStorage,cacheMode:"hybrid",oauthAccountId:n.id,oauthAccountIdentity:y.oauthAccountIdentity,isSubagent:y.isSubagent,retained:{cacheExpiresAt:y.cacheExpiresAt,nextPrewarmAt:e}});if(V2.tracked)C.add(y.id);return V2.tracked})})().catch(()=>{X0.warn("cachekeep","failed to restore tracked sessions")}),await S.loading,!V.size)return;if(z.dropExpiredTargets()===void 0)return;z.start(),T.publish(z.trackedSessions()).catch(()=>{X0.warn("cachekeep","failed to publish tracked sessions")})}};return S}function K1($){let{runtime:Z,source:Q}=$,V=new AbortController,M=z1(),C=M.get($.storageId)??t4($.storageId,$);M.set($.storageId,C);let{manager:q,registry:T}=C,H=async(L,S,O)=>{let b=O?AbortSignal.any([V.signal,O]):V.signal;b.throwIfAborted();let w=JSON.parse(await S.text()),f={providerID:"anthropic",modelID:w.model,sessionID:`oc2-cachekeep:${L.id}`,agent:"cachekeep",kind:"generate"},y=(c)=>{throw new A2(c)},n=h2({source:{...Q,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(c){return{...await Q.requestOptions?.(c,y),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(c,l){let s=await Z.read();b.throwIfAborted();let Z2=s.accounts.find((X)=>X.id===l);if(Z2?.type!=="oauth"||!B1(Z2))throw new A2("account-unavailable");if(m2(Z2)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!J0(s.policyStorage)||!p2(s.policyStorage)||!W1(s.policyStorage,new Date($.now?.()??Date.now())))return;let J=await Q.authorizeAccount(c,l,y);if(J?.provenance.kind==="local"&&m2({...Z2,binding:J.provenance.subject.binding,accountIdentity:J.provenance.subject.binding.identity})!==L.oauthAccountIdentity)throw new A2("credential-changed");if(J?.provenance.kind==="vault"&&J.provenance.credentialId!==Z2.credentialId)throw new A2("credential-changed");return J},async admitRequest(c){await Q.admitRequest?.(c,y);let l=await Z.read(),s=l.accounts.find((Z2)=>Z2.id===c.accountId);if(b.throwIfAborted(),!s)throw new A2("account-unavailable");if(m2(s)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!J0(l.policyStorage)||!p2(l.policyStorage)||!W1(l.policyStorage,new Date($.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),e,V2,j2=!1,$2=()=>n.forgetSession(f.sessionID);b.addEventListener("abort",$2,{once:!0});try{let c=await Z.read(),l=c.accounts.find((R)=>m2(R)===L.oauthAccountIdentity)?.id;if(!l)throw new A2(c.accounts.some((R)=>R.id===L.oauthAccountId)?"credential-changed":"account-unavailable");let s=await n.adapter.accountHeaders({...f,accountId:l});if(!("headers"in s)||typeof s.headers!=="object"||s.headers===null||typeof s.attempt!=="object"||s.attempt===null||s.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");e={...f,accountId:l,attemptId:crypto.randomUUID(),transport:"http",data:s.attempt};let Z2=await n.adapter.rewriteRequest?.({...f,accountId:l,attempt:e,request:new Request(L.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w),signal:b})});if(!Z2)throw Error("CacheKeep rewrite refused");b.throwIfAborted();let J=await($.fetch??fetch)(Z2),X=await n.adapter.rewriteResponse?.({...f,accountId:l,attempt:e,request:Z2,response:J});if(!X)throw Error("CacheKeep response rewrite refused");if(V2=X.status,n.adapter.quotaFromHeaders?.(X.headers,X.status,e),!X.ok)await n.adapter.limitFromResponse?.({status:V2,headers:X.headers,body:()=>X.clone().text(),attempt:e});let B=await X.arrayBuffer();return j2=!0,new Response(B,{status:V2,headers:X.headers})}catch(c){let l=a4(c);if(l)throw l;throw Error("Native CacheKeep was not completed")}finally{b.removeEventListener("abort",$2);try{if(e)await n.adapter.onAttemptEnd?.(e,{status:V2,outputStarted:!1,...j2?{}:{error:{reason:"cancelled"}}})}finally{n.dispose(),Q.forgetSession?.(f.sessionID)}}},G={generation:C.nextGeneration++,stopped:!1,loadStorage:async()=>(await Z.read()).policyStorage,send:H,inflight:new Set,read:()=>Z.read()},z=C.leases.size===0;C.leases.set(G.generation,G);let K=z?C.adopt():C.loading??Promise.resolve(),_;return{ready:K,async track(L){let S=(y)=>{X0.debug("cachekeep","tracking skipped",{session:L.sessionID,reason:y})};if(G.stopped)return S("lease-stopped");if(L.route!=="oauth")return S("not-oauth");if(L.agent==="cachekeep"||L.agent==="prime")return S("background-agent");if(L.kind!=="primary")return S("not-primary");let O=await Z.read();if(G.stopped)return S("lease-stopped");if(!p2(O.policyStorage)){for(let y of q.trackedSessions())q.untrack(y.id);return C.persistence.clear(),S("hybrid-inactive")}let b=!1;try{b=await $.isSubagent?.(L.sessionID)??!1}catch{return S("session-lookup-failed")}if(G.stopped)return S("lease-stopped");if(b&&!J0(O.policyStorage))return S("subagents-disabled");let w=O.accounts.find((y)=>y.id===L.accountId);if(!w?.accountIdentity)return S("account-identity-missing");if(L.provenance.kind==="local"&&JSON.stringify(w.binding)!==JSON.stringify(L.provenance.subject.binding))return S("local-binding-changed");if(L.provenance.kind==="vault"&&w.credentialId!==L.provenance.credentialId)return S("vault-credential-changed");let f=q.track({sessionId:L.sessionID,url:L.url,headers:new Headers,bodyText:L.bodyText,storage:O.policyStorage,cacheMode:"hybrid",oauthAccountId:L.accountId,oauthAccountIdentity:m2(w),isSubagent:b});return await T.publish(q.trackedSessions()),f},registry:T,dispose(){if(_)return _;G.stopped=!0,V.abort();for(let[S,O]of C.prepared)if(O.lease===G)C.prepared.delete(S);let L=C.leases.delete(G.generation)&&C.leases.size===0;if(L)C.retain();return _=(async()=>{try{if(L)await C.ticking;await K,await Promise.all(G.inflight),await C.persistence.drain()}finally{if(L&&C.leases.size===0)await T.dispose()}})(),_}}}async function M1($,Z,Q){let V=h2(Z),M=[],C=async(_,L,S)=>{let O=await $.session.hook(_,L,S);return M.push(O),O},q=new AbortController,T;try{T=await _0({session:{hook:C},event:$.event},V.adapter,{logger:Z.log,gateOnPlaceholder:Q})}catch(_){throw V.dispose(),await Promise.allSettled(M.map((L)=>L.dispose())),_}let H=(_)=>{V.forgetSession(_),T.forgetSession(_)},G=$.event,z=G?(async()=>{try{for await(let _ of G.subscribe({signal:q.signal}))if(_.type==="session.deleted")H(_.data.sessionID)}catch(_){if(!q.signal.aborted)Z.log?.warn("stopped listening for session deletion",{error:_ instanceof Error?_.name:"unknown"})}})():Promise.resolve(),K;return{installation:T,forgetSession:H,dispose(){if(K)return K;return V.dispose(),q.abort(),K=(async()=>{await T.dispose(),await z})(),K}}}import{effectiveRelayTransport as H1,getQuotaCheckIntervalMs as e4,logger as $8,nativeAccountCanServe as Z8,oauthProfileIsFresh as j8,quotaSnapshotCheckedAt as J8}from"@cortexkit/anthropic-auth-core";function N1($,Z){let Q=new AbortController,V,M=!1,C=async()=>{let H=await $.read();if(Q.signal.throwIfAborted(),H.policyStorage.relay?.enabled===!0&&H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="websocket")return;let G=H,z=e4(G.policyStorage);for(let K of G.accounts){if(Q.signal.aborted)return;if(!Z8(K)||K.type!=="oauth")continue;if(G.policyStorage.quota?.enabled!==!1&&Date.now()-J8(K.quota)>=z)await $.fetchQuota(K.id,Z,Q.signal,void 0,"background").catch(()=>{});if(!j8(K.profile)&&!Q.signal.aborted)await $.fetchProfile(K.id,Z,Q.signal).catch(()=>{})}},q=()=>{if(M||V)return V;return V=C().catch(()=>{if(!Q.signal.aborted)$8.debug("opencode2","native background readings did not complete")}).finally(()=>{V=void 0}),V},T=$.vault.watch({intervalMs:60000,onRefresh:q,shouldRefresh:async()=>{let H=await $.read();return H.policyStorage.relay?.enabled!==!0||H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){M=!0,T.close(),Q.abort(),await V}}}import{authorize as H8,buildCacheKeepStatusSummary as N8,buildClaudeQuotaSummary as _8,buildPrimeAccountStatuses as L8,buildPrimeStatusSummary as F8,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P8,effectiveRelayTransport as T8,exchange as C8,formatNativeAccountState as O8,formatOAuthAccountTier as E8,getCacheKeepWindow as q8,getHostClaustrumEnrollmentPaths as x8,isCacheKeepAlways as S8,isCacheKeepHybridActive as k8,isCacheKeepPersistentlyEnabled as R8,nativeAccountCanServe as b8,parseLogLevel as A8,resetClaustrumEnrollmentState as w8,setDumpEnabled as D8}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as X8,effectiveRelayStatus as G8,formatNativeAccountState as Y8,formatOAuthAccountTier as _1,getCacheKeepWindow as V8,getRoutingMode as Q8,isCacheKeepAlways as W8,isCacheKeepHybridActive as U8,isPermanentRefreshError as B8,isPrimePersistentlyEnabled as z8,nativeAccountCanServe as P1,refreshBackoffActive as L1}from"@cortexkit/anthropic-auth-core";var F1=($)=>P1($)&&$.state!=="unsupported-access"?void 0:Y8($)||void 0,K8=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return P1($)?"on-vault-served":"on-cold"},M8=($,Z)=>typeof $==="number"&&$>Z;function T1($,Z){let{now:Q}=Z,V=$.policyStorage,M=$.accounts.filter((z)=>z.type==="oauth"),C=M.find((z)=>z.id==="main"),q=C?F1(C):void 0,T=C?.lastQuotaRefreshError?.nextRetryAt,H=C?.lastRefreshError,G=V8(V);return G0({main:{quota:C?.quota??null,enabled:C?.enabled,tierLabel:_1(C?.profile),quotaBackedOff:M8(T,Q),quotaBackoffUntil:T,refreshBackedOff:L1(H,C?.accountIdentity,Q,void 0),refreshBackoffUntil:H?.nextRetryAt,stateLine:q,quotaDated:Boolean(q)},fallbacks:M.filter((z)=>z.id!=="main"&&(z.enabled||z.source==="vault")).map((z)=>{let K=F1(z),_=K8(z);return{id:z.id,label:z.label,quota:z.quota??null,enabled:z.enabled,tierLabel:_1(z.profile),needsReauth:B8(z.lastRefreshError)&&L1(z.lastRefreshError,z.accountIdentity,Q,void 0),..._==="on-vault-reauth"?{vaultReauth:!0}:{},..._==="on-vault-served"?{vaultServed:!0}:{},..._!=="off"?{custodyState:_}:{},stateLine:K,quotaDated:Boolean(K)}}),...Z.activeId!==void 0&&{activeId:Z.activeId},route:Q8(V),relay:G8(V.relay),fastMode:V.claudeFast?.enabled===!0,cacheKeep:{enabled:U8(V),...W8(V)?{window:"always"}:G&&{window:`${G.startHour}-${G.endHour}`},trackedSessions:Z.trackedSessions},prime:z8(V)?{enabled:!0,accounts:X8(V,{now:Q})}:void 0,lastUpdated:Q})}var q0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},C1=`For first-time model access, connect Anthropic with "${Q0}".
|
|
4
|
+
Run: opencode auth login anthropic --method ${V0}`,I8="No Claude accounts in the vault for this host yet. Add one with `ck auth login --provider anthropic`, then grant it to this host.",O1="The vault returned an account this plugin cannot use yet.";async function y8($){let Z=new AbortController,Q;try{return await Promise.race([$.vault.refresh(Z.signal).then(()=>"complete",()=>"failed"),new Promise((V)=>{Q=setTimeout(()=>{V("pending"),Z.abort()},2000)})])}finally{clearTimeout(Q)}}var E1=($)=>$.mode==="local"&&!$.accounts.some((Z)=>Z.id==="main"),f8=($)=>{let Z=$.id==="main"?"main":"fallback",Q=`${$.enabled?"enabled":"disabled"}, ${$.type}, ${$.source}${$.state?`, ${O8($)}`:""}`;if($.label)return`${$.label} [${Z}]: ${Q}
|
|
5
|
+
Route: ${$.id}`;return`${Z==="main"?"Main account":`Fallback ${$.id}`}: ${Q}`};function q1($){let{runtime:Z,source:Q}=$,V=new Map,M=!1,C=async(G,z)=>{await Z.updateSettings((K)=>({...K,[G]:{...q0(K[G]),...z}}))},q=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(G,z)=>{if(M)throw Error("Native menu is closed");switch(z.signal?.throwIfAborted(),G.action){case"enable":case"disable":return await Z.setEnabled(G.values.id,G.action==="enable"),q();case"remove":return await Z.remove(G.values.id),q();case"move-up":case"move-down":{let _=(await Z.read()).accounts.map((w)=>w.id),L=_.indexOf(G.values.id),S=L+(G.action==="move-up"?-1:1);if(L<0||S<0||S>=_.length)return{ok:!1,text:"Account cannot move in that direction."};let O=_[L],b=_[S];if(O===void 0||b===void 0)return{ok:!1,text:"Account order changed."};return _[L]=b,_[S]=O,await Z.reorder(_),q()}case"add-apikey":return await Z.addApi(G.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let K=new AbortController;V.get(G.sessionId)?.active.abort();let _={active:K,auth:void 0};V.set(G.sessionId,_);let L=await H8("max");if(M||K.signal.aborted||z.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return _.auth=L,{ok:!0,text:`Open ${L.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let K=V.get(G.sessionId);if(!K?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let _=await C8(G.values.code,K.auth.verifier,K.auth.redirectUri,K.auth.state);if(K.active.signal.throwIfAborted(),z.signal?.throwIfAborted(),M||_.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await Z.loginOAuth({routeId:crypto.randomUUID(),credential:{access:_.access,refresh:_.refresh,expires:_.expires},label:G.values.label}),K.active.signal.throwIfAborted(),z.signal?.throwIfAborted(),M)return{ok:!1,text:"Sign-in cancelled."};V.delete(G.sessionId);let L="OAuth account stored in the native account pool.";return{ok:!0,text:E1(await Z.read())?`${L}
|
|
6
6
|
|
|
7
7
|
${C1}
|
|
8
8
|
|
|
9
|
-
Adding an account here does not change OpenCode's Anthropic connection.`:L}}case"reset-backoff":{let K=await Z.read();for(let _ of K.accounts){if(z.signal?.throwIfAborted(),_.type!=="oauth")continue;let L=_.source==="vault"?await Z.authorizeVault(_.id,z.signal):await Z.captureLocalSubject(_.id);await Z.resetBackoff(_.id,L)}return q()}case"enrollment-reset":{let K=await
|
|
9
|
+
Adding an account here does not change OpenCode's Anthropic connection.`:L}}case"reset-backoff":{let K=await Z.read();for(let _ of K.accounts){if(z.signal?.throwIfAborted(),_.type!=="oauth")continue;let L=_.source==="vault"?await Z.authorizeVault(_.id,z.signal):await Z.captureLocalSubject(_.id);await Z.resetBackoff(_.id,L)}return q()}case"enrollment-reset":{let K=await w8(x8("opencode"),P8);return{ok:K==="reset",text:K==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":K==="refused-pending"?"An enrollment request may still be in progress. Quit OpenCode and run setup again; it picks up the same request.":"Only terminal enrollment state may be reset; active enrollment was left unchanged."}}case"quota-refresh":{let _=(await Z.read()).accounts.filter((O)=>O.type==="oauth"&&b8(O)),L=await Promise.allSettled(_.map((O)=>Z.fetchQuota(O.id,void 0,z.signal)));return{ok:L.every((O)=>O.status==="fulfilled"),text:`${L.filter((O)=>O.status==="fulfilled").length}/${_.length} native quota readings refreshed.`}}case"routing-reset":return await Q.resetRouting(G.sessionId),q();case"routing-mode":return await C("routing",{mode:G.values.mode}),q();case"killswitch-on":case"killswitch-off":return await C("killswitch",{enabled:G.action==="killswitch-on"}),q();case"killswitch-set":return await Z.updateSettings((K)=>{let _=q0(K.killswitch),L={...q0(_.accounts)},S=_.main;for(let O of G.values.entries){let b={five_hour:O.fh,seven_day:O.sd,...O.scoped!==void 0?{scoped:O.scoped}:{}};if(O.account==="main"||O.account==="all")S=b;if(O.account==="all")for(let w of Object.keys(L))L[w]=b;else if(O.account!=="main")L[O.account]=b}return{...K,killswitch:{..._,main:S,accounts:L}}}),q();case"cache-on":case"cache-off":return await C("claudeCache",{enabled:G.action==="cache-on"}),q();case"cache-mode":return await C("claudeCache",{mode:G.values.mode}),q();case"cachekeep-always":return await C("cacheKeep",{enabled:!0,always:!0}),q();case"cachekeep-off":return await C("cacheKeep",{enabled:!1}),q();case"cachekeep-window":return await C("cacheKeep",{enabled:!0,always:!1,startHour:G.values.startHour,endHour:G.values.endHour}),q();case"cachekeep-subagents":return await C("cacheKeep",{subagents:G.values.enabled==="on"}),q();case"dump-on":case"dump-off":{let K=G.action==="dump-on";await C("dump",{enabled:K});try{D8(K)}catch{}return q()}case"logging-level":{let K=A8(G.values.level);if(!K)throw Error("Invalid log level");return await Z.setLoggingLevel(K),q()}case"fast-on":case"fast-off":return await C("claudeFast",{enabled:G.action==="fast-on"}),q();case"prime-on":case"prime-off":return await C("prime",{enabled:G.action==="prime-on"}),q();case"start-fire":return await H(G.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},H=(G)=>$.start(G,Y0);return{dispatch:T,async readStatus(G){let z=await Z.read();if(G==="account"){let _="No native Claude accounts.",L=[];if(z.mode==="claustrum"){let O=z.policyStorage.relay;if(O?.enabled===!0&&T8(O.transport,O.url)==="websocket")return new b2().message;let b=await y8(Z);if(z=await Z.read(),z.mode==="claustrum"){let w=await Z.vault.read();if(b==="complete"&&!w?.view)b="failed";if(_=b==="complete"?I8:"No saved Claude accounts for this host yet.",w?.rejected?.length){if(_=O1,z.accounts.length)L.push(O1)}if(b==="pending")L.push("Vault account lookup is still running.");else if(b==="failed")L.push("Vault account lookup did not complete; reopen /claude to retry.")}}let S=[z.accounts.map(f8).join(`
|
|
10
10
|
`)||_,...L].join(`
|
|
11
11
|
`);return E1(z)?`${S}
|
|
12
12
|
|
|
13
13
|
${C1}
|
|
14
|
-
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:S}if(G==="quota")return _7({accounts:z.accounts.filter((_)=>_.type==="oauth").map((_)=>({name:_.label??_.id,role:_.id==="main"?"main":"fallback",enabled:_.enabled,quota:_.quota,tierLabel:E7(_.profile),lastRefreshedAt:_.lastRefreshedAt,error:_.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(G==="prime")return F7({enabled:z.policyStorage.prime?.enabled===!0,accounts:L7(z.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(G==="cachekeep"){let _=await $.cacheKeepRegistry?.list()??[];return N7({enabled:R7(z.policyStorage),always:S7(z.policyStorage),hybridActive:k7(z.policyStorage),trackedSessionDetails:_,window:q7(z.policyStorage),trackedSessions:_.length,nextPrewarmAt:_.length?Math.min(..._.map((L)=>L.nextPrewarmAt)):void 0})}let K={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(z.settings[K[G]]??{})},async readSidebar(G){let[z,K]=await Promise.all([Z.read(),$.cacheKeepRegistry?.list()??[]]);return G0(T1(z,{activeId:Q.servedAccount(G),trackedSessions:K.length,now:Date.now()}))},forgetSession(G){V.get(G)?.active.abort(),V.delete(G)},close(){M=!0;for(let G of V.values())G.active.abort();V.clear()}}}import{resolveClaudeModelCapabilities as v7}from"@cortexkit/anthropic-auth-core";function x1(){let $=new Map;return{install:(Q)=>Q.model.transform((V)=>{$.clear();for(let M of V.list("anthropic")){$.set(String(M.id),String(M.modelID));let C=v7(M.modelID)?.efforts.variants;if(!C)continue;V.update("anthropic",String(M.id),(q)=>{let T=q.variants.filter((H)=>!C.some((G)=>G===String(H.id)));q.variants=[...T,...C.map((H)=>({id:H,settings:{effort:H,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(Q)=>$.get(Q)??Q}}function S1($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as k1,effectiveRelayTransport as R1,nativeAccountCanServe as g7,PrimeManager as h7,tokenFingerprint as b1}from"@cortexkit/anthropic-auth-core";var A1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function w1($){let{runtime:Z,source:Q}=$,V=new AbortController,M=new Set,C=(H)=>({providerID:"anthropic",modelID:k1().model,sessionID:`oc2-prime:${H}`,agent:"prime",kind:"generate"}),q=async(H)=>{let G=C(H),z=h2({source:Q}),K=performance.now();try{for(let _=0;_<3;_++){if(V.signal.throwIfAborted(),(await Z.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let S=await z.adapter.accountHeaders({...G,accountId:H});if(!("headers"in S)||typeof S.headers!=="object"||S.headers===null||typeof S.attempt!=="object"||S.attempt===null)throw Error("Native Prime authorization refused");let O={...G,accountId:H,attemptId:crypto.randomUUID(),transport:"http",data:S.attempt},b,w=!1,f=!1,y=(n)=>{f=!0,n.body?.cancel().catch(()=>{})};try{let n=await z.adapter.rewriteRequest?.({...G,accountId:H,attempt:O,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(k1()),signal:V.signal})});if(!n)throw Error("Native Prime rewrite refused");let e=new Headers(n.headers);for(let[J,X]of Object.entries(S.headers))if(X===null)e.delete(J);else e.set(J,X);let V2=new Request(n,{headers:e}),j2=await($.fetch??fetch)(V2),$2=await z.adapter.rewriteResponse?.({...G,accountId:H,request:V2,response:j2,attempt:O})??j2;b=$2.status,z.adapter.quotaFromHeaders?.($2.headers,$2.status,O);let c=$2.ok?void 0:await z.adapter.limitFromResponse?.({status:$2.status,headers:$2.headers,body:()=>$2.clone().text(),attempt:O});if(c&&/^(vault-newer|local-newer|relay-direct):/.test(c.reason)&&_<2){if(y($2),(await Q.retrySameAccount?.({...G,accountId:H,attempt:_+1,limit:c,error:{type:"api_error",message:"Native Prime credential retry",status:$2.status}}))?.accountId!==H)throw Error("Native Prime retry changed account");continue}if(!$2.ok)return y($2),{ok:!1,status:b,ms:performance.now()-K,error:"Native Prime upstream refused the request"};let l=A1(await $2.json()),s=A1(l.usage),Z2={inputTokens:typeof s.input_tokens==="number"?s.input_tokens:void 0,outputTokens:typeof s.output_tokens==="number"?s.output_tokens:void 0};if(O.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test($2.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await Q.recordPrime(S.attempt.provenance,Z2),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:b,ms:performance.now()-K,usage:Z2}}finally{await z.adapter.onAttemptEnd?.(O,{status:b,outputStarted:!1,...w?{}:{error:{reason:f?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-K}}finally{z.dispose()}},T=new h7({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await Z.read()).policyStorage,async getAccountFingerprint(H){let G=await Z.read(),z=G.accounts.find((L)=>L.id===H);if(!g7(z)||z?.type!=="oauth")return;if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")return;if(z.source==="vault"){let L=await Z.authorizeVault(H,V.signal),S=await Z.getOrCreateAuthLineage(H,L);return S?b1(S):void 0}let K=await Z.authorizeLocal(H,{signal:V.signal});if(K.status!=="usable")return;let _=await Z.getOrCreateAuthLineage(H,K.subject);return _?b1(_):void 0},async refreshQuota(H){let G=await Z.read();if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await Z.fetchQuota(H,$.fetch,V.signal),fresh:!0}},sendPrime(H){let G=q(H);return M.add(G),G.finally(()=>M.delete(G)),G},async recordSuccess(H){let G=(await Z.read()).accounts.find((z)=>z.id===H);if(!G?.prime)throw Error("Native Prime counters are unavailable");return G.prime}});return T.start(),{manager:T,async dispose(){T.stop(),V.abort(),await Promise.allSettled(M)}}}import{createNativeUsagePublisher as m7,createNativeVaultNoRouteResponse as l7,decideStickyQuotaFailure as d7,effectiveRelayTransport as u7,getClaudeCodeIdentityForVerifiedAccount as W0,getQuotaCheckIntervalMs as p7,getRoutingMode as B0,isDumpPersistentlyEnabled as D1,isQuotaBearingHeaderFrame as c7,logger as i7,mergeHeaderQuotaForPersistence as o7,NativeVaultQuotaPolicyError as n7,nativeAccountCanServe as l2,nativeAccountPolicy as c2,nativeLocalAccountRefusal as r7,nativeLocalQuotaLineage as s7,nativePollQuotaGenerallyExhausted as a7,normalizeQuotaHeaders as t7,quotaSnapshotCheckedAt as I1,quotaSnapshotHasStandardWindows as e7,readNativeAccountsForRequest as $$,remapModelId as U0,StickySessionRouter as Z$,setDumpEnabled as j$,shouldFallbackStatus as J$,stickyQuotaSnapshotIsFresh as i2,stickyRetryAfterWithJitter as X$,stickyRouteFamilyForModel as y1}from"@cortexkit/anthropic-auth-core";var x0=($)=>["five_hour","seven_day"].some((Z)=>($?.[Z]?.remainingPercent??1)<=0);function G$($,Z,Q,V){let M=$.rerouteFrom;if($.phase!=="retry"||M?.limit.status!==429||B0(Z.policyStorage)!=="sticky-balanced")return;let C=Q.find((T)=>T.id===M.accountId);if(!C||!i2(C.quota,Z.policyStorage,Date.now(),V))return;let q=d7({quota:C.quota,modelId:V});if(q.action!=="hold")return;return{hold:{delayMs:X$($.sessionID,q.retryAfterSeconds)*1000}}}function m1($){let{runtime:Z}=$,Q=m7("native-auth"),V=h1(),M=new Set,C=new Map,q=(J)=>{let X=J.routingPath;if(!X)throw Error("Native routing storage is unavailable");let B=C.get(X);if(!B)B=new Z$({path:X,vaultSeed:J.routingSeed,onLockEvent:Z.onLockEvent,relocationGuard:Z.relocationGuard,localRecoveryPath:J.mode==="local"?J.routingRecoveryPath:void 0}),C.set(X,B);return B.setVaultSeed(J.routingSeed),B},T=new WeakMap,H=new Map,G=new Map,z=new Map,K=new Map,_=new WeakSet,L=!1,S=()=>{while(H.size>512){let J=H.keys().next();if(!J.done)H.delete(J.value)}},O=(J)=>{try{j$(D1(J.policyStorage))}catch{}},b=async()=>{try{let J=await Z.read();return O(J),D1(J.policyStorage)}catch{return!1}},w=(J)=>({providerID:J.providerID,sessionID:J.sessionID,kind:J.kind,modelID:J.modelID,agent:J.agent}),f=(J,X)=>JSON.stringify([J.providerID,J.sessionID,J.kind,J.modelID,J.agent,X]),y=(J)=>{if(L)throw Error("Native Anthropic source is closed");let X=z.get(J.sessionID);if(!X){X=new AbortController,z.set(J.sessionID,X);while(z.size>512){let B=z.keys().next();if(!B.done)Z2.forgetSession?.(B.value)}}return X},n=(J,X,B)=>l2(J)&&(J.type==="api"||c2(J,X,U0(B)).status==="allowed"),e=(J,X)=>J.source===X.source&&J.accountIdentity===X.accountIdentity&&J.credentialId===X.credentialId,V2=async(J,X,B,R,I)=>{let A=await Z.read();O(A),R.signal.throwIfAborted(),j2(A);let h=A.accounts.find((r)=>r.id===J);if(!h||h.type!==B||!n(h,A,X))return I?.(!h||!l2(h)?"account-unavailable":"account-policy"),!1;if(B==="api"){let r=A.accounts.find((m)=>m.id==="main"&&m.type==="oauth");return!!r&&i2(r.quota,A.policyStorage)&&x0(r.quota)}return!0},j2=(J)=>{let X=J.policyStorage.relay;if(X?.enabled===!0&&u7(X.transport,X.url)==="websocket")throw new b2},$2=async(J,X)=>{if(j2(J),X||J.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let B=await Z.getRelayConfig();if(!B)throw Error("request refused: native HTTP relay configuration is unavailable");if(B.transport!=="http")throw new b2;return{dispatch:{kind:"http-relay",url:B.url,token:B.token},relayFallback:B.fallbackToDirect}};async function c(J,X,B){if(J.kind==="local"){let R=await Z.publishLocal(J.subject,B);if(!R&&B.quota)i7.warn("quota","Quota publication discarded");return R}if(J.kind==="vault"&&X.receipt)await Z.vault.publish(X.receipt,B);else if(J.kind==="api"&&B.lastUsed!==void 0)await Z.publishApi(J.subject,{lastUsed:B.lastUsed});return!0}function l(J,X,B){if(J.kind!=="local")return;let R=J.subject.binding,I=I1(B),A={lineage:s7(R),accountUuid:R.identity,entry:{quota:B,checkedAt:I,refreshAfter:I},generalExhausted:a7(B),routeBeforeSave:!0};return Z.quotaObservations.hold(X.account.id,A)?A:void 0}function s(J,X){if(X.exhaustionReported)return;X.exhaustionReported=!0,V.report(J.sessionID,{accountIdentity:X.account.accountIdentity,credentialId:J.provenance.kind==="vault"?J.provenance.credentialId:X.account.credentialId},X.responseHeaders??new Headers,429,X.scope.modelID,!1)}let Z2={async chooseAccount(J){let X=y(J);$.onOwnedRequest?.();let B=await Z.read();O(B),X.signal.throwIfAborted(),j2(B);let R=U0(await $.resolveModelId?.(J)??J.modelID);if(X.signal.throwIfAborted(),B.mode==="claustrum")B=await $$(Z,X.signal),X.signal.throwIfAborted();if(B.policyStorage.quota?.enabled!==!1){let d=!1;for(let J2 of B.accounts){if(!l2(J2)||J2.type!=="oauth")continue;if(e7(J2.quota)?i2(J2.quota,B.policyStorage,Date.now(),R):Date.now()-I1(J2.quota)<p7(B.policyStorage))continue;try{await Z.fetchQuota(J2.id,$.fetch,X.signal,void 0,"admission"),d=!0}catch{X.signal.throwIfAborted()}}if(d)B=await Z.read();X.signal.throwIfAborted()}if(J.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(J.rerouteFrom.limit.reason))return;if(J.phase==="request")M.delete(J.sessionID);let I=await V.accountFor(J.sessionID,R);if(X.signal.throwIfAborted(),I)B=await Z.read(),X.signal.throwIfAborted(),j2(B);let A=[],h=new Map;for(let d of B.accounts){if(d.type!=="oauth")continue;let J2=c2(d,B,R);if(h.set(d.id,J2),J2.status!=="allowed")continue;if(d.source==="local"){let u=await Z.authorizeLocal(d.id,{signal:X.signal,policy:(Y,N)=>c2(Y,N,R)});if(X.signal.throwIfAborted(),u.status!=="usable")continue}A.push(d)}if(I){let d=A.find((Y)=>v1(I,Y)),J2=A.map((Y,N)=>({accountId:Y.id,order:N,quota:Y.quota??{kind:"unknown"}})),u=!I.hold||J.phase==="retry"&&J.rerouteFrom?.accountId===d?.id;if(d&&u&&(I.hold||d.id!==J.rerouteFrom?.accountId)&&g1(d.id,J2,B.policyStorage,R)){let Y=await q(B).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:J2.filter((N)=>N.accountId===d.id),retainAccountIds:new Set([d.id]),...B.mode==="claustrum"?{accountIdentities:new Map([[d.id,I.account_id]])}:{},storage:B.policyStorage,inputBytes:1,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),Y)return I.hold?{hold:{delayMs:I.hold.retry_after_ms}}:Y.accountId}V.override(J.sessionID,!u?"hold requires the same refused retry account":"unknown account, credential, account policy or Fable reserve")}let r=G$(J,B,A,R);if(r)return r;let m=A.filter((d)=>d.id!==J.rerouteFrom?.accountId);if(B0(B.policyStorage)==="sticky-balanced"){let d=m.map((u,Y)=>({accountId:u.id,order:Y,quota:u.quota??{kind:"unknown"}})),J2=await q(B).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:d,retainAccountIds:new Set(m.map((u)=>u.id)),...B.mode==="claustrum"?{accountIdentities:new Map(B.accounts.flatMap((u)=>u.accountIdentity?[[u.id,u.accountIdentity]]:[]))}:{},storage:B.policyStorage,inputBytes:1,preferredAccountId:J.previousAccountId,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),J2)return J2.accountId}else{let J2=B0(B.policyStorage)==="fallback-first"?[...m.filter((u)=>u.id!=="main"),...m.filter((u)=>u.id==="main")]:[...m.filter((u)=>u.id==="main"),...m.filter((u)=>u.id!=="main")];if(J2[0])return J2[0].id}if(B.mode==="claustrum")throw await n7.fromResponse(l7({snapshot:B,modelId:R,policies:h,sticky:B0(B.policyStorage)==="sticky-balanced"}));let a=B.accounts.find((d)=>d.id==="main"&&d.type==="oauth");if(!a)return;let W2=a.quota;if(J.rerouteFrom?.limit.status===429||!i2(W2,B.policyStorage))try{W2=await Z.fetchQuota("main",$.fetch,X.signal)}catch{return}if(X.signal.throwIfAborted(),!x0(W2))return;return B.accounts.find((d)=>d.type==="api"&&l2(d)&&d.id!==J.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(J){let X=J.limit?.reason,B=X?H.get(X):void 0;if(!B||f(B.scope,B.accountId)!==f(J,J.accountId))return;H.delete(B.reason);let R=y(J),I=await Z.read();R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let h=I.accounts.find((a)=>a.id===J.accountId);if(!h||!e(h,B.account)||!n(h,I,A))return;let r=f(J,J.accountId),m=G.get(r)??[];return m.push(B),G.set(r,m),{accountId:J.accountId}},dropSameAccountRetry(J){let X=f(J,J.accountId),B=G.get(X),R=B?.findIndex((I)=>!J.limit||I.reason===J.limit.reason)??-1;if(R!==-1)B?.splice(R,1);if(B?.length===0)G.delete(X)},async authorizeAccount(J,X,B){let R=y(J),I=await Z.read();O(I),R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let h=I.accounts.find((U)=>U.id===X);if(!h||!n(h,I,A)){B?.(!h||!l2(h)?"account-unavailable":"account-policy");return}let r=f(J,X),m=G.get(r),a=m?.shift();if(m?.length===0)G.delete(r);if(a&&!e(h,a.account))return;let{dispatch:W2,relayFallback:d}=await $2(I,a?.direct===!0);if(R.signal.throwIfAborted(),a?.auth){if(!await V2(X,A,a.auth.route,R,B))return;let U=T.get(a.auth.provenance);if(U?.receipt?.expiresAtMs!==void 0&&U.receipt.expiresAtMs!==null&&U.receipt.expiresAtMs<Date.now()+300000)return;if(U)T.set(a.auth.provenance,{...U,scope:{...J,modelID:A},account:h,active:R,relayFallback:d});return K.set(J.sessionID,X),{...a.auth,dispatch:W2}}let J2={scope:{...J,modelID:A},active:R,account:h,retry:a?.retry??!1,relayFallback:d,quota:h.quota};if(h.type==="api"){let U=I.accounts.find((g)=>g.id==="main"&&g.type==="oauth");if(!U||!i2(U.quota,I.policyStorage)||!x0(U.quota))return;let E=await Z.authorizeApi(X,R.signal);if(R.signal.throwIfAborted(),!await V2(X,A,"api",R))return;let x={kind:"api",subject:E.subject};return T.set(x,J2),K.set(J.sessionID,X),{route:"api",headers:E.authHeader==="authorization-bearer"?{authorization:`Bearer ${E.apiKey}`}:{"x-api-key":E.apiKey},baseURL:E.baseURL,provenance:x,dispatch:W2}}if(h.source==="vault"){let U=await Z.authorizeVault(X,R.signal);if(R.signal.throwIfAborted(),a&&(U.credentialId!==a.account.credentialId||U.assertedAccountIdentity!==a.account.accountIdentity))return;if(!await V2(X,A,"oauth",R,B))return;let E={kind:"vault",credentialId:U.credentialId,recordVersion:U.recordVersion};T.set(E,{...J2,receipt:U});let x=U.assertedAccountIdentity;if(!x){B?.("account-unavailable");return}return K.set(J.sessionID,X),{route:"oauth",accessToken:U.accessToken,provenance:E,dispatch:W2,identity:W0(x,x)}}let u=await Z.authorizeLocal(X,{signal:R.signal,policy:(U,E)=>c2(U,E,A)});if(R.signal.throwIfAborted(),u.status!=="usable"){let U=r7(u);if(U)B?.(U.reason);return}if(!await V2(X,A,"oauth",R,B))return;let Y={kind:"local",subject:u.subject};T.set(Y,{...J2,access:u.access}),K.set(J.sessionID,X);let N=u.subject.binding.identity;return{route:"oauth",accessToken:u.access,provenance:Y,dispatch:W2,identity:W0(N,N)}},async requestOptions(J,X){let B=y(J),R=await Z.read();O(R),B.signal.throwIfAborted();let I=R.accounts.find((h)=>h.id===J.accountId);if(!I||!n(I,R,J.modelID))throw X?.(!I||!l2(I)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let A=T.get(J.provenance);if(A)T.set(J.provenance,{...A,scope:{...A.scope,modelID:J.modelID}});return $.requestOptions(J,R)},async admitRequest(J,X){let B=T.get(J.provenance);if(!B||!await V2(J.accountId,J.modelID,J.route,B.active,X))throw Error("request refused: native account policy changed before dispatch");T.set(J.provenance,{...B,scope:{...B.scope,modelID:J.modelID}})},isDumpEnabled:()=>b(),onRequestPrepared:(J)=>$.onRequestPrepared?.(J),responseOptions(J){return $.responseOptions?.({...J,modelID:T.get(J.provenance)?.scope.modelID??J.modelID})},quotaFromHeaders(J,X){let B=T.get(X.provenance);if(B){B.responseHeaders=J;let W2=X.status<400&&!M.has(X.sessionID);if(W2)M.add(X.sessionID);if(X.status===429)s(X,B);else V.report(X.sessionID,{accountIdentity:B.account.accountIdentity,credentialId:X.provenance.kind==="vault"?X.provenance.credentialId:B.account.credentialId},J,X.status,B.scope.modelID,W2)}let R=f1(J);if(R)$.onRequestId?.(X,R);if(!B||X.route!=="oauth"||!c7(J))return;let I=X.provenance.kind==="local"?X.provenance.subject.binding.identity:B.receipt?.assertedAccountIdentity,A={...t7(J),...I?{accountIdentity:I}:{}},h=o7(B.quota,A);B.quota=h;let r=l(X.provenance,B,h),m=B.account.id,a=()=>{if(r)Z.quotaObservations.forget(m,r)};return Q.observe(c(X.provenance,B,{quota:h}).then((W2)=>{if(!W2)a()},(W2)=>{throw a(),W2})),A},async limitFromResponse(J){let X=T.get(J.provenance);if(!X)return;if(J.status===401&&X.receipt){if(!_.has(X.receipt))_.add(X.receipt),await Z.vault.reportFailure(X.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(X.retry||X.active.signal.aborted)return;let R=X.active,I=await Z.vault.prepareRetry(X.receipt,R.signal);if(R.signal.throwIfAborted(),!I.retry)return;let A=I.receipt,h=A.assertedAccountIdentity;if(!h)return;let r={kind:"vault",credentialId:A.credentialId,recordVersion:A.recordVersion};T.set(r,{...X,receipt:A,retry:!0});let m=`vault-newer:${J.attemptId}`;return H.set(m,{scope:w(J),reason:m,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:A.accessToken,provenance:r,identity:W0(h,h)}}),S(),{reason:m,status:401}}if(J.status===401&&J.provenance.kind==="local"&&X.access&&!X.retry){if(X.active.signal.aborted)return;let R=X.active,I=await Z.authorizeLocal(J.accountId,{rejectedAccessToken:X.access,signal:R.signal,policy:(m,a)=>c2(m,a,X.scope.modelID)});if(R.signal.throwIfAborted(),I.status!=="usable"||I.access===X.access)return;let A={kind:"local",subject:I.subject};T.set(A,{...X,access:I.access,retry:!0});let h=I.subject.binding.identity,r=`local-newer:${J.attemptId}`;return H.set(r,{scope:w(J),reason:r,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:I.access,provenance:A,identity:W0(h,h)}}),S(),{reason:r,status:401}}let B=await Z.read();if(J$(J.status,B.policyStorage))return{reason:`provider-${J.status}`,status:J.status};return},limitFromRelayFailure(J){let X=T.get(J.provenance);if(!X?.relayFallback||X.active.signal.aborted||!(J.status===401||J.status>=500))return;let B=`relay-direct:${J.attemptId}`;return H.set(B,{scope:w(J),reason:B,accountId:J.accountId,account:X.account,direct:!0,retry:!1}),S(),{reason:B}},limitFromStreamError(J){let X=T.get(J.provenance);if(X&&J.errorType==="rate_limit_error")s(J,X);return J.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(J,X){let B=T.get(X.provenance);if(X.dispatch==="http-relay"&&B?.relayFallback&&!B.active.signal.aborted&&J.status===void 0){let R=`relay-direct:${X.attemptId}`;return H.set(R,{scope:w(X),reason:R,accountId:X.accountId,account:B.account,direct:!0,retry:!1}),S(),{reason:R}}return},async onAttemptEnd(J,X){let B=T.get(J.provenance);if(!B)return;try{if(X.status===401&&B.receipt&&!_.has(B.receipt))_.add(B.receipt),await Z.vault.reportFailure(B.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(!X.localRefusal&&X.status!==void 0)Q.publish(()=>c(J.provenance,B,{lastUsed:Date.now()}))}finally{T.delete(J.provenance)}},forgetSession(J){M.delete(J),z.get(J)?.abort(),z.delete(J),K.delete(J);for(let[X,B]of H)if(B.scope.sessionID===J)H.delete(X);for(let[X,B]of G)if(B[0]?.scope.sessionID===J)G.delete(X);$.onForgetSession?.(J)},servedAccount:(J)=>K.get(J),resetRouting:async(J)=>q(await Z.read()).clear(J),async recordPrime(J,X){let B=T.get(J);if(!B||B.active.signal.aborted)return!1;if(J.kind==="local")return Z.incrementPrimeUsage(B.account.id,J.subject,X);if(J.kind==="vault"&&B.receipt)return Z.incrementPrimeUsage(B.account.id,B.receipt,X);return!1},drainRoutingPublications:()=>Promise.all([Z.drainRoutingPublications(),...[...C.values()].map((J)=>J.drain())]).then(()=>{}),close(){L=!0;for(let J of z.values())J.abort();return z.clear(),G.clear(),H.clear(),Promise.all([Q.drain(),Z2.drainRoutingPublications()]).then(()=>{})}};return Z2}import{remapModelId as Y$}from"@cortexkit/anthropic-auth-core";function u1(){let $=new l1,Z=new Map,Q=new Map,V=new Map,M=new Set,C=new Set,q=new Map,T=(H)=>{while(H.size>512){let G=H.keys().next();if(!G.done)H.delete(G.value)}};return{async install(H){let G=[];try{G.push(await H.session.hook("context",(z)=>{let K=z.messages.map((L)=>{return{info:{id:L.id,sessionID:z.sessionID,role:L.role,agent:z.agent,model:{providerID:z.model.providerID,modelID:z.model.id}},parts:L.content.map((S)=>({type:S.type,...S.type==="text"?{text:S.text}:{}}))}});$.observeMessages(K);let _=z.messages.findLast((L)=>L.role==="user"&&L.id);if(_?.id)Z.set(z.sessionID,_.id);if(_?.content.some((L)=>L.type==="text"&&L.text===Y0))M.add(z.sessionID);else M.delete(z.sessionID);T(Z)},{providerID:"anthropic"})),G.push(await H.session.hook("model.request",(z)=>{if(z.kind!=="primary")return;let K=Z.get(z.sessionID);if(!K)return;if($.markHeaders({sessionId:z.sessionID,messageId:K,agent:z.agent,headers:z.headers}),M.has(z.sessionID))z.headers[y2]="1"},{providerID:"anthropic"}))}catch(z){throw await Promise.allSettled(G.map((K)=>K.dispose())),z}return{dispose:async()=>{await Promise.all(G.map((z)=>z.dispose()))}}},requestOptions(H,G){let z=$.resolveHeader(H.correlation[e2]);if(z)Q.set(H.attemptId,z),T(Q);q.set(H.attemptId,H.sessionID),T(q);let K=H.correlation[y2]==="1";if(K)C.add(H.attemptId);return{cache1hEnabled:H.agent!=="compaction"&&H.agent!=="title"&&(G.policyStorage.claudeCache?.enabled??!0),cache1hMode:G.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:G.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:G.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:G.policyStorage.turnEndNote,serverSideFallbackEnabled:d1(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:K,billingLineage:z?{promptId:z.promptId,previousRequestId:z.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:V.get(H.sessionID)}},responseOptions(H){return{serverSideFallbackModel:Y$(H.modelID),laneStart:C.has(H.attemptId),onMessageStart(G){if(H.kind==="primary"&&typeof G.id==="string")V.set(H.sessionID,G.id),T(V)},onStreamEnd(){Q.delete(H.attemptId),C.delete(H.attemptId),q.delete(H.attemptId)}}},onRequestId(H,G){$.commit(Q.get(H.attemptId),G)},forgetSession(H){$.clearSession(H),Z.delete(H),V.delete(H),M.delete(H);for(let[G,z]of q)if(z===H)Q.delete(G),C.delete(G),q.delete(G)}}}var z0="cortexkit-anthropic-auth",E$='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',q$="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",x$="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function S$($){let Z=$.authorize??W$,Q=$.exchange??K$,V=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},M=async()=>{let T;try{T=await $.readMode()}catch{throw Error(x$)}return V(),T},C=async()=>{if(await M()!=="local")throw Error(E$)};return{integrationID:"anthropic",methods:[{method:{id:V0,type:"oauth",label:Q0},async authorize(){V(),await C();let T=await Z("max");return V(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(H)=>{V();let G=await Q(H,T.verifier,T.redirectUri,T.state);if(!$.isActive()||G.type!=="success")throw Error("Claude sign-in did not complete");return{access:G.access,refresh:G.refresh,expires:G.expires}}}}}],vault:{method:{id:p1,type:"oauth",label:"Claude vault accounts"},async activate(){if(V(),await M()!=="claustrum")throw Error(q$)}},async onLogin(T){V(),await C(),await $.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),V()},label:"Claude native account pool"}}function k$($){return{readMode:()=>_$("opencode",$),disconnectVault:()=>z$({host:"opencode",env:$})}}function k0($={}){return{id:z0,setup:(Z)=>i1(Z,$)}}async function R$($){try{return await A$($)}catch(Z){throw b$(Z)}}function b$($){let Z=$0($);if(Z)return Z;let Q=C$("decide where its account state is",[],$);return S0.error("state-layout",Q.message,{code:Q.code}),$0(Q)??Q}async function A$($){if($.paths){let Q=$.paths;return await Q$(Q),{paths:Q,holderRegistration:await L$({paths:Q,role:"opencode2",kind:N$(),policy:O$(),onLockEvent:$.local?.onLockEvent})}}let Z=await B$({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await F$(void 0,void 0,Z.layout),holderRegistration:Z.kind==="state-home"?void 0:Z.registration}}async function i1($,Z={}){let{paths:Q,holderRegistration:V}=await R$(Z),M=V$({paths:Q,host:"opencode",local:Z.local,vault:Z.vault}),C=k$(Z.vault?.env??process.env);try{let f=await M.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)T$(M$(f.policyStorage)??"info");P$(H$(f.policyStorage))}catch{}let q=!0,T=u1(),H=x1(),G,z,K,_=m1({runtime:M,paths:Q,fetch:Z.fetch,requestOptions:T.requestOptions,responseOptions:T.responseOptions,onRequestId:T.onRequestId,onForgetSession:T.forgetSession,onRequestPrepared:async(f)=>{try{await K?.track(f)}catch{S0.warn("cachekeep","live request tracking failed")}},resolveModelId:async(f)=>H.modelId(f.modelID),onOwnedRequest:()=>{G??=N1(M,Z.fetch),z??=w1({runtime:M,paths:Q,source:_,fetch:Z.fetch})}});K=K1({...Z.cacheKeep,runtime:M,source:_,storageId:Q.storageId,fetch:Z.fetch,isSubagent:async(f)=>Boolean((await $.session.get({sessionID:f})).parentID)}),await K.ready;let L=q1({runtime:M,source:_,cacheKeepRegistry:K.registry,start:async(f,y)=>{await $.session.synthetic({sessionID:f,text:y,description:"Claude lane start",resume:!0})}}),S=[],O=await M1($,{source:_,log:{warn:(f,y)=>S0.warn("opencode2",f,y)}},{credential:S1}).catch(async(f)=>{throw V?.close(),L.close(),await K?.dispose(),await _.close(),await M.drainQuotaPublications(),await M.close(),f}),b,w=()=>{if(b)return b;return q=!1,V?.close(),L.close(),_.close(),b=(async()=>{await Promise.allSettled([O.dispose(),G?.dispose(),z?.dispose(),K?.dispose(),...S.map((f)=>f.dispose())]),await _.close(),await M.drainQuotaPublications(),await M.close()})(),b};try{S.push(await T.install($)),S.push(await H.install($)),S.push(await H0($,S$({isActive:()=>q,readMode:C.readMode,runtime:M})));let f={host:"opencode",dispatch:L.dispatch,readStatus:(n)=>L.readStatus(n),readAccounts:()=>M.read(),readMode:C.readMode,disconnectVault:C.disconnectVault,interactive:!0},y=U$(f);return S.push(await c1($,y,L)),w}catch(f){throw await w(),f}}var K6={id:z0,setup:k0().setup,server:o1};export{i1 as setupAnthropicAuth,K6 as default,k0 as createAnthropicAuthPlugin,z0 as ANTHROPIC_AUTH_PLUGIN_ID};
|
|
14
|
+
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:S}if(G==="quota")return _8({accounts:z.accounts.filter((_)=>_.type==="oauth").map((_)=>({name:_.label??_.id,role:_.id==="main"?"main":"fallback",enabled:_.enabled,quota:_.quota,tierLabel:E8(_.profile),lastRefreshedAt:_.lastRefreshedAt,error:_.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(G==="prime")return F8({enabled:z.policyStorage.prime?.enabled===!0,accounts:L8(z.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(G==="cachekeep"){let _=await $.cacheKeepRegistry?.list()??[];return N8({enabled:R8(z.policyStorage),always:S8(z.policyStorage),hybridActive:k8(z.policyStorage),trackedSessionDetails:_,window:q8(z.policyStorage),trackedSessions:_.length,nextPrewarmAt:_.length?Math.min(..._.map((L)=>L.nextPrewarmAt)):void 0})}let K={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(z.settings[K[G]]??{})},async readSidebar(G){let[z,K]=await Promise.all([Z.read(),$.cacheKeepRegistry?.list()??[]]);return G0(T1(z,{activeId:Q.servedAccount(G),trackedSessions:K.length,now:Date.now()}))},forgetSession(G){V.get(G)?.active.abort(),V.delete(G)},close(){M=!0;for(let G of V.values())G.active.abort();V.clear()}}}import{resolveClaudeModelCapabilities as v8}from"@cortexkit/anthropic-auth-core";function x1(){let $=new Map;return{install:(Q)=>Q.model.transform((V)=>{$.clear();for(let M of V.list("anthropic")){$.set(String(M.id),String(M.modelID));let C=v8(M.modelID)?.efforts.variants;if(!C)continue;V.update("anthropic",String(M.id),(q)=>{let T=q.variants.filter((H)=>!C.some((G)=>G===String(H.id)));q.variants=[...T,...C.map((H)=>({id:H,settings:{effort:H,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(Q)=>$.get(Q)??Q}}function S1($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as k1,effectiveRelayTransport as R1,nativeAccountCanServe as g8,PrimeManager as h8,tokenFingerprint as b1}from"@cortexkit/anthropic-auth-core";var A1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function w1($){let{runtime:Z,source:Q}=$,V=new AbortController,M=new Set,C=(H)=>({providerID:"anthropic",modelID:k1().model,sessionID:`oc2-prime:${H}`,agent:"prime",kind:"generate"}),q=async(H)=>{let G=C(H),z=h2({source:Q}),K=performance.now();try{for(let _=0;_<3;_++){if(V.signal.throwIfAborted(),(await Z.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let S=await z.adapter.accountHeaders({...G,accountId:H});if(!("headers"in S)||typeof S.headers!=="object"||S.headers===null||typeof S.attempt!=="object"||S.attempt===null)throw Error("Native Prime authorization refused");let O={...G,accountId:H,attemptId:crypto.randomUUID(),transport:"http",data:S.attempt},b,w=!1,f=!1,y=(n)=>{f=!0,n.body?.cancel().catch(()=>{})};try{let n=await z.adapter.rewriteRequest?.({...G,accountId:H,attempt:O,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(k1()),signal:V.signal})});if(!n)throw Error("Native Prime rewrite refused");let e=new Headers(n.headers);for(let[J,X]of Object.entries(S.headers))if(X===null)e.delete(J);else e.set(J,X);let V2=new Request(n,{headers:e}),j2=await($.fetch??fetch)(V2),$2=await z.adapter.rewriteResponse?.({...G,accountId:H,request:V2,response:j2,attempt:O})??j2;b=$2.status,z.adapter.quotaFromHeaders?.($2.headers,$2.status,O);let c=$2.ok?void 0:await z.adapter.limitFromResponse?.({status:$2.status,headers:$2.headers,body:()=>$2.clone().text(),attempt:O});if(c&&/^(vault-newer|local-newer|relay-direct):/.test(c.reason)&&_<2){if(y($2),(await Q.retrySameAccount?.({...G,accountId:H,attempt:_+1,limit:c,error:{type:"api_error",message:"Native Prime credential retry",status:$2.status}}))?.accountId!==H)throw Error("Native Prime retry changed account");continue}if(!$2.ok)return y($2),{ok:!1,status:b,ms:performance.now()-K,error:"Native Prime upstream refused the request"};let l=A1(await $2.json()),s=A1(l.usage),Z2={inputTokens:typeof s.input_tokens==="number"?s.input_tokens:void 0,outputTokens:typeof s.output_tokens==="number"?s.output_tokens:void 0};if(O.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test($2.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await Q.recordPrime(S.attempt.provenance,Z2),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:b,ms:performance.now()-K,usage:Z2}}finally{await z.adapter.onAttemptEnd?.(O,{status:b,outputStarted:!1,...w?{}:{error:{reason:f?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-K}}finally{z.dispose()}},T=new h8({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await Z.read()).policyStorage,async getAccountFingerprint(H){let G=await Z.read(),z=G.accounts.find((L)=>L.id===H);if(!g8(z)||z?.type!=="oauth")return;if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")return;if(z.source==="vault"){let L=await Z.authorizeVault(H,V.signal),S=await Z.getOrCreateAuthLineage(H,L);return S?b1(S):void 0}let K=await Z.authorizeLocal(H,{signal:V.signal});if(K.status!=="usable")return;let _=await Z.getOrCreateAuthLineage(H,K.subject);return _?b1(_):void 0},async refreshQuota(H){let G=await Z.read();if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await Z.fetchQuota(H,$.fetch,V.signal),fresh:!0}},sendPrime(H){let G=q(H);return M.add(G),G.finally(()=>M.delete(G)),G},async recordSuccess(H){let G=(await Z.read()).accounts.find((z)=>z.id===H);if(!G?.prime)throw Error("Native Prime counters are unavailable");return G.prime}});return T.start(),{manager:T,async dispose(){T.stop(),V.abort(),await Promise.allSettled(M)}}}import{createNativeUsagePublisher as m8,createNativeVaultNoRouteResponse as l8,decideStickyQuotaFailure as d8,effectiveRelayTransport as u8,getClaudeCodeIdentityForVerifiedAccount as W0,getQuotaCheckIntervalMs as p8,getRoutingMode as B0,isDumpPersistentlyEnabled as D1,isQuotaBearingHeaderFrame as c8,logger as i8,mergeHeaderQuotaForPersistence as o8,NativeVaultQuotaPolicyError as n8,nativeAccountCanServe as l2,nativeAccountPolicy as c2,nativeLocalAccountRefusal as r8,nativeLocalQuotaLineage as s8,nativePollQuotaGenerallyExhausted as a8,normalizeQuotaHeaders as t8,quotaSnapshotCheckedAt as I1,quotaSnapshotHasStandardWindows as e8,readNativeAccountsForRequest as $$,remapModelId as U0,StickySessionRouter as Z$,setDumpEnabled as j$,shouldFallbackStatus as J$,stickyQuotaSnapshotIsFresh as i2,stickyRetryAfterWithJitter as X$,stickyRouteFamilyForModel as y1}from"@cortexkit/anthropic-auth-core";var x0=($)=>["five_hour","seven_day"].some((Z)=>($?.[Z]?.remainingPercent??1)<=0);function G$($,Z,Q,V){let M=$.rerouteFrom;if($.phase!=="retry"||M?.limit.status!==429||B0(Z.policyStorage)!=="sticky-balanced")return;let C=Q.find((T)=>T.id===M.accountId);if(!C||!i2(C.quota,Z.policyStorage,Date.now(),V))return;let q=d8({quota:C.quota,modelId:V});if(q.action!=="hold")return;return{hold:{delayMs:X$($.sessionID,q.retryAfterSeconds)*1000}}}function m1($){let{runtime:Z}=$,Q=m8("native-auth"),V=h1(),M=new Set,C=new Map,q=(J)=>{let X=J.routingPath;if(!X)throw Error("Native routing storage is unavailable");let B=C.get(X);if(!B)B=new Z$({path:X,vaultSeed:J.routingSeed,onLockEvent:Z.onLockEvent,relocationGuard:Z.relocationGuard,localRecoveryPath:J.mode==="local"?J.routingRecoveryPath:void 0}),C.set(X,B);return B.setVaultSeed(J.routingSeed),B},T=new WeakMap,H=new Map,G=new Map,z=new Map,K=new Map,_=new WeakSet,L=!1,S=()=>{while(H.size>512){let J=H.keys().next();if(!J.done)H.delete(J.value)}},O=(J)=>{try{j$(D1(J.policyStorage))}catch{}},b=async()=>{try{let J=await Z.read();return O(J),D1(J.policyStorage)}catch{return!1}},w=(J)=>({providerID:J.providerID,sessionID:J.sessionID,kind:J.kind,modelID:J.modelID,agent:J.agent}),f=(J,X)=>JSON.stringify([J.providerID,J.sessionID,J.kind,J.modelID,J.agent,X]),y=(J)=>{if(L)throw Error("Native Anthropic source is closed");let X=z.get(J.sessionID);if(!X){X=new AbortController,z.set(J.sessionID,X);while(z.size>512){let B=z.keys().next();if(!B.done)Z2.forgetSession?.(B.value)}}return X},n=(J,X,B)=>l2(J)&&(J.type==="api"||c2(J,X,U0(B)).status==="allowed"),e=(J,X)=>J.source===X.source&&J.accountIdentity===X.accountIdentity&&J.credentialId===X.credentialId,V2=async(J,X,B,R,I)=>{let A=await Z.read();O(A),R.signal.throwIfAborted(),j2(A);let h=A.accounts.find((r)=>r.id===J);if(!h||h.type!==B||!n(h,A,X))return I?.(!h||!l2(h)?"account-unavailable":"account-policy"),!1;if(B==="api"){let r=A.accounts.find((m)=>m.id==="main"&&m.type==="oauth");return!!r&&i2(r.quota,A.policyStorage)&&x0(r.quota)}return!0},j2=(J)=>{let X=J.policyStorage.relay;if(X?.enabled===!0&&u8(X.transport,X.url)==="websocket")throw new b2},$2=async(J,X)=>{if(j2(J),X||J.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let B=await Z.getRelayConfig();if(!B)throw Error("request refused: native HTTP relay configuration is unavailable");if(B.transport!=="http")throw new b2;return{dispatch:{kind:"http-relay",url:B.url,token:B.token},relayFallback:B.fallbackToDirect}};async function c(J,X,B){if(J.kind==="local"){let R=await Z.publishLocal(J.subject,B);if(!R&&B.quota)i8.warn("quota","Quota publication discarded");return R}if(J.kind==="vault"&&X.receipt)await Z.vault.publish(X.receipt,B);else if(J.kind==="api"&&B.lastUsed!==void 0)await Z.publishApi(J.subject,{lastUsed:B.lastUsed});return!0}function l(J,X,B){if(J.kind!=="local")return;let R=J.subject.binding,I=I1(B),A={lineage:s8(R),accountUuid:R.identity,entry:{quota:B,checkedAt:I,refreshAfter:I},generalExhausted:a8(B),routeBeforeSave:!0};return Z.quotaObservations.hold(X.account.id,A)?A:void 0}function s(J,X){if(X.exhaustionReported)return;X.exhaustionReported=!0,V.report(J.sessionID,{accountIdentity:X.account.accountIdentity,credentialId:J.provenance.kind==="vault"?J.provenance.credentialId:X.account.credentialId},X.responseHeaders??new Headers,429,X.scope.modelID,!1)}let Z2={async chooseAccount(J){let X=y(J);$.onOwnedRequest?.();let B=await Z.read();O(B),X.signal.throwIfAborted(),j2(B);let R=U0(await $.resolveModelId?.(J)??J.modelID);if(X.signal.throwIfAborted(),B.mode==="claustrum")B=await $$(Z,X.signal),X.signal.throwIfAborted();if(B.policyStorage.quota?.enabled!==!1){let d=!1;for(let J2 of B.accounts){if(!l2(J2)||J2.type!=="oauth")continue;if(e8(J2.quota)?i2(J2.quota,B.policyStorage,Date.now(),R):Date.now()-I1(J2.quota)<p8(B.policyStorage))continue;try{await Z.fetchQuota(J2.id,$.fetch,X.signal,void 0,"admission"),d=!0}catch{X.signal.throwIfAborted()}}if(d)B=await Z.read();X.signal.throwIfAborted()}if(J.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(J.rerouteFrom.limit.reason))return;if(J.phase==="request")M.delete(J.sessionID);let I=await V.accountFor(J.sessionID,R);if(X.signal.throwIfAborted(),I)B=await Z.read(),X.signal.throwIfAborted(),j2(B);let A=[],h=new Map;for(let d of B.accounts){if(d.type!=="oauth")continue;let J2=c2(d,B,R);if(h.set(d.id,J2),J2.status!=="allowed")continue;if(d.source==="local"){let u=await Z.authorizeLocal(d.id,{signal:X.signal,policy:(Y,N)=>c2(Y,N,R)});if(X.signal.throwIfAborted(),u.status!=="usable")continue}A.push(d)}if(I){let d=A.find((Y)=>v1(I,Y)),J2=A.map((Y,N)=>({accountId:Y.id,order:N,quota:Y.quota??{kind:"unknown"}})),u=!I.hold||J.phase==="retry"&&J.rerouteFrom?.accountId===d?.id;if(d&&u&&(I.hold||d.id!==J.rerouteFrom?.accountId)&&g1(d.id,J2,B.policyStorage,R)){let Y=await q(B).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:J2.filter((N)=>N.accountId===d.id),retainAccountIds:new Set([d.id]),...B.mode==="claustrum"?{accountIdentities:new Map([[d.id,I.account_id]])}:{},storage:B.policyStorage,inputBytes:1,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),Y)return I.hold?{hold:{delayMs:I.hold.retry_after_ms}}:Y.accountId}V.override(J.sessionID,!u?"hold requires the same refused retry account":"unknown account, credential, account policy or Fable reserve")}let r=G$(J,B,A,R);if(r)return r;let m=A.filter((d)=>d.id!==J.rerouteFrom?.accountId);if(B0(B.policyStorage)==="sticky-balanced"){let d=m.map((u,Y)=>({accountId:u.id,order:Y,quota:u.quota??{kind:"unknown"}})),J2=await q(B).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:d,retainAccountIds:new Set(m.map((u)=>u.id)),...B.mode==="claustrum"?{accountIdentities:new Map(B.accounts.flatMap((u)=>u.accountIdentity?[[u.id,u.accountIdentity]]:[]))}:{},storage:B.policyStorage,inputBytes:1,preferredAccountId:J.previousAccountId,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),J2)return J2.accountId}else{let J2=B0(B.policyStorage)==="fallback-first"?[...m.filter((u)=>u.id!=="main"),...m.filter((u)=>u.id==="main")]:[...m.filter((u)=>u.id==="main"),...m.filter((u)=>u.id!=="main")];if(J2[0])return J2[0].id}if(B.mode==="claustrum")throw await n8.fromResponse(l8({snapshot:B,modelId:R,policies:h,sticky:B0(B.policyStorage)==="sticky-balanced"}));let a=B.accounts.find((d)=>d.id==="main"&&d.type==="oauth");if(!a)return;let W2=a.quota;if(J.rerouteFrom?.limit.status===429||!i2(W2,B.policyStorage))try{W2=await Z.fetchQuota("main",$.fetch,X.signal)}catch{return}if(X.signal.throwIfAborted(),!x0(W2))return;return B.accounts.find((d)=>d.type==="api"&&l2(d)&&d.id!==J.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(J){let X=J.limit?.reason,B=X?H.get(X):void 0;if(!B||f(B.scope,B.accountId)!==f(J,J.accountId))return;H.delete(B.reason);let R=y(J),I=await Z.read();R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let h=I.accounts.find((a)=>a.id===J.accountId);if(!h||!e(h,B.account)||!n(h,I,A))return;let r=f(J,J.accountId),m=G.get(r)??[];return m.push(B),G.set(r,m),{accountId:J.accountId}},dropSameAccountRetry(J){let X=f(J,J.accountId),B=G.get(X),R=B?.findIndex((I)=>!J.limit||I.reason===J.limit.reason)??-1;if(R!==-1)B?.splice(R,1);if(B?.length===0)G.delete(X)},async authorizeAccount(J,X,B){let R=y(J),I=await Z.read();O(I),R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let h=I.accounts.find((U)=>U.id===X);if(!h||!n(h,I,A)){B?.(!h||!l2(h)?"account-unavailable":"account-policy");return}let r=f(J,X),m=G.get(r),a=m?.shift();if(m?.length===0)G.delete(r);if(a&&!e(h,a.account))return;let{dispatch:W2,relayFallback:d}=await $2(I,a?.direct===!0);if(R.signal.throwIfAborted(),a?.auth){if(!await V2(X,A,a.auth.route,R,B))return;let U=T.get(a.auth.provenance);if(U?.receipt?.expiresAtMs!==void 0&&U.receipt.expiresAtMs!==null&&U.receipt.expiresAtMs<Date.now()+300000)return;if(U)T.set(a.auth.provenance,{...U,scope:{...J,modelID:A},account:h,active:R,relayFallback:d});return K.set(J.sessionID,X),{...a.auth,dispatch:W2}}let J2={scope:{...J,modelID:A},active:R,account:h,retry:a?.retry??!1,relayFallback:d,quota:h.quota};if(h.type==="api"){let U=I.accounts.find((g)=>g.id==="main"&&g.type==="oauth");if(!U||!i2(U.quota,I.policyStorage)||!x0(U.quota))return;let E=await Z.authorizeApi(X,R.signal);if(R.signal.throwIfAborted(),!await V2(X,A,"api",R))return;let x={kind:"api",subject:E.subject};return T.set(x,J2),K.set(J.sessionID,X),{route:"api",headers:E.authHeader==="authorization-bearer"?{authorization:`Bearer ${E.apiKey}`}:{"x-api-key":E.apiKey},baseURL:E.baseURL,provenance:x,dispatch:W2}}if(h.source==="vault"){let U=await Z.authorizeVault(X,R.signal);if(R.signal.throwIfAborted(),a&&(U.credentialId!==a.account.credentialId||U.assertedAccountIdentity!==a.account.accountIdentity))return;if(!await V2(X,A,"oauth",R,B))return;let E={kind:"vault",credentialId:U.credentialId,recordVersion:U.recordVersion};T.set(E,{...J2,receipt:U});let x=U.assertedAccountIdentity;if(!x){B?.("account-unavailable");return}return K.set(J.sessionID,X),{route:"oauth",accessToken:U.accessToken,provenance:E,dispatch:W2,identity:W0(x,x)}}let u=await Z.authorizeLocal(X,{signal:R.signal,policy:(U,E)=>c2(U,E,A)});if(R.signal.throwIfAborted(),u.status!=="usable"){let U=r8(u);if(U)B?.(U.reason);return}if(!await V2(X,A,"oauth",R,B))return;let Y={kind:"local",subject:u.subject};T.set(Y,{...J2,access:u.access}),K.set(J.sessionID,X);let N=u.subject.binding.identity;return{route:"oauth",accessToken:u.access,provenance:Y,dispatch:W2,identity:W0(N,N)}},async requestOptions(J,X){let B=y(J),R=await Z.read();O(R),B.signal.throwIfAborted();let I=R.accounts.find((h)=>h.id===J.accountId);if(!I||!n(I,R,J.modelID))throw X?.(!I||!l2(I)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let A=T.get(J.provenance);if(A)T.set(J.provenance,{...A,scope:{...A.scope,modelID:J.modelID}});return $.requestOptions(J,R)},async admitRequest(J,X){let B=T.get(J.provenance);if(!B||!await V2(J.accountId,J.modelID,J.route,B.active,X))throw Error("request refused: native account policy changed before dispatch");T.set(J.provenance,{...B,scope:{...B.scope,modelID:J.modelID}})},isDumpEnabled:()=>b(),onRequestPrepared:(J)=>$.onRequestPrepared?.(J),responseOptions(J){return $.responseOptions?.({...J,modelID:T.get(J.provenance)?.scope.modelID??J.modelID})},quotaFromHeaders(J,X){let B=T.get(X.provenance);if(B){B.responseHeaders=J;let W2=X.status<400&&!M.has(X.sessionID);if(W2)M.add(X.sessionID);if(X.status===429)s(X,B);else V.report(X.sessionID,{accountIdentity:B.account.accountIdentity,credentialId:X.provenance.kind==="vault"?X.provenance.credentialId:B.account.credentialId},J,X.status,B.scope.modelID,W2)}let R=f1(J);if(R)$.onRequestId?.(X,R);if(!B||X.route!=="oauth"||!c8(J))return;let I=X.provenance.kind==="local"?X.provenance.subject.binding.identity:B.receipt?.assertedAccountIdentity,A={...t8(J),...I?{accountIdentity:I}:{}},h=o8(B.quota,A);B.quota=h;let r=l(X.provenance,B,h),m=B.account.id,a=()=>{if(r)Z.quotaObservations.forget(m,r)};return Q.observe(c(X.provenance,B,{quota:h}).then((W2)=>{if(!W2)a()},(W2)=>{throw a(),W2})),A},async limitFromResponse(J){let X=T.get(J.provenance);if(!X)return;if(J.status===401&&X.receipt){if(!_.has(X.receipt))_.add(X.receipt),await Z.vault.reportFailure(X.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(X.retry||X.active.signal.aborted)return;let R=X.active,I=await Z.vault.prepareRetry(X.receipt,R.signal);if(R.signal.throwIfAborted(),!I.retry)return;let A=I.receipt,h=A.assertedAccountIdentity;if(!h)return;let r={kind:"vault",credentialId:A.credentialId,recordVersion:A.recordVersion};T.set(r,{...X,receipt:A,retry:!0});let m=`vault-newer:${J.attemptId}`;return H.set(m,{scope:w(J),reason:m,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:A.accessToken,provenance:r,identity:W0(h,h)}}),S(),{reason:m,status:401}}if(J.status===401&&J.provenance.kind==="local"&&X.access&&!X.retry){if(X.active.signal.aborted)return;let R=X.active,I=await Z.authorizeLocal(J.accountId,{rejectedAccessToken:X.access,signal:R.signal,policy:(m,a)=>c2(m,a,X.scope.modelID)});if(R.signal.throwIfAborted(),I.status!=="usable"||I.access===X.access)return;let A={kind:"local",subject:I.subject};T.set(A,{...X,access:I.access,retry:!0});let h=I.subject.binding.identity,r=`local-newer:${J.attemptId}`;return H.set(r,{scope:w(J),reason:r,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:I.access,provenance:A,identity:W0(h,h)}}),S(),{reason:r,status:401}}let B=await Z.read();if(J$(J.status,B.policyStorage))return{reason:`provider-${J.status}`,status:J.status};return},limitFromRelayFailure(J){let X=T.get(J.provenance);if(!X?.relayFallback||X.active.signal.aborted||!(J.status===401||J.status>=500))return;let B=`relay-direct:${J.attemptId}`;return H.set(B,{scope:w(J),reason:B,accountId:J.accountId,account:X.account,direct:!0,retry:!1}),S(),{reason:B}},limitFromStreamError(J){let X=T.get(J.provenance);if(X&&J.errorType==="rate_limit_error")s(J,X);return J.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(J,X){let B=T.get(X.provenance);if(X.dispatch==="http-relay"&&B?.relayFallback&&!B.active.signal.aborted&&J.status===void 0){let R=`relay-direct:${X.attemptId}`;return H.set(R,{scope:w(X),reason:R,accountId:X.accountId,account:B.account,direct:!0,retry:!1}),S(),{reason:R}}return},async onAttemptEnd(J,X){let B=T.get(J.provenance);if(!B)return;try{if(X.status===401&&B.receipt&&!_.has(B.receipt))_.add(B.receipt),await Z.vault.reportFailure(B.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(!X.localRefusal&&X.status!==void 0)Q.publish(()=>c(J.provenance,B,{lastUsed:Date.now()}))}finally{T.delete(J.provenance)}},forgetSession(J){M.delete(J),z.get(J)?.abort(),z.delete(J),K.delete(J);for(let[X,B]of H)if(B.scope.sessionID===J)H.delete(X);for(let[X,B]of G)if(B[0]?.scope.sessionID===J)G.delete(X);$.onForgetSession?.(J)},servedAccount:(J)=>K.get(J),resetRouting:async(J)=>q(await Z.read()).clear(J),async recordPrime(J,X){let B=T.get(J);if(!B||B.active.signal.aborted)return!1;if(J.kind==="local")return Z.incrementPrimeUsage(B.account.id,J.subject,X);if(J.kind==="vault"&&B.receipt)return Z.incrementPrimeUsage(B.account.id,B.receipt,X);return!1},drainRoutingPublications:()=>Promise.all([Z.drainRoutingPublications(),...[...C.values()].map((J)=>J.drain())]).then(()=>{}),close(){L=!0;for(let J of z.values())J.abort();return z.clear(),G.clear(),H.clear(),Promise.all([Q.drain(),Z2.drainRoutingPublications()]).then(()=>{})}};return Z2}import{remapModelId as Y$}from"@cortexkit/anthropic-auth-core";function u1(){let $=new l1,Z=new Map,Q=new Map,V=new Map,M=new Set,C=new Set,q=new Map,T=(H)=>{while(H.size>512){let G=H.keys().next();if(!G.done)H.delete(G.value)}};return{async install(H){let G=[];try{G.push(await H.session.hook("context",(z)=>{let K=z.messages.map((L)=>{return{info:{id:L.id,sessionID:z.sessionID,role:L.role,agent:z.agent,model:{providerID:z.model.providerID,modelID:z.model.id}},parts:L.content.map((S)=>({type:S.type,...S.type==="text"?{text:S.text}:{}}))}});$.observeMessages(K);let _=z.messages.findLast((L)=>L.role==="user"&&L.id);if(_?.id)Z.set(z.sessionID,_.id);if(_?.content.some((L)=>L.type==="text"&&L.text===Y0))M.add(z.sessionID);else M.delete(z.sessionID);T(Z)},{providerID:"anthropic"})),G.push(await H.session.hook("model.request",(z)=>{if(z.kind!=="primary")return;let K=Z.get(z.sessionID);if(!K)return;if($.markHeaders({sessionId:z.sessionID,messageId:K,agent:z.agent,headers:z.headers}),M.has(z.sessionID))z.headers[y2]="1"},{providerID:"anthropic"}))}catch(z){throw await Promise.allSettled(G.map((K)=>K.dispose())),z}return{dispose:async()=>{await Promise.all(G.map((z)=>z.dispose()))}}},requestOptions(H,G){let z=$.resolveHeader(H.correlation[e2]);if(z)Q.set(H.attemptId,z),T(Q);q.set(H.attemptId,H.sessionID),T(q);let K=H.correlation[y2]==="1";if(K)C.add(H.attemptId);return{cache1hEnabled:H.agent!=="compaction"&&H.agent!=="title"&&(G.policyStorage.claudeCache?.enabled??!0),cache1hMode:G.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:G.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:G.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:G.policyStorage.turnEndNote,serverSideFallbackEnabled:d1(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:K,billingLineage:z?{promptId:z.promptId,previousRequestId:z.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:V.get(H.sessionID)}},responseOptions(H){return{serverSideFallbackModel:Y$(H.modelID),laneStart:C.has(H.attemptId),onMessageStart(G){if(H.kind==="primary"&&typeof G.id==="string")V.set(H.sessionID,G.id),T(V)},onStreamEnd(){Q.delete(H.attemptId),C.delete(H.attemptId),q.delete(H.attemptId)}}},onRequestId(H,G){$.commit(Q.get(H.attemptId),G)},forgetSession(H){$.clearSession(H),Z.delete(H),V.delete(H),M.delete(H);for(let[G,z]of q)if(z===H)Q.delete(G),C.delete(G),q.delete(G)}}}var z0="cortexkit-anthropic-auth",E$='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',q$="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",x$="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function S$($){let Z=$.authorize??W$,Q=$.exchange??K$,V=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},M=async()=>{let T;try{T=await $.readMode()}catch{throw Error(x$)}return V(),T},C=async()=>{if(await M()!=="local")throw Error(E$)};return{integrationID:"anthropic",methods:[{method:{id:V0,type:"oauth",label:Q0},async authorize(){V(),await C();let T=await Z("max");return V(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(H)=>{V();let G=await Q(H,T.verifier,T.redirectUri,T.state);if(!$.isActive()||G.type!=="success")throw Error("Claude sign-in did not complete");return{access:G.access,refresh:G.refresh,expires:G.expires}}}}}],vault:{method:{id:p1,type:"oauth",label:"Claude vault accounts"},async activate(){if(V(),await M()!=="claustrum")throw Error(q$)}},async onLogin(T){V(),await C(),await $.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),V()},label:"Claude native account pool"}}function k$($){return{readMode:()=>_$("opencode",$),disconnectVault:()=>z$({host:"opencode",env:$})}}function k0($={}){return{id:z0,setup:(Z)=>i1(Z,$)}}async function R$($){try{return await A$($)}catch(Z){throw b$(Z)}}function b$($){let Z=$0($);if(Z)return Z;let Q=C$("decide where its account state is",[],$);return S0.error("state-layout",Q.message,{code:Q.code}),$0(Q)??Q}async function A$($){if($.paths){let Q=$.paths;return await Q$(Q),{paths:Q,holderRegistration:await L$({paths:Q,role:"opencode2",kind:N$(),policy:O$(),onLockEvent:$.local?.onLockEvent})}}let Z=await B$({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await F$(void 0,void 0,Z.layout),holderRegistration:Z.kind==="state-home"?void 0:Z.registration}}async function i1($,Z={}){let{paths:Q,holderRegistration:V}=await R$(Z),M=V$({paths:Q,host:"opencode",local:Z.local,vault:Z.vault}),C=k$(Z.vault?.env??process.env);try{let f=await M.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)T$(M$(f.policyStorage)??"info");P$(H$(f.policyStorage))}catch{}let q=!0,T=u1(),H=x1(),G,z,K,_=m1({runtime:M,paths:Q,fetch:Z.fetch,requestOptions:T.requestOptions,responseOptions:T.responseOptions,onRequestId:T.onRequestId,onForgetSession:T.forgetSession,onRequestPrepared:async(f)=>{try{await K?.track(f)}catch{S0.warn("cachekeep","live request tracking failed")}},resolveModelId:async(f)=>H.modelId(f.modelID),onOwnedRequest:()=>{G??=N1(M,Z.fetch),z??=w1({runtime:M,paths:Q,source:_,fetch:Z.fetch})}});K=K1({...Z.cacheKeep,runtime:M,source:_,storageId:Q.storageId,fetch:Z.fetch,isSubagent:async(f)=>Boolean((await $.session.get({sessionID:f})).parentID)}),await K.ready;let L=q1({runtime:M,source:_,cacheKeepRegistry:K.registry,start:async(f,y)=>{await $.session.synthetic({sessionID:f,text:y,description:"Claude lane start",resume:!0})}}),S=[],O=await M1($,{source:_,log:{warn:(f,y)=>S0.warn("opencode2",f,y)}},{credential:S1}).catch(async(f)=>{throw V?.close(),L.close(),await K?.dispose(),await _.close(),await M.drainQuotaPublications(),await M.close(),f}),b,w=()=>{if(b)return b;return q=!1,V?.close(),L.close(),_.close(),b=(async()=>{await Promise.allSettled([O.dispose(),G?.dispose(),z?.dispose(),K?.dispose(),...S.map((f)=>f.dispose())]),await _.close(),await M.drainQuotaPublications(),await M.close()})(),b};try{S.push(await T.install($)),S.push(await H.install($)),S.push(await H0($,S$({isActive:()=>q,readMode:C.readMode,runtime:M})));let f={host:"opencode",dispatch:L.dispatch,readStatus:(n)=>L.readStatus(n),readAccounts:()=>M.read(),readMode:C.readMode,disconnectVault:C.disconnectVault,interactive:!0},y=U$(f);return S.push(await c1($,y,L)),w}catch(f){throw await w(),f}}var K6={id:z0,setup:k0().setup,server:o1};export{i1 as setupAnthropicAuth,K6 as default,k0 as createAnthropicAuthPlugin,z0 as ANTHROPIC_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.8",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@clack/prompts": "^1.6.0",
|
|
80
|
-
"@cortexkit/anthropic-auth-core": "2.4.
|
|
80
|
+
"@cortexkit/anthropic-auth-core": "2.4.8",
|
|
81
81
|
"@cortexkit/claustrum-client": "0.13.0",
|
|
82
82
|
"@cortexkit/private-files": "0.2.2",
|
|
83
83
|
"@cortexkit/subc-client": "^0.22.10",
|