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