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