@cortexkit/opencode-anthropic-auth 2.5.2 → 2.5.4

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