@cortexkit/opencode-anthropic-auth 2.9.0 → 2.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +45 -45
- package/dist/fable-fallback.d.ts +5 -5
- package/dist/{index-pxnn7mg1.js → index-m7k9zxem.js} +1 -1
- package/dist/{index-h508mdrx.js → index-pcyn2rkg.js} +1 -1
- package/dist/index-tqz6p5bw.js +45 -0
- package/dist/index.js +1 -1
- package/dist/setup/native-enrollment.d.ts +5 -1
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +7 -1
- package/dist/v2/adapter.d.ts +4 -1
- package/dist/v2/server.js +11 -11
- package/dist/v2/source.d.ts +1 -0
- package/dist/v2/tui.js +1 -1
- package/package.json +4 -3
- package/src/sidebar-state.ts +3 -2
- package/src/tui/quota-sidebar.js +296 -258
- package/src/tui-compiled/quota-sidebar.js +296 -258
- package/src/tui-compiled/sidebar-state.ts +3 -2
- package/dist/index-s1efwnr3.js +0 -45
package/dist/v2/server.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{a as _1,b as
|
|
2
|
-
`)}:{event:N,data:
|
|
3
|
-
`)}}function R1($,X){let N=new TextDecoder,W="",P=(S)=>{let O=B4(S);if(!O)return;try{$(O)}catch(z){X(z)}},T=()=>{for(;;){let S=/\r?\n\r?\n/.exec(W);if(!S)return;let O=W.slice(0,S.index);W=W.slice(S.index+S[0].length),P(O)}};return new TransformStream({transform(S,O){O.enqueue(S),W+=N.decode(S,{stream:!0}),T()},flush(){if(W+=N.decode(),T(),W.trim()!=="")P(W);W=""}})}var i1=512,A1=3621000,t2="x-common-auth-attempt",n2=($,X)=>JSON.stringify([$,X]),f2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function M4($){let X=$.headers;return typeof X==="object"&&X!==null}function K4($,X){let N=$.getReader();return new ReadableStream({async pull(W){let P;try{P=await N.read()}catch(T){X({reason:"failed",message:T instanceof Error?T.message:String(T)}),W.error(T);return}if(P.done)X(),W.close();else W.enqueue(P.value)},async cancel(W){X({reason:"cancelled",...W===void 0?{}:{message:String(W)}}),await N.cancel(W)}})}function U1($,X){for(let[N,W]of Object.entries(X)){let P=N.toLowerCase();for(let T of Object.keys($))if(T.toLowerCase()===P)delete $[T];if(W!==null)$[N]=W}}function z4($,X){for(let[N,W]of Object.entries(X))if(W===null)$.delete(N);else $.set(N,W)}async function w1($,X,N={}){let{providerID:W}=X,P=N.gateOnPlaceholder,T=(Z)=>P===void 0||P.credential(Z)===d2(W),S=N.logger,O=Math.max(1,N.maxRecords??i1),z=N.hostRetryLimit??10,U=[...N.hostCredentials??[d2(W)],...P?[d2(W)]:[]].filter((Z)=>Z!==""),V=new Map,C=new WeakMap,_=new Map,b=0,A=new Set,H=new Map,D=new Map,f=(Z)=>{let j=D.get(Z);return j?.ownedSeen===!0&&j.foreignSeen},o=(Z,j)=>{H.set(Z,j);let L=D.get(Z)??{ownedSeen:!1,foreignSeen:!1};if(j)L.ownedSeen=!0;else L.foreignSeen=!0;D.set(Z,L)},M=(Z,j)=>{let L=P?.refuseMisplaced,R=L?[...j].filter(([,i])=>i.includes(d2(W))):[],K=T(j)&&(!L||R.length>0);if(L){if(R.length>0&&(R.length!==1||!K))throw o(Z.sessionID,!1),new a2({kind:"placement-refused",providerID:W,sessionID:Z.sessionID,requestKind:Z.kind,message:L(R[0]?.[0]??"")})}return o(Z.sessionID,K),K},I=!1,x=!1,m=new Map,s=0,h=!1,Z2=new Map,$2=(Z,j)=>{try{S?.warn(Z,j)}catch{}},V2=(Z)=>Z instanceof Error?Z.message:String(Z),H2=(Z)=>Z.excluded.clear(),M2=(Z)=>Z.excluded.size===0?{}:{excluded:[...Z.excluded]},Q2=(Z,j,L)=>{if(!N.enforceRequestExclusion||Z===void 0||!L.excluded.has(Z))return!1;return $2("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:j.sessionID,kind:j.kind,phase:j.phase,accountId:Z}),!0},T2=new Map,F2=(Z,j)=>{let L=(T2.get(Z)??Promise.resolve()).then(j),R=L.then(()=>{},()=>{});return T2.set(Z,R),R.then(()=>{if(T2.get(Z)===R)T2.delete(Z)}),L},g2=(Z,j)=>{let L=T2.get(Z);return L?L.then(()=>g2(Z,j)):j()},L2=async(Z)=>{try{await X.dropChoice?.({...Z.input,accountId:Z.accountId})}catch(j){$2("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:Z.input.sessionID,error:V2(j)})}},a=async(Z)=>{try{await X.dropSameAccountRetry?.({...Z.input,accountId:Z.accountId})}catch(j){$2("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:Z.input.sessionID,error:V2(j)})}},J=async(Z)=>{if(Z.next)await L2(Z.next);if(Z.sameAccount)await a(Z.sameAccount)},Y=(Z)=>{let j=_.get(Z);if(_.delete(Z),j)F2(j.sessionID,()=>J(j))},Q=async(Z,j)=>{let L=m.get(Z);if(!L||L.size===0)return;await Promise.all([...L].map(async(R)=>{try{await R(j)}catch(K){$2("opencode2 auth listener threw; the request is unaffected",{event:Z,error:V2(K)})}}))},E=async(Z)=>{let j=new Set([...V.values()].filter((R)=>R.scope.sessionID===Z.sessionID).map((R)=>R.transport).filter((R)=>R!==void 0)),L=Z.handle?.transport??(j.size===1?[...j][0]:"unknown");try{S?.info?.("opencode2 auth retry decision",{sessionID:Z.sessionID,transport:L,attempt:Z.attempt,reason:Z.reason==="host-decides"&&f(Z.sessionID)?"mixed-session":Z.reason,retry:Z.decision.retry})}catch{}await Q("retry",Z)},y=async(Z,j)=>{try{await X.onAttemptEnd?.(Z,j)}catch(L){$2("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Z.attemptId,error:V2(L)})}},q=(Z,j)=>{if(Z.ended||!Z.attempt)return;let L={...Z.status===void 0?{}:{status:Z.status},outputStarted:Z.outputStarted,...Z.limit?{limit:Z.limit.signal}:{},...j?{error:j}:{}};if(j)Z.endError=j;if(j?.reason==="cancelled"||!j&&!Z.limit&&(Z.status===void 0||Z.status<400))H2(Z.request);Z.ended=y(Z.attempt,L)},l=(Z,j)=>q(Z,{reason:"abandoned",message:j}),c=(Z)=>[...V.values()].filter((j)=>j.key===Z),t=(Z)=>c(Z).at(-1),X2=(Z)=>{if(V.delete(Z.id),_.get(Z.key)?.attemptId===Z.id||!c(Z.key).length)Y(Z.key)},K2=(Z)=>{V.set(Z.id,Z);while(V.size>O){let j=V.values().next().value;if(j===void 0)break;l(j,"dropped to keep the record bound"),X2(j)}},d=(Z)=>Z.accountId===void 0?void 0:{...Z.scope,accountId:Z.accountId},e=(Z,j)=>new a2({kind:"no-account",providerID:W,sessionID:Z.sessionID,requestKind:Z.kind,...j===void 0?{}:{message:j}}),n=(Z)=>{Z2.get(Z)?.clear(),Z2.delete(Z)},G=async(Z,j)=>{let L=()=>e(Z,`${W} ${Z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(h)throw L();let R=Z2.get(Z.sessionID);if(!R)R=new Set,Z2.set(Z.sessionID,R);let K={};R.add(K);let i=()=>{if(!R.has(K))throw L()};try{return await j(i)}finally{if(R.delete(K),R.size===0&&Z2.get(Z.sessionID)===R)Z2.delete(Z.sessionID)}},F=(Z,j)=>{for(let[L,R]of j)if(U.some((K)=>R.includes(K)))throw new a2({kind:"host-credential-on-wire",providerID:W,sessionID:Z.sessionID,requestKind:Z.kind,message:`${W} ${Z.kind} request still carries the host's placeholder credential in ${L}; the adapter's account headers must replace it`})},B=(Z)=>{for(let j of c(Z))if(j.ended||!j.attempt)X2(j);else if(j.transport==="ws"||j.judged)l(j,"a newer attempt of its session and kind began"),X2(j)},k=async(Z,j,L,R)=>{let K=n2(Z.sessionID,Z.kind),{input:i,accountId:p,sameAccountRetry:u,request:N2}=await g2(Z.sessionID,async()=>{L();let C2=_.get(K);_.delete(K);let j1=c(K);if(C2&&j1.some((_2)=>_2.id!==C2.attemptId&&_2.attempt&&!_2.ended))$2("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:Z.sessionID,kind:Z.kind});if(!C2){let _2=new Set(j1.filter((A2)=>A2.attempt&&!A2.ended).map((A2)=>A2.request));for(let A2 of j1)if(!_2.has(A2.request))H2(A2.request)}let b2=C2?.request??{excluded:new Set},O2=C2?.accountId??t(K)?.accountId;B(K);let B2=C2?.next,S2=C2?.sameAccount,G2=S2!==void 0&&S2.input.modelID===Z.modelID&&S2.input.agent===Z.agent,R2=B2!==void 0&&B2.input.modelID===Z.modelID&&B2.input.agent===Z.agent,h2=C2?.wake,U2={...Z,phase:"request",...M2(b2),...O2===void 0?{}:{previousAccountId:O2},...C2?.rerouteFrom?{rerouteFrom:C2.rerouteFrom}:{},...h2===void 0?{}:{wake:h2,hostAttempt:B2?.input.hostAttempt}};if(B2&&(!R2||h2!==void 0))await F2(Z.sessionID,()=>L2(B2)),L();if(S2&&!G2)await F2(Z.sessionID,()=>a(S2)),L();if(S2?.continuation&&(!G2||f(Z.sessionID))){if(G2)await F2(Z.sessionID,()=>a(S2));throw e(Z)}let o2=G2?S2.accountId:R2&&h2===void 0?B2.accountId:await X.chooseAccount(U2),l2=typeof o2==="string"?o2:void 0;if(Q2(l2,U2,b2)){let _2=l2;if(G2&&S2)await F2(Z.sessionID,()=>a(S2));else if(_2!==void 0)await F2(Z.sessionID,()=>L2(R2&&B2?B2:{accountId:_2,input:U2}));l2=void 0,L()}return{input:U2,accountId:l2,sameAccountRetry:G2,request:b2}});L();let w2={},D2;if(p!==void 0){let C2=await X.accountHeaders({...Z,accountId:p});if(L(),M4(C2))w2=C2.headers,D2=C2.attempt;else w2=C2}let Y1=`attempt-${++s}`,y2={id:Y1,key:K,scope:Z,request:N2,accountId:p,headers:w2,attempt:p===void 0?void 0:{...Z,accountId:p,attemptId:Y1,transport:R,data:D2},...R===void 0?{}:{transport:R},outputStarted:!1,sameAccountRetry:u};if(K2(y2),y2.attempt)Q("select",{...Z,accountId:y2.attempt.accountId,hook:j,...i.previousAccountId===void 0?{}:{previousAccountId:i.previousAccountId},...i.rerouteFrom===void 0?{}:{rerouteFrom:i.rerouteFrom},handle:y2.attempt});return y2},w=async(Z,j,L,R,K)=>{let i=n2(Z.sessionID,Z.kind),p=R===void 0?void 0:V.get(R);if(p?.key!==i)p=void 0;if(!p){if(p=t(i),c(i).filter((N2)=>N2.transport===void 0&&!N2.ended).length>1&&!x)x=!0,$2("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Z.sessionID,kind:Z.kind})}if(!p||p.transport!==void 0||p.ended)p=await k(Z,j,K,L);else if(p.transport=L,p.attempt)p.attempt.transport=L;if(L==="ws"){for(let u of c(i))if(u!==p&&u.transport==="ws")l(u,"a newer attempt of its session and kind went out over WebSocket")}return p},g=async(Z,j)=>{try{return await j()}catch(L){throw q(Z,{reason:"failed",message:V2(L)}),L}},v=(Z,j)=>{let L=c(n2(Z,j)).filter((R)=>R.transport==="ws").at(-1);return L?.attempt!==void 0&&!L.ended?L:void 0},j2=(Z,j,L)=>{let R=d(Z);if(!R||!Z.attempt||Z.limit)return;Z.limit={signal:j,delivered:Q("limit",{...R,via:L,limit:j,outputStarted:Z.outputStarted,handle:Z.attempt})}},r=(Z,j,L,R)=>{let K=d(Z);if(!K||!Z.attempt)return;Q("quota",{...K,transport:j,...R===void 0?{}:{status:R},quota:L,handle:Z.attempt})},z2=(Z,j,L,R)=>{let K=Z.attempt;if(!K)return;let i=X.inspectEvent?.(R===void 0?{transport:j,data:L,attempt:K}:{transport:j,data:L,event:R,attempt:K});if(!i)return;if(i.quota!==void 0)r(Z,j,i.quota);if(i.outputStarted)Z.outputStarted=!0;if(i.hostRetry==="veto")Z.hostRetry="veto";if(i.limit)j2(Z,i.limit,j);if(i.error!==void 0)q(Z,{reason:"failed",message:i.error});else if(i.done)q(Z)},P2=(Z,j)=>{let L=Z.attempt;if(!L||j.accountId===Z.accountId)return;if(L.reboundFrom??=L.accountId,L.accountId=j.accountId,"data"in j)L.data=j.data;Z.accountId=j.accountId},k2=(Z)=>!Z.attempt||Z.endError!==void 0||Z.status!==void 0&&Z.status>=400,I2=(Z)=>{let j=[...V.values()].filter((u)=>u.scope.sessionID===Z),L=j.filter((u)=>u.limit&&!u.rerouted).at(-1);if(L)return L;let R=j.filter((u)=>u.scope.kind==="primary"),K=R.length>0?R:j;if(K.length<=1)return K[0];let i=K.filter((u)=>!u.judged&&k2(u)).at(-1);if(i)return i;let p=K.filter((u)=>u.attempt&&!u.ended);if(p.length>1)return"ambiguous";return p[0]??K.at(-1)},x2={providerID:W},q2=[];q2.push(await $.session.hook("model.request",(Z)=>{if(P)return;return G(f2(Z),async(j)=>{let L=await k(f2(Z),"model.request",j);if(j(),L.accountId===void 0)throw e(L.scope);U1(Z.headers,{...L.headers,[t2]:L.id})})},x2)),q2.push(await $.session.hook("http.request",(Z)=>{if(P){if(!M(f2(Z),Z.request.headers))return}return G(f2(Z),async(j)=>{let L=Z.request.headers.get(t2)??void 0,R=P?await k(f2(Z),"http.request",j,"http"):await w(f2(Z),"http.request","http",L,j);j();let K=d(R),i=R.attempt;if(!K||!i)throw e(R.scope);await g(R,async()=>{let p=Z.request;if(X.rewriteRequest){if(L!==void 0){let w2=new Headers(p.headers);w2.delete(t2),p=new Request(p,{headers:w2})}p=await X.rewriteRequest({...K,request:p,attempt:i})??p,j()}let u=new Headers(p.headers);u.delete(t2),z4(u,R.headers),F(R.scope,u.entries());let N2=new Request(p,{headers:u});C.set(N2,R),Z.request=N2})})},x2)),q2.push(await $.session.hook("http.response",async(Z)=>{let j=C.get(Z.request);if(!j){if(P)return;if(!I)I=!0,$2("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Z.sessionID,kind:Z.kind});return}let L=Z.response;if(X.answeredBy&&j.attempt){let u=j.attempt,N2=await g(j,async()=>X.answeredBy?.({request:Z.request,response:L,attempt:u}));if(N2)P2(j,N2)}let R=d(j),K=j.attempt;if(!R||!K)return;j.status=L.status;let i=X.quotaFromHeaders?.(L.headers,L.status,K);if(i!==void 0)r(j,"http",i,L.status);if(!L.ok&&X.limitFromResponse){let u=await X.limitFromResponse({status:L.status,headers:L.headers,body:()=>L.clone().text(),attempt:K});if(u)j2(j,u,"http")}if(!L.ok||!L.body)q(j);let p=L;if(L.body&&(X.inspectEvent||X.onAttemptEnd)){let u=L.body;if(X.inspectEvent)u=u.pipeThrough(R1((N2)=>z2(j,"http",N2.data,N2.event),(N2)=>$2("opencode2 auth event inspection threw",{error:V2(N2)})));p=new Response(K4(u,(N2)=>{if(N2?.reason==="failed")j.readFailed=!0;q(j,N2)}),{status:L.status,statusText:L.statusText,headers:L.headers})}if(X.rewriteResponse)p=await X.rewriteResponse({...R,request:Z.request,response:p,attempt:K})??p;if(X.responseRetry){if(await X.responseRetry({...R,request:Z.request,response:p,attempt:K})==="veto")j.hostRetry="veto"}if(p!==L)Z.response=p},x2)),q2.push(await $.session.hook("experimental.ws.handshake",(Z)=>{if(P){let j=n2(Z.sessionID,Z.kind);if(A.delete(j),!M(f2(Z),new Headers(Z.headers)))return}return G(f2(Z),async(j)=>{let L;for(let p of Object.keys(Z.headers)){if(p.toLowerCase()!==t2)continue;L??=Z.headers[p],delete Z.headers[p]}let R=P?await k(f2(Z),"experimental.ws.handshake",j,"ws"):await w(f2(Z),"experimental.ws.handshake","ws",L,j);j();let K=d(R),i=R.attempt;if(!K||!i)throw e(R.scope);await g(R,async()=>{if(!P?.refuseMisplaced)U1(Z.headers,R.headers);let p=X.rewriteHandshakeURL?.({...K,url:Z.url,attempt:i});if(p!==void 0)Z.url=p;if(P?.refuseMisplaced)U1(Z.headers,R.headers);if(F(R.scope,Object.entries(Z.headers)),P)A.add(R.key)})})},x2));let Y2=X.rewriteWebSocketFrame?.bind(X);if(Y2)q2.push(await $.session.hook("experimental.ws.send",async(Z)=>{let j=f2(Z);if(P&&!A.has(n2(j.sessionID,j.kind)))return;let L=v(j.sessionID,j.kind),R=await Y2({...j,attempt:L?.attempt,frame:Z.frame});if(R!==void 0)Z.frame=R},x2));q2.push(await $.session.hook("experimental.ws.receive",(Z)=>{if(P&&!A.has(n2(Z.sessionID,Z.kind)))return;let j=v(Z.sessionID,Z.kind);if(!j)return;try{z2(j,"ws",Z.frame)}catch(L){$2("opencode2 auth frame inspection threw",{error:V2(L)})}},x2)),q2.push(await $.session.hook("retry",async(Z)=>{if(P&&H.get(Z.sessionID)!==!0)return;let j=Z.decision,L=()=>E({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:j,decision:j});if(f(Z.sessionID)&&!X.retrySameAccount){await L();return}let R=I2(Z.sessionID);if(!R)return;if(R==="ambiguous"){await E({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:j,decision:j});return}let K=R,i=()=>K.hostRetry==="veto";await G(K.scope,async(p)=>{let u=p,N2=X.retrySameAccount?.bind(X),w2=K.attempt,D2=K.outputStarted;if(K.transport==="ws"&&D2&&!K.ended&&!K.limit&&!(K.status!==void 0&&K.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&Z.error.type==="provider.transport")K.readFailed=!0,q(K,{reason:"failed",message:Z.error.message});if(D2&&K.readFailed&&N2&&w2&&!f(Z.sessionID)){if(!K.limit){let b2=X.limitFromError?.(Z.error,w2);if(b2)j2(K,b2,"error")}if(K.ended)await K.ended;if(K.limit)await K.limit.delivered;u()}let Y1=()=>K.readFailed===!0&&Z.error.type==="provider.transport"&&j.retry&&z-Z.attempt>=1&&!K.limit&&!(K.status!==void 0&&K.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&!w2?.reboundFrom&&!i()&&!f(Z.sessionID);if(N2&&w2&&(!D2||Y1())&&(!i()||f(Z.sessionID))&&!K.sameAccountRetry){if(K.ended)await K.ended;if(K.limit)await K.limit.delivered;let b2=await F2(K.scope.sessionID,async()=>{u();let O2=w2.accountId,B2=()=>V.has(K.id)&&K.accountId===O2&&I2(Z.sessionID)===K&&K.outputStarted===D2&&(!D2||Y1())&&(!i()||f(Z.sessionID))&&(!P||H.get(Z.sessionID)===!0);if(!B2()||K.sameAccountRetry)return!1;K.sameAccountRetry=!0;let S2={...K.scope,accountId:O2,error:Z.error,attempt:Z.attempt,...K.limit?{limit:K.limit.signal}:{},...D2?{continuation:"interrupted-read"}:{}},G2;try{G2=await N2(S2)}catch(U2){$2("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:Z.sessionID,error:V2(U2)})}if(!G2)return u(),!1;let R2={accountId:G2.accountId,input:S2,...D2?{continuation:!0}:{}};try{u()}catch(U2){throw await a(R2),U2}if(!B2()||G2.accountId!==O2)return await a(R2),!1;let h2=_.get(K.key);if(_.delete(K.key),h2)await J(h2);try{u()}catch(U2){throw await a(R2),U2}if(!B2())return await a(R2),!1;return _.set(K.key,{request:K.request,attemptId:K.id,sessionID:K.scope.sessionID,order:++b,accountId:O2,sameAccount:R2}),K.judged=!0,Z.decision=D2?j:{retry:!0,delay:0},!0});if(u(),b2){await E({sessionID:Z.sessionID,accountId:K.accountId,kind:K.scope.kind,attempt:Z.attempt,reason:D2?"continue-same-account":"same-account",hostDecision:j,decision:Z.decision,handle:K.attempt});return}}if(f(Z.sessionID)){await L();return}K.judged=!0;let y2=K.attempt;if(y2&&!K.outputStarted){if(!K.limit){let b2=X.limitFromError?.(Z.error,y2);if(b2)j2(K,b2,"error")}if(K.ended)await K.ended;if(K.limit)await K.limit.delivered}u();let{decision:C2,reason:j1}=await F2(K.scope.sessionID,async()=>{if(u(),f(Z.sessionID))return{decision:j,reason:"host-decides"};let b2=_.get(K.key);if(_.delete(K.key),b2)await J(b2);if(u(),f(Z.sessionID))return{decision:j,reason:"host-decides"};let O2=j,B2,S2,G2,R2;if(K.accountId===void 0||!y2)O2={retry:!1},B2="no-account";else if(K.outputStarted)O2={retry:!1},B2="output-started";else if(i())O2={retry:!1},B2="adapter-veto";else if(K.limit){let h2={accountId:K.accountId,limit:K.limit.signal},U2,o2={...K.scope,phase:"retry",...M2(K.request),hostAttempt:Z.attempt,previousAccountId:K.accountId,rerouteFrom:h2};try{U2=await X.chooseAccount(o2)}catch(q1){$2("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:K.scope.sessionID,error:V2(q1)})}let l2=typeof U2==="string"?U2:typeof U2==="object"&&("hold"in U2)?K.accountId:void 0;if(Q2(l2,o2,K.request)){if(l2!==void 0)await L2({accountId:l2,input:o2});U2=void 0}let _2=typeof U2==="object"&&"hold"in U2?U2.hold:void 0,A2=typeof U2==="object"&&"waitThenReselect"in U2?U2.waitThenReselect:void 0,U4=typeof U2==="object"&&"hostRetry"in U2?U2.hostRetry:void 0,W1=typeof U2==="string"?U2:_2?K.accountId:void 0;if(W1!==void 0)G2={accountId:W1,input:o2};try{u()}catch(q1){if(G2)await L2(G2);throw q1}if(f(Z.sessionID)){if(G2)await L2(G2);return{decision:j,reason:"host-decides"}}if(i()||U4==="veto"){if(G2)await L2(G2);if(G2=void 0,u(),f(Z.sessionID))return{decision:j,reason:"host-decides"};K.hostRetry="veto",O2={retry:!1},B2="adapter-veto"}else if(!(z-Z.attempt>=1)){if(G2)await L2(G2);G2=void 0,B2="host-decides-last-account"}else if(A2&&Number.isFinite(A2.delayMs)&&A2.delayMs>=0&&A2.delayMs<=A1)O2={retry:!0,delay:Math.ceil(A2.delayMs)},B2="wait-then-reselect";else if(_2&&Number.isFinite(_2.delayMs)&&_2.delayMs>=0&&_2.delayMs<=A1){if(O2={retry:!0,delay:Math.ceil(_2.delayMs)},_2.target!==void 0)R2={target:_2.target,..._2.checkpoint===void 0?{}:{checkpoint:_2.checkpoint},..._2.kind===void 0?{}:{kind:_2.kind}};B2="hold"}else if(!_2&&W1!==void 0&&W1!==K.accountId)K.rerouted=!0,K.request.excluded.add(K.accountId),S2=h2,O2={retry:!0,delay:0},B2="reroute";else{if(_2&&G2)await L2(G2),G2=void 0;B2="host-decides-last-account"}}else B2="host-decides";if(Z.decision=O2,O2.retry&&K.accountId!==void 0&&V.has(K.id))_.set(K.key,{request:K.request,attemptId:K.id,sessionID:K.scope.sessionID,order:++b,accountId:K.accountId,...S2===void 0?{}:{rerouteFrom:S2},...G2===void 0?{}:{next:G2},...R2===void 0?{}:{wake:R2}});else if(G2)await L2(G2);if(!O2.retry)H2(K.request);return{decision:O2,reason:B2}});u(),await E({sessionID:Z.sessionID,...K.accountId===void 0?{}:{accountId:K.accountId},kind:K.scope.kind,attempt:Z.attempt,reason:j1,hostDecision:j,decision:C2,...y2===void 0?{}:{handle:y2}})})},x2));let J2=(Z)=>{if(n(Z),H.delete(Z),!D.get(Z)?.foreignSeen)D.delete(Z);for(let j of A)if(JSON.parse(j)[0]===Z)A.delete(j);for(let j of[...V.values()]){if(j.scope.sessionID!==Z)continue;l(j,"its session was forgotten"),H2(j.request),V.delete(j.id)}for(let[j,L]of _)if(L.sessionID===Z)Y(j)},E2=new AbortController,W2=$.event;if(W2)(async()=>{try{for await(let Z of W2.subscribe({signal:E2.signal}))if(Z.type==="session.deleted")J2(Z.data.sessionID);else if(Z.type==="session.status"&&Z.data.status.type==="idle"){let j=Z.data.sessionID,L=++b;F2(j,async()=>{for(let[R,K]of _)if(K.sessionID===j&&K.order<L)_.delete(R),H2(K.request),await J(K)})}}catch(Z){if(!E2.signal.aborted)$2("opencode2 auth stopped listening for session deletion",{error:V2(Z)})}})();return{on(Z,j){let L=m.get(Z);if(!L)L=new Set,m.set(Z,L);let R=j;return L.add(R),()=>{L.delete(R)}},accountFor(Z,j){return t(n2(Z,j))?.accountId},forgetSession:J2,get size(){return V.size},async dispose(){if(h)return;h=!0;for(let Z of Z2.keys())n(Z);E2.abort();for(let Z of V.values())l(Z,"the installation was disposed");V.clear();for(let Z of _.keys())Y(Z);A.clear(),H.clear(),D.clear(),m.clear(),await Promise.all(T2.values()),await Promise.all(q2.map(async(Z)=>{try{await Z.dispose()}catch(j){$2("opencode2 auth hook did not dispose cleanly",{error:V2(j)})}}))}}}import{createHash as o1}from"node:crypto";import{AnthropicOAuthOriginError as _4,applyCustomHeaders as N4,applyRunnerTurnNotes as H4,assertHostAuthorityStable as B1,assertNotCustodyTombstone as F4,classifyGzipRejection as L4,createDumpResponseObserver as P4,createProviderErrorRedactor as n1,createProviderErrorResponseScope as r1,decideRequestGzip as O4,dumpDirectRequest as s1,dumpRelayRequest as a1,dumpResponseArtifact as M1,encodeGzipRequestBody as T4,getRequestGzipLatch as E4,getRequestGzipLatchPath as C4,isDumpEnabled as S4,MessageThreadTracker as x4,mergeAnthropicBetas as q4,prepareMessageThreadRequest as k4,remapModelId as t1,remapRequestBodyModel as b4,requestCacheLifetimeMs as R4,requestSignal as A4,resolveNativePoolPaths as w4,runWithRequestSignal as e1,sendWithRequestGzip as D4,setDumpEnabled as $0,signRequestBody as I4,stateLayoutOfPaths as y4,stateRefusalCause as f4,stateRefusalPublicMessage as v4,stripEmptyTrailingAssistantMessages as g4,TrailingAssistantHistoryError as h4}from"@cortexkit/anthropic-auth-core";var e2="anthropic",B0="x-common-auth-attempt",m4=["x-session-affinity","x-opencode-session","x-parent-session-id",J0,_1,p2,B0],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,M0=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=($,X="provider request failed")=>({type:M0.has($.type)?$.type:"provider_error",message:X,...$.status!==void 0?{status:$.status}:{}});class K0 extends Error{sessionID;requestKind;kind="no-account";providerID=e2;constructor($,X){super(d4);this.sessionID=$;this.requestKind=X;this.name="NativeAnthropicNoAccountError"}}class K1 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=e2;constructor($,X){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=X;this.name="NativeAnthropicRevokedError"}}class m2 extends Error{kind="unsupported-transport";providerID=e2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class z0 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=e2;constructor($){super(v4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function N1($){let X=f4($);return X?new _0(X):void 0}var u2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function i4($){let X=new Set;while(u2($)&&!X.has($)){if(X.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 Z0($){if($.status!==400&&$.status!==404||!$.body)return $;return new Response($.body.pipeThrough(new TransformStream),$)}function G1($){try{return JSON.parse($)}catch{return}}function I1($){let X={};for(let[N,W]of Object.entries($??{}))X[N.toLowerCase()]=W;return X}function X0($){let X={};for(let N of m4){let W=$.get(N);if(W!==null&&N!==B0)X[N]=W;$.delete(N)}return X}function o4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function n4($){return $ instanceof h4||$ instanceof Y0||$ instanceof _4?new z0($):void 0}function r4($,X){let N=[];if($.oauth)N.push($.oauth.accessToken);for(let[W,P]of Object.entries($.apiHeaders??{})){if(P===null||!z1.has(W))continue;N.push(P.replace(/^Bearer\s+/i,""))}for(let W of z1){let P=X.get(W);if(P!==null)N.push(P.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")N.push($.dispatch.token);return[...new Set(N.filter(Boolean))]}var s4=new Set(["oauth-2025-04-20","claude-code-20250219",G0]);function a4($){let X=$.split(",").map((N)=>N.trim()).filter((N)=>N&&!s4.has(N));return q4(null,X)}function t4($,X,N){let W=G1($);if(!u2(W))return $;let P=g4(W.messages),T=Object.hasOwn(W,"fallbacks"),{droppedMarkers:S}=V0(W,!1),O=T&&!Object.hasOwn(W,"fallbacks"),z=b4(W);return H4(W,{sessionId:X,modelId:N,isOAuth:!1}),P>0||S>0||O||z?JSON.stringify(W):$}async function e4($,X){if(!($ instanceof Promise))return"settled";let N;try{return await Promise.race([$.then(()=>"settled"),new Promise((W)=>{N=setTimeout(()=>W("timed-out"),X)})])}finally{if(N!==void 0)clearTimeout(N)}}function $1($){let{source:X,log:N}=$,W=Math.max(1,$.maxPendingSends??u4),P=$.attemptEndTimeoutMs??p4,T=$.requestGzipLatch,S=async()=>{if(T)return T;let G=await w4();return T??=E4(C4(G.legacyConfig,y4(G))),T},O=new WeakSet,z=new Map,U=new WeakMap,V=new WeakMap,C=(G)=>JSON.stringify([G.providerID,G.sessionID,G.kind,G.modelID,G.agent,G.accountId]),_=new Map,b=new WeakMap,A=new Map,H=new WeakMap,D=n1([]);D.dispose();let f=(G)=>(G&&A.get(G)?.redactor)??D,o=(G)=>{t.get(G)?.thread.fail(),t.delete(G);let F=A.get(G);if(!F)return;A.delete(G),F.redactor.dispose(),F.scope.dispose()},M=(G,F,B,k)=>{let w=r4(F,k),g=r1(w,B);I.set(G,B),A.set(G,{sessionID:F.sessionID,redactor:n1(w),scope:g}),g.settled.then(()=>{if(A.get(G)?.scope===g)o(G)});while(A.size>W){let v=A.keys().next().value;if(v===void 0)break;o(v)}},I=new WeakMap,x=(G,F)=>{let B=G?I.get(G):void 0;if(!B||!F.ok)return D.redactResponse(F);let k=r1([],B),w=k.redactResponse(F);return k.dispose(),w},m=(G,F)=>{let B=G?A.get(G)?.scope:void 0;if(!B)return x(G,F);try{return B.redactResponse(F)}catch{return x(G,F)}},s=!1,h=new Map,Z2=new WeakMap,$2=new WeakMap,V2=new WeakMap,H2=(G)=>G.agent==="cachekeep"||G.agent==="prime",M2=async()=>{try{if(X.isDumpEnabled)return await X.isDumpEnabled()}catch{return!1}try{return S4()}catch{return!1}},Q2=(G)=>{h.delete(G)},T2=new WeakMap,F2=new WeakMap,g2=new WeakMap,L2=(G,F)=>{if(G&&!F.ok)T2.set(F.headers,G);let B=G?.route==="oauth"&&F.ok?F2.get(G):void 0;if(B)g2.set(F,B);return F},a=(G,F)=>{if(F.dispatch!=="http-relay")return!0;let B=/^req_[A-Za-z0-9_-]+$/.test(G.get("request-id")??"");return V.set(F,B),B},J=(G)=>new K0(G.sessionID,G.kind),Y=new Map,Q=async(G,F)=>{if(s)throw new K1(G.sessionID,G.kind);let B={revoked:!1},k=Y.get(G.sessionID);if(!k)k=new Set,Y.set(G.sessionID,k);k.add(B);let w=()=>{if(A4()?.throwIfAborted(),s||B.revoked)throw new K1(G.sessionID,G.kind)};try{let g=await F(w);return w(),g}finally{let g=Y.get(G.sessionID);if(g?.delete(B)&&g.size===0)Y.delete(G.sessionID)}},E=(G,F)=>{z.set(G,F);while(z.size>W){let B=z.keys().next().value;if(B===void 0)break;z.delete(B),N?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:W})}},y=(G,F)=>({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:F.route,provenance:X2.get(F)??F.provenance,dispatch:F.dispatch}),q=(G)=>Q(G,async(F)=>{let{accountId:B,...k}=G,w;try{w=await X.authorizeAccount(k,B)}catch(g){let v=N1(g);if(v)throw N?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:v.cause instanceof Error?v.cause.name:""}),v;throw g}return F(),l(k,w)}),l=(G,F)=>{if(!F)throw J(G);if(F.dispatch?.kind==="websocket-relay")throw new m2;let B=F.dispatch?.kind==="http-relay"?"http-relay":"direct",k=F.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":F.dispatch.token}:void 0;if(F.route==="oauth"){if(!F.accessToken)throw J(G);F4(F.accessToken,e2);let v=Object.freeze({route:"oauth",provenance:F.provenance,dispatch:B});E(v,{sessionID:G.sessionID,oauth:{accessToken:F.accessToken,credentialId:F.credentialId,...F.identity?{identity:F.identity}:{}},dispatch:F.dispatch,oauthHeaders:F.headers});let j2=I1(F.headers);for(let r of z1)delete j2[r];return delete j2["anthropic-beta"],{headers:k??{...j2,"x-api-key":null,authorization:`Bearer ${F.accessToken}`},attempt:v}}let w={authorization:null,"x-api-key":null,...I1(F.headers)};if(!w.authorization&&!w["x-api-key"])throw J(G);let g=Object.freeze({route:"api",provenance:F.provenance,dispatch:B});return E(g,{sessionID:G.sessionID,...F.baseURL?{baseURL:F.baseURL}:{},dispatch:F.dispatch,apiHeaders:w}),{headers:k??w,attempt:g}},c=new x4,t=new WeakMap,X2=new WeakMap,K2=new WeakSet,d=(G)=>Q(G,(F)=>e(G,F)),e=async(G,F)=>{let{request:B,attempt:k}=G,w=k.data;_.set(C(G),k);while(_.size>W){let Y2=_.keys().next();if(!Y2.done)_.delete(Y2.value)}let g=w?z.get(w):void 0;if(w)z.delete(w);if(!w||!g||w.route==="oauth"&&!g.oauth)throw J(G);let v=new Headers(B.headers);N4(v);let j2=X0(v),r=B.body===null?void 0:await B.text();F();let z2=r!==void 0&&o4(B.url),P2=W0(B.url,g.baseURL!==void 0?{baseURL:g.baseURL}:{}).url?.toString()??B.url;try{if(w.route==="oauth"&&g.oauth){j0(P2);let{accessToken:Y2,identity:J2}=g.oauth;for(let[W2,Z]of Object.entries(I1(g.oauthHeaders))){if(z1.has(W2))continue;if(Z===null)v.delete(W2);else v.set(W2,Z)}let E2=null;if(r!==void 0&&z2){let W2={...y(k,w),modelID:(()=>{let L=G1(r);return t1(u2(L)&&typeof L.model==="string"?L.model:G.modelID)})(),route:"oauth",correlation:j2},Z=await X.requestOptions?.(W2)??{};if(F(),k.agent!=="cachekeep")r=await U0(r,{...Z,deferSigning:!0,...J2?{identity:J2}:{},sessionId:G.sessionID,modelId:G.modelID,isOAuth:!0,onToolNameMap:(L)=>b.set(w,L)});let j=G1(r);E2=u2(j)?j:null}Q0(v,Y2,{body:E2,...J2?{identity:J2}:{},requestClass:k.kind!=="primary"||y1(k.agent)?"auxiliary":"main"})}else{if(r!==void 0&&z2)r=t4(r,G.sessionID,G.modelID);v.delete("authorization"),v.delete("x-api-key");for(let[J2,E2]of Object.entries(g.apiHeaders??{}))if(E2===null)v.delete(J2);else v.set(J2,E2);if(r!==void 0&&z2&&!v.has("content-type"))v.set("content-type","application/json");let Y2=v.get("anthropic-beta");if(Y2!==null){let J2=a4(Y2);if(J2)v.set("anthropic-beta",J2);else v.delete("anthropic-beta")}}}catch(Y2){let J2=n4(Y2);if(!J2)throw Y2;throw U.set(w,J2.check),N?.warn("refused an Anthropic request locally; nothing was sent",{check:J2.check}),J2}let k2=r!==void 0?G1(r):void 0;if(await X.admitRequest?.({...y(k,w),modelID:t1(u2(k2)&&typeof k2.model==="string"?k2.model:G.modelID)}),X0(v),r!==void 0)v.delete("content-length");if(F(),M(w,g,u2(k2)&&k2.stream===!0?"event-stream":"http",v),w.route==="oauth"&&z2&&r!==void 0)await X.onRequestPrepared?.({...y(k,w),url:P2,bodyText:r,signal:B.signal}),F();if(w.route==="oauth"&&g.oauth&&z2&&r!==void 0&&k.kind==="primary"&&!y1(k.agent)&&k.agent!=="cachekeep"&&k.agent!=="compaction"&&j2[p2]!=="1"){let Y2=g.oauth.identity?.accountUuid,J2,E2=await k4(c,{session:G.sessionID,account:g.oauth.identity?.accountUuid??G.accountId,credential:g.oauth.credentialId,bodyText:r,replyToolNames:b.get(w),headers:v,signal:B.signal});r=E2.bodyText,t.set(w,{thread:E2,beforeResend:async()=>{if(K2.has(w)||!A.has(w))return!1;F(),B.signal.throwIfAborted();let W2=await e1(B.signal,async()=>X.authorizeAccount(G,G.accountId));if(F(),B.signal.throwIfAborted(),!A.has(w)||W2?.route!=="oauth"||!W2.accessToken||!Y2||W2.identity?.accountUuid!==Y2)return!1;if((W2.dispatch?.kind??"direct")!==(g.dispatch?.kind??"direct"))return!1;if(await e1(B.signal,async()=>X.admitRequest?.({...y(k,w),provenance:W2.provenance})),F(),!A.has(w))return!1;return J2=W2,{credential:W2.credentialId}},resend:async(W2)=>{F(),B.signal.throwIfAborted();let Z=J2;if(J2=void 0,!A.has(w))throw new K1(G.sessionID,G.kind);if(Z?.route!=="oauth"||!Z.accessToken)throw J(G);X2.set(w,Z.provenance);let j=new Headers(v);j.set("authorization",`Bearer ${Z.accessToken}`),o(w),M(w,{...g,oauth:{accessToken:Z.accessToken,credentialId:Z.credentialId,identity:Z.identity}},"event-stream",j);let L=Z.dispatch,R=async(i,p)=>{try{B1(),q2(B,W2);let u=await($.fetch??globalThis.fetch)(i,p);if(u.ok&&a(u.headers,w))F2.set(w,{at:$.now?.()??Date.now()});return u}catch(u){if(B.signal.throwIfAborted(),!i4(u))throw u;return Response.json({type:"error",error:{type:"api_error",message:"Connection lost while resending a rejected thread request"}},{status:502})}},K;if(L?.kind==="http-relay"){let i={protocol:1,type:"request",affinity:G.sessionID,upstream:{url:P2,method:B.method,headers:Object.fromEntries(j)},mode:"full_sync",revision:1,body:W2,next_hash:`sha256:${o1("sha256").update(W2).digest("hex")}`};h.set(w,{affinity:G.sessionID,route:G.accountId,bodyText:W2,url:P2,method:B.method,headers:j,dispatch:"http-relay",relayUrl:L.url,envelope:i,relayBytes:JSON.stringify(i).length}),K=await R(L.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":L.token},body:JSON.stringify(i),signal:B.signal,redirect:"error"})}else{if(L?.kind==="websocket-relay")throw new m2;h.set(w,{affinity:G.sessionID,route:G.accountId,bodyText:W2,url:P2,method:B.method,headers:j,dispatch:"direct"}),K=await D4({url:P2,body:W2,headers:j,latch:await S(),send:(i,p)=>{return B1(),R(P2,{method:B.method,body:i,headers:p,signal:B.signal,redirect:"error"})}})}return Z0(K)}}),F()}else if(w.route==="oauth"&&z2&&r!==void 0&&k.agent!=="cachekeep")r=await I4(r),F();if(g.dispatch?.kind==="http-relay"){let Y2=r??"";v.delete("x-relay-token");let J2={protocol:1,type:"request",affinity:G.sessionID,upstream:{url:P2,method:B.method,headers:Object.fromEntries(v)},mode:"full_sync",revision:1,body:Y2,next_hash:`sha256:${o1("sha256").update(Y2).digest("hex")}`};if(z2&&r!==void 0&&!H2(k)){let Z=j2[p2]==="1"?"start":void 0,j=JSON.stringify(J2);h.set(w,{affinity:G.sessionID,route:G.accountId,bodyText:Y2,url:P2,method:B.method,headers:new Headers(v),dispatch:"http-relay",relayUrl:g.dispatch.url,envelope:J2,relayBytes:j.length,...Z?{tag:Z}:{}})}else Q2(w);B1();let E2=v.get("x-client-request-id"),W2=new Request(g.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":g.dispatch.token,...E2?{"x-client-request-id":E2}:{}},redirect:"error",signal:B.signal,body:JSON.stringify(J2)});return q2(W2,r),W2}let I2=r;if(w.route==="oauth"&&z2&&r!==void 0){let Y2=await O4({url:P2,body:r,latch:await S()});if(F(),Y2.gzip)I2=await T4(r),v.set("content-encoding","gzip"),O.add(w),F()}if(z2&&r!==void 0&&!H2(k)){let Y2=j2[p2]==="1"?"start":void 0;h.set(w,{affinity:G.sessionID,route:G.accountId,bodyText:r,url:P2,method:B.method,headers:new Headers(v),dispatch:"direct",...Y2?{tag:Y2}:{}})}else Q2(w);B1();let x2=new Request(P2,{method:B.method,headers:v,redirect:w.route==="oauth"?"error":B.redirect,signal:B.signal,...I2!==void 0?{body:I2}:{}});return q2(x2,r),x2;function q2(Y2,J2){if(w?.route!=="oauth"||!z2||J2===void 0)return;try{X.onFinalRequestPrepared?.({attemptId:k.attemptId,requestId:Y2.headers.get("x-client-request-id")??void 0,bodyText:J2,ttlMs:R4(J2)})}catch{}}},n={providerID:e2,chooseAccount:(G)=>Q(G,async()=>{let F=await X.chooseAccount(G);if(typeof F==="object"&&G.phase==="retry")return F;if(typeof F!=="string"||!F)throw J(G);return F}),dropChoice:(G)=>X.dropChoice?.(G),async retrySameAccount(G){if(!X.retrySameAccount)return;let F=C(G),B=_.get(F);_.delete(F);let k=G.limit??(B?n.limitFromError?.(G.error,B):void 0);return X.retrySameAccount({...G,error:D1(G.error),...k?{limit:k}:{}})},dropSameAccountRetry:(G)=>X.dropSameAccountRetry?.({...G,error:D1(G.error)}),accountHeaders:q,rewriteRequest:d,rewriteHandshakeURL(){throw new m2},async rewriteResponse({response:G,attempt:F}){let B=F.data,k=B?t.get(B):void 0,w=k?.thread.fail;if(B)t.delete(B);if(k&&B&&a(G.headers,B))G=await k.thread.recover(Z0(G),k.resend,k.beforeResend),G=k.thread.observe(G);else k?.thread.fail();if(B&&!a(G.headers,B)){if(B)Q2(B);if(G.status===401)return o(B),G.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return m(B,G)}if(B&&O.has(B))O.delete(B),L4(G).then(async(j)=>{if(!j)return;(await S()).latchProcess(),N?.warn("gzipped request body rejected; later requests go uncompressed",{kind:j,status:G.status})},()=>{});let g=null,v=B?h.get(B):void 0;if(B&&v){let j=!1;try{j=await M2()}catch{j=!1}if(!j)Q2(B);else{try{$0(!0)}catch{}try{if(v.dispatch==="http-relay")g=await a1({affinity:v.affinity,transport:"http",protocol:1,mode:"full_sync",status:G.status,bodyText:v.bodyText,payload:v.envelope??{},relayBytes:v.relayBytes??0,...v.tag?{tag:v.tag}:{}});else g=await s1({affinity:v.affinity,route:v.route,status:G.status,bodyText:v.bodyText,url:v.url,method:v.method,headers:v.headers,...v.tag?{tag:v.tag}:{}})}catch{g=null}if(Q2(B),g){Z2.set(B,g);try{await M1(g,{status:G.status,message:null,complete:!1})}catch{}V2.set(B,Promise.resolve())}}}let j2=m(B,G);if(B?.route!=="oauth"||!j2.body)return L2(B,j2);let r={...y(F,B),status:G.status},z2=X.responseOptions?.(r)??{},P2=(G.headers.get("content-type")??"").includes("application/json"),k2={...z2,toolNameMap:B?b.get(B):void 0,onResponseFailure:w,onToolNameRefusal:()=>{if(!B)return;U.set(B,"response_tool_names"),o(B)},laneStartOAuthServed:!0,...P2?{responseMode:"json"}:{}};if(!B||!g)return L2(B,f1(j2,k2));let I2=g,x2=G.status,q2=P4(I2,x2),Y2=(j)=>{let R=(V2.get(B)??Promise.resolve()).then(()=>j().then(()=>{return})).catch(()=>{return});V2.set(B,R)},J2=z2.onMessageStart,E2=z2.onMessageDelta,W2=z2.onMessageResponse,Z=z2.onStreamEnd;return L2(B,f1(j2,{...k2,onSseEvent:q2.observe,onMessageStart:(j)=>{try{J2?.(j)}catch{}try{$2.set(B,{...j}),Y2(()=>M1(I2,{status:x2,message:j,complete:!1}))}catch{}},onMessageDelta:(j)=>{try{E2?.(j)}catch{}try{let L=$2.get(B)??{},R=L.usage&&typeof L.usage==="object"&&!Array.isArray(L.usage)?L.usage:{},K={...L,...j.usage?{usage:{...R,...j.usage}}:{},...j.stopReason?{stop_reason:j.stopReason}:{}};Y2(()=>M1(I2,{status:x2,message:K,complete:!0,reply_text_edges:q2.replyTextEdges()}))}catch{}},onMessageResponse:(j)=>{try{W2?.(j)}catch{}try{Y2(()=>M1(I2,{status:x2,message:j,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await Z?.()}catch{}try{await(V2.get(B)??Promise.resolve())}catch{}}}))},quotaFromHeaders(G,F,B){let k=B.data;if(!k||!a(G,k))return;if(k.route==="oauth"&&F>=200&&F<300)F2.set(k,{at:$.now?.()??Date.now()});return X.quotaFromHeaders?.(G,{...y(B,k),status:F})},async limitFromResponse({status:G,headers:F,body:B,attempt:k}){let w=k.data;if(!w||U.get(w)==="response_tool_names")return;if(!a(F,w))return X.limitFromRelayFailure?.({...y(k,w),status:G});if(H.set(w,`provider responded with HTTP ${G}`),!X.limitFromResponse)return;let g=T2.get(F)===w,v=f(w),j2=await X.limitFromResponse({...y(k,w),status:G,headers:F,body:async()=>g?await B():v.redactText(await B())});if(j2)K2.add(w);return j2},inspectEvent({data:G,event:F,attempt:B}){if(B.data&&U.get(B.data)==="response_tool_names")return;let k=G1(G);if(!u2(k))return;let w=typeof k.type==="string"?k.type:F;if(w==="content_block_start"||w==="content_block_delta")return{outputStarted:!0};if(w==="message_stop")return{done:!0};if(w!=="error")return;let g=B.data,v=f(g),j2=u2(k.error)?k.error:{},r=typeof j2.type!=="string"?void 0:M0.has(j2.type)?j2.type:v.redactText(j2.type),z2=typeof j2.message==="string"?v.redactText(j2.message):void 0;if(g?.dispatch==="http-relay"&&V.get(g)===!1)return;let P2=g?X.limitFromStreamError?.({...y(B,g),errorType:r,message:z2}):void 0,k2={error:[r??"error",z2].filter(Boolean).join(": ").slice(0,c4),...P2?{limit:P2}:{}};if(g&&k2.error)H.set(g,k2.error);return k2},limitFromError(G,F){let B=F.data;if(!B||U.has(B))return;let k=D1(G,H.get(B));if(o(B),B.dispatch==="http-relay"&&V.get(B)===!1)return;return X.limitFromHostError?.(k,y(F,B))},async onAttemptEnd(G,F){let B=G.data;if(!B)return;z.delete(B);let k=h.get(B);if(k){Q2(B);try{if(await M2()){try{$0(!0)}catch{}try{if(k.dispatch==="http-relay"){if(F.status!==void 0)await a1({affinity:k.affinity,transport:"http",protocol:1,mode:"full_sync",status:F.status,bodyText:k.bodyText,payload:k.envelope??{},relayBytes:k.relayBytes??0,...k.tag?{tag:k.tag}:{}})}else await s1({affinity:k.affinity,route:k.route,status:F.status,error:F.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 w=F.error?.reason;if(w==="cancelled"||w==="abandoned"||w===void 0&&(F.status===void 0||F.status<400))o(B);let g=U.get(B),{status:v,...j2}=F,r=X.onAttemptEnd?.(y(G,B),{...j2,...v!==void 0&&(B.dispatch!=="http-relay"||V.get(B)===!0)?{status:v}:{},...g!==void 0?{localRefusal:{check:g}}:{}});if(await e4(r,P)==="timed-out")N?.warn("the account source did not finish recording a send",{timeoutMs:P})}};return{adapter:n,acceptedResponse:(G)=>g2.get(G),dispose(){s=!0;for(let[G,F]of Y){for(let B of F)B.revoked=!0;X.forgetSession?.(G)}Y.clear(),z.clear(),_.clear(),h.clear();for(let G of[...A.keys()])o(G)},forgetSession(G){c.forget(G);for(let F of Y.get(G)??[])F.revoked=!0;Y.delete(G);for(let[F,B]of _)if(B.sessionID===G)_.delete(F);for(let[F,B]of z)if(B.sessionID===G)z.delete(F);for(let[F,B]of[...A])if(B.sessionID===G)o(F);for(let[F,B]of[...h])if(B.affinity===G)h.delete(F);X.forgetSession?.(G)},get pendingSendCount(){return z.size},get heldCredentialCount(){let G=0;for(let F of z.values())if(F.oauth)G++;return G},get heldRedactorCount(){return A.size},get operationsInProgress(){let G=0;for(let F of Y.values())G+=F.size;return G}}}import{setTimeout as X9}from"node:timers/promises";import{CacheKeepManager as J9,CacheKeepPrewarmError as g1,CacheKeepSessionRegistry as Y9,CacheKeepWarmRefusal as h1,getCacheKeepRegistryDirectories as j9,isCacheKeepActiveNow as N0,isCacheKeepHybridActive as X1,isCacheKeepSubagentsEnabled as r2,logger as i2,NativeAccountRefusal as c2,nativeAccountCanServe as L0,nativeAccountRefusal as G9,readSessionCachePolicy as v2,requestCacheLifetimeMs as H0,sessionCacheActivity as V9}from"@cortexkit/anthropic-auth-core";import{CacheKeepStore as Z9}from"@cortexkit/anthropic-auth-core";var H1="2.9.0";import{cacheKeepStoreDirectory as v8,legacyCacheKeepStoreDirectory as g8}from"@cortexkit/anthropic-auth-core";class v1 extends Z9{constructor($,X){super({...$,pluginVersion:H1},X)}}var P0=new WeakMap;function Z1($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}function Q9($,X){if(!$)return"foreign-identity";try{let N=JSON.parse($);if(!Array.isArray(N))return"foreign-identity";let[W,,P,T,S]=N;if(W==="local"&&typeof T==="string"&&typeof S==="string")return X.some((O)=>O.binding?.storageId===T&&O.binding.rowId===S)?"foreign-identity":"account-gone";if(W==="vault"&&typeof P==="string")return X.some((O)=>O.credentialId===P)?"foreign-identity":"account-gone"}catch{}return"foreign-identity"}function O0($,X,N){if(!N){$.hybridDisabled=!1;return}let W=(S)=>v2(S,!0)?.keep_warm!==void 0,P=!1;for(let S of $.manager.trackedSessions())if(W(S.id)||$.manager.hasPlannedTarget?.(S.id))P=!0;else $.manager.untrack(S.id,"disabled");if($.hybridDisabled)return;$.hybridDisabled=!0;let T=$.persistence;$.localCleanup=($.localCleanup??Promise.resolve()).then(async()=>{await T.drain(),await T.load(X,(O)=>{if(!$.hybridDisabled)return;if(O.policyState?.planned||W(O.policyState?.ownerSessionId??O.id)){P=!0;return}return T.removed(O.id),"invalid"});let S=$.manager.trackedSessions().some((O)=>W(O.id)||$.manager.hasPlannedTarget?.(O.id));if(!P&&!S&&$.hybridDisabled)T.clear()}).catch(()=>i2.warn("cachekeep","local restart cleanup failed"))}var F0=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function T0(){let $=globalThis;return $[F0]??=new Map,$[F0]}function W9($,X,N){let W=new Map,P=new Map,T=new Set,S=0,O=new Y9({...j9("opencode",X.registryDirectory),now:X.now}),z=()=>{let H;for(let D of P.values())H=D;return H},U=X.setIntervalImpl??globalThis.setInterval,V=new J9({loadStorage:async()=>{let H=z(),D=H?await H.loadStorage():null;if(H)O0(A,X.now?.()??Date.now(),!X1(D));return D},now:X.now,setIntervalImpl:(H,D)=>U(()=>{let f=V.tick();return A.ticking=f.catch(()=>{i2.warn("cachekeep","tick failed")}),A.ticking},D),clearIntervalImpl:X.clearIntervalImpl,setTimeoutImpl:X.setTimeoutImpl,clearTimeoutImpl:X.clearTimeoutImpl,reserveWarm:(H)=>A.persistence.reserveWarm(H),settleWarm:(H)=>V.isCurrentTarget(H)?A.persistence.reserveWarm(H):Promise.resolve(!1),deferWarmReservation:!0,responseTtlMs:(H)=>P0.get(H),onTargetChanged:(H)=>A.persistence.changed(H),onTargetRemoved:(H)=>{T.delete(H),A.persistence.removed(H)},onTrackedSessionsChanged:(H)=>O.publish(P.size===0?[]:H),prepareHeaders(H,D,f){let o=z();if(!o)return;return W.set(f.id,{target:D,attempt:f,lease:o}),new Headers({"x-native-cachekeep-attempt":String(f.id)})},fetchImpl:async(H,D)=>{let f=new Request(H,D),o=Number(f.headers.get("x-native-cachekeep-attempt")),M=W.get(o);if(W.delete(o),!M||M.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(T.delete(M.target.id))await X9(Math.max(0,S+3000-Date.now()),void 0,{signal:M.attempt.signal}),S=Date.now();let I=M.lease.send(M.target,f,M.attempt.signal),x=I.then(()=>{},()=>{});return M.lease.inflight.add(x),x.then(()=>M.lease.inflight.delete(x)),I},onComplete:({attempt:H})=>{W.delete(H.id)}}),C,_=()=>{if(C!==void 0)clearTimeout(C);C=void 0},b=()=>{if(_(),P.size>0)return;let H=V.dropExpiredTargets();if(H===void 0){let f=T0();if(f.get($)===A)f.delete($);return}let D=X.now?.()??Date.now();if(C=setTimeout(b,Math.max(0,H-D)),typeof C==="object"&&"unref"in C)C.unref()},A={manager:V,registry:O,persistence:N,persistenceFollowsOwner:!0,prepared:W,leases:P,nextGeneration:0,retain(){V.stop(),W.clear(),b()},async adopt(){if(_(),A.loading??=(async()=>{let H=z();if(!H)return;let D=await H.read(),f=X.now?.()??Date.now(),o=0;await A.persistence.load(f,(M)=>{if(!P.size||V.trackedRequest(M.id))return;if(!X1(D.policyStorage)&&v2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0)return"invalid";let I=D.accounts.find((s)=>Z1(s)===M.oauthAccountIdentity);if(!I)return Q9(M.oauthAccountIdentity,D.accounts);if(I.type!=="oauth"||!L0(I))return"account-gone";if(M.isSubagent&&v2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!r2(D.policyStorage))return"invalid";let x=M.nextPrewarmAt<=f?f+o++*3000:M.nextPrewarmAt,m=V.track({sessionId:M.id,url:M.url,headers:new Headers,bodyText:M.bodyText,storage:D.policyStorage,cacheMode:"hybrid",oauthAccountId:I.id,oauthAccountIdentity:M.oauthAccountIdentity,isSubagent:M.isSubagent,retained:{cacheExpiresAt:M.cacheExpiresAt,nextPrewarmAt:x,ttlMs:M.ttlMs,lastTouchAt:M.lastTouchAt,lastTouchKind:M.lastTouchKind,policyState:M.policyState}});if(m.tracked)T.add(M.id);return m.tracked?!0:"invalid"})})().catch(()=>{i2.warn("cachekeep","failed to restore tracked sessions")}),await A.loading,!P.size)return;if(V.dropExpiredTargets()===void 0)return;V.start(),O.publish(V.registrySessions?.()??V.trackedSessions()).catch(()=>{i2.warn("cachekeep","failed to publish tracked sessions")})}};return A}function E0($){let{runtime:X,source:N}=$,W=new AbortController,P=T0(),T=P.get($.storageId),S=new v1({storageId:$.storageId,...$.persistence},T?.persistence),O=T??W9($.storageId,$,S);if(T&&!T.persistenceFollowsOwner){O.legacyPersistence??=O.persistence;let M=O.legacyPersistence;M.changed=(I)=>S.changed(I),M.removed=(I)=>S.removed(I),M.clear=()=>S.clear(),M.load=(I,x)=>S.load(I,x)}O.persistence=S,P.set($.storageId,O);let{manager:z,registry:U}=O,V=new Map,C=async(M,I)=>{let x=V.get(M),m=()=>!H.stopped&&x!==void 0&&z.trackedPolicyState?.(M)===x;if(!m())return;if(!I){z.updateSubagent?.(M,!1);return}let s=()=>[...O.leases.values()].at(-1),h=s(),Z2=await h?.loadStorage();if(!m()||!h||s()!==h)return;if(Z2&&v2(M,!0)?.keep_warm===void 0&&!r2(Z2))z.untrack(M,"policy-refused"),V.delete(M);else z.updateSubagent?.(M,I)},_=new Map,b=(M)=>{let I=_.get(M);return _.delete(M),I?.signal?.removeEventListener("abort",I.onAbort),I?.target},A=async(M,I,x)=>{let m=x?AbortSignal.any([W.signal,x]):W.signal;if(m.aborted)throw new g1("authorization",m.reason);let s=await I.text(),h;if(!z.reserveWarmDispatch&&(M.policyState?.planned||v2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm!==void 0)){if(!O.plannedUnsupportedLogged)O.plannedUnsupportedLogged=!0,i2.debug("cachekeep","planned warming requires a server restart after an older owner reload");throw new h1("unsupported")}let Z2=JSON.parse(s),$2={providerID:"anthropic",modelID:Z2.model,sessionID:`oc2-cachekeep:${M.id}`,agent:"cachekeep",kind:"generate"},V2=(a)=>{throw new c2(a)},H2=H0(s),M2=$1({source:{...N,onRequestPrepared:void 0,onFinalRequestPrepared:({ttlMs:a})=>{H2=a},responseOptions:void 0,async requestOptions(a){return{...await N.requestOptions?.(a,V2),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(a,J){let Y=await X.read();h=Y.policyStorage,m.throwIfAborted();let Q=Y.accounts.find((y)=>y.id===J);if(Q?.type!=="oauth"||!L0(Q))throw new c2("account-unavailable");if(Z1(Q)!==M.oauthAccountIdentity)throw new c2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&v2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!r2(Y.policyStorage)||!X1(Y.policyStorage)||!N0(Y.policyStorage,new Date($.now?.()??Date.now()))))return;let E=await N.authorizeAccount(a,J,V2);if(E?.provenance.kind==="local"&&Z1({...Q,binding:E.provenance.subject.binding,accountIdentity:E.provenance.subject.binding.identity})!==M.oauthAccountIdentity)throw new c2("credential-changed");if(E?.provenance.kind==="vault"&&E.provenance.credentialId!==Q.credentialId)throw new c2("credential-changed");return E},async admitRequest(a){await N.admitRequest?.(a,V2);let J=await X.read();h=J.policyStorage;let Y=J.accounts.find((Q)=>Q.id===a.accountId);if(m.throwIfAborted(),!Y)throw new c2("account-unavailable");if(Z1(Y)!==M.oauthAccountIdentity)throw new c2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&v2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!r2(J.policyStorage)||!X1(J.policyStorage)||!N0(J.policyStorage,new Date($.now?.()??Date.now()))))throw Error("CacheKeep policy changed before dispatch")}}}),Q2,T2,F2="authorization",g2=!1,L2=()=>M2.forgetSession($2.sessionID);m.addEventListener("abort",L2,{once:!0});try{let a=await X.read();h=a.policyStorage;let J=a.accounts.find((K2)=>Z1(K2)===M.oauthAccountIdentity)?.id;if(!J)throw new c2(a.accounts.some((K2)=>K2.id===M.oauthAccountId)?"credential-changed":"account-unavailable");let Y=await M2.adapter.accountHeaders({...$2,accountId:J});if(!("headers"in Y)||typeof Y.headers!=="object"||Y.headers===null||typeof Y.attempt!=="object"||Y.attempt===null||Y.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");Q2={...$2,accountId:J,attemptId:crypto.randomUUID(),transport:"http",data:Y.attempt};let Q=await M2.adapter.rewriteRequest?.({...$2,accountId:J,attempt:Q2,request:new Request(M.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(Z2),signal:m})});if(!Q)throw Error("CacheKeep rewrite refused");m.throwIfAborted();let E=M.policyState?.ownerSessionId??M.id,y=v2(E,!0)?.keep_warm!==void 0,q=y?void 0:$.subagent?.(E);if(!y&&$.subagent&&q===void 0)throw new g1("authorization",void 0);if(q&&!r2(h))throw new h1("subagents-disabled");await z.reserveWarmDispatch?.(M),m.throwIfAborted(),F2="send";let l=await($.fetch??fetch)(Q);F2="response",T2=l.status;let c=await M2.adapter.rewriteResponse?.({...$2,accountId:J,attempt:Q2,request:Q,response:l});if(!c)throw Error("CacheKeep response rewrite refused");if(T2=c.status,M2.adapter.quotaFromHeaders?.(c.headers,c.status,Q2),!c.ok)await M2.adapter.limitFromResponse?.({status:T2,headers:c.headers,body:()=>c.clone().text(),attempt:Q2});let t=await c.arrayBuffer();if(c.ok&&!m.aborted&&!M.sourceWarm&&(z.isCurrentTarget?.(M)??!0))V9.recordPrewarm(M.id,J,$.now?.()??Date.now(),H2);g2=!0;let X2=new Response(t,{status:T2,headers:c.headers});return P0.set(X2,H2),X2}catch(a){if(a instanceof h1)throw a;let J=G9(a);if(J)throw J;throw new g1(F2,a,T2)}finally{m.removeEventListener("abort",L2);try{if(Q2)await M2.adapter.onAttemptEnd?.(Q2,{status:T2,outputStarted:!1,...g2?{}:{error:{reason:"cancelled"}}})}finally{M2.dispose(),N.forgetSession?.($2.sessionID)}}},H={generation:O.nextGeneration++,stopped:!1,loadStorage:async()=>(await X.read()).policyStorage,send:A,inflight:new Set,read:()=>X.read(),subagent:$.subagent},D=O.leases.size===0;O.leases.set(H.generation,H);let f=(D?O.adopt():O.loading??Promise.resolve()).then(()=>{if(!H.stopped)for(let M of z.trackedSessions())$.subagent?.(M.id)}),o;return{ready:f,async track(M){let I=($2)=>{b(M.attemptId),i2.debug("cachekeep","tracking skipped",{session:M.sessionID,reason:$2})};if(H.stopped)return I("lease-stopped");if(M.route!=="oauth")return I("not-oauth");if(M.agent==="cachekeep"||M.agent==="prime")return I("background-agent");if(M.kind!=="primary")return I("not-primary");if(M.signal?.aborted)return I("attempt-ended");b(M.attemptId);let x={sessionID:M.sessionID,signal:M.signal,onAbort:()=>b(M.attemptId)};_.set(M.attemptId,x),M.signal?.addEventListener("abort",x.onAbort,{once:!0});let m=M.admission?.snapshot??await X.read();if(H.stopped)return I("lease-stopped");let s=v2(M.sessionID,!0);if(s?.keep_warm!==void 0&&!z.reserveWarmDispatch){if(!O.plannedUnsupportedLogged)O.plannedUnsupportedLogged=!0,i2.debug("cachekeep","planned warming requires a server restart after an older owner reload");return I("planned-owner-requires-restart")}if(O0(O,$.now?.()??Date.now(),!X1(m.policyStorage)),!X1(m.policyStorage)){if(s?.keep_warm===void 0)return I("hybrid-inactive")}let h=!1;try{h=$.subagent?$.subagent(M.sessionID)??!1:await $.isSubagent?.(M.sessionID)??!1}catch{return I("session-lookup-failed")}if(H.stopped)return I("lease-stopped");if(s?.keep_warm===void 0&&h&&!r2(m.policyStorage))return I("subagents-disabled");let Z2=M.admission?.account??m.accounts.find(($2)=>$2.id===M.accountId);if(!Z2?.accountIdentity)return I("account-identity-missing");if(M.provenance.kind==="local"&&JSON.stringify(Z2.binding)!==JSON.stringify(M.provenance.subject.binding))return I("local-binding-changed");if(M.provenance.kind==="vault"&&Z2.credentialId!==M.provenance.credentialId)return I("vault-credential-changed");if(_.get(M.attemptId)!==x)return I("attempt-ended");x.target={sessionId:M.sessionID,url:M.url,headers:new Headers,bodyText:M.bodyText,storage:m.policyStorage,cacheMode:"hybrid",oauthAccountId:M.accountId,oauthAccountIdentity:Z1(Z2),isSubagent:h,ttlMs:H0(M.bodyText)||(v2(M.sessionID,!0)?.ttl!==void 0?0:void 0)}},onResponseHeaders(M){let I=b(M.attemptId);if(!H.stopped&&M.status>=200&&M.status<300&&I){let x=I.sessionId;if(!x)return;let m=$.subagent?.(x);if(m!==void 0)I.isSubagent=m;if(I.isSubagent&&v2(x,!0)?.keep_warm===void 0&&!r2(I.storage)){z.untrack(x,"policy-refused");return}let s=z.track({...I,acceptedUsage:M.acceptedUsage,...M.acceptedAt!==void 0&&{acceptedAt:M.acceptedAt},...M.ttlMs!==void 0&&{ttlMs:M.ttlMs}});if(s.tracked){for(let Z2 of O.leases.values())Z2.subagent?.(x);V.delete(x);let h=z.trackedPolicyState?.(x);if(h)V.set(x,h);if(V.size>4096){let Z2=V.keys().next().value;if(Z2!==void 0)V.delete(Z2)}}if(s.tracked)U.publish(z.registrySessions?.()??z.trackedSessions()).catch(()=>{i2.warn("cachekeep","failed to publish tracked sessions")});return s}},discardAttempt(M){b(M)},recordAcceptedUsage(M,I,x){z.recordAcceptedUsage?.(M,I,x)},resolvedParent:C,forgetSession(M){V.delete(M),z.untrack(M);for(let[I,x]of _)if(x.sessionID===M)b(I)},registry:U,dispose(){if(o)return o;H.stopped=!0;for(let I of _.keys())b(I);W.abort();for(let[I,x]of O.prepared)if(x.lease===H)O.prepared.delete(I);let M=O.leases.delete(H.generation)&&O.leases.size===0;if(M)O.retain();return o=(async()=>{try{if(M)await O.ticking;await f,await Promise.all(H.inflight),await O.persistence.drain()}finally{if(M&&O.leases.size===0)await U.dispose()}})(),o}}}import{runWithRequestSignal as U9,withSessionCacheReportHandoff as B9}from"@cortexkit/anthropic-auth-core";async function C0($,X,N){let W=$1(X),P=new Set,T={...W.adapter,onAttemptEnd(H,D){let f=Promise.resolve(W.adapter.onAttemptEnd?.(H,D));return P.add(f),f.finally(()=>P.delete(f)).catch(()=>{}),f}},S=async()=>{await Promise.allSettled([...P])},O=[],z=async(H,D,f)=>{let o=await $.session.hook(H,async(M)=>{if(H==="http.response")return B9(async()=>{let x=!1;try{let m=await D(M);return x=!0,m}finally{if("request"in M&&M.request instanceof Request)try{let m="response"in M&&M.response instanceof Response?M.response:void 0;X.source.onResponseHandedToHost?.(M.request,x&&m?W.acceptedResponse(m):void 0)}catch{}}})();if(H!=="http.request")return D(M);let I="request"in M&&M.request instanceof Request?M.request.signal:void 0;return U9(I,async()=>D(M))},f);return O.push(o),o},U=new AbortController,V;try{V=await w1({session:{hook:z},event:$.event},T,{logger:X.log,gateOnPlaceholder:N})}catch(H){throw W.dispose(),await Promise.allSettled(O.map((D)=>D.dispose())),H}let C=(H)=>{W.forgetSession(H),V.forgetSession(H)},_=$.event,b=_?(async()=>{try{for await(let H of _.subscribe({signal:U.signal})){if(H.type==="session.deleted")C(H.data.sessionID);if(H.type==="session.idle"||H.type==="session.status"&&H.data.status.type==="idle")X.source.forgetTurn?.(H.data.sessionID)}}catch(H){if(!U.signal.aborted)X.log?.warn("stopped listening for session deletion",{error:H instanceof Error?H.name:"unknown"})}})():Promise.resolve(),A;return{installation:V,forgetSession:C,drain:S,dispose(){if(A)return A;return W.dispose(),U.abort(),A=(async()=>{await V.dispose(),await b,await S()})(),A}}}import{effectiveRelayTransport as S0,getQuotaCheckIntervalMs as M9,logger as K9,nativeAccountCanServe as z9,oauthProfileIsFresh as _9,quotaSnapshotCheckedAt as N9}from"@cortexkit/anthropic-auth-core";function x0($,X){let N=new AbortController,W,P=!1,T=async()=>{let z=await $.read();if(N.signal.throwIfAborted(),z.policyStorage.relay?.enabled===!0&&S0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="websocket")return;let U=z,V=M9(U.policyStorage);for(let C of U.accounts){if(N.signal.aborted)return;if(!z9(C)||C.type!=="oauth")continue;if(U.policyStorage.quota?.enabled!==!1&&Date.now()-N9(C.quota)>=V)await $.fetchQuota(C.id,X,N.signal,void 0,"background").catch(()=>{});if(!_9(C.profile)&&!N.signal.aborted)await $.fetchProfile(C.id,X,N.signal).catch(()=>{})}},S=()=>{if(P||W)return W;return W=T().catch(()=>{if(!N.signal.aborted)K9.debug("opencode2","native background readings did not complete")}).finally(()=>{W=void 0}),W},O=$.vault.watch({intervalMs:60000,onRefresh:S,shouldRefresh:async()=>{let z=await $.read();return z.policyStorage.relay?.enabled!==!0||S0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="http"}});return O.ready.catch(()=>{}),{async dispose(){P=!0,O.close(),N.abort(),await W}}}import{authorize as k9,buildCacheKeepStatusSummary as b9,buildClaudeQuotaSummary as R9,buildPrimeAccountStatuses as A9,buildPrimeStatusSummary as w9,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as D9,effectiveRelayTransport as I9,exchange as y9,formatNativeAccountState as f9,formatOAuthAccountTier as v9,getCacheKeepWindow as g9,getHostClaustrumEnrollmentPaths as h9,isCacheKeepAlways as m9,isCacheKeepHybridActive as l9,isCacheKeepPersistentlyEnabled as d9,isVaultHosted as u9,nativeAccountCanServe as p9,parseLogLevel as c9,resetClaustrumEnrollmentState as i9,setDumpEnabled as o9,VAULT_HOST_CONNECT_REFUSAL as n9}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as H9,effectiveRelayStatus as F9,formatNativeAccountState as L9,formatOAuthAccountTier as q0,getCacheKeepWindow as P9,getRoutingMode as O9,isCacheKeepAlways as T9,isCacheKeepHybridActive as E9,isPermanentRefreshError as C9,isPrimePersistentlyEnabled as S9,nativeAccountCanServe as R0,refreshBackoffActive as k0}from"@cortexkit/anthropic-auth-core";var b0=($)=>R0($)&&$.state!=="unsupported-access"?void 0:L9($)||void 0,x9=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return R0($)?"on-vault-served":"on-cold"},q9=($,X)=>typeof $==="number"&&$>X;function A0($,X){let{now:N}=X,W=$.policyStorage,P=$.accounts.filter((V)=>V.type==="oauth"),T=P.find((V)=>V.id==="main"),S=T?b0(T):void 0,O=T?.lastQuotaRefreshError?.nextRetryAt,z=T?.lastRefreshError,U=P9(W);return F1({main:{quota:T?.quota??null,enabled:T?.enabled,tierLabel:q0(T?.profile),quotaBackedOff:q9(O,N),quotaBackoffUntil:O,refreshBackedOff:k0(z,T?.accountIdentity,N,void 0),refreshBackoffUntil:z?.nextRetryAt,stateLine:S,quotaDated:Boolean(S)},fallbacks:P.filter((V)=>V.id!=="main"&&(V.enabled||V.source==="vault")).map((V)=>{let C=b0(V),_=x9(V);return{id:V.id,label:V.label,quota:V.quota??null,enabled:V.enabled,tierLabel:q0(V.profile),needsReauth:C9(V.lastRefreshError)&&k0(V.lastRefreshError,V.accountIdentity,N,void 0),..._==="on-vault-reauth"?{vaultReauth:!0}:{},..._==="on-vault-served"?{vaultServed:!0}:{},..._!=="off"?{custodyState:_}:{},stateLine:C,quotaDated:Boolean(C)}}),...X.activeId!==void 0&&{activeId:X.activeId},route:O9(W),relay:F9(W.relay),fastMode:W.claudeFast?.enabled===!0,cacheKeep:{enabled:E9(W),...T9(W)?{window:"always"}:U&&{window:`${U.startHour}-${U.endHour}`},trackedSessions:X.trackedSessions},prime:S9(W)?{enabled:!0,accounts:H9(W,{now:N})}:void 0,lastUpdated:N})}var m1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},w0=`For first-time model access, connect Anthropic with "${O1}".
|
|
4
|
-
Run: opencode auth login anthropic --method ${
|
|
5
|
-
Route: ${$.id}`;return`${
|
|
1
|
+
import{a as _1,b as $4,c as j4,d as V0,e as Q0,f as P1,g as p2,h as W0,i as y1,j as Z4,k as X4,l as J4,m as U0,n as G4,o as B0,p as z0,q as K0,r as M0,s as v1,t as z4}from"../index-tqz6p5bw.js";import"../index-2ra790fx.js";import"../index-jc8zwxvw.js";import{y as U4}from"../index-pcyn2rkg.js";import{A as T1,C as W4,z as O1}from"../index-qqs4ec18.js";import"../index-k6303ymz.js";import{M as L1}from"../index-m7k9zxem.js";import"../index-crx0xd9j.js";import"../index-n8xr16kr.js";import{acquireNativeAccountRuntime as v$,assertUnmanagedInjectedPaths as g$,authorize as h$,connectVaultHost as m$,createNativeUi as l$,decideOpenCodeStateLayoutOnce as u$,disconnectNativeVaultForHost as d$,exchange as p$,getPersistedLogLevel as c$,isDumpPersistentlyEnabled as i$,isVaultHosted as o$,logger as q1,NativeCustodyError as n$,nativeVaultRuntimeKey as r$,openCodeHolderKind as s$,readNativeEnrollmentMode as a$,registerNativePoolHolder as t$,resolveNativePoolPaths as e$,setDumpEnabled as $9,setLogLevel as Z9,stateLayoutIoFailure as X9,unmovedRegistrationPolicy as J9}from"@cortexkit/anthropic-auth-core";class a2 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 d2($){return`common-auth-placeholder.${$}`}function c1($){let J=d2($.integrationID);return{type:"oauth",methodID:$.methodID,access:J,refresh:J,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function R1($,J){if($?.type!=="oauth")return!1;let N=J===void 0?void 0:d2(J),U=(P)=>N===void 0?P.startsWith("common-auth-placeholder."):P===N;return U($.access)&&U($.refresh)}var i1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function b1($,J){let N=J.now??Date.now,{integrationID:U}=J,P=(O)=>c1({integrationID:U,methodID:O,now:N()}),T=async(O,H)=>{return await J.onLogin(O,{integrationID:U,methodID:H}),P(H)},S=(O)=>async(H)=>{let W=O.method.id,j=await O.authorize(H),E={url:j.url,instructions:j.instructions,...j.expiresAt===void 0?{}:{expiresAt:j.expiresAt}};if(j.mode==="auto")return{...E,mode:"auto",callback:j.callback.then((k)=>T(k,W))};let L=j.callback;return{...E,mode:"code",callback:async(k)=>T(await L(k),W)}};return $.integration.transform((O)=>{let H=J.label===void 0?{}:{label:()=>J.label};for(let E of J.methods)O.method.update({integrationID:U,method:E.method,authorize:S(E),refresh:async(L)=>{if(!R1(L,U))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return P(L.methodID)},...H});let W=J.vault;if(W===void 0)return;let j=W.method.id;O.method.update({integrationID:U,method:W.method,authorize:async()=>({url:"",instructions:W.instructions??i1,mode:"auto",callback:Promise.resolve().then(()=>W.activate({integrationID:U,methodID:j})).then(()=>P(j))}),refresh:async(E)=>{if(!R1(E,U)||E.methodID!==j)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return P(j)},...H})})}function M4($){let J=[],N;for(let U of $.split(/\r?\n/))if(U.startsWith("data:"))J.push(U.slice(5).replace(/^ /,""));else if(U.startsWith("event:"))N=U.slice(6).trim();if(J.length===0)return;return N===void 0?{data:J.join(`
|
|
2
|
+
`)}:{event:N,data:J.join(`
|
|
3
|
+
`)}}function A1($,J){let N=new TextDecoder,U="",P=(S)=>{let O=M4(S);if(!O)return;try{$(O)}catch(H){J(H)}},T=()=>{for(;;){let S=/\r?\n\r?\n/.exec(U);if(!S)return;let O=U.slice(0,S.index);U=U.slice(S.index+S[0].length),P(O)}};return new TransformStream({transform(S,O){O.enqueue(S),U+=N.decode(S,{stream:!0}),T()},flush(){if(U+=N.decode(),T(),U.trim()!=="")P(U);U=""}})}var o1=512,w1=3621000,t2="x-common-auth-attempt",n2=($,J)=>JSON.stringify([$,J]),y2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function _4($){let J=$.headers;return typeof J==="object"&&J!==null}function N4($,J){let N=$.getReader();return new ReadableStream({async pull(U){let P;try{P=await N.read()}catch(T){J({reason:"failed",message:T instanceof Error?T.message:String(T)}),U.error(T);return}if(P.done)J(),U.close();else U.enqueue(P.value)},async cancel(U){J({reason:"cancelled",...U===void 0?{}:{message:String(U)}}),await N.cancel(U)}})}function B1($,J){for(let[N,U]of Object.entries(J)){let P=N.toLowerCase();for(let T of Object.keys($))if(T.toLowerCase()===P)delete $[T];if(U!==null)$[N]=U}}function H4($,J){for(let[N,U]of Object.entries(J))if(U===null)$.delete(N);else $.set(N,U)}async function D1($,J,N={}){let{providerID:U}=J,P=N.gateOnPlaceholder,T=(Z)=>P===void 0||P.credential(Z)===d2(U),S=N.logger,O=Math.max(1,N.maxRecords??o1),H=N.hostRetryLimit??10,W=[...N.hostCredentials??[d2(U)],...P?[d2(U)]:[]].filter((Z)=>Z!==""),j=new Map,E=new WeakMap,L=new Map,k=0,w=new Set,_=new Map,A=new Map,f=(Z)=>{let G=A.get(Z);return G?.ownedSeen===!0&&G.foreignSeen},$2=(Z,G)=>{_.set(Z,G);let F=A.get(Z)??{ownedSeen:!1,foreignSeen:!1};if(G)F.ownedSeen=!0;else F.foreignSeen=!0;A.set(Z,F)},B=(Z,G)=>{let F=P?.refuseMisplaced,b=F?[...G].filter(([,y])=>y.includes(d2(U))):[],K=T(G)&&(!F||b.length>0);if(F){if(b.length>0&&(b.length!==1||!K))throw $2(Z.sessionID,!1),new a2({kind:"placement-refused",providerID:U,sessionID:Z.sessionID,requestKind:Z.kind,message:F(b[0]?.[0]??"")})}return $2(Z.sessionID,K),K},D=!1,R=!1,d=new Map,t=0,c=!1,o=new Map,Y2=(Z,G)=>{try{S?.warn(Z,G)}catch{}},U2=(Z)=>Z instanceof Error?Z.message:String(Z),M2=(Z)=>Z.excluded.clear(),z2=(Z)=>Z.excluded.size===0?{}:{excluded:[...Z.excluded]},B2=(Z,G,F)=>{if(!N.enforceRequestExclusion||Z===void 0||!F.excluded.has(Z))return!1;return Y2("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:G.sessionID,kind:G.kind,phase:G.phase,accountId:Z}),!0},F2=new Map,T2=(Z,G)=>{let F=(F2.get(Z)??Promise.resolve()).then(G),b=F.then(()=>{},()=>{});return F2.set(Z,b),b.then(()=>{if(F2.get(Z)===b)F2.delete(Z)}),F},D2=(Z,G)=>{let F=F2.get(Z);return F?F.then(()=>D2(Z,G)):G()},E2=async(Z)=>{try{await J.dropChoice?.({...Z.input,accountId:Z.accountId})}catch(G){Y2("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:Z.input.sessionID,error:U2(G)})}},s=async(Z)=>{try{await J.dropSameAccountRetry?.({...Z.input,accountId:Z.accountId})}catch(G){Y2("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:Z.input.sessionID,error:U2(G)})}},X=async(Z)=>{if(Z.next)await E2(Z.next);if(Z.sameAccount)await s(Z.sameAccount)},Y=(Z)=>{let G=L.get(Z);if(L.delete(Z),G)T2(G.sessionID,()=>X(G))},Q=async(Z,G)=>{let F=d.get(Z);if(!F||F.size===0)return;await Promise.all([...F].map(async(b)=>{try{await b(G)}catch(K){Y2("opencode2 auth listener threw; the request is unaffected",{event:Z,error:U2(K)})}}))},C=async(Z)=>{let G=new Set([...j.values()].filter((b)=>b.scope.sessionID===Z.sessionID).map((b)=>b.transport).filter((b)=>b!==void 0)),F=Z.handle?.transport??(G.size===1?[...G][0]:"unknown");try{S?.info?.("opencode2 auth retry decision",{sessionID:Z.sessionID,transport:F,attempt:Z.attempt,reason:Z.reason==="host-decides"&&f(Z.sessionID)?"mixed-session":Z.reason,retry:Z.decision.retry})}catch{}await Q("retry",Z)},v=async(Z,G)=>{try{await J.onAttemptEnd?.(Z,G)}catch(F){Y2("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Z.attemptId,error:U2(F)})}},x=(Z,G)=>{if(Z.ended||!Z.attempt)return;let F={...Z.status===void 0?{}:{status:Z.status},outputStarted:Z.outputStarted,...Z.limit?{limit:Z.limit.signal}:{},...G?{error:G}:{}};if(G)Z.endError=G;if(G?.reason==="cancelled"||!G&&!Z.limit&&(Z.status===void 0||Z.status<400))M2(Z.request);Z.ended=v(Z.attempt,F)},u=(Z,G)=>x(Z,{reason:"abandoned",message:G}),r=(Z)=>[...j.values()].filter((G)=>G.key===Z),J2=(Z)=>r(Z).at(-1),Z2=(Z)=>{if(j.delete(Z.id),L.get(Z.key)?.attemptId===Z.id||!r(Z.key).length)Y(Z.key)},L2=(Z)=>{j.set(Z.id,Z);while(j.size>O){let G=j.values().next().value;if(G===void 0)break;u(G,"dropped to keep the record bound"),Z2(G)}},g=(Z)=>Z.accountId===void 0?void 0:{...Z.scope,accountId:Z.accountId},e=(Z,G)=>new a2({kind:"no-account",providerID:U,sessionID:Z.sessionID,requestKind:Z.kind,...G===void 0?{}:{message:G}}),n=(Z)=>{o.get(Z)?.clear(),o.delete(Z)},V2=async(Z,G)=>{let F=()=>e(Z,`${U} ${Z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(c)throw F();let b=o.get(Z.sessionID);if(!b)b=new Set,o.set(Z.sessionID,b);let K={};b.add(K);let y=()=>{if(!b.has(K))throw F()};try{return await G(y)}finally{if(b.delete(K),b.size===0&&o.get(Z.sessionID)===b)o.delete(Z.sessionID)}},V=(Z,G)=>{for(let[F,b]of G)if(W.some((K)=>b.includes(K)))throw new a2({kind:"host-credential-on-wire",providerID:U,sessionID:Z.sessionID,requestKind:Z.kind,message:`${U} ${Z.kind} request still carries the host's placeholder credential in ${F}; the adapter's account headers must replace it`})},M=(Z)=>{for(let G of r(Z))if(G.ended||!G.attempt)Z2(G);else if(G.transport==="ws"||G.judged)u(G,"a newer attempt of its session and kind began"),Z2(G)},z=async(Z,G,F,b)=>{let K=n2(Z.sessionID,Z.kind),{input:y,accountId:m,sameAccountRetry:l,request:Q2}=await D2(Z.sessionID,async()=>{F();let x2=L.get(K);L.delete(K);let V1=r(K);if(x2&&V1.some((H2)=>H2.id!==x2.attemptId&&H2.attempt&&!H2.ended))Y2("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:Z.sessionID,kind:Z.kind});if(!x2){let H2=new Set(V1.filter((w2)=>w2.attempt&&!w2.ended).map((w2)=>w2.request));for(let w2 of V1)if(!H2.has(w2.request))M2(w2.request)}let b2=x2?.request??{excluded:new Set},C2=x2?.accountId??J2(K)?.accountId;M(K);let K2=x2?.next,q2=x2?.sameAccount,G2=q2!==void 0&&q2.input.modelID===Z.modelID&&q2.input.agent===Z.agent,A2=K2!==void 0&&K2.input.modelID===Z.modelID&&K2.input.agent===Z.agent,g2=x2?.wake,W2={...Z,phase:"request",...z2(b2),...C2===void 0?{}:{previousAccountId:C2},...x2?.rerouteFrom?{rerouteFrom:x2.rerouteFrom}:{},...g2===void 0?{}:{wake:g2,hostAttempt:K2?.input.hostAttempt}};if(K2&&(!A2||g2!==void 0))await T2(Z.sessionID,()=>E2(K2)),F();if(q2&&!G2)await T2(Z.sessionID,()=>s(q2)),F();if(q2?.continuation&&(!G2||f(Z.sessionID))){if(G2)await T2(Z.sessionID,()=>s(q2));throw e(Z)}let o2=G2?q2.accountId:A2&&g2===void 0?K2.accountId:await J.chooseAccount(W2),u2=typeof o2==="string"?o2:void 0;if(B2(u2,W2,b2)){let H2=u2;if(G2&&q2)await T2(Z.sessionID,()=>s(q2));else if(H2!==void 0)await T2(Z.sessionID,()=>E2(A2&&K2?K2:{accountId:H2,input:W2}));u2=void 0,F()}return{input:W2,accountId:u2,sameAccountRetry:G2,request:b2}});F();let N2={},O2;if(m!==void 0){let x2=await J.accountHeaders({...Z,accountId:m});if(F(),_4(x2))N2=x2.headers,O2=x2.attempt;else N2=x2}let G1=`attempt-${++t}`,f2={id:G1,key:K,scope:Z,request:Q2,accountId:m,headers:N2,attempt:m===void 0?void 0:{...Z,accountId:m,attemptId:G1,transport:b,data:O2},...b===void 0?{}:{transport:b},outputStarted:!1,sameAccountRetry:l};if(L2(f2),f2.attempt)Q("select",{...Z,accountId:f2.attempt.accountId,hook:G,...y.previousAccountId===void 0?{}:{previousAccountId:y.previousAccountId},...y.rerouteFrom===void 0?{}:{rerouteFrom:y.rerouteFrom},handle:f2.attempt});return f2},I=async(Z,G,F,b,K)=>{let y=n2(Z.sessionID,Z.kind),m=b===void 0?void 0:j.get(b);if(m?.key!==y)m=void 0;if(!m){if(m=J2(y),r(y).filter((Q2)=>Q2.transport===void 0&&!Q2.ended).length>1&&!R)R=!0,Y2("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Z.sessionID,kind:Z.kind})}if(!m||m.transport!==void 0||m.ended)m=await z(Z,G,K,F);else if(m.transport=F,m.attempt)m.attempt.transport=F;if(F==="ws"){for(let l of r(y))if(l!==m&&l.transport==="ws")u(l,"a newer attempt of its session and kind went out over WebSocket")}return m},q=async(Z,G)=>{try{return await G()}catch(F){throw x(Z,{reason:"failed",message:U2(F)}),F}},p=(Z,G)=>{let F=r(n2(Z,G)).filter((b)=>b.transport==="ws").at(-1);return F?.attempt!==void 0&&!F.ended?F:void 0},h=(Z,G,F)=>{let b=g(Z);if(!b||!Z.attempt||Z.limit)return;Z.limit={signal:G,delivered:Q("limit",{...b,via:F,limit:G,outputStarted:Z.outputStarted,handle:Z.attempt})}},a=(Z,G,F,b)=>{let K=g(Z);if(!K||!Z.attempt)return;Q("quota",{...K,transport:G,...b===void 0?{}:{status:b},quota:F,handle:Z.attempt})},i=(Z,G,F,b)=>{let K=Z.attempt;if(!K)return;let y=J.inspectEvent?.(b===void 0?{transport:G,data:F,attempt:K}:{transport:G,data:F,event:b,attempt:K});if(!y)return;if(y.quota!==void 0)a(Z,G,y.quota);if(y.outputStarted)Z.outputStarted=!0;if(y.hostRetry==="veto")Z.hostRetry="veto";if(y.limit)h(Z,y.limit,G);if(y.error!==void 0)x(Z,{reason:"failed",message:y.error});else if(y.done)x(Z)},_2=(Z,G)=>{let F=Z.attempt;if(!F||G.accountId===Z.accountId)return;if(F.reboundFrom??=F.accountId,F.accountId=G.accountId,"data"in G)F.data=G.data;Z.accountId=G.accountId},P2=(Z)=>!Z.attempt||Z.endError!==void 0||Z.status!==void 0&&Z.status>=400,k2=(Z)=>{let G=[...j.values()].filter((l)=>l.scope.sessionID===Z),F=G.filter((l)=>l.limit&&!l.rerouted).at(-1);if(F)return F;let b=G.filter((l)=>l.scope.kind==="primary"),K=b.length>0?b:G;if(K.length<=1)return K[0];let y=K.filter((l)=>!l.judged&&P2(l)).at(-1);if(y)return y;let m=K.filter((l)=>l.attempt&&!l.ended);if(m.length>1)return"ambiguous";return m[0]??K.at(-1)},S2={providerID:U},R2=[];R2.push(await $.session.hook("model.request",(Z)=>{if(P)return;return V2(y2(Z),async(G)=>{let F=await z(y2(Z),"model.request",G);if(G(),F.accountId===void 0)throw e(F.scope);B1(Z.headers,{...F.headers,[t2]:F.id})})},S2)),R2.push(await $.session.hook("http.request",(Z)=>{if(P){if(!B(y2(Z),Z.request.headers))return}return V2(y2(Z),async(G)=>{let F=Z.request.headers.get(t2)??void 0,b=P?await z(y2(Z),"http.request",G,"http"):await I(y2(Z),"http.request","http",F,G);G();let K=g(b),y=b.attempt;if(!K||!y)throw e(b.scope);await q(b,async()=>{let m=Z.request;if(J.rewriteRequest){if(F!==void 0){let N2=new Headers(m.headers);N2.delete(t2),m=new Request(m,{headers:N2})}m=await J.rewriteRequest({...K,request:m,attempt:y})??m,G()}let l=new Headers(m.headers);l.delete(t2),H4(l,b.headers),V(b.scope,l.entries());let Q2=new Request(m,{headers:l});E.set(Q2,b),Z.request=Q2})})},S2)),R2.push(await $.session.hook("http.response",async(Z)=>{let G=E.get(Z.request);if(!G){if(P)return;if(!D)D=!0,Y2("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Z.sessionID,kind:Z.kind});return}let F=Z.response;if(J.answeredBy&&G.attempt){let l=G.attempt,Q2=await q(G,async()=>J.answeredBy?.({request:Z.request,response:F,attempt:l}));if(Q2)_2(G,Q2)}let b=g(G),K=G.attempt;if(!b||!K)return;G.status=F.status;let y=J.quotaFromHeaders?.(F.headers,F.status,K);if(y!==void 0)a(G,"http",y,F.status);if(!F.ok&&J.limitFromResponse){let l=await J.limitFromResponse({status:F.status,headers:F.headers,body:()=>F.clone().text(),attempt:K});if(l)h(G,l,"http")}if(!F.ok||!F.body)x(G);let m=F;if(F.body&&(J.inspectEvent||J.onAttemptEnd)){let l=F.body;if(J.inspectEvent)l=l.pipeThrough(A1((Q2)=>i(G,"http",Q2.data,Q2.event),(Q2)=>Y2("opencode2 auth event inspection threw",{error:U2(Q2)})));m=new Response(N4(l,(Q2)=>{if(Q2?.reason==="failed")G.readFailed=!0;x(G,Q2)}),{status:F.status,statusText:F.statusText,headers:F.headers})}if(J.rewriteResponse)m=await J.rewriteResponse({...b,request:Z.request,response:m,attempt:K})??m;if(J.responseRetry){if(await J.responseRetry({...b,request:Z.request,response:m,attempt:K})==="veto")G.hostRetry="veto"}if(m!==F)Z.response=m},S2)),R2.push(await $.session.hook("experimental.ws.handshake",(Z)=>{if(P){let G=n2(Z.sessionID,Z.kind);if(w.delete(G),!B(y2(Z),new Headers(Z.headers)))return}return V2(y2(Z),async(G)=>{let F;for(let m of Object.keys(Z.headers)){if(m.toLowerCase()!==t2)continue;F??=Z.headers[m],delete Z.headers[m]}let b=P?await z(y2(Z),"experimental.ws.handshake",G,"ws"):await I(y2(Z),"experimental.ws.handshake","ws",F,G);G();let K=g(b),y=b.attempt;if(!K||!y)throw e(b.scope);await q(b,async()=>{if(!P?.refuseMisplaced)B1(Z.headers,b.headers);let m=J.rewriteHandshakeURL?.({...K,url:Z.url,attempt:y});if(m!==void 0)Z.url=m;if(P?.refuseMisplaced)B1(Z.headers,b.headers);if(V(b.scope,Object.entries(Z.headers)),P)w.add(b.key)})})},S2));let l2=J.rewriteWebSocketFrame?.bind(J);if(l2)R2.push(await $.session.hook("experimental.ws.send",async(Z)=>{let G=y2(Z);if(P&&!w.has(n2(G.sessionID,G.kind)))return;let F=p(G.sessionID,G.kind),b=await l2({...G,attempt:F?.attempt,frame:Z.frame});if(b!==void 0)Z.frame=b},S2));R2.push(await $.session.hook("experimental.ws.receive",(Z)=>{if(P&&!w.has(n2(Z.sessionID,Z.kind)))return;let G=p(Z.sessionID,Z.kind);if(!G)return;try{i(G,"ws",Z.frame)}catch(F){Y2("opencode2 auth frame inspection threw",{error:U2(F)})}},S2)),R2.push(await $.session.hook("retry",async(Z)=>{if(P&&_.get(Z.sessionID)!==!0)return;let G=Z.decision,F=()=>C({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:G,decision:G});if(f(Z.sessionID)&&!J.retrySameAccount){await F();return}let b=k2(Z.sessionID);if(!b)return;if(b==="ambiguous"){await C({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:G,decision:G});return}let K=b,y=()=>K.hostRetry==="veto";await V2(K.scope,async(m)=>{let l=m,Q2=J.retrySameAccount?.bind(J),N2=K.attempt,O2=K.outputStarted;if(K.transport==="ws"&&O2&&!K.ended&&!K.limit&&!(K.status!==void 0&&K.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&Z.error.type==="provider.transport")K.readFailed=!0,x(K,{reason:"failed",message:Z.error.message});if(O2&&K.readFailed&&Q2&&N2&&!f(Z.sessionID)){if(!K.limit){let b2=J.limitFromError?.(Z.error,N2);if(b2)h(K,b2,"error")}if(K.ended)await K.ended;if(K.limit)await K.limit.delivered;l()}let G1=()=>K.readFailed===!0&&Z.error.type==="provider.transport"&&G.retry&&H-Z.attempt>=1&&!K.limit&&!(K.status!==void 0&&K.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&!N2?.reboundFrom&&!y()&&!f(Z.sessionID);if(Q2&&N2&&(!O2||G1())&&(!y()||f(Z.sessionID))&&!K.sameAccountRetry){if(K.ended)await K.ended;if(K.limit)await K.limit.delivered;let b2=await T2(K.scope.sessionID,async()=>{l();let C2=N2.accountId,K2=()=>j.has(K.id)&&K.accountId===C2&&k2(Z.sessionID)===K&&K.outputStarted===O2&&(!O2||G1())&&(!y()||f(Z.sessionID))&&(!P||_.get(Z.sessionID)===!0);if(!K2()||K.sameAccountRetry)return!1;K.sameAccountRetry=!0;let q2={...K.scope,accountId:C2,error:Z.error,attempt:Z.attempt,...K.limit?{limit:K.limit.signal}:{},...O2?{continuation:"interrupted-read"}:{}},G2;try{G2=await Q2(q2)}catch(W2){Y2("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:Z.sessionID,error:U2(W2)})}if(!G2)return l(),!1;let A2={accountId:G2.accountId,input:q2,...O2?{continuation:!0}:{}};try{l()}catch(W2){throw await s(A2),W2}if(!K2()||G2.accountId!==C2)return await s(A2),!1;let g2=L.get(K.key);if(L.delete(K.key),g2)await X(g2);try{l()}catch(W2){throw await s(A2),W2}if(!K2())return await s(A2),!1;return L.set(K.key,{request:K.request,attemptId:K.id,sessionID:K.scope.sessionID,order:++k,accountId:C2,sameAccount:A2}),K.judged=!0,Z.decision=O2?G:{retry:!0,delay:0},!0});if(l(),b2){await C({sessionID:Z.sessionID,accountId:K.accountId,kind:K.scope.kind,attempt:Z.attempt,reason:O2?"continue-same-account":"same-account",hostDecision:G,decision:Z.decision,handle:K.attempt});return}}if(f(Z.sessionID)){await F();return}K.judged=!0;let f2=K.attempt;if(f2&&!K.outputStarted){if(!K.limit){let b2=J.limitFromError?.(Z.error,f2);if(b2)h(K,b2,"error")}if(K.ended)await K.ended;if(K.limit)await K.limit.delivered}l();let{decision:x2,reason:V1}=await T2(K.scope.sessionID,async()=>{if(l(),f(Z.sessionID))return{decision:G,reason:"host-decides"};let b2=L.get(K.key);if(L.delete(K.key),b2)await X(b2);if(l(),f(Z.sessionID))return{decision:G,reason:"host-decides"};let C2=G,K2,q2,G2,A2;if(K.accountId===void 0||!f2)C2={retry:!1},K2="no-account";else if(K.outputStarted)C2={retry:!1},K2="output-started";else if(y())C2={retry:!1},K2="adapter-veto";else if(K.limit){let g2={accountId:K.accountId,limit:K.limit.signal},W2,o2={...K.scope,phase:"retry",...z2(K.request),hostAttempt:Z.attempt,previousAccountId:K.accountId,rerouteFrom:g2};try{W2=await J.chooseAccount(o2)}catch(k1){Y2("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:K.scope.sessionID,error:U2(k1)})}let u2=typeof W2==="string"?W2:typeof W2==="object"&&("hold"in W2)?K.accountId:void 0;if(B2(u2,o2,K.request)){if(u2!==void 0)await E2({accountId:u2,input:o2});W2=void 0}let H2=typeof W2==="object"&&"hold"in W2?W2.hold:void 0,w2=typeof W2==="object"&&"waitThenReselect"in W2?W2.waitThenReselect:void 0,K4=typeof W2==="object"&&"hostRetry"in W2?W2.hostRetry:void 0,U1=typeof W2==="string"?W2:H2?K.accountId:void 0;if(U1!==void 0)G2={accountId:U1,input:o2};try{l()}catch(k1){if(G2)await E2(G2);throw k1}if(f(Z.sessionID)){if(G2)await E2(G2);return{decision:G,reason:"host-decides"}}if(y()||K4==="veto"){if(G2)await E2(G2);if(G2=void 0,l(),f(Z.sessionID))return{decision:G,reason:"host-decides"};K.hostRetry="veto",C2={retry:!1},K2="adapter-veto"}else if(!(H-Z.attempt>=1)){if(G2)await E2(G2);G2=void 0,K2="host-decides-last-account"}else if(w2&&Number.isFinite(w2.delayMs)&&w2.delayMs>=0&&w2.delayMs<=w1)C2={retry:!0,delay:Math.ceil(w2.delayMs)},K2="wait-then-reselect";else if(H2&&Number.isFinite(H2.delayMs)&&H2.delayMs>=0&&H2.delayMs<=w1){if(C2={retry:!0,delay:Math.ceil(H2.delayMs)},H2.target!==void 0)A2={target:H2.target,...H2.checkpoint===void 0?{}:{checkpoint:H2.checkpoint},...H2.kind===void 0?{}:{kind:H2.kind}};K2="hold"}else if(!H2&&U1!==void 0&&U1!==K.accountId)K.rerouted=!0,K.request.excluded.add(K.accountId),q2=g2,C2={retry:!0,delay:0},K2="reroute";else{if(H2&&G2)await E2(G2),G2=void 0;K2="host-decides-last-account"}}else K2="host-decides";if(Z.decision=C2,C2.retry&&K.accountId!==void 0&&j.has(K.id))L.set(K.key,{request:K.request,attemptId:K.id,sessionID:K.scope.sessionID,order:++k,accountId:K.accountId,...q2===void 0?{}:{rerouteFrom:q2},...G2===void 0?{}:{next:G2},...A2===void 0?{}:{wake:A2}});else if(G2)await E2(G2);if(!C2.retry)M2(K.request);return{decision:C2,reason:K2}});l(),await C({sessionID:Z.sessionID,...K.accountId===void 0?{}:{accountId:K.accountId},kind:K.scope.kind,attempt:Z.attempt,reason:V1,hostDecision:G,decision:x2,...f2===void 0?{}:{handle:f2}})})},S2));let I2=(Z)=>{if(n(Z),_.delete(Z),!A.get(Z)?.foreignSeen)A.delete(Z);for(let G of w)if(JSON.parse(G)[0]===Z)w.delete(G);for(let G of[...j.values()]){if(G.scope.sessionID!==Z)continue;u(G,"its session was forgotten"),M2(G.request),j.delete(G.id)}for(let[G,F]of L)if(F.sessionID===Z)Y(G)},j2=new AbortController,X2=$.event;if(X2)(async()=>{try{for await(let Z of X2.subscribe({signal:j2.signal}))if(Z.type==="session.deleted")I2(Z.data.sessionID);else if(Z.type==="session.status"&&Z.data.status.type==="idle"){let G=Z.data.sessionID,F=++k;T2(G,async()=>{for(let[b,K]of L)if(K.sessionID===G&&K.order<F)L.delete(b),M2(K.request),await X(K)})}}catch(Z){if(!j2.signal.aborted)Y2("opencode2 auth stopped listening for session deletion",{error:U2(Z)})}})();return{on(Z,G){let F=d.get(Z);if(!F)F=new Set,d.set(Z,F);let b=G;return F.add(b),()=>{F.delete(b)}},accountFor(Z,G){return J2(n2(Z,G))?.accountId},forgetSession:I2,get size(){return j.size},async dispose(){if(c)return;c=!0;for(let Z of o.keys())n(Z);j2.abort();for(let Z of j.values())u(Z,"the installation was disposed");j.clear();for(let Z of L.keys())Y(Z);w.clear(),_.clear(),A.clear(),d.clear(),await Promise.all(F2.values()),await Promise.all(R2.map(async(Z)=>{try{await Z.dispose()}catch(G){Y2("opencode2 auth hook did not dispose cleanly",{error:U2(G)})}}))}}}import{createHash as n1}from"node:crypto";import{AnthropicOAuthOriginError as F4,applyCustomHeaders as L4,applyRunnerTurnNotes as P4,assertHostAuthorityStable as z1,assertNotCustodyTombstone as O4,classifyGzipRejection as T4,createDumpResponseObserver as E4,createProviderErrorRedactor as r1,createProviderErrorResponseScope as s1,decideRequestGzip as C4,dumpDirectRequest as a1,dumpRelayRequest as t1,dumpResponseArtifact as Q1,encodeGzipRequestBody as x4,getRequestGzipLatch as q4,getRequestGzipLatchPath as S4,guardAnthropicStreamResponse as k4,isDumpEnabled as R4,MessageThreadTracker as b4,mergeAnthropicBetas as A4,observeAnthropicBillingResponse as e1,prepareMessageThreadRequest as w4,remapModelId as $0,remapRequestBodyModel as D4,reportAnthropicBillingFailure as Z0,requestCacheLifetimeMs as X0,requestSignal as I4,resolveNativePoolPaths as f4,runWithRequestSignal as J0,sendWithRequestGzip as y4,setDumpEnabled as Y0,signRequestBody as v4,stateLayoutOfPaths as g4,stateRefusalCause as h4,stateRefusalPublicMessage as m4,stripEmptyTrailingAssistantMessages as l4,TrailingAssistantHistoryError as u4}from"@cortexkit/anthropic-auth-core";var $1="anthropic",_0="x-common-auth-attempt",d4=["x-session-affinity","x-opencode-session","x-parent-session-id",V0,_1,p2,_0],M1=new Set(["authorization","x-api-key"]),p4="physical send before a response",c4="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",i4=512,o4=5000,n4=500,N0=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"]),I1=($,J="provider request failed")=>({type:N0.has($.type)?$.type:"provider_error",message:J,...$.status!==void 0?{status:$.status}:{}});class H0 extends Error{sessionID;requestKind;kind="no-account";providerID=$1;constructor($,J){super(c4);this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicNoAccountError"}}class K1 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=$1;constructor($,J){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicRevokedError"}}class m2 extends Error{kind="unsupported-transport";providerID=$1;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class F0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class L0 extends Error{kind="state-relocated";providerID=$1;constructor($){super(m4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function N1($){let J=h4($);return J?new L0(J):void 0}var h2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function r4($){let J=new Set;while(h2($)&&!J.has($)){if(J.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 j0($){if($.status!==400&&$.status!==404||!$.body)return $;return new Response($.body.pipeThrough(new TransformStream),$)}function e2($){try{return JSON.parse($)}catch{return}}function f1($){let J={};for(let[N,U]of Object.entries($??{}))J[N.toLowerCase()]=U;return J}function G0($){let J={};for(let N of d4){let U=$.get(N);if(U!==null&&N!==_0)J[N]=U;$.delete(N)}return J}function s4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function a4($){return $ instanceof u4||$ instanceof Q0||$ instanceof F4?new F0($):void 0}function t4($,J){let N=[];if($.oauth)N.push($.oauth.accessToken);for(let[U,P]of Object.entries($.apiHeaders??{})){if(P===null||!M1.has(U))continue;N.push(P.replace(/^Bearer\s+/i,""))}for(let U of M1){let P=J.get(U);if(P!==null)N.push(P.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")N.push($.dispatch.token);return[...new Set(N.filter(Boolean))]}var e4=new Set(["oauth-2025-04-20","claude-code-20250219",U0]);function $8($){let J=$.split(",").map((N)=>N.trim()).filter((N)=>N&&!e4.has(N));return A4(null,J)}function Z8($,J,N){let U=e2($);if(!h2(U))return $;let P=l4(U.messages),T=Object.hasOwn(U,"fallbacks"),{droppedMarkers:S}=B0(U,!1),O=T&&!Object.hasOwn(U,"fallbacks"),H=D4(U);return P4(U,{sessionId:J,modelId:N,isOAuth:!1}),P>0||S>0||O||H?JSON.stringify(U):$}async function X8($,J){if(!($ instanceof Promise))return"settled";let N;try{return await Promise.race([$.then(()=>"settled"),new Promise((U)=>{N=setTimeout(()=>U("timed-out"),J)})])}finally{if(N!==void 0)clearTimeout(N)}}function Z1($){let{source:J,log:N}=$,U=Math.max(1,$.maxPendingSends??i4),P=$.attemptEndTimeoutMs??o4,T=new WeakMap,S=$.requestGzipLatch,O=async()=>{if(S)return S;let V=await f4();return S??=q4(S4(V.legacyConfig,g4(V))),S},H=new WeakSet,W=new Map,j=new WeakMap,E=new WeakMap,L=(V)=>JSON.stringify([V.providerID,V.sessionID,V.kind,V.modelID,V.agent,V.accountId]),k=new Map,w=new WeakMap,_=new Map,A=new WeakMap,f=r1([]);f.dispose();let $2=(V)=>(V&&_.get(V)?.redactor)??f,B=(V)=>{Z2.get(V)?.thread.fail(),Z2.delete(V);let M=_.get(V);if(!M)return;_.delete(V),M.redactor.dispose(),M.scope.dispose()},D=(V,M,z,I)=>{let q=t4(M,I),p=s1(q,z);R.set(V,z),_.set(V,{sessionID:M.sessionID,redactor:r1(q),scope:p}),p.settled.then(()=>{if(_.get(V)?.scope===p)B(V)});while(_.size>U){let h=_.keys().next().value;if(h===void 0)break;B(h)}},R=new WeakMap,d=(V,M)=>{let z=V?R.get(V):void 0;if(!z||!M.ok)return f.redactResponse(M);let I=s1([],z),q=I.redactResponse(M);return I.dispose(),q},t=(V,M)=>{let z=V?_.get(V)?.scope:void 0;if(!z)return d(V,M);try{return z.redactResponse(M)}catch{return d(V,M)}},c=!1,o=new Map,Y2=new WeakMap,U2=new WeakMap,M2=new WeakMap,z2=(V)=>V.agent==="cachekeep"||V.agent==="prime",B2=async()=>{try{if(J.isDumpEnabled)return await J.isDumpEnabled()}catch{return!1}try{return R4()}catch{return!1}},F2=(V)=>{o.delete(V)},T2=new WeakMap,D2=new WeakMap,E2=new WeakMap,s=(V,M)=>{if(V&&!M.ok)T2.set(M.headers,V);let z=V?.route==="oauth"&&M.ok?D2.get(V):void 0;if(z)E2.set(M,z);return M},X=(V,M)=>{if(M.dispatch!=="http-relay")return!0;let z=/^req_[A-Za-z0-9_-]+$/.test(V.get("request-id")??"");return E.set(M,z),z},Y=(V)=>new H0(V.sessionID,V.kind),Q=new Map,C=async(V,M)=>{if(c)throw new K1(V.sessionID,V.kind);let z={revoked:!1},I=Q.get(V.sessionID);if(!I)I=new Set,Q.set(V.sessionID,I);I.add(z);let q=()=>{if(I4()?.throwIfAborted(),c||z.revoked)throw new K1(V.sessionID,V.kind)};try{let p=await M(q);return q(),p}finally{let p=Q.get(V.sessionID);if(p?.delete(z)&&p.size===0)Q.delete(V.sessionID)}},v=(V,M)=>{W.set(V,M);while(W.size>U){let z=W.keys().next().value;if(z===void 0)break;W.delete(z),N?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:U})}},x=(V,M)=>({providerID:V.providerID,modelID:V.modelID,sessionID:V.sessionID,agent:V.agent,kind:V.kind,accountId:V.accountId,attemptId:V.attemptId,transport:V.transport,route:M.route,provenance:L2.get(M)??M.provenance,dispatch:M.dispatch}),u=(V)=>C(V,async(M)=>{let{accountId:z,...I}=V,q;try{q=await J.authorizeAccount(I,z)}catch(p){let h=N1(p);if(h)throw N?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:h.cause instanceof Error?h.cause.name:""}),h;throw p}return M(),r(I,q)}),r=(V,M)=>{if(!M)throw Y(V);if(M.dispatch?.kind==="websocket-relay")throw new m2;let z=M.dispatch?.kind==="http-relay"?"http-relay":"direct",I=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 Y(V);O4(M.accessToken,$1);let h=Object.freeze({route:"oauth",provenance:M.provenance,dispatch:z});v(h,{sessionID:V.sessionID,oauth:{accessToken:M.accessToken,credentialId:M.credentialId,...M.identity?{identity:M.identity}:{}},dispatch:M.dispatch,oauthHeaders:M.headers});let a=f1(M.headers);for(let i of M1)delete a[i];return delete a["anthropic-beta"],{headers:I??{...a,"x-api-key":null,authorization:`Bearer ${M.accessToken}`},attempt:h}}let q={authorization:null,"x-api-key":null,...f1(M.headers)};if(!q.authorization&&!q["x-api-key"])throw Y(V);let p=Object.freeze({route:"api",provenance:M.provenance,dispatch:z});return v(p,{sessionID:V.sessionID,...M.baseURL?{baseURL:M.baseURL}:{},dispatch:M.dispatch,apiHeaders:q}),{headers:I??q,attempt:p}},J2=new b4,Z2=new WeakMap,L2=new WeakMap,g=new WeakSet,e=(V)=>C(V,(M)=>n(V,M)),n=async(V,M)=>{let{request:z,attempt:I}=V,q=I.data;k.set(L(V),I);while(k.size>U){let j2=k.keys().next();if(!j2.done)k.delete(j2.value)}let p=q?W.get(q):void 0;if(q)W.delete(q);if(!q||!p||q.route==="oauth"&&!p.oauth)throw Y(V);let h=new Headers(z.headers);L4(h);let a=G0(h),i=z.body===null?void 0:await z.text();M();let _2=i!==void 0&&s4(z.url),P2=K0(z.url,p.baseURL!==void 0?{baseURL:p.baseURL}:{}).url?.toString()??z.url;try{if(q.route==="oauth"&&p.oauth){W0(P2);let{accessToken:j2,identity:X2}=p.oauth;for(let[G,F]of Object.entries(f1(p.oauthHeaders))){if(M1.has(G))continue;if(F===null)h.delete(G);else h.set(G,F)}let Z=null;if(i!==void 0&&_2){let G={...x(I,q),modelID:(()=>{let K=e2(i);return $0(h2(K)&&typeof K.model==="string"?K.model:V.modelID)})(),route:"oauth",correlation:a},F=await J.requestOptions?.(G)??{};if(M(),I.agent!=="cachekeep")i=await M0(i,{...F,deferSigning:!0,...X2?{identity:X2}:{},sessionId:V.sessionID,modelId:V.modelID,isOAuth:!0,onToolNameMap:(K)=>w.set(q,K)});let b=e2(i);Z=h2(b)?b:null}z0(h,j2,{body:Z,...X2?{identity:X2}:{},requestClass:I.kind!=="primary"||y1(I.agent)?"auxiliary":"main"})}else{if(i!==void 0&&_2)i=Z8(i,V.sessionID,V.modelID);h.delete("authorization"),h.delete("x-api-key");for(let[X2,Z]of Object.entries(p.apiHeaders??{}))if(Z===null)h.delete(X2);else h.set(X2,Z);if(i!==void 0&&_2&&!h.has("content-type"))h.set("content-type","application/json");let j2=h.get("anthropic-beta");if(j2!==null){let X2=$8(j2);if(X2)h.set("anthropic-beta",X2);else h.delete("anthropic-beta")}}}catch(j2){let X2=a4(j2);if(!X2)throw j2;throw j.set(q,X2.check),N?.warn("refused an Anthropic request locally; nothing was sent",{check:X2.check}),X2}let k2=i!==void 0?e2(i):void 0;if(await J.admitRequest?.({...x(I,q),modelID:$0(h2(k2)&&typeof k2.model==="string"?k2.model:V.modelID)}),G0(h),i!==void 0)h.delete("content-length");M();let S2=h2(k2)&&k2.stream===!0?"event-stream":"http";if(D(q,p,S2,h),q.route==="oauth"&&_2&&i!==void 0)await J.onRequestPrepared?.({...x(I,q),url:P2,bodyText:i,signal:z.signal}),M();if(q.route==="oauth"&&p.oauth&&_2&&i!==void 0&&I.kind==="primary"&&!y1(I.agent)&&I.agent!=="cachekeep"&&I.agent!=="compaction"&&a[p2]!=="1"){let j2=p.oauth.identity?.accountUuid,X2,Z=await w4(J2,{session:V.sessionID,account:p.oauth.identity?.accountUuid??V.accountId,credential:p.oauth.credentialId,bodyText:i,replyToolNames:w.get(q),headers:h,signal:z.signal});i=Z.bodyText,Z2.set(q,{thread:Z,beforeResend:async()=>{if(g.has(q)||!_.has(q))return!1;M(),z.signal.throwIfAborted();let G=await J0(z.signal,async()=>J.authorizeAccount(V,V.accountId));if(M(),z.signal.throwIfAborted(),!_.has(q)||G?.route!=="oauth"||!G.accessToken||!j2||G.identity?.accountUuid!==j2)return!1;if((G.dispatch?.kind??"direct")!==(p.dispatch?.kind??"direct"))return!1;if(await J0(z.signal,async()=>J.admitRequest?.({...x(I,q),provenance:G.provenance})),M(),!_.has(q))return!1;return X2=G,{credential:G.credentialId}},resend:async(G)=>{M(),z.signal.throwIfAborted();let F=X2;if(X2=void 0,!_.has(q))throw new K1(V.sessionID,V.kind);if(F?.route!=="oauth"||!F.accessToken)throw Y(V);L2.set(q,F.provenance);let b=new Headers(h);b.set("authorization",`Bearer ${F.accessToken}`),B(q),D(q,{...p,oauth:{accessToken:F.accessToken,credentialId:F.credentialId,identity:F.identity}},S2,b);let K=F.dispatch,y=async(l,Q2)=>{try{z1(),I2(z,G);let N2=await($.fetch??globalThis.fetch)(l,Q2);if(z.signal.aborted)N2.body?.cancel().catch(()=>{}),z.signal.throwIfAborted();let O2=T.get(q);if(O2){if(O2.received=!0,X(N2.headers,q))N2=e1({...O2.input,attemptId:void 0},N2)}if(N2.ok&&X(N2.headers,q))D2.set(q,{at:$.now?.()??Date.now()});return N2}catch(N2){let O2=T.get(q);if(O2&&!O2.received&&K?.kind!=="http-relay")O2.received=!0,Z0({...O2.input,attemptId:void 0});if(z.signal.throwIfAborted(),!r4(N2))throw N2;return Response.json({type:"error",error:{type:"api_error",message:"Connection lost while resending a rejected thread request"}},{status:502})}},m;if(K?.kind==="http-relay"){let l={protocol:1,type:"request",affinity:V.sessionID,upstream:{url:P2,method:z.method,headers:Object.fromEntries(b)},mode:"full_sync",revision:1,body:G,next_hash:`sha256:${n1("sha256").update(G).digest("hex")}`};o.set(q,{affinity:V.sessionID,route:V.accountId,bodyText:G,url:P2,method:z.method,headers:b,dispatch:"http-relay",relayUrl:K.url,envelope:l,relayBytes:JSON.stringify(l).length}),m=await y(K.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":K.token},body:JSON.stringify(l),signal:z.signal,redirect:"error"})}else{if(K?.kind==="websocket-relay")throw new m2;o.set(q,{affinity:V.sessionID,route:V.accountId,bodyText:G,url:P2,method:z.method,headers:b,dispatch:"direct"}),m=await y4({url:P2,body:G,headers:b,latch:await O(),send:(l,Q2)=>{return z1(),y(P2,{method:z.method,body:l,headers:Q2,signal:z.signal,redirect:"error"})}})}return j0(m)}}),M()}else if(q.route==="oauth"&&_2&&i!==void 0&&I.agent!=="cachekeep")i=await v4(i),M();if(p.dispatch?.kind==="http-relay"){let j2=i??"";h.delete("x-relay-token");let X2={protocol:1,type:"request",affinity:V.sessionID,upstream:{url:P2,method:z.method,headers:Object.fromEntries(h)},mode:"full_sync",revision:1,body:j2,next_hash:`sha256:${n1("sha256").update(j2).digest("hex")}`};if(_2&&i!==void 0&&!z2(I)){let F=a[p2]==="1"?"start":void 0,b=JSON.stringify(X2);o.set(q,{affinity:V.sessionID,route:V.accountId,bodyText:j2,url:P2,method:z.method,headers:new Headers(h),dispatch:"http-relay",relayUrl:p.dispatch.url,envelope:X2,relayBytes:b.length,...F?{tag:F}:{}})}else F2(q);z1();let Z=h.get("x-client-request-id"),G=new Request(p.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":p.dispatch.token,...Z?{"x-client-request-id":Z}:{}},redirect:"error",signal:z.signal,body:JSON.stringify(X2)});return I2(G,i),G}let R2=i;if(q.route==="oauth"&&_2&&i!==void 0){let j2=await C4({url:P2,body:i,latch:await O()});if(M(),j2.gzip)R2=await x4(i),h.set("content-encoding","gzip"),H.add(q),M()}if(_2&&i!==void 0&&!z2(I)){let j2=a[p2]==="1"?"start":void 0;o.set(q,{affinity:V.sessionID,route:V.accountId,bodyText:i,url:P2,method:z.method,headers:new Headers(h),dispatch:"direct",...j2?{tag:j2}:{}})}else F2(q);z1();let l2=new Request(P2,{method:z.method,headers:h,redirect:q.route==="oauth"?"error":z.redirect,signal:z.signal,...R2!==void 0?{body:R2}:{}});return I2(l2,i),l2;function I2(j2,X2){if(q&&_2&&X2!==void 0)try{let Z=J.billingRequest?.(x(I,q));if(Z){let G=e2(X2),F=X0(X2);T.set(q,{input:{...Z,attemptId:I.attemptId,model:h2(G)&&typeof G.model==="string"?G.model:Z.model,...F>0?{cache:{...Z.cache,ttlMs:F}}:{}},received:!1})}}catch{}if(q?.route!=="oauth"||!_2||X2===void 0)return;try{J.onFinalRequestPrepared?.({attemptId:I.attemptId,requestId:j2.headers.get("x-client-request-id")??void 0,bodyText:X2,ttlMs:X0(X2)})}catch{}}},V2={providerID:$1,chooseAccount:(V)=>C(V,async()=>{let M=await J.chooseAccount(V);if(typeof M==="object"&&V.phase==="retry")return M;if(typeof M!=="string"||!M)throw Y(V);return M}),dropChoice:(V)=>J.dropChoice?.(V),async retrySameAccount(V){if(!J.retrySameAccount)return;let M=L(V),z=k.get(M);k.delete(M);let I=V.limit??(z?V2.limitFromError?.(V.error,z):void 0);return J.retrySameAccount({...V,error:I1(V.error),...I?{limit:I}:{}})},dropSameAccountRetry:(V)=>J.dropSameAccountRetry?.({...V,error:I1(V.error)}),accountHeaders:u,rewriteRequest:e,rewriteHandshakeURL(){throw new m2},async rewriteResponse({response:V,attempt:M}){let z=M.data,I=z?T.get(z):void 0;if(I){if(I.received=!0,z&&X(V.headers,z))V=e1(I.input,V)}let q=z?Z2.get(z):void 0,p=q?.thread.fail;if(z)Z2.delete(z);if(q&&z&&X(V.headers,z))V=await q.thread.recover(j0(V),q.resend,q.beforeResend),V=q.thread.observe(V);else q?.thread.fail();if(z&&!X(V.headers,z)){if(z)F2(z);if(V.status===401)return B(z),V.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return t(z,V)}if(z&&H.has(z))H.delete(z),T4(V).then(async(y)=>{if(!y)return;(await O()).latchProcess(),N?.warn("gzipped request body rejected; later requests go uncompressed",{kind:y,status:V.status})},()=>{});let h=null,a=z?o.get(z):void 0;if(z&&a){let y=!1;try{y=await B2()}catch{y=!1}if(!y)F2(z);else{try{Y0(!0)}catch{}try{if(a.dispatch==="http-relay")h=await t1({affinity:a.affinity,transport:"http",protocol:1,mode:"full_sync",status:V.status,bodyText:a.bodyText,payload:a.envelope??{},relayBytes:a.relayBytes??0,...a.tag?{tag:a.tag}:{}});else h=await a1({affinity:a.affinity,route:a.route,status:V.status,bodyText:a.bodyText,url:a.url,method:a.method,headers:a.headers,...a.tag?{tag:a.tag}:{}})}catch{h=null}if(F2(z),h){Y2.set(z,h);try{await Q1(h,{status:V.status,message:null,complete:!1})}catch{}M2.set(z,Promise.resolve())}}}let i=t(z,V),_2,P2=async(y)=>{if(z)await M2.get(z);if(_2){_2.fail(y),await _2.finish();return}await Q1(h??null,{status:V.status,message:null,complete:!1,incomplete_stream:y})};if(z?.route!=="oauth"||!i.body)return s(z,z&&R.get(z)==="event-stream"?k4(i,P2):i);let k2={...x(M,z),status:V.status},S2=J.responseOptions?.(k2)??{},R2=z?R.get(z)==="http":(V.headers.get("content-type")??"").includes("application/json"),l2={...S2,requireMessageStop:!0,onIncompleteStream:P2,toolNameMap:z?w.get(z):void 0,onResponseFailure:p,onToolNameRefusal:()=>{if(!z)return;j.set(z,"response_tool_names"),B(z)},laneStartOAuthServed:!0,...R2?{responseMode:"json"}:{}};if(!z||!h)return s(z,v1(i,l2));let I2=h,j2=V.status,X2=E4(I2,j2);_2=X2;let Z=(y)=>{let l=(M2.get(z)??Promise.resolve()).then(()=>y().then(()=>{return})).catch(()=>{return});M2.set(z,l)},G=S2.onMessageStart,F=S2.onMessageDelta,b=S2.onMessageResponse,K=S2.onStreamEnd;return s(z,v1(i,{...l2,onSseEvent:X2.observe,onMessageStart:(y)=>{try{G?.(y)}catch{}try{U2.set(z,{...y}),Z(()=>Q1(I2,{status:j2,message:y,complete:!1}))}catch{}},onMessageDelta:(y)=>{try{F?.(y)}catch{}try{let m=U2.get(z)??{},l=m.usage&&typeof m.usage==="object"&&!Array.isArray(m.usage)?m.usage:{},Q2={...m,...y.usage?{usage:{...l,...y.usage}}:{},...y.stopReason?{stop_reason:y.stopReason}:{}};Z(()=>Q1(I2,{status:j2,message:Q2,complete:!0,reply_text_edges:X2.replyTextEdges()}))}catch{}},onMessageResponse:(y)=>{try{b?.(y)}catch{}try{Z(()=>Q1(I2,{status:j2,message:y,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await K?.()}catch{}try{await(M2.get(z)??Promise.resolve())}catch{}}}))},quotaFromHeaders(V,M,z){let I=z.data;if(!I||!X(V,I))return;if(I.route==="oauth"&&M>=200&&M<300)D2.set(I,{at:$.now?.()??Date.now()});return J.quotaFromHeaders?.(V,{...x(z,I),status:M})},async limitFromResponse({status:V,headers:M,body:z,attempt:I}){let q=I.data;if(!q||j.get(q)==="response_tool_names")return;if(!X(M,q))return J.limitFromRelayFailure?.({...x(I,q),status:V});if(A.set(q,`provider responded with HTTP ${V}`),!J.limitFromResponse)return;let p=T2.get(M)===q,h=$2(q),a=await J.limitFromResponse({...x(I,q),status:V,headers:M,body:async()=>p?await z():h.redactText(await z())});if(a)g.add(q);return a},inspectEvent({data:V,event:M,attempt:z}){if(z.data&&j.get(z.data)==="response_tool_names")return;let I=e2(V);if(!h2(I))return;let q=typeof I.type==="string"?I.type:M;if(q==="content_block_start"||q==="content_block_delta")return{outputStarted:!0};if(q==="message_stop")return{done:!0};if(q!=="error")return;let p=z.data,h=$2(p),a=h2(I.error)?I.error:{},i=typeof a.type!=="string"?void 0:N0.has(a.type)?a.type:h.redactText(a.type),_2=typeof a.message==="string"?h.redactText(a.message):void 0;if(p?.dispatch==="http-relay"&&E.get(p)===!1)return;let P2=p?J.limitFromStreamError?.({...x(z,p),errorType:i,message:_2}):void 0,k2={error:[i??"error",_2].filter(Boolean).join(": ").slice(0,n4),...P2?{limit:P2}:{}};if(p&&k2.error)A.set(p,k2.error);return k2},limitFromError(V,M){let z=M.data;if(!z||j.has(z))return;let I=I1(V,A.get(z));if(B(z),z.dispatch==="http-relay"&&E.get(z)===!1)return;return J.limitFromHostError?.(I,x(M,z))},async onAttemptEnd(V,M){let z=V.data;if(!z)return;let I=T.get(z);if(T.delete(z),I&&!I.received&&!j.has(z)&&z.dispatch==="direct")Z0(I.input);W.delete(z);let q=o.get(z);if(q){F2(z);try{if(await B2()){try{Y0(!0)}catch{}try{if(q.dispatch==="http-relay"){if(M.status!==void 0)await t1({affinity:q.affinity,transport:"http",protocol:1,mode:"full_sync",status:M.status,bodyText:q.bodyText,payload:q.envelope??{},relayBytes:q.relayBytes??0,...q.tag?{tag:q.tag}:{}})}else await a1({affinity:q.affinity,route:q.route,status:M.status,error:M.status===void 0?p4:void 0,bodyText:q.bodyText,url:q.url,method:q.method,headers:q.headers,...q.tag?{tag:q.tag}:{}})}catch{}}}catch{}}let p=M.error?.reason;if(p==="cancelled"||p==="abandoned"||p===void 0&&(M.status===void 0||M.status<400))B(z);let h=j.get(z),{status:a,...i}=M,_2=J.onAttemptEnd?.(x(V,z),{...i,...a!==void 0&&(z.dispatch!=="http-relay"||E.get(z)===!0)?{status:a}:{},...h!==void 0?{localRefusal:{check:h}}:{}});if(await X8(_2,P)==="timed-out")N?.warn("the account source did not finish recording a send",{timeoutMs:P})}};return{adapter:V2,discardUnsentBilling:(V)=>{T.delete(V)},acceptedResponse:(V)=>E2.get(V),dispose(){c=!0;for(let[V,M]of Q){for(let z of M)z.revoked=!0;J.forgetSession?.(V)}Q.clear(),W.clear(),k.clear(),o.clear();for(let V of[..._.keys()])B(V)},forgetSession(V){J2.forget(V);for(let M of Q.get(V)??[])M.revoked=!0;Q.delete(V);for(let[M,z]of k)if(z.sessionID===V)k.delete(M);for(let[M,z]of W)if(z.sessionID===V)W.delete(M);for(let[M,z]of[..._])if(z.sessionID===V)B(M);for(let[M,z]of[...o])if(z.affinity===V)o.delete(M);J.forgetSession?.(V)},get pendingSendCount(){return W.size},get heldCredentialCount(){let V=0;for(let M of W.values())if(M.oauth)V++;return V},get heldRedactorCount(){return _.size},get operationsInProgress(){let V=0;for(let M of Q.values())V+=M.size;return V}}}import{setTimeout as j8}from"node:timers/promises";import{CacheKeepManager as G8,CacheKeepPrewarmError as h1,CacheKeepSessionRegistry as V8,CacheKeepWarmRefusal as F1,getCacheKeepRegistryDirectories as Q8,isCacheKeepActiveNow as P0,isCacheKeepHybridActive as J1,isCacheKeepSubagentsEnabled as r2,logger as i2,NativeAccountRefusal as c2,nativeAccountCanServe as E0,nativeAccountRefusal as W8,readSessionCachePolicy as v2,requestCacheLifetimeMs as O0,sessionCacheActivity as U8}from"@cortexkit/anthropic-auth-core";import{CacheKeepStore as Y8}from"@cortexkit/anthropic-auth-core";var H1="2.10.0";import{cacheKeepStoreDirectory as l9,legacyCacheKeepStoreDirectory as u9}from"@cortexkit/anthropic-auth-core";class g1 extends Y8{constructor($,J){super({...$,pluginVersion:H1},J)}}var C0=new WeakMap;function X1($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}function B8($,J){if(!$)return"foreign-identity";try{let N=JSON.parse($);if(!Array.isArray(N))return"foreign-identity";let[U,,P,T,S]=N;if(U==="local"&&typeof T==="string"&&typeof S==="string")return J.some((O)=>O.binding?.storageId===T&&O.binding.rowId===S)?"foreign-identity":"account-gone";if(U==="vault"&&typeof P==="string")return J.some((O)=>O.credentialId===P)?"foreign-identity":"account-gone"}catch{}return"foreign-identity"}function x0($,J,N){if(!N){$.hybridDisabled=!1;return}let U=(S)=>v2(S,!0)?.keep_warm!==void 0,P=!1;for(let S of $.manager.trackedSessions())if(U(S.id)||$.manager.hasPlannedTarget?.(S.id))P=!0;else $.manager.untrack(S.id,"disabled");if($.hybridDisabled)return;$.hybridDisabled=!0;let T=$.persistence;$.localCleanup=($.localCleanup??Promise.resolve()).then(async()=>{await T.drain(),await T.load(J,(O)=>{if(!$.hybridDisabled)return;if(O.policyState?.planned||U(O.policyState?.ownerSessionId??O.id)){P=!0;return}return T.removed(O.id),"invalid"});let S=$.manager.trackedSessions().some((O)=>U(O.id)||$.manager.hasPlannedTarget?.(O.id));if(!P&&!S&&$.hybridDisabled)T.clear()}).catch(()=>i2.warn("cachekeep","local restart cleanup failed"))}var T0=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function q0(){let $=globalThis;return $[T0]??=new Map,$[T0]}function z8($,J,N){let U=new Map,P=new Map,T=new Set,S=0,O=new V8({...Q8("opencode",J.registryDirectory),now:J.now}),H=()=>{let _;for(let A of P.values())_=A;return _},W=J.setIntervalImpl??globalThis.setInterval,j=new G8({loadStorage:async()=>{let _=H(),A=_?await _.loadStorage():null;if(_)x0(w,J.now?.()??Date.now(),!J1(A));return A},now:J.now,setIntervalImpl:(_,A)=>W(()=>{let f=j.tick();return w.ticking=f.catch(()=>{i2.warn("cachekeep","tick failed")}),w.ticking},A),clearIntervalImpl:J.clearIntervalImpl,setTimeoutImpl:J.setTimeoutImpl,clearTimeoutImpl:J.clearTimeoutImpl,reserveWarm:(_)=>w.persistence.reserveWarm(_),settleWarm:(_)=>j.isCurrentTarget(_)?w.persistence.reserveWarm(_):Promise.resolve(!1),deferWarmReservation:!0,responseTtlMs:(_)=>C0.get(_),onTargetChanged:(_)=>w.persistence.changed(_),onTargetRemoved:(_)=>{T.delete(_),w.persistence.removed(_)},onTrackedSessionsChanged:(_)=>O.publish(P.size===0?[]:_),prepareHeaders(_,A,f){let $2=H();if(!$2)return;return U.set(f.id,{target:A,attempt:f,lease:$2}),new Headers({"x-native-cachekeep-attempt":String(f.id)})},fetchImpl:async(_,A)=>{let f=new Request(_,A),$2=Number(f.headers.get("x-native-cachekeep-attempt")),B=U.get($2);if(U.delete($2),!B||B.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(T.delete(B.target.id))await j8(Math.max(0,S+3000-Date.now()),void 0,{signal:B.attempt.signal}),S=Date.now();let D=B.lease.send(B.target,f,B.attempt.signal),R=D.then(()=>{},()=>{});return B.lease.inflight.add(R),R.then(()=>B.lease.inflight.delete(R)),D},onComplete:({attempt:_})=>{U.delete(_.id)}}),E,L=()=>{if(E!==void 0)clearTimeout(E);E=void 0},k=()=>{if(L(),P.size>0)return;let _=j.dropExpiredTargets();if(_===void 0){let f=q0();if(f.get($)===w)f.delete($);return}let A=J.now?.()??Date.now();if(E=setTimeout(k,Math.max(0,_-A)),typeof E==="object"&&"unref"in E)E.unref()},w={manager:j,registry:O,persistence:N,persistenceFollowsOwner:!0,prepared:U,leases:P,nextGeneration:0,retain(){j.stop(),U.clear(),k()},async adopt(){if(L(),w.loading??=(async()=>{let _=H();if(!_)return;let A=await _.read(),f=J.now?.()??Date.now(),$2=0;await w.persistence.load(f,(B)=>{if(!P.size||j.trackedRequest(B.id))return;if(!J1(A.policyStorage)&&v2(B.policyState?.ownerSessionId??B.id,!0)?.keep_warm===void 0)return"invalid";let D=A.accounts.find((t)=>X1(t)===B.oauthAccountIdentity);if(!D)return B8(B.oauthAccountIdentity,A.accounts);if(D.type!=="oauth"||!E0(D))return"account-gone";if(B.isSubagent&&v2(B.policyState?.ownerSessionId??B.id,!0)?.keep_warm===void 0&&!r2(A.policyStorage))return"invalid";let R=B.nextPrewarmAt<=f?f+$2++*3000:B.nextPrewarmAt,d=j.track({sessionId:B.id,url:B.url,headers:new Headers,bodyText:B.bodyText,storage:A.policyStorage,cacheMode:"hybrid",oauthAccountId:D.id,oauthAccountIdentity:B.oauthAccountIdentity,isSubagent:B.isSubagent,retained:{cacheExpiresAt:B.cacheExpiresAt,nextPrewarmAt:R,ttlMs:B.ttlMs,lastTouchAt:B.lastTouchAt,lastTouchKind:B.lastTouchKind,policyState:B.policyState}});if(d.tracked)T.add(B.id);return d.tracked?!0:"invalid"})})().catch(()=>{i2.warn("cachekeep","failed to restore tracked sessions")}),await w.loading,!P.size)return;if(j.dropExpiredTargets()===void 0)return;j.start(),O.publish(j.registrySessions?.()??j.trackedSessions()).catch(()=>{i2.warn("cachekeep","failed to publish tracked sessions")})}};return w}function S0($){let{runtime:J,source:N}=$,U=new AbortController,P=q0(),T=P.get($.storageId),S=new g1({storageId:$.storageId,...$.persistence},T?.persistence),O=T??z8($.storageId,$,S);if(T&&!T.persistenceFollowsOwner){O.legacyPersistence??=O.persistence;let B=O.legacyPersistence;B.changed=(D)=>S.changed(D),B.removed=(D)=>S.removed(D),B.clear=()=>S.clear(),B.load=(D,R)=>S.load(D,R)}O.persistence=S,P.set($.storageId,O);let{manager:H,registry:W}=O,j=new Map,E=async(B,D)=>{let R=j.get(B),d=()=>!_.stopped&&R!==void 0&&H.trackedPolicyState?.(B)===R;if(!d())return;if(!D){H.updateSubagent?.(B,!1);return}let t=()=>[...O.leases.values()].at(-1),c=t(),o=await c?.loadStorage();if(!d()||!c||t()!==c)return;if(o&&v2(B,!0)?.keep_warm===void 0&&!r2(o))H.untrack(B,"policy-refused"),j.delete(B);else H.updateSubagent?.(B,D)},L=new Map,k=(B)=>{let D=L.get(B);return L.delete(B),D?.signal?.removeEventListener("abort",D.onAbort),D?.target},w=async(B,D,R)=>{let d=R?AbortSignal.any([U.signal,R]):U.signal;if(d.aborted)throw new h1("authorization",d.reason);let t=await D.text(),c;if(!H.reserveWarmDispatch&&(B.policyState?.planned||v2(B.policyState?.ownerSessionId??B.id,!0)?.keep_warm!==void 0)){if(!O.plannedUnsupportedLogged)O.plannedUnsupportedLogged=!0,i2.debug("cachekeep","planned warming requires a server restart after an older owner reload");throw new F1("unsupported")}let o=JSON.parse(t),Y2={providerID:"anthropic",modelID:o.model,sessionID:`oc2-cachekeep:${B.id}`,agent:"cachekeep",kind:"generate"},U2=(s)=>{throw new c2(s)},M2=O0(t),z2=Z1({source:{...N,billingRequest(s){let X=N.billingRequest?.(s);return X?{...X,sessionId:B.policyState?.ownerSessionId??B.id,requestKind:"keep_warm",cache:{warming:{on:!0}}}:void 0},onRequestPrepared:void 0,onFinalRequestPrepared:({ttlMs:s})=>{M2=s},responseOptions:void 0,async requestOptions(s){return{...await N.requestOptions?.(s,U2),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(s,X){let Y=await J.read();c=Y.policyStorage,d.throwIfAborted();let Q=Y.accounts.find((v)=>v.id===X);if(Q?.type!=="oauth"||!E0(Q))throw new c2("account-unavailable");if(X1(Q)!==B.oauthAccountIdentity)throw new c2("credential-changed");if(!B.policyState?.planned&&(B.isSubagent&&v2(B.policyState?.ownerSessionId??B.id,!0)?.keep_warm===void 0&&!r2(Y.policyStorage)||!J1(Y.policyStorage)||!P0(Y.policyStorage,new Date($.now?.()??Date.now()))))return;let C=await N.authorizeAccount(s,X,U2);if(C?.provenance.kind==="local"&&X1({...Q,binding:C.provenance.subject.binding,accountIdentity:C.provenance.subject.binding.identity})!==B.oauthAccountIdentity)throw new c2("credential-changed");if(C?.provenance.kind==="vault"&&C.provenance.credentialId!==Q.credentialId)throw new c2("credential-changed");return C},async admitRequest(s){await N.admitRequest?.(s,U2);let X=await J.read();c=X.policyStorage;let Y=X.accounts.find((Q)=>Q.id===s.accountId);if(d.throwIfAborted(),!Y)throw new c2("account-unavailable");if(X1(Y)!==B.oauthAccountIdentity)throw new c2("credential-changed");if(!B.policyState?.planned&&(B.isSubagent&&v2(B.policyState?.ownerSessionId??B.id,!0)?.keep_warm===void 0&&!r2(X.policyStorage)||!J1(X.policyStorage)||!P0(X.policyStorage,new Date($.now?.()??Date.now()))))throw Error("CacheKeep policy changed before dispatch")}}}),B2,F2,T2="authorization",D2=!1,E2=()=>z2.forgetSession(Y2.sessionID);d.addEventListener("abort",E2,{once:!0});try{let s=await J.read();c=s.policyStorage;let X=B.policyState?.ownerSessionId??B.id,Y=H.trackedRequest(X)?.bodyText,Q=Y?JSON.parse(Y).model:o.model,C=H.trackedRequest(B.id)?N.peekAccount?.(X,Q,s):void 0;if(C!==void 0&&C!==(B.oauthAccountId??"main"))throw new F1("routing-moved");let v=s.accounts.find((V2)=>X1(V2)===B.oauthAccountIdentity)?.id;if(!v)throw new c2(s.accounts.some((V2)=>V2.id===B.oauthAccountId)?"credential-changed":"account-unavailable");let x=await z2.adapter.accountHeaders({...Y2,accountId:v});if(!("headers"in x)||typeof x.headers!=="object"||x.headers===null||typeof x.attempt!=="object"||x.attempt===null||x.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");B2={...Y2,accountId:v,attemptId:crypto.randomUUID(),transport:"http",data:x.attempt};let u=await z2.adapter.rewriteRequest?.({...Y2,accountId:v,attempt:B2,request:new Request(B.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(o),signal:d})});if(!u)throw Error("CacheKeep rewrite refused");d.throwIfAborted();let r=B.policyState?.ownerSessionId??B.id,J2=v2(r,!0)?.keep_warm!==void 0,Z2=J2?void 0:$.subagent?.(r);if(!J2&&$.subagent&&Z2===void 0)throw new h1("authorization",void 0);if(Z2&&!r2(c))throw new F1("subagents-disabled");await H.reserveWarmDispatch?.(B),d.throwIfAborted(),T2="send";let L2=await($.fetch??fetch)(u);T2="response",F2=L2.status;let g=await z2.adapter.rewriteResponse?.({...Y2,accountId:v,attempt:B2,request:u,response:L2});if(!g)throw Error("CacheKeep response rewrite refused");if(F2=g.status,z2.adapter.quotaFromHeaders?.(g.headers,g.status,B2),!g.ok)await z2.adapter.limitFromResponse?.({status:F2,headers:g.headers,body:()=>g.clone().text(),attempt:B2});let e=await g.arrayBuffer();if(g.ok&&!d.aborted&&!B.sourceWarm&&(H.isCurrentTarget?.(B)??!0))U8.recordPrewarm(B.id,v,$.now?.()??Date.now(),M2);D2=!0;let n=new Response(e,{status:F2,headers:g.headers});return C0.set(n,M2),n}catch(s){if(s instanceof F1)throw s;let X=W8(s);if(X)throw X;throw new h1(T2,s,F2)}finally{if(d.removeEventListener("abort",E2),B2?.data&&T2==="authorization")z2.discardUnsentBilling(B2.data);try{if(B2)await z2.adapter.onAttemptEnd?.(B2,{status:F2,outputStarted:!1,...D2?{}:{error:{reason:"cancelled"}}})}finally{z2.dispose(),N.forgetSession?.(Y2.sessionID)}}},_={generation:O.nextGeneration++,stopped:!1,loadStorage:async()=>(await J.read()).policyStorage,send:w,inflight:new Set,read:()=>J.read(),subagent:$.subagent},A=O.leases.size===0;O.leases.set(_.generation,_);let f=(A?O.adopt():O.loading??Promise.resolve()).then(()=>{if(!_.stopped)for(let B of H.trackedSessions())$.subagent?.(B.id)}),$2;return{ready:f,async track(B){let D=(Y2)=>{k(B.attemptId),i2.debug("cachekeep","tracking skipped",{session:B.sessionID,reason:Y2})};if(_.stopped)return D("lease-stopped");if(B.route!=="oauth")return D("not-oauth");if(B.agent==="cachekeep"||B.agent==="prime")return D("background-agent");if(B.kind!=="primary")return D("not-primary");if(B.signal?.aborted)return D("attempt-ended");k(B.attemptId);let R={sessionID:B.sessionID,signal:B.signal,onAbort:()=>k(B.attemptId)};L.set(B.attemptId,R),B.signal?.addEventListener("abort",R.onAbort,{once:!0});let d=B.admission?.snapshot??await J.read();if(_.stopped)return D("lease-stopped");let t=v2(B.sessionID,!0);if(t?.keep_warm!==void 0&&!H.reserveWarmDispatch){if(!O.plannedUnsupportedLogged)O.plannedUnsupportedLogged=!0,i2.debug("cachekeep","planned warming requires a server restart after an older owner reload");return D("planned-owner-requires-restart")}if(x0(O,$.now?.()??Date.now(),!J1(d.policyStorage)),!J1(d.policyStorage)){if(t?.keep_warm===void 0)return D("hybrid-inactive")}let c=!1;try{c=$.subagent?$.subagent(B.sessionID)??!1:await $.isSubagent?.(B.sessionID)??!1}catch{return D("session-lookup-failed")}if(_.stopped)return D("lease-stopped");if(t?.keep_warm===void 0&&c&&!r2(d.policyStorage))return D("subagents-disabled");let o=B.admission?.account??d.accounts.find((Y2)=>Y2.id===B.accountId);if(!o?.accountIdentity)return D("account-identity-missing");if(B.provenance.kind==="local"&&JSON.stringify(o.binding)!==JSON.stringify(B.provenance.subject.binding))return D("local-binding-changed");if(B.provenance.kind==="vault"&&o.credentialId!==B.provenance.credentialId)return D("vault-credential-changed");if(L.get(B.attemptId)!==R)return D("attempt-ended");R.target={sessionId:B.sessionID,url:B.url,headers:new Headers,bodyText:B.bodyText,storage:d.policyStorage,cacheMode:"hybrid",oauthAccountId:B.accountId,oauthAccountIdentity:X1(o),isSubagent:c,ttlMs:O0(B.bodyText)||(v2(B.sessionID,!0)?.ttl!==void 0?0:void 0)}},onResponseHeaders(B){let D=k(B.attemptId);if(!_.stopped&&B.status>=200&&B.status<300&&D){let R=D.sessionId;if(!R)return;let d=$.subagent?.(R);if(d!==void 0)D.isSubagent=d;if(D.isSubagent&&v2(R,!0)?.keep_warm===void 0&&!r2(D.storage)){H.untrack(R,"policy-refused");return}let t=H.track({...D,acceptedUsage:B.acceptedUsage,...B.acceptedAt!==void 0&&{acceptedAt:B.acceptedAt},...B.ttlMs!==void 0&&{ttlMs:B.ttlMs}});if(t.tracked){for(let o of O.leases.values())o.subagent?.(R);j.delete(R);let c=H.trackedPolicyState?.(R);if(c)j.set(R,c);if(j.size>4096){let o=j.keys().next().value;if(o!==void 0)j.delete(o)}}if(t.tracked)W.publish(H.registrySessions?.()??H.trackedSessions()).catch(()=>{i2.warn("cachekeep","failed to publish tracked sessions")});return t}},discardAttempt(B){k(B)},recordAcceptedUsage(B,D,R){H.recordAcceptedUsage?.(B,D,R)},resolvedParent:E,forgetSession(B){j.delete(B),H.untrack(B);for(let[D,R]of L)if(R.sessionID===B)k(D)},registry:W,dispose(){if($2)return $2;_.stopped=!0;for(let D of L.keys())k(D);U.abort();for(let[D,R]of O.prepared)if(R.lease===_)O.prepared.delete(D);let B=O.leases.delete(_.generation)&&O.leases.size===0;if(B)O.retain();return $2=(async()=>{try{if(B)await O.ticking;await f,await Promise.all(_.inflight),await O.persistence.drain()}finally{if(B&&O.leases.size===0)await W.dispose()}})(),$2}}}import{runWithRequestSignal as K8,withSessionCacheReportHandoff as M8}from"@cortexkit/anthropic-auth-core";async function k0($,J,N){let U=Z1(J),P=new Set,T={...U.adapter,onAttemptEnd(_,A){let f=Promise.resolve(U.adapter.onAttemptEnd?.(_,A));return P.add(f),f.finally(()=>P.delete(f)).catch(()=>{}),f}},S=async()=>{await Promise.allSettled([...P])},O=[],H=async(_,A,f)=>{let $2=await $.session.hook(_,async(B)=>{if(_==="http.response")return M8(async()=>{let R=!1;try{let d=await A(B);return R=!0,d}finally{if("request"in B&&B.request instanceof Request)try{let d="response"in B&&B.response instanceof Response?B.response:void 0;J.source.onResponseHandedToHost?.(B.request,R&&d?U.acceptedResponse(d):void 0)}catch{}}})();if(_!=="http.request")return A(B);let D="request"in B&&B.request instanceof Request?B.request.signal:void 0;return K8(D,async()=>A(B))},f);return O.push($2),$2},W=new AbortController,j;try{j=await D1({session:{hook:H},event:$.event},T,{logger:J.log,gateOnPlaceholder:N})}catch(_){throw U.dispose(),await Promise.allSettled(O.map((A)=>A.dispose())),_}let E=(_)=>{U.forgetSession(_),j.forgetSession(_)},L=$.event,k=L?(async()=>{try{for await(let _ of L.subscribe({signal:W.signal})){if(_.type==="session.deleted")E(_.data.sessionID);if(_.type==="session.idle"||_.type==="session.status"&&_.data.status.type==="idle")J.source.forgetTurn?.(_.data.sessionID)}}catch(_){if(!W.signal.aborted)J.log?.warn("stopped listening for session deletion",{error:_ instanceof Error?_.name:"unknown"})}})():Promise.resolve(),w;return{installation:j,forgetSession:E,drain:S,dispose(){if(w)return w;return U.dispose(),W.abort(),w=(async()=>{await j.dispose(),await k,await S()})(),w}}}import{effectiveRelayTransport as R0,getQuotaCheckIntervalMs as _8,logger as N8,nativeAccountCanServe as H8,oauthProfileIsFresh as F8,quotaSnapshotCheckedAt as L8}from"@cortexkit/anthropic-auth-core";function b0($,J){let N=new AbortController,U,P=!1,T=async()=>{let H=await $.read();if(N.signal.throwIfAborted(),H.policyStorage.relay?.enabled===!0&&R0(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="websocket")return;let W=H,j=_8(W.policyStorage);for(let E of W.accounts){if(N.signal.aborted)return;if(!H8(E)||E.type!=="oauth")continue;if(W.policyStorage.quota?.enabled!==!1&&Date.now()-L8(E.quota)>=j)await $.fetchQuota(E.id,J,N.signal,void 0,"background").catch(()=>{});if(!F8(E.profile)&&!N.signal.aborted)await $.fetchProfile(E.id,J,N.signal).catch(()=>{})}},S=()=>{if(P||U)return U;return U=T().catch(()=>{if(!N.signal.aborted)N8.debug("opencode2","native background readings did not complete")}).finally(()=>{U=void 0}),U},O=$.vault.watch({intervalMs:60000,onRefresh:S,shouldRefresh:async()=>{let H=await $.read();return H.policyStorage.relay?.enabled!==!0||R0(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="http"}});return O.ready.catch(()=>{}),{async dispose(){P=!0,O.close(),N.abort(),await U}}}import{authorize as A8,buildCacheKeepStatusSummary as w8,buildClaudeQuotaSummary as D8,buildPrimeAccountStatuses as I8,buildPrimeStatusSummary as f8,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as y8,effectiveRelayTransport as v8,exchange as g8,formatNativeAccountState as h8,formatOAuthAccountTier as m8,getCacheKeepWindow as l8,getHostClaustrumEnrollmentPaths as u8,isCacheKeepAlways as d8,isCacheKeepHybridActive as p8,isCacheKeepPersistentlyEnabled as c8,isVaultHosted as i8,nativeAccountCanServe as o8,parseLogLevel as n8,resetClaustrumEnrollmentState as r8,setDumpEnabled as s8,VAULT_HOST_CONNECT_REFUSAL as a8}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as P8,effectiveRelayStatus as O8,formatNativeAccountState as T8,formatOAuthAccountTier as A0,getCacheKeepWindow as E8,getRoutingMode as C8,isCacheKeepAlways as x8,isCacheKeepHybridActive as q8,isPermanentRefreshError as S8,isPrimePersistentlyEnabled as k8,nativeAccountCanServe as I0,refreshBackoffActive as w0}from"@cortexkit/anthropic-auth-core";var D0=($)=>I0($)&&$.state!=="unsupported-access"?void 0:T8($)||void 0,R8=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return I0($)?"on-vault-served":"on-cold"},b8=($,J)=>typeof $==="number"&&$>J;function f0($,J){let{now:N}=J,U=$.policyStorage,P=$.accounts.filter((j)=>j.type==="oauth"),T=P.find((j)=>j.id==="main"),S=T?D0(T):void 0,O=T?.lastQuotaRefreshError?.nextRetryAt,H=T?.lastRefreshError,W=E8(U);return L1({main:{quota:T?.quota??null,enabled:T?.enabled,tierLabel:A0(T?.profile),quotaBackedOff:b8(O,N),quotaBackoffUntil:O,refreshBackedOff:w0(H,T?.accountIdentity,N,void 0),refreshBackoffUntil:H?.nextRetryAt,stateLine:S,quotaDated:Boolean(S)},fallbacks:P.filter((j)=>j.id!=="main"&&(j.enabled||j.source==="vault")).map((j)=>{let E=D0(j),L=R8(j);return{id:j.id,label:j.label,quota:j.quota??null,enabled:j.enabled,tierLabel:A0(j.profile),needsReauth:S8(j.lastRefreshError)&&w0(j.lastRefreshError,j.accountIdentity,N,void 0),...L==="on-vault-reauth"?{vaultReauth:!0}:{},...L==="on-vault-served"?{vaultServed:!0}:{},...L!=="off"?{custodyState:L}:{},stateLine:E,quotaDated:Boolean(E)}}),...J.activeId!==void 0&&{activeId:J.activeId},route:C8(U),relay:O8(U.relay),fastMode:U.claudeFast?.enabled===!0,cacheKeep:{enabled:q8(U),...x8(U)?{window:"always"}:W&&{window:`${W.startHour}-${W.endHour}`},trackedSessions:J.trackedSessions},prime:k8(U)?{enabled:!0,accounts:P8(U,{now:N})}:void 0,lastUpdated:N})}var m1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},y0=`For first-time model access, connect Anthropic with "${T1}".
|
|
4
|
+
Run: opencode auth login anthropic --method ${O1}`,t8="No Claude accounts in the vault for this host yet. Add one with `ck auth login --provider anthropic`, then grant it to this host.",v0="The vault returned an account this plugin cannot use yet.";async function e8($){let J=new AbortController,N;try{return await Promise.race([$.vault.refresh(J.signal).then(()=>"complete",()=>"failed"),new Promise((U)=>{N=setTimeout(()=>{U("pending"),J.abort()},2000)})])}finally{clearTimeout(N)}}var g0=($)=>$.mode==="local"&&!$.accounts.some((J)=>J.id==="main"),$$=($)=>{let J=$.id==="main"?"main":"fallback",N=`${$.enabled?"enabled":"disabled"}, ${$.type}, ${$.source}${$.state?`, ${h8($)}`:""}`;if($.label)return`${$.label} [${J}]: ${N}
|
|
5
|
+
Route: ${$.id}`;return`${J==="main"?"Main account":`Fallback ${$.id}`}: ${N}`};function h0($){let{runtime:J,source:N}=$,U=new Map,P=!1,T=async(W,j)=>{await J.updateSettings((E)=>({...E,[W]:{...m1(E[W]),...j}}))},S=()=>({ok:!0,text:"Native Claude settings updated."}),O=async(W,j)=>{if(i8()&&["enrollment-reset","add-oauth-start","add-oauth-finish","add-apikey"].includes(W.action))throw Error(a8);if(P)throw Error("Native menu is closed");switch(j.signal?.throwIfAborted(),W.action){case"enable":case"disable":return await J.setEnabled(W.values.id,W.action==="enable"),S();case"remove":return await J.remove(W.values.id),S();case"move-up":case"move-down":{let L=(await J.read()).accounts.map((f)=>f.id),k=L.indexOf(W.values.id),w=k+(W.action==="move-up"?-1:1);if(k<0||w<0||w>=L.length)return{ok:!1,text:"Account cannot move in that direction."};let _=L[k],A=L[w];if(_===void 0||A===void 0)return{ok:!1,text:"Account order changed."};return L[k]=A,L[w]=_,await J.reorder(L),S()}case"add-apikey":return await J.addApi(W.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let E=new AbortController;U.get(W.sessionId)?.active.abort();let L={active:E,auth:void 0};U.set(W.sessionId,L);let k=await A8("max");if(P||E.signal.aborted||j.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return L.auth=k,{ok:!0,text:`Open ${k.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let E=U.get(W.sessionId);if(!E?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let L=await g8(W.values.code,E.auth.verifier,E.auth.redirectUri,E.auth.state);if(E.active.signal.throwIfAborted(),j.signal?.throwIfAborted(),P||L.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await J.loginOAuth({routeId:crypto.randomUUID(),credential:{access:L.access,refresh:L.refresh,expires:L.expires},label:W.values.label}),E.active.signal.throwIfAborted(),j.signal?.throwIfAborted(),P)return{ok:!1,text:"Sign-in cancelled."};U.delete(W.sessionId);let k="OAuth account stored in the native account pool.";return{ok:!0,text:g0(await J.read())?`${k}
|
|
6
6
|
|
|
7
|
-
${
|
|
7
|
+
${y0}
|
|
8
8
|
|
|
9
|
-
Adding an account here does not change OpenCode's Anthropic connection.`:
|
|
10
|
-
`)||
|
|
11
|
-
`);return
|
|
9
|
+
Adding an account here does not change OpenCode's Anthropic connection.`:k}}case"reset-backoff":{let E=await J.read();for(let L of E.accounts){if(j.signal?.throwIfAborted(),L.type!=="oauth")continue;let k=L.source==="vault"?await J.authorizeVault(L.id,j.signal):await J.captureLocalSubject(L.id);await J.resetBackoff(L.id,k)}return S()}case"enrollment-reset":{let E=await r8(u8("opencode"),y8);return{ok:E==="reset",text:E==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":E==="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 L=(await J.read()).accounts.filter((_)=>_.type==="oauth"&&o8(_)),k=await Promise.allSettled(L.map((_)=>J.fetchQuota(_.id,void 0,j.signal)));return{ok:k.every((_)=>_.status==="fulfilled"),text:`${k.filter((_)=>_.status==="fulfilled").length}/${L.length} native quota readings refreshed.`}}case"routing-reset":return await N.resetRouting(W.sessionId),S();case"routing-mode":return await T("routing",{mode:W.values.mode}),S();case"routing-max-same-account-wait":return await T("routing",{maxSameAccountWait:W.values.maxSameAccountWait}),S();case"killswitch-on":case"killswitch-off":return await T("killswitch",{enabled:W.action==="killswitch-on"}),S();case"killswitch-set":return await J.updateSettings((E)=>{let L=m1(E.killswitch),k={...m1(L.accounts)},w=L.main;for(let _ of W.values.entries){let A={five_hour:_.fh,seven_day:_.sd,..._.scoped!==void 0?{scoped:_.scoped}:{}};if(_.account==="main"||_.account==="all")w=A;if(_.account==="all")for(let f of Object.keys(k))k[f]=A;else if(_.account!=="main")k[_.account]=A}return{...E,killswitch:{...L,main:w,accounts:k}}}),S();case"cache-on":case"cache-off":return await T("claudeCache",{enabled:W.action==="cache-on"}),S();case"cache-mode":return await T("claudeCache",{mode:W.values.mode}),S();case"cachekeep-always":return await T("cacheKeep",{enabled:!0,always:!0}),S();case"cachekeep-off":return await T("cacheKeep",{enabled:!1}),S();case"cachekeep-window":return await T("cacheKeep",{enabled:!0,always:!1,startHour:W.values.startHour,endHour:W.values.endHour}),S();case"cachekeep-subagents":return await T("cacheKeep",{subagents:W.values.enabled==="on"}),S();case"dump-on":case"dump-off":{let E=W.action==="dump-on";await T("dump",{enabled:E});try{s8(E)}catch{}return S()}case"logging-level":{let E=n8(W.values.level);if(!E)throw Error("Invalid log level");return await J.setLoggingLevel(E),S()}case"fast-on":case"fast-off":return await T("claudeFast",{enabled:W.action==="fast-on"}),S();case"prime-on":case"prime-off":return await T("prime",{enabled:W.action==="prime-on"}),S();case"start-fire":return await H(W.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},H=(W)=>$.start(W,P1);return{dispatch:O,async readStatus(W){let j=await J.read();if(W==="account"){let L="No native Claude accounts.",k=[];if(j.mode==="claustrum"){let _=j.policyStorage.relay;if(_?.enabled===!0&&v8(_.transport,_.url)==="websocket")return new m2().message;let A=await e8(J);if(j=await J.read(),j.mode==="claustrum"){let f=await J.vault.read();if(A==="complete"&&!f?.view)A="failed";if(L=A==="complete"?t8:"No saved Claude accounts for this host yet.",f?.rejected?.length){if(L=v0,j.accounts.length)k.push(v0)}if(A==="pending")k.push("Vault account lookup is still running.");else if(A==="failed")k.push("Vault account lookup did not complete; reopen /claude to retry.")}}let w=[j.accounts.map($$).join(`
|
|
10
|
+
`)||L,...k].join(`
|
|
11
|
+
`);return g0(j)?`${w}
|
|
12
12
|
|
|
13
|
-
${
|
|
14
|
-
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:A}if(U==="quota")return R9({accounts:V.accounts.filter((_)=>_.type==="oauth").map((_)=>({name:_.label??_.id,role:_.id==="main"?"main":"fallback",enabled:_.enabled,quota:_.quota,tierLabel:v9(_.profile),lastRefreshedAt:_.lastRefreshedAt,error:_.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(U==="prime")return w9({enabled:V.policyStorage.prime?.enabled===!0,accounts:A9(V.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(U==="cachekeep"){let _=await $.cacheKeepRegistry?.list()??[];return b9({enabled:d9(V.policyStorage),always:m9(V.policyStorage),hybridActive:l9(V.policyStorage),trackedSessionDetails:_,window:g9(V.policyStorage),trackedSessions:_.length,nextPrewarmAt:_.length?Math.min(..._.map((b)=>b.nextPrewarmAt)):void 0})}let C={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(V.settings[C[U]]??{})},async readSidebar(U){let[V,C]=await Promise.all([X.read(),$.cacheKeepRegistry?.list()??[]]);return F1(A0(V,{activeId:N.servedAccount(U),trackedSessions:C.length,now:Date.now()}))},forgetSession(U){W.get(U)?.active.abort(),W.delete(U)},close(){P=!0;for(let U of W.values())U.active.abort();W.clear()}}}import{CLAUDE_MODEL_CAPABILITIES as t9,resolveClaudeModelCapabilities as e9}from"@cortexkit/anthropic-auth-core";function v0($=[]){return $.map((X)=>({id:X,settings:{effort:X,thinking:{type:"adaptive",display:"summarized"}}}))}function f0($){return{input:$.input,output:$.output,cache:{read:$.cacheRead,write:$.cacheWrite5m}}}function $$(){return t9.flatMap(($)=>{let X=$.catalogue;if(!X)return[];return[{id:$.id,modelID:$.id,providerID:"anthropic",type:"chat",family:`claude-${$.family}`,name:$.name,capabilities:{tools:!0,input:["text","image","pdf"],output:["text"],temperature:!1},variants:v0($.efforts.variants),time:{released:Date.parse(X.releaseDate)},cost:[f0(X.pricing),...X.longContext?[{...f0(X.longContext.pricing),tier:{type:"context",size:X.longContext.inputTokensAbove}}]:[]],status:"active",enabled:!0,limit:{context:X.contextWindow,output:X.maxOutputTokens}}]})}function g0(){let $=new Map;return{install:(W)=>W.model.transform((P)=>{$.clear();for(let T of P.list("anthropic")){$.set(String(T.id),String(T.modelID));let S=e9(T.modelID)?.efforts.variants;if(!S)continue;P.update("anthropic",String(T.id),(O)=>{let z=O.variants.filter((U)=>!S.some((V)=>V===String(U.id)));O.variants=[...z,...v0(S)]})}}),installProviderModels:(W)=>W.provider.transform((P)=>{let T=P.get("anthropic");if(!T)return;let S=$$().filter((O)=>!T.models.has(String(O.id)));if(!S.length)return;P.models.set("anthropic",[...T.models.values(),...S])}),modelId:(W)=>$.get(W)??W}}function h0($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as m0,effectiveRelayTransport as l0,nativeAccountCanServe as Z$,PrimeManager as X$,tokenFingerprint as d0}from"@cortexkit/anthropic-auth-core";var u0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function p0($){let{runtime:X,source:N}=$,W=new AbortController,P=new Set,T=(z)=>({providerID:"anthropic",modelID:m0().model,sessionID:`oc2-prime:${z}`,agent:"prime",kind:"generate"}),S=async(z)=>{let U=T(z),V=$1({source:N}),C=performance.now();try{for(let _=0;_<3;_++){if(W.signal.throwIfAborted(),(await X.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let A=await V.adapter.accountHeaders({...U,accountId:z});if(!("headers"in A)||typeof A.headers!=="object"||A.headers===null||typeof A.attempt!=="object"||A.attempt===null)throw Error("Native Prime authorization refused");let H={...U,accountId:z,attemptId:crypto.randomUUID(),transport:"http",data:A.attempt},D,f=!1,o=!1,M=(I)=>{o=!0,I.body?.cancel().catch(()=>{})};try{let I=await V.adapter.rewriteRequest?.({...U,accountId:z,attempt:H,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(m0()),signal:W.signal})});if(!I)throw Error("Native Prime rewrite refused");let x=new Headers(I.headers);for(let[M2,Q2]of Object.entries(A.headers))if(Q2===null)x.delete(M2);else x.set(M2,Q2);let m=new Request(I,{headers:x}),s=await($.fetch??fetch)(m),h=await V.adapter.rewriteResponse?.({...U,accountId:z,request:m,response:s,attempt:H})??s;D=h.status,V.adapter.quotaFromHeaders?.(h.headers,h.status,H);let Z2=h.ok?void 0:await V.adapter.limitFromResponse?.({status:h.status,headers:h.headers,body:()=>h.clone().text(),attempt:H});if(Z2&&/^(vault-newer|local-newer|relay-direct):/.test(Z2.reason)&&_<2){if(M(h),(await N.retrySameAccount?.({...U,accountId:z,attempt:_+1,limit:Z2,error:{type:"api_error",message:"Native Prime credential retry",status:h.status}}))?.accountId!==z)throw Error("Native Prime retry changed account");continue}if(!h.ok)return M(h),{ok:!1,status:D,ms:performance.now()-C,error:"Native Prime upstream refused the request"};let $2=u0(await h.json()),V2=u0($2.usage),H2={inputTokens:typeof V2.input_tokens==="number"?V2.input_tokens:void 0,outputTokens:typeof V2.output_tokens==="number"?V2.output_tokens:void 0};if(H.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(h.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(f=await N.recordPrime(A.attempt.provenance,H2),!f)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:D,ms:performance.now()-C,usage:H2}}finally{await V.adapter.onAttemptEnd?.(H,{status:D,outputStarted:!1,...f?{}:{error:{reason:o?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-C}}finally{V.dispose()}},O=new X$({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await X.read()).policyStorage,async getAccountFingerprint(z){let U=await X.read(),V=U.accounts.find((b)=>b.id===z);if(!Z$(V)||V?.type!=="oauth")return;if(U.policyStorage.relay?.enabled===!0&&l0(U.policyStorage.relay.transport,U.policyStorage.relay.url)==="websocket")return;if(V.source==="vault"){let b=await X.authorizeVault(z,W.signal),A=await X.getOrCreateAuthLineage(z,b);return A?d0(A):void 0}let C=await X.authorizeLocal(z,{signal:W.signal});if(C.status!=="usable")return;let _=await X.getOrCreateAuthLineage(z,C.subject);return _?d0(_):void 0},getAccountIdentity:async(z)=>(await X.read()).accounts.find((U)=>U.id===z)?.accountIdentity,async refreshQuota(z){let U=await X.read();if(U.policyStorage.relay?.enabled===!0&&l0(U.policyStorage.relay.transport,U.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await X.fetchQuota(z,$.fetch,W.signal),fresh:!0}},sendPrime(z){let U=S(z);return P.add(U),U.finally(()=>P.delete(U)),U},async recordSuccess(z){let U=(await X.read()).accounts.find((V)=>V.id===z);if(!U?.prime)throw Error("Native Prime counters are unavailable");return U.prime}});return O.start(),{manager:O,async dispose(){O.stop(),W.abort(),await Promise.allSettled(P)}}}import{logger as J$,NativeCustodyError as l1}from"@cortexkit/anthropic-auth-core";var c0=Symbol.for("cortexkit.anthropic-auth.opencode2.requests.v2");function Y$(){let $=globalThis;return $[c0]??={live:new Map,requests:new WeakMap},$[c0]}function i0($,X,N=H1){let W=Y$(),P={hooks:new Map,version:N,registrations:[]},T=new Map,S=!1,O=!1,z=()=>{if(!S)return P;let V=W.live.get(X),C=V&&[...V].at(-1);if(!C)throw new l1("closed");if(C.version!==P.version||JSON.stringify(C.registrations)!==JSON.stringify(P.registrations)){if(!O)O=!0,J$.debug("opencode2","reload handoff refused: different plugin version or hook registration shape",{version:P.version,successorVersion:C.version});throw new l1("closed")}return C},U=async(V,C,_)=>{let b=P.hooks.get(V)??[],A=b.length;return b.push(C),P.hooks.set(V,b),P.registrations.push([V,A]),$.session.hook(V,async(H)=>{let D;if(V==="http.response")D=W.requests.get(H.request)??P;else if(V==="retry"||V==="experimental.ws.receive"||V==="experimental.ws.send")if(T.has(H.sessionID)){let o=T.get(H.sessionID);if(!o)return;D=o}else D=P;else D=z();if(V==="http.request"||V==="experimental.ws.handshake"){let o=T.get(H.sessionID);T.set(H.sessionID,T.has(H.sessionID)&&o!==D?void 0:D);while(T.size>512){let M=T.keys().next();if(!M.done)T.delete(M.value)}}let f=D.hooks.get(V)?.[A];if(!f)throw new l1("closed");try{await f(H)}finally{if(V==="http.request")W.requests.set(H.request,D)}},_)};return{context:{...$,session:{...$.session,hook:U}},activate(){let V=W.live.get(X)??new Set;V.add(P),W.live.set(X,V)},retire(){S=!0;let V=W.live.get(X);if(V?.delete(P),V?.size===0)W.live.delete(X)}}}import{createNativeUsagePublisher as j$,createNativeVaultNoRouteResponse as G$,decideStickyQuotaFailure as V$,effectiveRelayTransport as Q$,getClaudeCodeIdentityForVerifiedAccount as T1,getMaxSameAccountWait as W$,getQuotaCheckIntervalMs as U$,getRoutingMode as E1,isDumpPersistentlyEnabled as o0,isQuotaBearingHeaderFrame as B$,localMessageThreadCredential as n0,logger as M$,mergeHeaderQuotaForPersistence as K$,NativeVaultQuotaPolicyError as z$,nativeAccountCanServe as s2,nativeAccountPolicy as J1,nativeLocalAccountRefusal as _$,nativeLocalQuotaLineage as N$,nativePollQuotaGenerallyExhausted as H$,normalizeQuotaHeaders as F$,quotaSnapshotCheckedAt as r0,quotaSnapshotHasStandardWindows as L$,readNativeAccountsForRequest as P$,readSessionCachePolicy as O$,remapModelId as V1,reportSessionCacheTouch as T$,requestCacheLifetimeMs as E$,requestSignal as C$,StickyQuotaRetryCounter as S$,StickySessionRouter as x$,sessionCacheActivity as C1,setDumpEnabled as q$,shouldFallbackStatus as k$,stickyQuotaSnapshotIsFresh as Q1,stickyRetainRetryHeaders as b$,stickyRetryAfterWithJitter as R$,stickyRouteFamilyForModel as s0}from"@cortexkit/anthropic-auth-core";var d1=($)=>["five_hour","seven_day"].some((X)=>($?.[X]?.remainingPercent??1)<=0);function A$($,X,N,W,P,T,S){let O=$.rerouteFrom;if($.phase!=="retry"||O?.limit.status!==429||E1(X.policyStorage)!=="sticky-balanced")return;let z=N.find((V)=>V.id===O.accountId);if(!z)return;let U=V$({quota:S||Q1(z.quota,X.policyStorage,Date.now(),W)?z.quota:void 0,modelId:W,responseHeaders:S,sessionId:$.sessionID,unconfirmedRetry:{counter:P,sessionId:$.sessionID,turnId:T,accountId:z.id},holdUntil:C1.holdUntil($.sessionID,z.id,Date.now(),W$(X.policyStorage))});if(U.action==="retain")return{hold:{delayMs:Number(b$(S??new Headers).get("retry-after-ms"))}};if(U.action!=="hold")return;return{hold:{delayMs:Math.min(900000,R$($.sessionID,U.retryAfterSeconds)*1000)}}}function Z4($){let{runtime:X}=$,N=j$("native-auth"),W=$4(async(J)=>{return(await X.read()).accounts.find((Q)=>Q.accountIdentity===J.accountIdentity&&(!J.credentialId||Q.credentialId===J.credentialId))?.quota}),P=new Set,T=new S$,S=new Map,O=new Map,z=(J)=>{let Y=J.routingPath;if(!Y)throw Error("Native routing storage is unavailable");let Q=O.get(Y);if(!Q)Q=new x$({path:Y,vaultSeed:J.routingSeed,onLockEvent:X.onLockEvent,relocationGuard:X.relocationGuard,localRecoveryPath:J.mode==="local"?J.routingRecoveryPath:void 0}),O.set(Y,Q);return Q.setVaultSeed(J.routingSeed),Q},U=new WeakMap,V=new Map,C=new Map,_=new Map,b=new Map,A=new Map,H=new Map,D=new Map,f=new Map,o=new WeakSet,M=!1,I=()=>{while(_.size>512){let J=_.keys().next();if(!J.done)_.delete(J.value)}},x=(J)=>{try{q$(o0(J.policyStorage))}catch{}},m=async()=>{try{let J=await X.read();return x(J),o0(J.policyStorage)}catch{return!1}},s=(J)=>({providerID:J.providerID,sessionID:J.sessionID,kind:J.kind,modelID:J.modelID,agent:J.agent}),h=(J,Y)=>JSON.stringify([J.providerID,J.sessionID,J.kind,J.modelID,J.agent,Y]),Z2=(J)=>{if(M)throw Error("Native Anthropic source is closed");let Y=H.get(J.sessionID);if(!Y){Y=new AbortController,H.set(J.sessionID,Y);while(H.size>512){let E=H.keys().next();if(!E.done)a.forgetSession?.(E.value)}}let Q=C$();return Q?{signal:AbortSignal.any([Y.signal,Q]),abort:Y.abort.bind(Y)}:Y},$2=(J,Y,Q)=>s2(J)&&(J.type==="api"||J1(J,Y,V1(Q)).status==="allowed"),V2=(J,Y)=>J.source===Y.source&&J.accountIdentity===Y.accountIdentity&&J.credentialId===Y.credentialId,H2=(J,Y)=>{D.set(J.sessionID,Y.id);let Q=h(J,Y.id);if(f.delete(Q),f.set(Q,{scope:s(J),account:Y}),f.size>512){let E=f.keys().next().value;if(E!==void 0)f.delete(E)}},M2=async(J,Y,Q,E,y)=>{let q=await X.read();x(q),E.signal.throwIfAborted(),Q2(q);let l=q.accounts.find((c)=>c.id===J);if(!l||l.type!==Q||!$2(l,q,Y))return y?.(!l||!s2(l)?"account-unavailable":"account-policy"),!1;if(Q==="api"){let c=q.accounts.find((t)=>t.id==="main"&&t.type==="oauth");if(!(!!c&&Q1(c.quota,q.policyStorage)&&d1(c.quota)))return!1}return{snapshot:q,account:l}},Q2=(J)=>{let Y=J.policyStorage.relay;if(Y?.enabled===!0&&Q$(Y.transport,Y.url)==="websocket")throw new m2},T2=async(J,Y)=>{if(Q2(J),Y||J.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let Q=await X.getRelayConfig();if(!Q)throw Error("request refused: native HTTP relay configuration is unavailable");if(Q.transport!=="http")throw new m2;return{dispatch:{kind:"http-relay",url:Q.url,token:Q.token},relayFallback:Q.fallbackToDirect}};async function F2(J,Y,Q){if(J.kind==="local"){let E=await X.publishLocal(J.subject,Q,N.signal);if(!E&&Q.quota)M$.warn("quota","Quota publication discarded");return E}if(J.kind==="vault"&&Y.receipt)await X.vault.publish(Y.receipt,Q,N.signal);else if(J.kind==="api"&&Q.lastUsed!==void 0)await X.publishApi(J.subject,{lastUsed:Q.lastUsed},N.signal);return!0}function g2(J,Y,Q){if(J.kind!=="local")return;let E=J.subject.binding,y=r0(Q),q={lineage:N$(E),accountUuid:E.identity,entry:{quota:Q,checkedAt:y,refreshAfter:y},generalExhausted:H$(Q),routeBeforeSave:!0};return X.quotaObservations.hold(Y.account.id,q)?q:void 0}function L2(J,Y){if(Y.exhaustionReported)return;Y.exhaustionReported=!0,W.report(J.sessionID,{accountIdentity:Y.account.accountIdentity,credentialId:J.provenance.kind==="vault"?J.provenance.credentialId:Y.account.credentialId},Y.responseHeaders??new Headers,429,Y.scope.modelID,!1)}let a={async chooseAccount(J){let Y=Z2(J);$.onOwnedRequest?.();let Q=await X.read();x(Q),Y.signal.throwIfAborted(),Q2(Q);let E=V1(await $.resolveModelId?.(J)??J.modelID);if(Y.signal.throwIfAborted(),Q.mode==="claustrum")Q=await P$(X,Y.signal),Y.signal.throwIfAborted();if(Q.policyStorage.quota?.enabled!==!1){let d=!1;for(let e of Q.accounts){if(!s2(e)||e.type!=="oauth")continue;if(L$(e.quota)?Q1(e.quota,Q.policyStorage,Date.now(),E):Date.now()-r0(e.quota)<U$(Q.policyStorage))continue;try{await X.fetchQuota(e.id,$.fetch,Y.signal,void 0,"admission"),d=!0}catch{Y.signal.throwIfAborted()}}if(d)Q=await X.read();Y.signal.throwIfAborted()}if(J.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(J.rerouteFrom.limit.reason))return;if(J.phase==="request")P.delete(J.sessionID);let y=await W.accountFor(J.sessionID,E,Q.accounts.filter((d)=>d.type==="oauth"&&s2(d)&&J1(d,Q,E).status==="allowed"));if(Y.signal.throwIfAborted(),y)Q=await X.read(),Y.signal.throwIfAborted(),Q2(Q);let q=[],l=new Map;for(let d of Q.accounts){if(d.type!=="oauth")continue;let e=J1(d,Q,E);if(l.set(d.id,e),e.status!=="allowed")continue;if(d.source==="local"){let n=await X.authorizeLocal(d.id,{signal:Y.signal,policy:(G,F)=>J1(G,F,E)});if(Y.signal.throwIfAborted(),n.status!=="usable")continue}q.push(d)}if(y){let d=q.find((G)=>t0(y,G)),e=q.map((G,F)=>({accountId:G.id,order:F,quota:G.quota??{kind:"unknown"}})),n=!y.hold||J.phase==="retry"&&J.rerouteFrom?.accountId===d?.id;if(d&&n&&(y.hold||d.id!==J.rerouteFrom?.accountId)&&e0(d.id,e,Q.policyStorage,E)){let G=await z(Q).resolve({sessionId:J.sessionID,family:s0(E),modelId:E,affinityModelId:J.modelID,candidates:e.filter((F)=>F.accountId===d.id),retainAccountIds:new Set([d.id]),...Q.mode==="claustrum"?{accountIdentities:new Map([[d.id,y.account_id]])}:{},storage:Q.policyStorage,inputBytes:1,preserveOnNoCandidate:!0});if(Y.signal.throwIfAborted(),G?.migrated)T.clear(J.sessionID);if(G)return y.hold?{hold:{delayMs:y.hold.retry_after_ms}}:G.accountId}W.override(J.sessionID,!n?"hold requires the same refused retry account":"unknown account, credential, account policy or Fable reserve")}let c=A$(J,Q,q,E,T,S.get(J.sessionID)??J.kind,J.rerouteFrom?b.get(h({...J,modelID:E},J.rerouteFrom.accountId))?.headers:void 0);if(c)return c;let t=q.filter((d)=>d.id!==J.rerouteFrom?.accountId);if(E1(Q.policyStorage)==="sticky-balanced"){let d=t.map((n,G)=>({accountId:n.id,order:G,quota:n.quota??{kind:"unknown"}})),e=await z(Q).resolve({sessionId:J.sessionID,family:s0(E),modelId:E,affinityModelId:J.modelID,candidates:d,retainAccountIds:new Set(t.map((n)=>n.id)),...Q.mode==="claustrum"?{accountIdentities:new Map(Q.accounts.flatMap((n)=>n.accountIdentity?[[n.id,n.accountIdentity]]:[]))}:{},storage:Q.policyStorage,inputBytes:1,preferredAccountId:J.previousAccountId,preserveOnNoCandidate:!0});if(Y.signal.throwIfAborted(),e){if(e.migrated||J.rerouteFrom&&e.accountId!==J.rerouteFrom.accountId)T.clear(J.sessionID);return e.accountId}}else{let e=E1(Q.policyStorage)==="fallback-first"?[...t.filter((n)=>n.id!=="main"),...t.filter((n)=>n.id==="main")]:[...t.filter((n)=>n.id==="main"),...t.filter((n)=>n.id!=="main")];if(e[0])return e[0].id}if(Q.mode==="claustrum")throw await z$.fromResponse(G$({snapshot:Q,sessionId:J.sessionID,modelId:E,policies:l,sticky:E1(Q.policyStorage)==="sticky-balanced"}));let X2=Q.accounts.find((d)=>d.id==="main"&&d.type==="oauth");if(!X2)return;let K2=X2.quota;if(J.rerouteFrom?.limit.status===429||!Q1(K2,Q.policyStorage))try{K2=await X.fetchQuota("main",$.fetch,Y.signal)}catch{return}if(Y.signal.throwIfAborted(),!d1(K2))return;return Q.accounts.find((d)=>d.type==="api"&&s2(d)&&d.id!==J.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(J){if(J.continuation==="interrupted-read"){let X2=f.get(h(J,J.accountId));if(!X2)return;let K2=Z2(J),d=await X.read();K2.signal.throwIfAborted(),Q2(d);let e=V1(await $.resolveModelId?.(J)??J.modelID);K2.signal.throwIfAborted();let n=d.accounts.find((G)=>G.id===J.accountId);return n&&V2(n,X2.account)&&$2(n,d,e)?{accountId:J.accountId}:void 0}let Y=J.limit?.reason,Q=Y?_.get(Y):void 0;if(!Q||h(Q.scope,Q.accountId)!==h(J,J.accountId))return;_.delete(Q.reason);let E=Z2(J),y=await X.read();E.signal.throwIfAborted(),Q2(y);let q=V1(await $.resolveModelId?.(J)??J.modelID);E.signal.throwIfAborted();let l=y.accounts.find((X2)=>X2.id===J.accountId);if(!l||!V2(l,Q.account)||!$2(l,y,q))return;let c=h(J,J.accountId),t=A.get(c)??[];return t.push(Q),A.set(c,t),{accountId:J.accountId}},dropSameAccountRetry(J){if(!J.limit)return;let Y=h(J,J.accountId),Q=A.get(Y),E=Q?.findIndex((y)=>y.reason===J.limit?.reason)??-1;if(E!==-1)Q?.splice(E,1);if(Q?.length===0)A.delete(Y)},async authorizeAccount(J,Y,Q){let E=Z2(J),y=await X.read();x(y),E.signal.throwIfAborted(),Q2(y);let q=V1(await $.resolveModelId?.(J)??J.modelID);E.signal.throwIfAborted();let l=y.accounts.find((B)=>B.id===Y);if(!l||!$2(l,y,q)){Q?.(!l||!s2(l)?"account-unavailable":"account-policy");return}let c=h(J,Y),t=A.get(c),X2=t?.shift();if(t?.length===0)A.delete(c);if(X2&&!V2(l,X2.account))return;let{dispatch:K2,relayFallback:d}=await T2(y,X2?.direct===!0);if(E.signal.throwIfAborted(),X2?.auth){if(!await M2(Y,q,X2.auth.route,E,Q))return;let B=U.get(X2.auth.provenance);if(B?.receipt?.expiresAtMs!==void 0&&B.receipt.expiresAtMs!==null&&B.receipt.expiresAtMs<Date.now()+300000)return;if(B)U.set(X2.auth.provenance,{...B,scope:{...J,modelID:q},account:l,active:E,relayFallback:d});return H2(J,l),{...X2.auth,dispatch:K2}}let e={scope:{...J,modelID:q},active:E,account:l,retry:X2?.retry??!1,relayFallback:d,quota:l.quota};if(l.type==="api"){let B=y.accounts.find((v)=>v.id==="main"&&v.type==="oauth");if(!B||!Q1(B.quota,y.policyStorage)||!d1(B.quota))return;let k=await X.authorizeApi(Y,E.signal);if(E.signal.throwIfAborted(),!await M2(Y,q,"api",E))return;let w={kind:"api",subject:k.subject};return U.set(w,e),H2(J,l),{route:"api",headers:k.authHeader==="authorization-bearer"?{authorization:`Bearer ${k.apiKey}`}:{"x-api-key":k.apiKey},baseURL:k.baseURL,provenance:w,dispatch:K2}}if(l.source==="vault"){let B=await X.authorizeVault(Y,E.signal);if(E.signal.throwIfAborted(),X2&&(B.credentialId!==X2.account.credentialId||B.assertedAccountIdentity!==X2.account.accountIdentity))return;if(!await M2(Y,q,"oauth",E,Q))return;let k={kind:"vault",credentialId:B.credentialId,recordVersion:B.recordVersion};U.set(k,{...e,receipt:B});let w=B.assertedAccountIdentity;if(!w){Q?.("account-unavailable");return}return H2(J,l),{route:"oauth",accessToken:B.accessToken,credentialId:B.credentialId,provenance:k,dispatch:K2,identity:T1(w,w)}}let n=await X.authorizeLocal(Y,{signal:E.signal,policy:(B,k)=>J1(B,k,q)});if(E.signal.throwIfAborted(),n.status!=="usable"){let B=_$(n);if(B)Q?.(B.reason);return}if(!await M2(Y,q,"oauth",E,Q))return;let G={kind:"local",subject:n.subject};U.set(G,{...e,access:n.access}),H2(J,l);let F=n.subject.binding.identity;return{route:"oauth",accessToken:n.access,credentialId:n0(n.subject.binding),provenance:G,dispatch:K2,identity:T1(F,F)}},async requestOptions(J,Y){let Q=Z2(J),E=await X.read();x(E),Q.signal.throwIfAborted();let y=E.accounts.find((t)=>t.id===J.accountId);if(!y||!$2(y,E,J.modelID))throw Y?.(!y||!s2(y)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let q=$.requestOptions(J,E),l=q.billingLineage?.promptId;if(l&&S.get(J.sessionID)!==l)T.clear(J.sessionID),S.set(J.sessionID,l);let c=U.get(J.provenance);if(c)U.set(J.provenance,{...c,scope:{...c.scope,modelID:J.modelID}});return q},async admitRequest(J,Y){let Q=U.get(J.provenance),E=Q&&await M2(J.accountId,J.modelID,J.route,Q.active,Y);if(!Q||!E)throw Error("request refused: native account policy changed before dispatch");U.set(J.provenance,{...Q,snapshot:E.snapshot,account:E.account,scope:{...Q.scope,modelID:J.modelID}})},isDumpEnabled:()=>m(),onRequestPrepared:(J)=>{if(J.route==="oauth"&&J.agent!=="prime"&&J.agent!=="cachekeep"&&!J.signal?.aborted){if(V.set(J.attemptId,{sessionID:J.sessionID,accountId:J.accountId,signal:J.signal,cacheTtlMs:E$(J.bodyText),ttlOverridden:O$(J.sessionID,!0)?.ttl!==void 0,bodyText:J.bodyText,sessionSignal:U.get(J.provenance)?.active.signal}),V.size>4096){let Q=V.keys().next().value;if(Q!==void 0)V.delete(Q)}}let Y=U.get(J.provenance);return $.onRequestPrepared?.({...J,...Y?.snapshot&&{admission:{snapshot:Y.snapshot,account:Y.account}}})},onFinalRequestPrepared(J){let Y=V.get(J.attemptId);if(!Y)return;if(J.requestId){if(C.set(J.requestId,{attemptId:J.attemptId,sessionID:Y.sessionID}),C.size>4096){let Q=C.keys().next().value;if(Q!==void 0)C.delete(Q)}}Y.finalWire={ttlMs:J.ttlMs}},onResponseHandedToHost(J,Y){let Q=J.headers.get("x-client-request-id");if(!Q)return;let E=C.get(Q);if(!E)return;let{attemptId:y}=E;C.delete(Q);let q=V.get(y);if(!q)return;if(q.handedOff=!0,q.accepted=Boolean(Y&&q.finalWire&&!q.signal?.aborted&&!q.sessionSignal?.aborted),$.onCacheResponse?.({attemptId:y,acceptedUsage:q.usage,...q.accepted&&Y&&{acceptedAt:Y.at},ttlMs:q.finalWire?.ttlMs===0&&!q.ttlOverridden?void 0:q.finalWire?.ttlMs}),q.accepted&&Y&&q.finalWire){if(C1.record(q.sessionID,q.accountId,q.finalWire.ttlMs===0&&!q.ttlOverridden?void 0:q.finalWire.ttlMs,Y.at),q.usage)$.onCacheUsage?.(q.sessionID,q.bodyText,q.usage);T$(q.sessionID,{at:Y.at,ttlMs:q.finalWire.ttlMs,source:"response"})}if(q.ended)V.delete(y)},responseOptions(J){let Y=V.get(J.attemptId),Q=U.get(J.provenance)?.active.signal;if(Y&&Q)Y.sessionSignal=Q;let E=$.responseOptions?.({...J,modelID:U.get(J.provenance)?.scope.modelID??J.modelID}),y=(q)=>{if(!Y||Y.signal?.aborted||Y.sessionSignal?.aborted||!q||typeof q!=="object")return;let l=q.usage;if(!l||typeof l!=="object"||Array.isArray(l))return;if(Y.usage={...Y.usage,...l},Y.accepted)$.onCacheUsage?.(Y.sessionID,Y.bodyText,Y.usage)};return{...E,onMessageStart:(q)=>{E?.onMessageStart?.(q),y(q)},onMessageResponse:(q)=>{E?.onMessageResponse?.(q),y(q)},onMessageDelta:(q)=>{E?.onMessageDelta?.(q),y(q)}}},quotaFromHeaders(J,Y){$.onResponseHeaders?.(Y);let Q=U.get(Y.provenance),E=V.get(Y.attemptId);if(Q){if(Y.route==="oauth"&&Y.status>=200&&Y.status<300&&!Q.active.signal.aborted&&E?.sessionID===Y.sessionID&&E.accountId===Y.accountId&&!E.signal?.aborted)C1.record(Y.sessionID,Y.accountId,(E.finalWire?.ttlMs??E.cacheTtlMs)===0&&!E.ttlOverridden?void 0:E.finalWire?.ttlMs??E.cacheTtlMs);let d=h({...Y,modelID:Q.scope.modelID},Y.accountId);if(Y.status===429){if(b.delete(d),b.set(d,{sessionID:Y.sessionID,headers:J}),b.size>512){let n=b.keys().next().value;if(n!==void 0)b.delete(n)}}else b.delete(d);Q.responseHeaders=J;let e=Y.status<400&&!P.has(Y.sessionID);if(e)P.add(Y.sessionID);if(Y.status===429)L2(Y,Q);else W.report(Y.sessionID,{accountIdentity:Q.account.accountIdentity,credentialId:Y.provenance.kind==="vault"?Y.provenance.credentialId:Q.account.credentialId},J,Y.status,Q.scope.modelID,e)}let y=a0(J);if(y)$.onRequestId?.(Y,y);if(!Q||Y.route!=="oauth"||!B$(J))return;let q=Y.provenance.kind==="local"?Y.provenance.subject.binding.identity:Q.receipt?.assertedAccountIdentity,l={...F$(J),...q?{accountIdentity:q}:{}},c=K$(Q.quota,l);Q.quota=c;let t=g2(Y.provenance,Q,c),X2=Q.account.id,K2=()=>{if(t)X.quotaObservations.forget(X2,t)};return N.observe(F2(Y.provenance,Q,{quota:c}).then((d)=>{if(!d)K2()},(d)=>{throw K2(),d})),l},async limitFromResponse(J){let Y=U.get(J.provenance);if(!Y)return;if(J.status===401&&Y.receipt){if(!o.has(Y.receipt))o.add(Y.receipt),await X.vault.reportFailure(Y.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(Y.retry||Y.active.signal.aborted)return;let E=Y.active,y=await X.vault.prepareRetry(Y.receipt,E.signal);if(E.signal.throwIfAborted(),!y.retry)return;let q=y.receipt,l=q.assertedAccountIdentity;if(!l)return;let c={kind:"vault",credentialId:q.credentialId,recordVersion:q.recordVersion};U.set(c,{...Y,receipt:q,retry:!0});let t=`vault-newer:${J.attemptId}`;return _.set(t,{scope:s(J),reason:t,accountId:J.accountId,account:Y.account,retry:!0,auth:{route:"oauth",accessToken:q.accessToken,credentialId:q.credentialId,provenance:c,identity:T1(l,l)}}),I(),{reason:t,status:401}}if(J.status===401&&J.provenance.kind==="local"&&Y.access&&!Y.retry){if(Y.active.signal.aborted)return;let E=Y.active,y=await X.authorizeLocal(J.accountId,{rejectedAccessToken:Y.access,signal:E.signal,policy:(t,X2)=>J1(t,X2,Y.scope.modelID)});if(E.signal.throwIfAborted(),y.status!=="usable"||y.access===Y.access)return;let q={kind:"local",subject:y.subject};U.set(q,{...Y,access:y.access,retry:!0});let l=y.subject.binding.identity,c=`local-newer:${J.attemptId}`;return _.set(c,{scope:s(J),reason:c,accountId:J.accountId,account:Y.account,retry:!0,auth:{route:"oauth",accessToken:y.access,credentialId:n0(y.subject.binding),provenance:q,identity:T1(l,l)}}),I(),{reason:c,status:401}}let Q=await X.read();if(k$(J.status,Q.policyStorage))return{reason:`provider-${J.status}`,status:J.status};return},limitFromRelayFailure(J){let Y=U.get(J.provenance);if(!Y?.relayFallback||Y.active.signal.aborted||!(J.status===401||J.status>=500))return;let Q=`relay-direct:${J.attemptId}`;return _.set(Q,{scope:s(J),reason:Q,accountId:J.accountId,account:Y.account,direct:!0,retry:!1}),I(),{reason:Q}},limitFromStreamError(J){let Y=U.get(J.provenance);if(Y&&J.errorType==="rate_limit_error")L2(J,Y);return J.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(J,Y){let Q=U.get(Y.provenance);if(Y.dispatch==="http-relay"&&Q?.relayFallback&&!Q.active.signal.aborted&&J.status===void 0){let E=`relay-direct:${Y.attemptId}`;return _.set(E,{scope:s(Y),reason:E,accountId:Y.accountId,account:Q.account,direct:!0,retry:!1}),I(),{reason:E}}return},async onAttemptEnd(J,Y){let Q=V.get(J.attemptId);if(Q)Q.ended=!0;if(Q?.handedOff||Y.status===void 0)V.delete(J.attemptId);await $.onAttemptEnd?.(J,Y);let E=U.get(J.provenance);if(!E)return;try{if(Y.status===401&&E.receipt&&!o.has(E.receipt))o.add(E.receipt),await X.vault.reportFailure(E.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(!Y.localRefusal&&Y.status!==void 0)N.publish(()=>F2(J.provenance,E,{lastUsed:Date.now()}))}finally{U.delete(J.provenance)}},forgetTurn(J){T.clear(J),S.delete(J)},forgetSession(J){for(let[Y,Q]of C)if(Q.sessionID===J)C.delete(Y);a.forgetTurn?.(J);for(let[Y,Q]of V)if(Q.sessionID===J)V.delete(Y);C1.forget(J);for(let[Y,Q]of b)if(Q.sessionID===J)b.delete(Y);P.delete(J),H.get(J)?.abort(),H.delete(J),D.delete(J);for(let[Y,Q]of f)if(Q.scope.sessionID===J)f.delete(Y);for(let[Y,Q]of _)if(Q.scope.sessionID===J)_.delete(Y);for(let[Y,Q]of A)if(Q[0]?.scope.sessionID===J)A.delete(Y);$.onForgetSession?.(J)},servedAccount:(J)=>D.get(J),resetRouting:async(J)=>{a.forgetTurn?.(J),await z(await X.read()).clear(J)},async recordPrime(J,Y){let Q=U.get(J);if(!Q||Q.active.signal.aborted)return!1;if(J.kind==="local")return X.incrementPrimeUsage(Q.account.id,J.subject,Y);if(J.kind==="vault"&&Q.receipt)return X.incrementPrimeUsage(Q.account.id,Q.receipt,Y);return!1},drainRoutingPublications:()=>Promise.all([X.drainRoutingPublications(),...[...O.values()].map((J)=>J.drain())]).then(()=>{}),close(){C.clear(),V.clear(),M=!0;for(let J of H.values())J.abort();return H.clear(),f.clear(),A.clear(),_.clear(),Promise.all([N.close(),a.drainRoutingPublications()]).then(()=>{})}};return a}import{remapModelId as w$}from"@cortexkit/anthropic-auth-core";function Y4(){let $=new X4,X=new Map,N=new Map,W=new Map,P=new Set,T=new Set,S=new Map,O=(z)=>{while(z.size>512){let U=z.keys().next();if(!U.done)z.delete(U.value)}};return{async install(z){let U=[];try{U.push(await z.session.hook("context",(V)=>{let C=V.messages.map((b)=>{return{info:{id:b.id,sessionID:V.sessionID,role:b.role,agent:V.agent,model:{providerID:V.model.providerID,modelID:V.model.id}},parts:b.content.map((A)=>({type:A.type,...A.type==="text"?{text:A.text}:{}}))}});$.observeMessages(C);let _=V.messages.findLast((b)=>b.role==="user"&&b.id);if(_?.id)X.set(V.sessionID,_.id);if(_?.content.some((b)=>b.type==="text"&&b.text===L1))P.add(V.sessionID);else P.delete(V.sessionID);O(X)},{providerID:"anthropic"})),U.push(await z.session.hook("model.request",(V)=>{if(V.kind!=="primary")return;let C=X.get(V.sessionID);if(!C)return;if($.markHeaders({sessionId:V.sessionID,messageId:C,agent:V.agent,headers:V.headers}),P.has(V.sessionID))V.headers[p2]="1"},{providerID:"anthropic"}))}catch(V){throw await Promise.allSettled(U.map((C)=>C.dispose())),V}return{dispose:async()=>{await Promise.all(U.map((V)=>V.dispose()))}}},requestOptions(z,U){let V=$.resolveHeader(z.correlation[_1]);if(V)N.set(z.attemptId,V),O(N);S.set(z.attemptId,z.sessionID),O(S);let C=z.correlation[p2]==="1";if(C)T.add(z.attemptId);return{cache1hEnabled:z.agent!=="compaction"&&z.agent!=="title"&&(U.policyStorage.claudeCache?.enabled??!0),cache1hMode:U.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:U.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:U.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:U.policyStorage.turnEndNote,serverSideFallbackEnabled:J4(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:C,billingLineage:V?{promptId:V.promptId,previousRequestId:V.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:W.get(z.sessionID)}},responseOptions(z){return{serverSideFallbackModel:w$(z.modelID),laneStart:T.has(z.attemptId),onMessageStart(U){if(z.kind==="primary"&&typeof U.id==="string")W.set(z.sessionID,U.id),O(W)},onStreamEnd(){N.delete(z.attemptId),T.delete(z.attemptId),S.delete(z.attemptId)}}},onRequestId(z,U){$.commit(N.get(z.attemptId),U)},forgetSession(z){$.clearSession(z),X.delete(z),W.delete(z),P.delete(z);for(let[U,V]of S)if(V===z)N.delete(U),T.delete(U),S.delete(U)}}}var x1="cortexkit-anthropic-auth",$8='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',j4="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",Z8="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function X8($){let X=$.authorize??y$,N=$.exchange??m$,W=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},P=async()=>{let O;try{O=await $.readMode()}catch{throw Error(Z8)}return W(),O},T=async()=>{if(await P()!=="local")throw Error($8)};return{integrationID:"anthropic",methods:[{method:{id:P1,type:"oauth",label:O1},async authorize(){W(),await T();let O=await X("max");return W(),{mode:"code",url:O.url,instructions:"Paste the authorization code returned by Claude.",callback:async(z)=>{W();let U=await N(z,O.verifier,O.redirectUri,O.state);if(!$.isActive()||U.type!=="success")throw Error("Claude sign-in did not complete");return{access:U.access,refresh:U.refresh,expires:U.expires}}}}}],vault:{method:{id:G4,type:"oauth",label:"Claude vault accounts"},async activate(){if(W(),await P()!=="claustrum")throw Error(j4);if(u$()){if($.verifyVault)await $.verifyVault();else try{let O=f$("anthropic-auth");await Promise.resolve(O.close()).catch(()=>{return})}catch{throw new p$("unavailable")}if(W(),await P()!=="claustrum")throw Error(j4)}}},async onLogin(O){W(),await T(),await $.runtime.loginOAuth({routeId:"main",credential:O,replace:!0}),W()},label:"Claude native account pool"}}function J8($){return{readMode:()=>o$("opencode",$),disconnectVault:()=>h$({host:"opencode",env:$})}}function u1($={}){return{id:x1,setup:(X)=>Q4(X,$)}}async function Y8($){try{return await G8($)}catch(X){throw j8(X)}}function j8($){let X=N1($);if(X)return X;let N=t$("decide where its account state is",[],$);return S1.error("state-layout",N.message,{code:N.code}),N1(N)??N}async function G8($){if($.paths){let N=$.paths;return await I$(N),{paths:N,holderRegistration:await n$({paths:N,role:"opencode2",kind:i$(),policy:e$(),onLockEvent:$.local?.onLockEvent})}}let X=await g$({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await r$(void 0,void 0,X.layout),holderRegistration:X.kind==="state-home"?void 0:X.registration}}async function Q4($,X={}){let{paths:N,holderRegistration:W}=await Y8(X),P=i0($,c$({...X.vault,paths:N,host:"opencode"}));$=P.context;let T=D$({paths:N,host:"opencode",local:X.local,vault:X.vault}),S=J8(X.vault?.env??process.env);try{let x=await T.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)a$(l$(x.policyStorage)??"info");s$(d$(x.policyStorage))}catch{}let O=!0,z=Y4(),U=g0(),V,C,_,b=new Map,A=(x)=>{let m=b.get(x);if(m)return m.value;let s={};if(b.set(x,s),b.size>4096){let h=b.keys().next().value;if(h!==void 0)b.delete(h)}Promise.resolve().then(()=>$.session.get({sessionID:x})).then((h)=>{if(!O||b.get(x)!==s)return;return s.value=Boolean(h.parentID),_?.resolvedParent(x,s.value)}).catch(()=>{if(b.get(x)===s)b.delete(x)});return},H=Z4({runtime:T,paths:N,fetch:X.fetch,requestOptions:(x,m)=>{if(x.agent!=="cachekeep"&&x.agent!=="prime")A(x.sessionID);return z.requestOptions(x,m)},responseOptions:z.responseOptions,onRequestId:z.onRequestId,onForgetSession:(x)=>{b.delete(x),z.forgetSession(x),_?.forgetSession(x)},onRequestPrepared:async(x)=>{try{await _?.track(x)}catch{S1.warn("cachekeep","live request tracking failed")}},onCacheResponse:(x)=>{try{_?.onResponseHeaders({...x,status:x.acceptedAt===void 0?0:200})}catch{S1.warn("cachekeep","live request tracking failed")}},onAttemptEnd:(x,m)=>{if(m.status===void 0)_?.discardAttempt(x.attemptId)},onCacheUsage:(x,m,s)=>_?.recordAcceptedUsage(x,m,s),resolveModelId:async(x)=>U.modelId(x.modelID),onOwnedRequest:()=>{V??=x0(T,X.fetch),C??=p0({runtime:T,paths:N,source:H,fetch:X.fetch})}});_=E0({...X.cacheKeep,runtime:T,source:H,storageId:N.storageId,fetch:X.fetch,subagent:A}),await _.ready;let D=y0({runtime:T,source:H,cacheKeepRegistry:_.registry,start:async(x,m)=>{await $.session.synthetic({sessionID:x,text:m,description:"Claude lane start",resume:!0})}}),f=[],o=await C0($,{source:H,now:X.cacheKeep?.now,log:{warn:(x,m)=>S1.warn("opencode2",x,m)}},{credential:h0}).catch(async(x)=>{throw W?.close(),D.close(),await _?.dispose(),await Promise.all([H.close(),T.drainQuotaPublications()]),await T.close(),x}),M,I=()=>{if(M)return M;return O=!1,b.clear(),P.retire(),W?.close(),D.close(),H.close(),M=(async()=>{await Promise.allSettled([o.dispose(),V?.dispose(),C?.dispose(),_?.dispose(),...f.map((x)=>x.dispose())]),await o.drain(),await Promise.all([H.close(),T.drainQuotaPublications()]),await T.close()})(),M};try{f.push(await z.install($)),f.push(await U.installProviderModels($)),f.push(await U.install($)),f.push(await b1($,X8({isActive:()=>O,readMode:S.readMode,verifyVault:()=>T.vault.refresh(),runtime:T})));let x={host:"opencode",dispatch:D.dispatch,readStatus:(s)=>D.readStatus(s),readAccounts:()=>T.read(),readMode:S.readMode,disconnectVault:S.disconnectVault,interactive:!0},m=v$(x);return f.push(await V4($,m,D)),P.activate(),I}catch(x){throw await I(),x}}var u5={id:x1,setup:u1().setup,server:W4};export{Q4 as setupAnthropicAuth,u5 as default,u1 as createAnthropicAuthPlugin,x1 as ANTHROPIC_AUTH_PLUGIN_ID};
|
|
13
|
+
${y0}
|
|
14
|
+
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:w}if(W==="quota")return D8({accounts:j.accounts.filter((L)=>L.type==="oauth").map((L)=>({name:L.label??L.id,role:L.id==="main"?"main":"fallback",enabled:L.enabled,quota:L.quota,tierLabel:m8(L.profile),lastRefreshedAt:L.lastRefreshedAt,error:L.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(W==="prime")return f8({enabled:j.policyStorage.prime?.enabled===!0,accounts:I8(j.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(W==="cachekeep"){let L=await $.cacheKeepRegistry?.list()??[];return w8({enabled:c8(j.policyStorage),always:d8(j.policyStorage),hybridActive:p8(j.policyStorage),trackedSessionDetails:L,window:l8(j.policyStorage),trackedSessions:L.length,nextPrewarmAt:L.length?Math.min(...L.map((k)=>k.nextPrewarmAt)):void 0})}let E={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(j.settings[E[W]]??{})},async readSidebar(W){let[j,E]=await Promise.all([J.read(),$.cacheKeepRegistry?.list()??[]]);return L1(f0(j,{activeId:N.servedAccount(W),trackedSessions:E.length,now:Date.now()}))},forgetSession(W){U.get(W)?.active.abort(),U.delete(W)},close(){P=!0;for(let W of U.values())W.active.abort();U.clear()}}}import{CLAUDE_MODEL_CAPABILITIES as Z$,resolveClaudeModelCapabilities as X$}from"@cortexkit/anthropic-auth-core";function l0($=[]){return $.map((J)=>({id:J,settings:{effort:J,thinking:{type:"adaptive",display:"summarized"}}}))}function m0($){return{input:$.input,output:$.output,cache:{read:$.cacheRead,write:$.cacheWrite5m}}}function J$(){return Z$.flatMap(($)=>{let J=$.catalogue;if(!J)return[];return[{id:$.id,modelID:$.id,providerID:"anthropic",type:"chat",family:`claude-${$.family}`,name:$.name,capabilities:{tools:!0,input:["text","image","pdf"],output:["text"],temperature:!1},variants:l0($.efforts.variants),time:{released:Date.parse(J.releaseDate)},cost:[m0(J.pricing),...J.longContext?[{...m0(J.longContext.pricing),tier:{type:"context",size:J.longContext.inputTokensAbove}}]:[]],status:"active",enabled:!0,limit:{context:J.contextWindow,output:J.maxOutputTokens}}]})}function u0(){let $=new Map;return{install:(U)=>U.model.transform((P)=>{$.clear();for(let T of P.list("anthropic")){$.set(String(T.id),String(T.modelID));let S=X$(T.modelID)?.efforts.variants;if(!S)continue;P.update("anthropic",String(T.id),(O)=>{let H=O.variants.filter((W)=>!S.some((j)=>j===String(W.id)));O.variants=[...H,...l0(S)]})}}),installProviderModels:(U)=>U.provider.transform((P)=>{let T=P.get("anthropic");if(!T)return;let S=J$().filter((O)=>!T.models.has(String(O.id)));if(!S.length)return;P.models.set("anthropic",[...T.models.values(),...S])}),modelId:(U)=>$.get(U)??U}}function d0($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as p0,effectiveRelayTransport as c0,nativeAccountCanServe as Y$,PrimeManager as j$,tokenFingerprint as i0}from"@cortexkit/anthropic-auth-core";var o0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function n0($){let{runtime:J,source:N}=$,U=new AbortController,P=new Set,T=(H)=>({providerID:"anthropic",modelID:p0().model,sessionID:`oc2-prime:${H}`,agent:"prime",kind:"generate"}),S=async(H)=>{let W=T(H),j=Z1({source:N}),E=performance.now();try{for(let L=0;L<3;L++){if(U.signal.throwIfAborted(),(await J.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let w=await j.adapter.accountHeaders({...W,accountId:H});if(!("headers"in w)||typeof w.headers!=="object"||w.headers===null||typeof w.attempt!=="object"||w.attempt===null)throw Error("Native Prime authorization refused");let _={...W,accountId:H,attemptId:crypto.randomUUID(),transport:"http",data:w.attempt},A,f=!1,$2=!1,B=(D)=>{$2=!0,D.body?.cancel().catch(()=>{})};try{let D=await j.adapter.rewriteRequest?.({...W,accountId:H,attempt:_,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(p0()),signal:U.signal})});if(!D)throw Error("Native Prime rewrite refused");let R=new Headers(D.headers);for(let[z2,B2]of Object.entries(w.headers))if(B2===null)R.delete(z2);else R.set(z2,B2);let d=new Request(D,{headers:R}),t=await($.fetch??fetch)(d),c=await j.adapter.rewriteResponse?.({...W,accountId:H,request:d,response:t,attempt:_})??t;A=c.status,j.adapter.quotaFromHeaders?.(c.headers,c.status,_);let o=c.ok?void 0:await j.adapter.limitFromResponse?.({status:c.status,headers:c.headers,body:()=>c.clone().text(),attempt:_});if(o&&/^(vault-newer|local-newer|relay-direct):/.test(o.reason)&&L<2){if(B(c),(await N.retrySameAccount?.({...W,accountId:H,attempt:L+1,limit:o,error:{type:"api_error",message:"Native Prime credential retry",status:c.status}}))?.accountId!==H)throw Error("Native Prime retry changed account");continue}if(!c.ok)return B(c),{ok:!1,status:A,ms:performance.now()-E,error:"Native Prime upstream refused the request"};let Y2=o0(await c.json()),U2=o0(Y2.usage),M2={inputTokens:typeof U2.input_tokens==="number"?U2.input_tokens:void 0,outputTokens:typeof U2.output_tokens==="number"?U2.output_tokens:void 0};if(_.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(c.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(f=await N.recordPrime(w.attempt.provenance,M2),!f)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:A,ms:performance.now()-E,usage:M2}}finally{await j.adapter.onAttemptEnd?.(_,{status:A,outputStarted:!1,...f?{}:{error:{reason:$2?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-E}}finally{j.dispose()}},O=new j$({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await J.read()).policyStorage,async getAccountFingerprint(H){let W=await J.read(),j=W.accounts.find((k)=>k.id===H);if(!Y$(j)||j?.type!=="oauth")return;if(W.policyStorage.relay?.enabled===!0&&c0(W.policyStorage.relay.transport,W.policyStorage.relay.url)==="websocket")return;if(j.source==="vault"){let k=await J.authorizeVault(H,U.signal),w=await J.getOrCreateAuthLineage(H,k);return w?i0(w):void 0}let E=await J.authorizeLocal(H,{signal:U.signal});if(E.status!=="usable")return;let L=await J.getOrCreateAuthLineage(H,E.subject);return L?i0(L):void 0},getAccountIdentity:async(H)=>(await J.read()).accounts.find((W)=>W.id===H)?.accountIdentity,async refreshQuota(H){let W=await J.read();if(W.policyStorage.relay?.enabled===!0&&c0(W.policyStorage.relay.transport,W.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await J.fetchQuota(H,$.fetch,U.signal),fresh:!0}},sendPrime(H){let W=S(H);return P.add(W),W.finally(()=>P.delete(W)),W},async recordSuccess(H){let W=(await J.read()).accounts.find((j)=>j.id===H);if(!W?.prime)throw Error("Native Prime counters are unavailable");return W.prime}});return O.start(),{manager:O,async dispose(){O.stop(),U.abort(),await Promise.allSettled(P)}}}import{logger as G$,NativeCustodyError as l1}from"@cortexkit/anthropic-auth-core";var r0=Symbol.for("cortexkit.anthropic-auth.opencode2.requests.v2");function V$(){let $=globalThis;return $[r0]??={live:new Map,requests:new WeakMap},$[r0]}function s0($,J,N=H1){let U=V$(),P={hooks:new Map,version:N,registrations:[]},T=new Map,S=!1,O=!1,H=()=>{if(!S)return P;let j=U.live.get(J),E=j&&[...j].at(-1);if(!E)throw new l1("closed");if(E.version!==P.version||JSON.stringify(E.registrations)!==JSON.stringify(P.registrations)){if(!O)O=!0,G$.debug("opencode2","reload handoff refused: different plugin version or hook registration shape",{version:P.version,successorVersion:E.version});throw new l1("closed")}return E},W=async(j,E,L)=>{let k=P.hooks.get(j)??[],w=k.length;return k.push(E),P.hooks.set(j,k),P.registrations.push([j,w]),$.session.hook(j,async(_)=>{let A;if(j==="http.response")A=U.requests.get(_.request)??P;else if(j==="retry"||j==="experimental.ws.receive"||j==="experimental.ws.send")if(T.has(_.sessionID)){let $2=T.get(_.sessionID);if(!$2)return;A=$2}else A=P;else A=H();if(j==="http.request"||j==="experimental.ws.handshake"){let $2=T.get(_.sessionID);T.set(_.sessionID,T.has(_.sessionID)&&$2!==A?void 0:A);while(T.size>512){let B=T.keys().next();if(!B.done)T.delete(B.value)}}let f=A.hooks.get(j)?.[w];if(!f)throw new l1("closed");try{await f(_)}finally{if(j==="http.request")U.requests.set(_.request,A)}},L)};return{context:{...$,session:{...$.session,hook:W}},activate(){let j=U.live.get(J)??new Set;j.add(P),U.live.set(J,j)},retire(){S=!0;let j=U.live.get(J);if(j?.delete(P),j?.size===0)U.live.delete(J)}}}import{createNativeUsagePublisher as Q$,createNativeVaultNoRouteResponse as W$,decideStickyQuotaFailure as U$,effectiveRelayTransport as B$,getClaudeCodeIdentityForVerifiedAccount as E1,getMaxSameAccountWait as z$,getQuotaCheckIntervalMs as K$,getRoutingMode as C1,isDumpPersistentlyEnabled as a0,isQuotaBearingHeaderFrame as M$,localMessageThreadCredential as u1,logger as _$,mergeHeaderQuotaForPersistence as N$,NativeVaultQuotaPolicyError as H$,nativeAccountCanServe as s2,nativeAccountPolicy as Y1,nativeLocalAccountRefusal as F$,nativeLocalQuotaLineage as L$,nativePollQuotaGenerallyExhausted as P$,normalizeQuotaHeaders as O$,peekRoutingAccount as T$,quotaSnapshotCheckedAt as t0,quotaSnapshotHasStandardWindows as E$,readNativeAccountsForRequest as C$,readSessionCachePolicy as x$,remapModelId as j1,reportSessionCacheTouch as q$,requestCacheLifetimeMs as S$,requestSignal as k$,StickyQuotaRetryCounter as R$,StickySessionRouter as b$,sessionCacheActivity as x1,setDumpEnabled as A$,shouldFallbackStatus as w$,stickyQuotaSnapshotIsFresh as W1,stickyRetainRetryHeaders as D$,stickyRetryAfterWithJitter as I$,stickyRouteFamilyForModel as e0}from"@cortexkit/anthropic-auth-core";var d1=($)=>["five_hour","seven_day"].some((J)=>($?.[J]?.remainingPercent??1)<=0);function f$($,J,N,U,P,T,S){let O=$.rerouteFrom;if($.phase!=="retry"||O?.limit.status!==429||C1(J.policyStorage)!=="sticky-balanced")return;let H=N.find((j)=>j.id===O.accountId);if(!H)return;let W=U$({quota:S||W1(H.quota,J.policyStorage,Date.now(),U)?H.quota:void 0,modelId:U,responseHeaders:S,sessionId:$.sessionID,unconfirmedRetry:{counter:P,sessionId:$.sessionID,turnId:T,accountId:H.id},holdUntil:x1.holdUntil($.sessionID,H.id,Date.now(),z$(J.policyStorage))});if(W.action==="retain")return{hold:{delayMs:Number(D$(S??new Headers).get("retry-after-ms"))}};if(W.action!=="hold")return;return{hold:{delayMs:Math.min(900000,I$($.sessionID,W.retryAfterSeconds)*1000)}}}function Y4($){let{runtime:J}=$,N=Q$("native-auth"),U=J4(async(X)=>{return(await J.read()).accounts.find((Q)=>Q.accountIdentity===X.accountIdentity&&(!X.credentialId||Q.credentialId===X.credentialId))?.quota}),P=new Set,T=new R$,S=new Map,O=new Map,H=(X)=>{let Y=X.routingPath;if(!Y)throw Error("Native routing storage is unavailable");let Q=O.get(Y);if(!Q)Q=new b$({path:Y,vaultSeed:X.routingSeed,onLockEvent:J.onLockEvent,relocationGuard:J.relocationGuard,localRecoveryPath:X.mode==="local"?X.routingRecoveryPath:void 0}),O.set(Y,Q);return Q.setVaultSeed(X.routingSeed),Q},W=new WeakMap,j=new Map,E=new Map,L=new Map,k=new Map,w=new Map,_=new Map,A=new Map,f=new Map,$2=new WeakSet,B=!1,D=()=>{while(L.size>512){let X=L.keys().next();if(!X.done)L.delete(X.value)}},R=(X)=>{try{A$(a0(X.policyStorage))}catch{}},d=async()=>{try{let X=await J.read();return R(X),a0(X.policyStorage)}catch{return!1}},t=(X)=>({providerID:X.providerID,sessionID:X.sessionID,kind:X.kind,modelID:X.modelID,agent:X.agent}),c=(X,Y)=>JSON.stringify([X.providerID,X.sessionID,X.kind,X.modelID,X.agent,Y]),o=(X)=>{if(B)throw Error("Native Anthropic source is closed");let Y=_.get(X.sessionID);if(!Y){Y=new AbortController,_.set(X.sessionID,Y);while(_.size>512){let C=_.keys().next();if(!C.done)s.forgetSession?.(C.value)}}let Q=k$();return Q?{signal:AbortSignal.any([Y.signal,Q]),abort:Y.abort.bind(Y)}:Y},Y2=(X,Y,Q)=>s2(X)&&(X.type==="api"||Y1(X,Y,j1(Q)).status==="allowed"),U2=(X,Y)=>X.source===Y.source&&X.accountIdentity===Y.accountIdentity&&X.credentialId===Y.credentialId,M2=(X,Y)=>{A.set(X.sessionID,Y.id);let Q=c(X,Y.id);if(f.delete(Q),f.set(Q,{scope:t(X),account:Y}),f.size>512){let C=f.keys().next().value;if(C!==void 0)f.delete(C)}},z2=async(X,Y,Q,C,v)=>{let x=await J.read();R(x),C.signal.throwIfAborted(),B2(x);let u=x.accounts.find((r)=>r.id===X);if(!u||u.type!==Q||!Y2(u,x,Y))return v?.(!u||!s2(u)?"account-unavailable":"account-policy"),!1;if(Q==="api"){let r=x.accounts.find((J2)=>J2.id==="main"&&J2.type==="oauth");if(!(!!r&&W1(r.quota,x.policyStorage)&&d1(r.quota)))return!1}return{snapshot:x,account:u}},B2=(X)=>{let Y=X.policyStorage.relay;if(Y?.enabled===!0&&B$(Y.transport,Y.url)==="websocket")throw new m2},F2=async(X,Y)=>{if(B2(X),Y||X.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let Q=await J.getRelayConfig();if(!Q)throw Error("request refused: native HTTP relay configuration is unavailable");if(Q.transport!=="http")throw new m2;return{dispatch:{kind:"http-relay",url:Q.url,token:Q.token},relayFallback:Q.fallbackToDirect}};async function T2(X,Y,Q){if(X.kind==="local"){let C=await J.publishLocal(X.subject,Q,N.signal);if(!C&&Q.quota)_$.warn("quota","Quota publication discarded");return C}if(X.kind==="vault"&&Y.receipt)await J.vault.publish(Y.receipt,Q,N.signal);else if(X.kind==="api"&&Q.lastUsed!==void 0)await J.publishApi(X.subject,{lastUsed:Q.lastUsed},N.signal);return!0}function D2(X,Y,Q){if(X.kind!=="local")return;let C=X.subject.binding,v=t0(Q),x={lineage:L$(C),accountUuid:C.identity,entry:{quota:Q,checkedAt:v,refreshAfter:v},generalExhausted:P$(Q),routeBeforeSave:!0};return J.quotaObservations.hold(Y.account.id,x)?x:void 0}function E2(X,Y){if(Y.exhaustionReported)return;Y.exhaustionReported=!0,U.report(X.sessionID,{accountIdentity:Y.account.accountIdentity,credentialId:X.provenance.kind==="vault"?X.provenance.credentialId:Y.account.credentialId},Y.responseHeaders??new Headers,429,Y.scope.modelID,!1)}let s={billingRequest(X){if(X.agent==="prime")return;let Y=W.get(X.provenance);if(!Y)return;let Q=X.provenance;return{sessionId:X.sessionID,credentialId:Q.kind==="vault"?Q.credentialId:Q.kind==="local"?u1(Q.subject.binding):Q.subject.credentialFingerprint,accountId:Y.account.accountIdentity,model:Y.scope.modelID,requestKind:X.agent==="cachekeep"?"keep_warm":X.kind,chargeBasis:X.route==="api"?"metered_api":"subscription_included"}},async chooseAccount(X){let Y=o(X);$.onOwnedRequest?.();let Q=await J.read();R(Q),Y.signal.throwIfAborted(),B2(Q);let C=j1(await $.resolveModelId?.(X)??X.modelID);if(Y.signal.throwIfAborted(),Q.mode==="claustrum")Q=await C$(J,Y.signal),Y.signal.throwIfAborted();if(Q.policyStorage.quota?.enabled!==!1){let g=!1;for(let e of Q.accounts){if(!s2(e)||e.type!=="oauth")continue;if(E$(e.quota)?W1(e.quota,Q.policyStorage,Date.now(),C):Date.now()-t0(e.quota)<K$(Q.policyStorage))continue;try{await J.fetchQuota(e.id,$.fetch,Y.signal,void 0,"admission"),g=!0}catch{Y.signal.throwIfAborted()}}if(g)Q=await J.read();Y.signal.throwIfAborted()}if(X.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(X.rerouteFrom.limit.reason))return;if(X.phase==="request")P.delete(X.sessionID);let v=await U.accountFor(X.sessionID,C,Q.accounts.filter((g)=>g.type==="oauth"&&s2(g)&&Y1(g,Q,C).status==="allowed"));if(Y.signal.throwIfAborted(),v)Q=await J.read(),Y.signal.throwIfAborted(),B2(Q);let x=[],u=new Map;for(let g of Q.accounts){if(g.type!=="oauth")continue;let e=Y1(g,Q,C);if(u.set(g.id,e),e.status!=="allowed")continue;if(g.source==="local"){let n=await J.authorizeLocal(g.id,{signal:Y.signal,policy:(V2,V)=>Y1(V2,V,C)});if(Y.signal.throwIfAborted(),n.status!=="usable")continue}x.push(g)}if(v){let g=x.find((V2)=>Z4(v,V2)),e=x.map((V2,V)=>({accountId:V2.id,order:V,quota:V2.quota??{kind:"unknown"}})),n=!v.hold||X.phase==="retry"&&X.rerouteFrom?.accountId===g?.id;if(g&&n&&(v.hold||g.id!==X.rerouteFrom?.accountId)&&X4(g.id,e,Q.policyStorage,C)){let V2=await H(Q).resolve({sessionId:X.sessionID,family:e0(C),modelId:C,affinityModelId:X.modelID,candidates:e.filter((V)=>V.accountId===g.id),retainAccountIds:new Set([g.id]),...Q.mode==="claustrum"?{accountIdentities:new Map([[g.id,v.account_id]])}:{},storage:Q.policyStorage,inputBytes:1,preserveOnNoCandidate:!0});if(Y.signal.throwIfAborted(),V2?.migrated)T.clear(X.sessionID);if(V2)return v.hold?{hold:{delayMs:v.hold.retry_after_ms}}:V2.accountId}U.override(X.sessionID,!n?"hold requires the same refused retry account":"unknown account, credential, account policy or Fable reserve")}let r=f$(X,Q,x,C,T,S.get(X.sessionID)??X.kind,X.rerouteFrom?k.get(c({...X,modelID:C},X.rerouteFrom.accountId))?.headers:void 0);if(r)return r;let J2=x.filter((g)=>g.id!==X.rerouteFrom?.accountId);if(C1(Q.policyStorage)==="sticky-balanced"){let g=J2.map((n,V2)=>({accountId:n.id,order:V2,quota:n.quota??{kind:"unknown"}})),e=await H(Q).resolve({sessionId:X.sessionID,family:e0(C),modelId:C,affinityModelId:X.modelID,candidates:g,retainAccountIds:new Set(J2.map((n)=>n.id)),...Q.mode==="claustrum"?{accountIdentities:new Map(Q.accounts.flatMap((n)=>n.accountIdentity?[[n.id,n.accountIdentity]]:[]))}:{},storage:Q.policyStorage,inputBytes:1,preferredAccountId:X.previousAccountId,preserveOnNoCandidate:!0});if(Y.signal.throwIfAborted(),e){if(e.migrated||X.rerouteFrom&&e.accountId!==X.rerouteFrom.accountId)T.clear(X.sessionID);return e.accountId}}else{let e=C1(Q.policyStorage)==="fallback-first"?[...J2.filter((n)=>n.id!=="main"),...J2.filter((n)=>n.id==="main")]:[...J2.filter((n)=>n.id==="main"),...J2.filter((n)=>n.id!=="main")];if(e[0])return e[0].id}if(Q.mode==="claustrum")throw await H$.fromResponse(W$({snapshot:Q,sessionId:X.sessionID,modelId:C,policies:u,sticky:C1(Q.policyStorage)==="sticky-balanced"}));let Z2=Q.accounts.find((g)=>g.id==="main"&&g.type==="oauth");if(!Z2)return;let L2=Z2.quota;if(X.rerouteFrom?.limit.status===429||!W1(L2,Q.policyStorage))try{L2=await J.fetchQuota("main",$.fetch,Y.signal)}catch{return}if(Y.signal.throwIfAborted(),!d1(L2))return;return Q.accounts.find((g)=>g.type==="api"&&s2(g)&&g.id!==X.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(X){if(X.continuation==="interrupted-read"){let Z2=f.get(c(X,X.accountId));if(!Z2)return;let L2=o(X),g=await J.read();L2.signal.throwIfAborted(),B2(g);let e=j1(await $.resolveModelId?.(X)??X.modelID);L2.signal.throwIfAborted();let n=g.accounts.find((V2)=>V2.id===X.accountId);return n&&U2(n,Z2.account)&&Y2(n,g,e)?{accountId:X.accountId}:void 0}let Y=X.limit?.reason,Q=Y?L.get(Y):void 0;if(!Q||c(Q.scope,Q.accountId)!==c(X,X.accountId))return;L.delete(Q.reason);let C=o(X),v=await J.read();C.signal.throwIfAborted(),B2(v);let x=j1(await $.resolveModelId?.(X)??X.modelID);C.signal.throwIfAborted();let u=v.accounts.find((Z2)=>Z2.id===X.accountId);if(!u||!U2(u,Q.account)||!Y2(u,v,x))return;let r=c(X,X.accountId),J2=w.get(r)??[];return J2.push(Q),w.set(r,J2),{accountId:X.accountId}},dropSameAccountRetry(X){if(!X.limit)return;let Y=c(X,X.accountId),Q=w.get(Y),C=Q?.findIndex((v)=>v.reason===X.limit?.reason)??-1;if(C!==-1)Q?.splice(C,1);if(Q?.length===0)w.delete(Y)},async authorizeAccount(X,Y,Q){let C=o(X),v=await J.read();R(v),C.signal.throwIfAborted(),B2(v);let x=j1(await $.resolveModelId?.(X)??X.modelID);C.signal.throwIfAborted();let u=v.accounts.find((M)=>M.id===Y);if(!u||!Y2(u,v,x)){Q?.(!u||!s2(u)?"account-unavailable":"account-policy");return}let r=c(X,Y),J2=w.get(r),Z2=J2?.shift();if(J2?.length===0)w.delete(r);if(Z2&&!U2(u,Z2.account))return;let{dispatch:L2,relayFallback:g}=await F2(v,Z2?.direct===!0);if(C.signal.throwIfAborted(),Z2?.auth){if(!await z2(Y,x,Z2.auth.route,C,Q))return;let M=W.get(Z2.auth.provenance);if(M?.receipt?.expiresAtMs!==void 0&&M.receipt.expiresAtMs!==null&&M.receipt.expiresAtMs<Date.now()+300000)return;if(M)W.set(Z2.auth.provenance,{...M,scope:{...X,modelID:x},account:u,active:C,relayFallback:g});return M2(X,u),{...Z2.auth,dispatch:L2}}let e={scope:{...X,modelID:x},active:C,account:u,retry:Z2?.retry??!1,relayFallback:g,quota:u.quota};if(u.type==="api"){let M=v.accounts.find((p)=>p.id==="main"&&p.type==="oauth");if(!M||!W1(M.quota,v.policyStorage)||!d1(M.quota))return;let z=await J.authorizeApi(Y,C.signal);if(C.signal.throwIfAborted(),!await z2(Y,x,"api",C))return;let I={kind:"api",subject:z.subject};return W.set(I,e),M2(X,u),{route:"api",headers:z.authHeader==="authorization-bearer"?{authorization:`Bearer ${z.apiKey}`}:{"x-api-key":z.apiKey},baseURL:z.baseURL,provenance:I,dispatch:L2}}if(u.source==="vault"){let M=await J.authorizeVault(Y,C.signal);if(C.signal.throwIfAborted(),Z2&&(M.credentialId!==Z2.account.credentialId||M.assertedAccountIdentity!==Z2.account.accountIdentity))return;if(!await z2(Y,x,"oauth",C,Q))return;let z={kind:"vault",credentialId:M.credentialId,recordVersion:M.recordVersion};W.set(z,{...e,receipt:M});let I=M.assertedAccountIdentity;if(!I){Q?.("account-unavailable");return}return M2(X,u),{route:"oauth",accessToken:M.accessToken,credentialId:M.credentialId,provenance:z,dispatch:L2,identity:E1(I,I)}}let n=await J.authorizeLocal(Y,{signal:C.signal,policy:(M,z)=>Y1(M,z,x)});if(C.signal.throwIfAborted(),n.status!=="usable"){let M=F$(n);if(M)Q?.(M.reason);return}if(!await z2(Y,x,"oauth",C,Q))return;let V2={kind:"local",subject:n.subject};W.set(V2,{...e,access:n.access}),M2(X,u);let V=n.subject.binding.identity;return{route:"oauth",accessToken:n.access,credentialId:u1(n.subject.binding),provenance:V2,dispatch:L2,identity:E1(V,V)}},async requestOptions(X,Y){let Q=o(X),C=await J.read();R(C),Q.signal.throwIfAborted();let v=C.accounts.find((J2)=>J2.id===X.accountId);if(!v||!Y2(v,C,X.modelID))throw Y?.(!v||!s2(v)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let x=$.requestOptions(X,C),u=x.billingLineage?.promptId;if(u&&S.get(X.sessionID)!==u)T.clear(X.sessionID),S.set(X.sessionID,u);let r=W.get(X.provenance);if(r)W.set(X.provenance,{...r,scope:{...r.scope,modelID:X.modelID}});return x},async admitRequest(X,Y){let Q=W.get(X.provenance),C=Q&&await z2(X.accountId,X.modelID,X.route,Q.active,Y);if(!Q||!C)throw Error("request refused: native account policy changed before dispatch");W.set(X.provenance,{...Q,snapshot:C.snapshot,account:C.account,scope:{...Q.scope,modelID:X.modelID}})},isDumpEnabled:()=>d(),onRequestPrepared:(X)=>{if(X.route==="oauth"&&X.agent!=="prime"&&X.agent!=="cachekeep"&&!X.signal?.aborted){if(j.set(X.attemptId,{sessionID:X.sessionID,accountId:X.accountId,signal:X.signal,cacheTtlMs:S$(X.bodyText),ttlOverridden:x$(X.sessionID,!0)?.ttl!==void 0,bodyText:X.bodyText,sessionSignal:W.get(X.provenance)?.active.signal}),j.size>4096){let Q=j.keys().next().value;if(Q!==void 0)j.delete(Q)}}let Y=W.get(X.provenance);return $.onRequestPrepared?.({...X,...Y?.snapshot&&{admission:{snapshot:Y.snapshot,account:Y.account}}})},onFinalRequestPrepared(X){let Y=j.get(X.attemptId);if(!Y)return;if(X.requestId){if(E.set(X.requestId,{attemptId:X.attemptId,sessionID:Y.sessionID}),E.size>4096){let Q=E.keys().next().value;if(Q!==void 0)E.delete(Q)}}Y.finalWire={ttlMs:X.ttlMs}},onResponseHandedToHost(X,Y){let Q=X.headers.get("x-client-request-id");if(!Q)return;let C=E.get(Q);if(!C)return;let{attemptId:v}=C;E.delete(Q);let x=j.get(v);if(!x)return;if(x.handedOff=!0,x.accepted=Boolean(Y&&x.finalWire&&!x.signal?.aborted&&!x.sessionSignal?.aborted),$.onCacheResponse?.({attemptId:v,acceptedUsage:x.usage,...x.accepted&&Y&&{acceptedAt:Y.at},ttlMs:x.finalWire?.ttlMs===0&&!x.ttlOverridden?void 0:x.finalWire?.ttlMs}),x.accepted&&Y&&x.finalWire){if(x1.record(x.sessionID,x.accountId,x.finalWire.ttlMs===0&&!x.ttlOverridden?void 0:x.finalWire.ttlMs,Y.at),x.usage)$.onCacheUsage?.(x.sessionID,x.bodyText,x.usage);q$(x.sessionID,{at:Y.at,ttlMs:x.finalWire.ttlMs,source:"response"})}if(x.ended)j.delete(v)},responseOptions(X){let Y=j.get(X.attemptId),Q=W.get(X.provenance)?.active.signal;if(Y&&Q)Y.sessionSignal=Q;let C=$.responseOptions?.({...X,modelID:W.get(X.provenance)?.scope.modelID??X.modelID}),v=(x)=>{if(!Y||Y.signal?.aborted||Y.sessionSignal?.aborted||!x||typeof x!=="object")return;let u=x.usage;if(!u||typeof u!=="object"||Array.isArray(u))return;if(Y.usage={...Y.usage,...u},Y.accepted)$.onCacheUsage?.(Y.sessionID,Y.bodyText,Y.usage)};return{...C,onMessageStart:(x)=>{C?.onMessageStart?.(x),v(x)},onMessageResponse:(x)=>{C?.onMessageResponse?.(x),v(x)},onMessageDelta:(x)=>{C?.onMessageDelta?.(x),v(x)}}},quotaFromHeaders(X,Y){$.onResponseHeaders?.(Y);let Q=W.get(Y.provenance),C=j.get(Y.attemptId);if(Q){if(Y.route==="oauth"&&Y.status>=200&&Y.status<300&&!Q.active.signal.aborted&&C?.sessionID===Y.sessionID&&C.accountId===Y.accountId&&!C.signal?.aborted)x1.record(Y.sessionID,Y.accountId,(C.finalWire?.ttlMs??C.cacheTtlMs)===0&&!C.ttlOverridden?void 0:C.finalWire?.ttlMs??C.cacheTtlMs);let g=c({...Y,modelID:Q.scope.modelID},Y.accountId);if(Y.status===429){if(k.delete(g),k.set(g,{sessionID:Y.sessionID,headers:X}),k.size>512){let n=k.keys().next().value;if(n!==void 0)k.delete(n)}}else k.delete(g);Q.responseHeaders=X;let e=Y.status<400&&!P.has(Y.sessionID);if(e)P.add(Y.sessionID);if(Y.status===429)E2(Y,Q);else U.report(Y.sessionID,{accountIdentity:Q.account.accountIdentity,credentialId:Y.provenance.kind==="vault"?Y.provenance.credentialId:Q.account.credentialId},X,Y.status,Q.scope.modelID,e)}let v=$4(X);if(v)$.onRequestId?.(Y,v);if(!Q||Y.route!=="oauth"||!M$(X))return;let x=Y.provenance.kind==="local"?Y.provenance.subject.binding.identity:Q.receipt?.assertedAccountIdentity,u={...O$(X),...x?{accountIdentity:x}:{}},r=N$(Q.quota,u);Q.quota=r;let J2=D2(Y.provenance,Q,r),Z2=Q.account.id,L2=()=>{if(J2)J.quotaObservations.forget(Z2,J2)};return N.observe(T2(Y.provenance,Q,{quota:r}).then((g)=>{if(!g)L2()},(g)=>{throw L2(),g})),u},async limitFromResponse(X){let Y=W.get(X.provenance);if(!Y)return;if(X.status===401&&Y.receipt){if(!$2.has(Y.receipt))$2.add(Y.receipt),await J.vault.reportFailure(Y.receipt,401,X.dispatch==="http-relay"?"relay_status_field":"direct");if(Y.retry||Y.active.signal.aborted)return;let C=Y.active,v=await J.vault.prepareRetry(Y.receipt,C.signal);if(C.signal.throwIfAborted(),!v.retry)return;let x=v.receipt,u=x.assertedAccountIdentity;if(!u)return;let r={kind:"vault",credentialId:x.credentialId,recordVersion:x.recordVersion};W.set(r,{...Y,receipt:x,retry:!0});let J2=`vault-newer:${X.attemptId}`;return L.set(J2,{scope:t(X),reason:J2,accountId:X.accountId,account:Y.account,retry:!0,auth:{route:"oauth",accessToken:x.accessToken,credentialId:x.credentialId,provenance:r,identity:E1(u,u)}}),D(),{reason:J2,status:401}}if(X.status===401&&X.provenance.kind==="local"&&Y.access&&!Y.retry){if(Y.active.signal.aborted)return;let C=Y.active,v=await J.authorizeLocal(X.accountId,{rejectedAccessToken:Y.access,signal:C.signal,policy:(J2,Z2)=>Y1(J2,Z2,Y.scope.modelID)});if(C.signal.throwIfAborted(),v.status!=="usable"||v.access===Y.access)return;let x={kind:"local",subject:v.subject};W.set(x,{...Y,access:v.access,retry:!0});let u=v.subject.binding.identity,r=`local-newer:${X.attemptId}`;return L.set(r,{scope:t(X),reason:r,accountId:X.accountId,account:Y.account,retry:!0,auth:{route:"oauth",accessToken:v.access,credentialId:u1(v.subject.binding),provenance:x,identity:E1(u,u)}}),D(),{reason:r,status:401}}let Q=await J.read();if(w$(X.status,Q.policyStorage))return{reason:`provider-${X.status}`,status:X.status};return},limitFromRelayFailure(X){let Y=W.get(X.provenance);if(!Y?.relayFallback||Y.active.signal.aborted||!(X.status===401||X.status>=500))return;let Q=`relay-direct:${X.attemptId}`;return L.set(Q,{scope:t(X),reason:Q,accountId:X.accountId,account:Y.account,direct:!0,retry:!1}),D(),{reason:Q}},limitFromStreamError(X){let Y=W.get(X.provenance);if(Y&&X.errorType==="rate_limit_error")E2(X,Y);return X.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(X,Y){let Q=W.get(Y.provenance);if(Y.dispatch==="http-relay"&&Q?.relayFallback&&!Q.active.signal.aborted&&X.status===void 0){let C=`relay-direct:${Y.attemptId}`;return L.set(C,{scope:t(Y),reason:C,accountId:Y.accountId,account:Q.account,direct:!0,retry:!1}),D(),{reason:C}}return},async onAttemptEnd(X,Y){let Q=j.get(X.attemptId);if(Q)Q.ended=!0;if(Q?.handedOff||Y.status===void 0)j.delete(X.attemptId);await $.onAttemptEnd?.(X,Y);let C=W.get(X.provenance);if(!C)return;try{if(Y.status===401&&C.receipt&&!$2.has(C.receipt))$2.add(C.receipt),await J.vault.reportFailure(C.receipt,401,X.dispatch==="http-relay"?"relay_status_field":"direct");if(!Y.localRefusal&&Y.status!==void 0)N.publish(()=>T2(X.provenance,C,{lastUsed:Date.now()}))}finally{W.delete(X.provenance)}},forgetTurn(X){T.clear(X),S.delete(X)},forgetSession(X){for(let[Y,Q]of E)if(Q.sessionID===X)E.delete(Y);s.forgetTurn?.(X);for(let[Y,Q]of j)if(Q.sessionID===X)j.delete(Y);x1.forget(X);for(let[Y,Q]of k)if(Q.sessionID===X)k.delete(Y);P.delete(X),_.get(X)?.abort(),_.delete(X),A.delete(X);for(let[Y,Q]of f)if(Q.scope.sessionID===X)f.delete(Y);for(let[Y,Q]of L)if(Q.scope.sessionID===X)L.delete(Y);for(let[Y,Q]of w)if(Q[0]?.scope.sessionID===X)w.delete(Y);$.onForgetSession?.(X)},peekAccount:(X,Y,Q)=>T$({snapshot:Q,router:Q.routingPath?O.get(Q.routingPath):void 0,sessionId:X,modelId:Y?j1(Y):void 0}),servedAccount:(X)=>A.get(X),resetRouting:async(X)=>{s.forgetTurn?.(X),await H(await J.read()).clear(X)},async recordPrime(X,Y){let Q=W.get(X);if(!Q||Q.active.signal.aborted)return!1;if(X.kind==="local")return J.incrementPrimeUsage(Q.account.id,X.subject,Y);if(X.kind==="vault"&&Q.receipt)return J.incrementPrimeUsage(Q.account.id,Q.receipt,Y);return!1},drainRoutingPublications:()=>Promise.all([J.drainRoutingPublications(),...[...O.values()].map((X)=>X.drain())]).then(()=>{}),close(){E.clear(),j.clear(),B=!0;for(let X of _.values())X.abort();return _.clear(),f.clear(),w.clear(),L.clear(),Promise.all([N.close(),s.drainRoutingPublications()]).then(()=>{})}};return s}import{remapModelId as y$}from"@cortexkit/anthropic-auth-core";function V4(){let $=new j4,J=new Map,N=new Map,U=new Map,P=new Set,T=new Set,S=new Map,O=(H)=>{while(H.size>512){let W=H.keys().next();if(!W.done)H.delete(W.value)}};return{async install(H){let W=[];try{W.push(await H.session.hook("context",(j)=>{let E=j.messages.map((k)=>{return{info:{id:k.id,sessionID:j.sessionID,role:k.role,agent:j.agent,model:{providerID:j.model.providerID,modelID:j.model.id}},parts:k.content.map((w)=>({type:w.type,...w.type==="text"?{text:w.text}:{}}))}});$.observeMessages(E);let L=j.messages.findLast((k)=>k.role==="user"&&k.id);if(L?.id)J.set(j.sessionID,L.id);if(L?.content.some((k)=>k.type==="text"&&k.text===P1))P.add(j.sessionID);else P.delete(j.sessionID);O(J)},{providerID:"anthropic"})),W.push(await H.session.hook("model.request",(j)=>{if(j.kind!=="primary")return;let E=J.get(j.sessionID);if(!E)return;if($.markHeaders({sessionId:j.sessionID,messageId:E,agent:j.agent,headers:j.headers}),P.has(j.sessionID))j.headers[p2]="1"},{providerID:"anthropic"}))}catch(j){throw await Promise.allSettled(W.map((E)=>E.dispose())),j}return{dispose:async()=>{await Promise.all(W.map((j)=>j.dispose()))}}},requestOptions(H,W){let j=$.resolveHeader(H.correlation[_1]);if(j)N.set(H.attemptId,j),O(N);S.set(H.attemptId,H.sessionID),O(S);let E=H.correlation[p2]==="1";if(E)T.add(H.attemptId);return{cache1hEnabled:H.agent!=="compaction"&&H.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:G4(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:E,billingLineage:j?{promptId:j.promptId,previousRequestId:j.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:U.get(H.sessionID)}},responseOptions(H){return{serverSideFallbackModel:y$(H.modelID),laneStart:T.has(H.attemptId),onMessageStart(W){if(H.kind==="primary"&&typeof W.id==="string")U.set(H.sessionID,W.id),O(U)},onStreamEnd(){N.delete(H.attemptId),T.delete(H.attemptId),S.delete(H.attemptId)}}},onRequestId(H,W){$.commit(N.get(H.attemptId),W)},forgetSession(H){$.clearSession(H),J.delete(H),U.delete(H),P.delete(H);for(let[W,j]of S)if(j===H)N.delete(W),T.delete(W),S.delete(W)}}}var S1="cortexkit-anthropic-auth",Y9='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',Q4="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",j9="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function G9($){let J=$.authorize??h$,N=$.exchange??p$,U=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},P=async()=>{let O;try{O=await $.readMode()}catch{throw Error(j9)}return U(),O},T=async()=>{if(await P()!=="local")throw Error(Y9)};return{integrationID:"anthropic",methods:[{method:{id:O1,type:"oauth",label:T1},async authorize(){U(),await T();let O=await J("max");return U(),{mode:"code",url:O.url,instructions:"Paste the authorization code returned by Claude.",callback:async(H)=>{U();let W=await N(H,O.verifier,O.redirectUri,O.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:W4,type:"oauth",label:"Claude vault accounts"},async activate(){if(U(),await P()!=="claustrum")throw Error(Q4);if(o$()){if($.verifyVault)await $.verifyVault();else try{let O=m$("anthropic-auth");await Promise.resolve(O.close()).catch(()=>{return})}catch{throw new n$("unavailable")}if(U(),await P()!=="claustrum")throw Error(Q4)}}},async onLogin(O){U(),await T(),await $.runtime.loginOAuth({routeId:"main",credential:O,replace:!0}),U()},label:"Claude native account pool"}}function V9($){return{readMode:()=>a$("opencode",$),disconnectVault:()=>d$({host:"opencode",env:$})}}function p1($={}){return{id:S1,setup:(J)=>B4(J,$)}}async function Q9($){try{return await U9($)}catch(J){throw W9(J)}}function W9($){let J=N1($);if(J)return J;let N=X9("decide where its account state is",[],$);return q1.error("state-layout",N.message,{code:N.code}),N1(N)??N}async function U9($){if($.paths){let N=$.paths;return await g$(N),{paths:N,holderRegistration:await t$({paths:N,role:"opencode2",kind:s$(),policy:J9(),onLockEvent:$.local?.onLockEvent})}}let J=await u$({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await e$(void 0,void 0,J.layout),holderRegistration:J.kind==="state-home"?void 0:J.registration}}async function B4($,J={}){let{paths:N,holderRegistration:U}=await Q9(J),P=s0($,r$({...J.vault,paths:N,host:"opencode"}));$=P.context;let T=v$({paths:N,host:"opencode",local:J.local,vault:J.vault}),S=V9(J.vault?.env??process.env);try{let R=await T.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)Z9(c$(R.policyStorage)??"info");$9(i$(R.policyStorage))}catch{}let O=!0,H=V4(),W=u0(),j,E,L,k=new Map,w=(R)=>{let d=k.get(R);if(d)return d.value;let t={};if(k.set(R,t),k.size>4096){let c=k.keys().next().value;if(c!==void 0)k.delete(c)}Promise.resolve().then(()=>$.session.get({sessionID:R})).then((c)=>{if(!O||k.get(R)!==t)return;return t.value=Boolean(c.parentID),L?.resolvedParent(R,t.value)}).catch(()=>{if(k.get(R)===t)k.delete(R)});return},_=Y4({runtime:T,paths:N,fetch:J.fetch,requestOptions:(R,d)=>{if(R.agent!=="cachekeep"&&R.agent!=="prime")w(R.sessionID);return H.requestOptions(R,d)},responseOptions:H.responseOptions,onRequestId:H.onRequestId,onForgetSession:(R)=>{k.delete(R),H.forgetSession(R),L?.forgetSession(R)},onRequestPrepared:async(R)=>{try{await L?.track(R)}catch{q1.warn("cachekeep","live request tracking failed")}},onCacheResponse:(R)=>{try{L?.onResponseHeaders({...R,status:R.acceptedAt===void 0?0:200})}catch{q1.warn("cachekeep","live request tracking failed")}},onAttemptEnd:(R,d)=>{if(d.status===void 0)L?.discardAttempt(R.attemptId)},onCacheUsage:(R,d,t)=>L?.recordAcceptedUsage(R,d,t),resolveModelId:async(R)=>W.modelId(R.modelID),onOwnedRequest:()=>{j??=b0(T,J.fetch),E??=n0({runtime:T,paths:N,source:_,fetch:J.fetch})}});L=S0({...J.cacheKeep,runtime:T,source:_,storageId:N.storageId,fetch:J.fetch,subagent:w}),await L.ready;let A=h0({runtime:T,source:_,cacheKeepRegistry:L.registry,start:async(R,d)=>{await $.session.synthetic({sessionID:R,text:d,description:"Claude lane start",resume:!0})}}),f=[],$2=await k0($,{source:_,now:J.cacheKeep?.now,log:{warn:(R,d)=>q1.warn("opencode2",R,d)}},{credential:d0}).catch(async(R)=>{throw U?.close(),A.close(),await L?.dispose(),await Promise.all([_.close(),T.drainQuotaPublications()]),await T.close(),R}),B,D=()=>{if(B)return B;return O=!1,k.clear(),P.retire(),U?.close(),A.close(),_.close(),B=(async()=>{await Promise.allSettled([$2.dispose(),j?.dispose(),E?.dispose(),L?.dispose(),...f.map((R)=>R.dispose())]),await $2.drain(),await Promise.all([_.close(),T.drainQuotaPublications()]),await T.close()})(),B};try{f.push(await H.install($)),f.push(await W.installProviderModels($)),f.push(await W.install($)),f.push(await b1($,G9({isActive:()=>O,readMode:S.readMode,verifyVault:()=>T.vault.refresh(),runtime:T})));let R={host:"opencode",dispatch:A.dispatch,readStatus:(t)=>A.readStatus(t),readAccounts:()=>T.read(),readMode:S.readMode,disconnectVault:S.disconnectVault,interactive:!0},d=l$(R);return f.push(await U4($,d,A)),P.activate(),D}catch(R){throw await D(),R}}var o5={id:S1,setup:p1().setup,server:z4};export{B4 as setupAnthropicAuth,o5 as default,p1 as createAnthropicAuthPlugin,S1 as ANTHROPIC_AUTH_PLUGIN_ID};
|