@cortexkit/opencode-anthropic-auth 2.4.13 → 2.5.1

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