@cortexkit/opencode-anthropic-auth 2.14.0 → 2.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type NativeCustodyActivationHooks, type NativeCustodyInventory } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { type NativeVaultEnrollmentOptions } from './native-enrollment.ts';
|
|
3
3
|
import { type NativeSetupPaths } from './native-paths.ts';
|
|
4
|
-
import { type CommandRunner, type HarnessKind, type ProcessFence } from './types.ts';
|
|
4
|
+
import { type CommandRunner, type HarnessKind, type ProcessFence, type SharedSetupRunnerEntry } from './types.ts';
|
|
5
5
|
type HostIndependentActivationCode = 'auth-content-refused' | 'host-auth-invalid' | 'primary-conflict' | 'consent-required' | 'primary-unverified';
|
|
6
6
|
/** Activation codes whose remedy names the host, so the host is required. */
|
|
7
7
|
type HostActivationCode = 'no-read-grant' | 'grant-reaches-nothing';
|
|
@@ -12,7 +12,7 @@ export declare class NativeVaultActivationError extends Error {
|
|
|
12
12
|
constructor(code: HostIndependentActivationCode);
|
|
13
13
|
constructor(code: HostActivationCode, host: HarnessKind, approvedName?: string);
|
|
14
14
|
}
|
|
15
|
-
export interface NativeVaultActivationOptions {
|
|
15
|
+
export interface NativeVaultActivationOptions extends SharedSetupRunnerEntry {
|
|
16
16
|
env: NodeJS.ProcessEnv;
|
|
17
17
|
runner: CommandRunner;
|
|
18
18
|
fence: ProcessFence;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ClaustrumEnrollmentClient, type ClaustrumEnrollmentPaths } from '@cortexkit/common-auth/claustrum';
|
|
2
|
-
import type { CommandRunner, HarnessKind } from './types.ts';
|
|
2
|
+
import type { CommandRunner, HarnessKind, SharedSetupRunnerEntry } from './types.ts';
|
|
3
3
|
export declare const NATIVE_VAULT_HOST_NAMES: {
|
|
4
4
|
readonly opencode: "anthropic-auth-opencode";
|
|
5
5
|
readonly pi: "anthropic-auth-pi";
|
|
@@ -48,4 +48,4 @@ export declare function enrollNativeVaultForHost(host: HarnessKind, options: Nat
|
|
|
48
48
|
*/
|
|
49
49
|
export declare function nativeVaultGrantArgs(host: HarnessKind, approvedName?: string): string[];
|
|
50
50
|
/** Grant this host read access only when enrollment could not propose permissions. */
|
|
51
|
-
export declare function grantNativeVaultForHost(host: HarnessKind, options: Pick<NativeVaultEnrollmentOptions, 'env' | 'runner' | 'processFence' | 'ckBinary' | 'paths'>): Promise<string | undefined>;
|
|
51
|
+
export declare function grantNativeVaultForHost(host: HarnessKind, options: Pick<NativeVaultEnrollmentOptions, 'env' | 'runner' | 'processFence' | 'ckBinary' | 'paths'> & SharedSetupRunnerEntry): Promise<string | undefined>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type NativeMigrationPreflight, readNativeMigrationJournal } from '@cortexkit/anthropic-auth-core';
|
|
2
2
|
import { type NativeSetupPaths } from './native-paths';
|
|
3
|
-
import { type HarnessKind, type ProcessFence } from './types';
|
|
3
|
+
import { type HarnessKind, type ProcessFence, type SharedSetupRunnerEntry } from './types';
|
|
4
4
|
export interface NativeOfflineLogin {
|
|
5
5
|
credential: {
|
|
6
6
|
type: 'oauth';
|
|
@@ -10,7 +10,7 @@ export interface NativeOfflineLogin {
|
|
|
10
10
|
};
|
|
11
11
|
accountIdentity: string;
|
|
12
12
|
}
|
|
13
|
-
export interface NativeLocalSetupOptions {
|
|
13
|
+
export interface NativeLocalSetupOptions extends SharedSetupRunnerEntry {
|
|
14
14
|
env: NodeJS.ProcessEnv;
|
|
15
15
|
fence: ProcessFence;
|
|
16
16
|
paths?: NativeSetupPaths;
|
|
@@ -24,6 +24,8 @@ export interface NativeLocalSetupOptions {
|
|
|
24
24
|
export declare const SEPARATE_HOST_LOGIN_NOTICE = "OpenCode's separate Anthropic login is not used. Add that account through /claude Accounts if needed, or remove the separate login from OpenCode.";
|
|
25
25
|
export declare function requireNativeLocalEnrollment(hosts: readonly HarnessKind[], env: NodeJS.ProcessEnv): Promise<void>;
|
|
26
26
|
export declare function nativeLocalProcessFence(host: HarnessKind, options: NativeLocalSetupOptions): () => Promise<void>;
|
|
27
|
+
/** Read-only planning still refuses environment-provided host auth and vault enrollment. */
|
|
28
|
+
export declare function validateNativeLocalSetup(host: HarnessKind, options: NativeLocalSetupOptions): Promise<void>;
|
|
27
29
|
export declare function nativeSetupFileFingerprint(path: string): Promise<string>;
|
|
28
30
|
export declare function inspectSetupHostAuth(host: HarnessKind, path: string): Promise<{
|
|
29
31
|
kind: 'absent' | 'oauth' | 'api' | 'api_key' | 'activation';
|
package/dist/setup/types.d.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
export type HarnessKind = 'opencode' | 'pi';
|
|
2
|
+
export interface SharedSetupRunnerEntry {
|
|
3
|
+
/**
|
|
4
|
+
* Only the setup CLI sets this: the shared runner listed processes immediately
|
|
5
|
+
* before calling the adapter. Standalone callers must keep the entry check.
|
|
6
|
+
*/
|
|
7
|
+
sharedRunnerCheckedEntry?: true;
|
|
8
|
+
}
|
|
2
9
|
export declare function setupRefusalMessage(error: unknown): string | undefined;
|
|
3
10
|
/** runSetup prints failures from its own stopped-host checks; provider callbacks need a displayable refusal for their separate process checks. */
|
|
4
11
|
export declare function setupProcessInspectionMessage(error: unknown): string | undefined;
|
package/dist/v2/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import{a as N1,b as X4,c as W4,d as W0,e as M0,f as L1,g as o2,h as f1,i as y1,j as j4,k as Y4,l as V4,m as G4,n as B0,o as M4,p as U0,q as z0,r as K0,s as N0,t as g1,u as _4}from"../index-e91y2kqv.js";import"../index-6q2f3m0v.js";import"../index-77sph3hf.js";import{z as K4}from"../index-2debh0ym.js";import{A as C1,B as O1,D as z4}from"../index-gqxrgdvk.js";import"../index-427t44z7.js";import{N as P1}from"../index-0btjtgy5.js";import"../index-27dah13x.js";import"../index-dpxaxyck.js";import{acquireNativeAccountRuntime as M9,assertUnmanagedInjectedPaths as B9,authorize as U9,connectVaultHost as z9,createNativeAccountRuntime as K9,createNativeUi as N9,decideOpenCodeStateLayoutOnce as _9,disconnectNativeVaultForHost as H9,exchange as F9,getPersistedLogLevel as P9,getSettingsFilePath as L9,isDumpPersistentlyEnabled as C9,isVaultHosted as O9,legacySettingsProtection as T9,logger as V1,NativeCustodyError as E9,nativeVaultRuntimeKey as x9,openCodeHolderKind as k9,readNativeEnrollmentMode as q9,readPeerLegacySettingsProtection as S9,registerNativePoolHolder as A9,resolveNativePoolPaths as R9,resolveSettingsPaths as b9,setDumpEnabled as D9,setLogLevel as w9,startSettings as I9,stateLayoutIoFailure as v9,stateLayoutOfPaths as f9,unmovedRegistrationPolicy as y9}from"@cortexkit/anthropic-auth-core";class t2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function m2($){return`common-auth-placeholder.${$}`}function i1($){let J=m2($.integrationID);return{type:"oauth",methodID:$.methodID,access:J,refresh:J,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function A1($,J){if($?.type!=="oauth")return!1;let K=J===void 0?void 0:m2(J),Q=(O)=>K===void 0?O.startsWith("common-auth-placeholder."):O===K;return Q($.access)&&Q($.refresh)}var o1="No browser sign-in: this connects the plugin to the accounts in its vault.";async function R1($,J){let K=J.now??Date.now,{integrationID:Q}=J,O=(F)=>i1({integrationID:Q,methodID:F,now:K()}),q=async(F,z)=>{return await J.onLogin(F,{integrationID:Q,methodID:z}),O(z)},D=(F)=>async(z)=>{let P=F.method.id,W=await F.authorize(z),_={url:W.url,instructions:W.instructions,...W.expiresAt===void 0?{}:{expiresAt:W.expiresAt}};if(W.mode==="auto")return{..._,mode:"auto",callback:W.callback.then((E)=>q(E,P))};let k=W.callback;return{..._,mode:"code",callback:async(E)=>q(await k(E),P)}};return $.integration.transform((F)=>{let z=J.label===void 0?{}:{label:()=>J.label};for(let _ of J.methods)F.method.update({integrationID:Q,method:_.method,authorize:D(_),refresh:async(k)=>{if(!A1(k,Q))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return O(k.methodID)},...z});let P=J.vault;if(P===void 0)return;let W=P.method.id;F.method.update({integrationID:Q,method:P.method,authorize:async()=>({url:"",instructions:P.instructions??o1,mode:"auto",callback:Promise.resolve().then(()=>P.activate({integrationID:Q,methodID:W})).then(()=>O(W))}),refresh:async(_)=>{if(!A1(_,Q)||_.methodID!==W)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return O(W)},...z})})}function F4($){let J=[],K;for(let Q of $.split(/\r?\n/))if(Q.startsWith("data:"))J.push(Q.slice(5).replace(/^ /,""));else if(Q.startsWith("event:"))K=Q.slice(6).trim();if(J.length===0)return;return K===void 0?{data:J.join(`
|
|
2
2
|
`)}:{event:K,data:J.join(`
|
|
3
|
-
`)}}function b1($,J){let K=new TextDecoder,Q="",O=(D)=>{let F=F4(D);if(!F)return;try{$(F)}catch(z){J(z)}},q=()=>{for(;;){let D=/\r?\n\r?\n/.exec(Q);if(!D)return;let F=Q.slice(0,D.index);Q=Q.slice(D.index+D[0].length),O(F)}};return new TransformStream({transform(D,F){F.enqueue(D),Q+=K.decode(D,{stream:!0}),q()},flush(){if(Q+=K.decode(),q(),Q.trim()!=="")O(Q);Q=""}})}var n1=512,D1=3621000,e2="x-common-auth-attempt",s2=($,J)=>JSON.stringify([$,J]),y2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function P4($){let J=$.headers;return typeof J==="object"&&J!==null}function L4($,J){let K=$.getReader();return new ReadableStream({async pull(Q){let O;try{O=await K.read()}catch(q){J({reason:"failed",message:q instanceof Error?q.message:String(q)}),Q.error(q);return}if(O.done)J(),Q.close();else Q.enqueue(O.value)},async cancel(Q){J({reason:"cancelled",...Q===void 0?{}:{message:String(Q)}}),await K.cancel(Q)}})}function B1($,J){for(let[K,Q]of Object.entries(J)){let O=K.toLowerCase();for(let q of Object.keys($))if(q.toLowerCase()===O)delete $[q];if(Q!==null)$[K]=Q}}function C4($,J){for(let[K,Q]of Object.entries(J))if(Q===null)$.delete(K);else $.set(K,Q)}async function w1($,J,K={}){let{providerID:Q}=J,O=K.gateOnPlaceholder,q=(Z)=>O===void 0||O.credential(Z)===m2(Q),D=K.logger,F=Math.max(1,K.maxRecords??n1),z=K.hostRetryLimit??10,P=[...K.hostCredentials??[m2(Q)],...O?[m2(Q)]:[]].filter((Z)=>Z!==""),W=new Map,_=new WeakMap,k=new Map,E=0,L=new Set,C=new Map,m=new Map,y=(Z)=>{let B=m.get(Z);return B?.ownedSeen===!0&&B.foreignSeen},b=(Z,B)=>{C.set(Z,B);let T=m.get(Z)??{ownedSeen:!1,foreignSeen:!1};if(B)T.ownedSeen=!0;else T.foreignSeen=!0;m.set(Z,T)},w=(Z,B)=>{let T=O?.refuseMisplaced,f=T?[...B].filter(([,a])=>a.includes(m2(Q))):[],N=q(B)&&(!T||f.length>0);if(T){if(f.length>0&&(f.length!==1||!N))throw b(Z.sessionID,!1),new t2({kind:"placement-refused",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,message:T(f[0]?.[0]??"")})}return b(Z.sessionID,N),N},n=!1,X2=!1,M=new Map,d=0,v=!1,u=new Map,c=(Z,B)=>{try{D?.warn(Z,B)}catch{}},s=(Z)=>Z instanceof Error?Z.message:String(Z),t=(Z)=>Z.excluded.clear(),I=(Z)=>Z.excluded.size===0?{}:{excluded:[...Z.excluded]},i=(Z,B,T)=>{if(!K.enforceRequestExclusion||Z===void 0||!T.excluded.has(Z))return!1;return c("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:B.sessionID,kind:B.kind,phase:B.phase,accountId:Z}),!0},j2=new Map,H2=(Z,B)=>{let T=(j2.get(Z)??Promise.resolve()).then(B),f=T.then(()=>{},()=>{});return j2.set(Z,f),f.then(()=>{if(j2.get(Z)===f)j2.delete(Z)}),T},T2=(Z,B)=>{let T=j2.get(Z);return T?T.then(()=>T2(Z,B)):B()},F2=async(Z)=>{try{await J.dropChoice?.({...Z.input,accountId:Z.accountId})}catch(B){c("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:Z.input.sessionID,error:s(B)})}},k2=async(Z)=>{try{await J.dropSameAccountRetry?.({...Z.input,accountId:Z.accountId})}catch(B){c("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:Z.input.sessionID,error:s(B)})}},R2=async(Z)=>{if(Z.next)await F2(Z.next);if(Z.sameAccount)await k2(Z.sameAccount)},X=(Z)=>{let B=k.get(Z);if(k.delete(Z),B)H2(B.sessionID,()=>R2(B))},j=async(Z,B)=>{let T=M.get(Z);if(!T||T.size===0)return;await Promise.all([...T].map(async(f)=>{try{await f(B)}catch(N){c("opencode2 auth listener threw; the request is unaffected",{event:Z,error:s(N)})}}))},V=async(Z)=>{let B=new Set([...W.values()].filter((f)=>f.scope.sessionID===Z.sessionID).map((f)=>f.transport).filter((f)=>f!==void 0)),T=Z.handle?.transport??(B.size===1?[...B][0]:"unknown");try{D?.info?.("opencode2 auth retry decision",{sessionID:Z.sessionID,transport:T,attempt:Z.attempt,reason:Z.reason==="host-decides"&&y(Z.sessionID)?"mixed-session":Z.reason,retry:Z.decision.retry})}catch{}await j("retry",Z)},U=async(Z,B)=>{try{await J.onAttemptEnd?.(Z,B)}catch(T){c("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Z.attemptId,error:s(T)})}},h=(Z,B)=>{if(Z.ended||!Z.attempt)return;let T={...Z.status===void 0?{}:{status:Z.status},outputStarted:Z.outputStarted,...Z.limit?{limit:Z.limit.signal}:{},...B?{error:B}:{}};if(B)Z.endError=B;if(B?.reason==="cancelled"||!B&&!Z.limit&&(Z.status===void 0||Z.status<400))t(Z.request);Z.ended=U(Z.attempt,T)},S=(Z,B)=>h(Z,{reason:"abandoned",message:B}),R=(Z)=>[...W.values()].filter((B)=>B.key===Z),Z2=(Z)=>R(Z).at(-1),W2=(Z)=>{if(W.delete(Z.id),k.get(Z.key)?.attemptId===Z.id||!R(Z.key).length)X(Z.key)},G2=(Z)=>{W.set(Z.id,Z);while(W.size>F){let B=W.values().next().value;if(B===void 0)break;S(B,"dropped to keep the record bound"),W2(B)}},P2=(Z)=>Z.accountId===void 0?void 0:{...Z.scope,accountId:Z.accountId},K2=(Z,B)=>new t2({kind:"no-account",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,...B===void 0?{}:{message:B}}),o=(Z)=>{u.get(Z)?.clear(),u.delete(Z)},Q2=async(Z,B)=>{let T=()=>K2(Z,`${Q} ${Z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(v)throw T();let f=u.get(Z.sessionID);if(!f)f=new Set,u.set(Z.sessionID,f);let N={};f.add(N);let a=()=>{if(!f.has(N))throw T()};try{return await B(a)}finally{if(f.delete(N),f.size===0&&u.get(Z.sessionID)===f)u.delete(Z.sessionID)}},Y2=(Z,B)=>{for(let[T,f]of B)if(P.some((N)=>f.includes(N)))throw new t2({kind:"host-credential-on-wire",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,message:`${Q} ${Z.kind} request still carries the host's placeholder credential in ${T}; the adapter's account headers must replace it`})},N2=(Z)=>{for(let B of R(Z))if(B.ended||!B.attempt)W2(B);else if(B.transport==="ws"||B.judged)S(B,"a newer attempt of its session and kind began"),W2(B)},Y=async(Z,B,T,f)=>{let N=s2(Z.sessionID,Z.kind),{input:a,accountId:l,sameAccountRetry:A,request:$2}=await T2(Z.sessionID,async()=>{T();let A2=k.get(N);k.delete(N);let u2=R(N);if(A2&&u2.some((x2)=>x2.id!==A2.attemptId&&x2.attempt&&!x2.ended))c("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:Z.sessionID,kind:Z.kind});if(!A2){let x2=new Set(u2.filter((v2)=>v2.attempt&&!v2.ended).map((v2)=>v2.request));for(let v2 of u2)if(!x2.has(v2.request))t(v2.request)}let q2=A2?.request??{excluded:new Set},E2=A2?.accountId??Z2(N)?.accountId;N2(N);let B2=A2?.next,U2=A2?.sameAccount,z2=U2!==void 0&&U2.input.modelID===Z.modelID&&U2.input.agent===Z.agent,I2=B2!==void 0&&B2.input.modelID===Z.modelID&&B2.input.agent===Z.agent,h2=A2?.wake,C2={...Z,phase:"request",...I(q2),...E2===void 0?{}:{previousAccountId:E2},...A2?.rerouteFrom?{rerouteFrom:A2.rerouteFrom}:{},...h2===void 0?{}:{wake:h2,hostAttempt:B2?.input.hostAttempt}};if(B2&&(!I2||h2!==void 0))await H2(Z.sessionID,()=>F2(B2)),T();if(U2&&!z2)await H2(Z.sessionID,()=>k2(U2)),T();if(U2?.continuation&&(!z2||y(Z.sessionID))){if(z2)await H2(Z.sessionID,()=>k2(U2));throw K2(Z)}let r2=z2?U2.accountId:I2&&h2===void 0?B2.accountId:await J.chooseAccount(C2),i2=typeof r2==="string"?r2:void 0;if(i(i2,C2,q2)){let x2=i2;if(z2&&U2)await H2(Z.sessionID,()=>k2(U2));else if(x2!==void 0)await H2(Z.sessionID,()=>F2(I2&&B2?B2:{accountId:x2,input:C2}));i2=void 0,T()}return{input:C2,accountId:i2,sameAccountRetry:z2,request:q2}});T();let J2={},M2;if(l!==void 0){let A2=await J.accountHeaders({...Z,accountId:l});if(T(),P4(A2))J2=A2.headers,M2=A2.attempt;else J2=A2}let S2=`attempt-${++d}`,_2={id:S2,key:N,scope:Z,request:$2,accountId:l,headers:J2,attempt:l===void 0?void 0:{...Z,accountId:l,attemptId:S2,transport:f,data:M2},...f===void 0?{}:{transport:f},outputStarted:!1,sameAccountRetry:A};if(G2(_2),_2.attempt)j("select",{...Z,accountId:_2.attempt.accountId,hook:B,...a.previousAccountId===void 0?{}:{previousAccountId:a.previousAccountId},...a.rerouteFrom===void 0?{}:{rerouteFrom:a.rerouteFrom},handle:_2.attempt});return _2},H=async(Z,B,T,f,N)=>{let a=s2(Z.sessionID,Z.kind),l=f===void 0?void 0:W.get(f);if(l?.key!==a)l=void 0;if(!l){if(l=Z2(a),R(a).filter(($2)=>$2.transport===void 0&&!$2.ended).length>1&&!X2)X2=!0,c("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Z.sessionID,kind:Z.kind})}if(!l||l.transport!==void 0||l.ended)l=await Y(Z,B,N,T);else if(l.transport=T,l.attempt)l.attempt.transport=T;if(T==="ws"){for(let A of R(a))if(A!==l&&A.transport==="ws")S(A,"a newer attempt of its session and kind went out over WebSocket")}return l},G=async(Z,B)=>{try{return await B()}catch(T){throw h(Z,{reason:"failed",message:s(T)}),T}},g=(Z,B)=>{let T=R(s2(Z,B)).filter((f)=>f.transport==="ws").at(-1);return T?.attempt!==void 0&&!T.ended?T:void 0},x=(Z,B,T)=>{let f=P2(Z);if(!f||!Z.attempt||Z.limit)return;Z.limit={signal:B,delivered:j("limit",{...f,via:T,limit:B,outputStarted:Z.outputStarted,handle:Z.attempt})}},r=(Z,B,T,f)=>{let N=P2(Z);if(!N||!Z.attempt)return;j("quota",{...N,transport:B,...f===void 0?{}:{status:f},quota:T,handle:Z.attempt})},p=(Z,B,T,f)=>{let N=Z.attempt;if(!N)return;let a=J.inspectEvent?.(f===void 0?{transport:B,data:T,attempt:N}:{transport:B,data:T,event:f,attempt:N});if(!a)return;if(a.quota!==void 0)r(Z,B,a.quota);if(a.outputStarted)Z.outputStarted=!0;if(a.hostRetry==="veto")Z.hostRetry="veto";if(a.limit)x(Z,a.limit,B);if(a.error!==void 0)h(Z,{reason:"failed",message:a.error});else if(a.done)h(Z)},V2=(Z,B)=>{let T=Z.attempt;if(!T||B.accountId===Z.accountId)return;if(T.reboundFrom??=T.accountId,T.accountId=B.accountId,"data"in B)T.data=B.data;Z.accountId=B.accountId},e=(Z)=>!Z.attempt||Z.endError!==void 0||Z.status!==void 0&&Z.status>=400,D2=(Z)=>{let B=[...W.values()].filter((A)=>A.scope.sessionID===Z),T=B.filter((A)=>A.limit&&!A.rerouted).at(-1);if(T)return T;let f=B.filter((A)=>A.scope.kind==="primary"),N=f.length>0?f:B;if(N.length<=1)return N[0];let a=N.filter((A)=>!A.judged&&e(A)).at(-1);if(a)return a;let l=N.filter((A)=>A.attempt&&!A.ended);if(l.length>1)return"ambiguous";return l[0]??N.at(-1)},O2={providerID:Q},L2=[];L2.push(await $.session.hook("model.request",(Z)=>{if(O)return;return Q2(y2(Z),async(B)=>{let T=await Y(y2(Z),"model.request",B);if(B(),T.accountId===void 0)throw K2(T.scope);B1(Z.headers,{...T.headers,[e2]:T.id})})},O2)),L2.push(await $.session.hook("http.request",(Z)=>{if(O){if(!w(y2(Z),Z.request.headers))return}return Q2(y2(Z),async(B)=>{let T=Z.request.headers.get(e2)??void 0,f=O?await Y(y2(Z),"http.request",B,"http"):await H(y2(Z),"http.request","http",T,B);B();let N=P2(f),a=f.attempt;if(!N||!a)throw K2(f.scope);await G(f,async()=>{let l=Z.request;if(J.rewriteRequest){if(T!==void 0){let J2=new Headers(l.headers);J2.delete(e2),l=new Request(l,{headers:J2})}l=await J.rewriteRequest({...N,request:l,attempt:a})??l,B()}let A=new Headers(l.headers);A.delete(e2),C4(A,f.headers),Y2(f.scope,A.entries());let $2=new Request(l,{headers:A});_.set($2,f),Z.request=$2})})},O2)),L2.push(await $.session.hook("http.response",async(Z)=>{let B=_.get(Z.request);if(!B){if(O)return;if(!n)n=!0,c("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Z.sessionID,kind:Z.kind});return}let T=Z.response;if(J.answeredBy&&B.attempt){let A=B.attempt,$2=await G(B,async()=>J.answeredBy?.({request:Z.request,response:T,attempt:A}));if($2)V2(B,$2)}let f=P2(B),N=B.attempt;if(!f||!N)return;B.status=T.status;let a=J.quotaFromHeaders?.(T.headers,T.status,N);if(a!==void 0)r(B,"http",a,T.status);if(!T.ok&&J.limitFromResponse){let A=await J.limitFromResponse({status:T.status,headers:T.headers,body:()=>T.clone().text(),attempt:N});if(A)x(B,A,"http")}if(!T.ok||!T.body)h(B);let l=T;if(T.body&&(J.inspectEvent||J.onAttemptEnd)){let A=T.body;if(J.inspectEvent)A=A.pipeThrough(b1(($2)=>p(B,"http",$2.data,$2.event),($2)=>c("opencode2 auth event inspection threw",{error:s($2)})));l=new Response(L4(A,($2)=>{if($2?.reason==="failed")B.readFailed=!0;h(B,$2)}),{status:T.status,statusText:T.statusText,headers:T.headers})}if(J.rewriteResponse)l=await J.rewriteResponse({...f,request:Z.request,response:l,attempt:N})??l;if(J.responseRetry){if(await J.responseRetry({...f,request:Z.request,response:l,attempt:N})==="veto")B.hostRetry="veto"}if(l!==T)Z.response=l},O2)),L2.push(await $.session.hook("experimental.ws.handshake",(Z)=>{if(O){let B=s2(Z.sessionID,Z.kind);if(L.delete(B),!w(y2(Z),new Headers(Z.headers)))return}return Q2(y2(Z),async(B)=>{let T;for(let l of Object.keys(Z.headers)){if(l.toLowerCase()!==e2)continue;T??=Z.headers[l],delete Z.headers[l]}let f=O?await Y(y2(Z),"experimental.ws.handshake",B,"ws"):await H(y2(Z),"experimental.ws.handshake","ws",T,B);B();let N=P2(f),a=f.attempt;if(!N||!a)throw K2(f.scope);await G(f,async()=>{if(!O?.refuseMisplaced)B1(Z.headers,f.headers);let l=J.rewriteHandshakeURL?.({...N,url:Z.url,attempt:a});if(l!==void 0)Z.url=l;if(O?.refuseMisplaced)B1(Z.headers,f.headers);if(Y2(f.scope,Object.entries(Z.headers)),O)L.add(f.key)})})},O2));let f2=J.rewriteWebSocketFrame?.bind(J);if(f2)L2.push(await $.session.hook("experimental.ws.send",async(Z)=>{let B=y2(Z);if(O&&!L.has(s2(B.sessionID,B.kind)))return;let T=g(B.sessionID,B.kind),f=await f2({...B,attempt:T?.attempt,frame:Z.frame});if(f!==void 0)Z.frame=f},O2));L2.push(await $.session.hook("experimental.ws.receive",(Z)=>{if(O&&!L.has(s2(Z.sessionID,Z.kind)))return;let B=g(Z.sessionID,Z.kind);if(!B)return;try{p(B,"ws",Z.frame)}catch(T){c("opencode2 auth frame inspection threw",{error:s(T)})}},O2)),L2.push(await $.session.hook("retry",async(Z)=>{if(O&&C.get(Z.sessionID)!==!0)return;let B=Z.decision,T=()=>V({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:B,decision:B});if(y(Z.sessionID)&&!J.retrySameAccount){await T();return}let f=D2(Z.sessionID);if(!f)return;if(f==="ambiguous"){await V({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:B,decision:B});return}let N=f,a=()=>N.hostRetry==="veto";await Q2(N.scope,async(l)=>{let A=l,$2=J.retrySameAccount?.bind(J),J2=N.attempt,M2=N.outputStarted;if(N.transport==="ws"&&M2&&!N.ended&&!N.limit&&!(N.status!==void 0&&N.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&Z.error.type==="provider.transport")N.readFailed=!0,h(N,{reason:"failed",message:Z.error.message});if(M2&&N.readFailed&&$2&&J2&&!y(Z.sessionID)){if(!N.limit){let q2=J.limitFromError?.(Z.error,J2);if(q2)x(N,q2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered;A()}let S2=()=>N.readFailed===!0&&Z.error.type==="provider.transport"&&B.retry&&z-Z.attempt>=1&&!N.limit&&!(N.status!==void 0&&N.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&!J2?.reboundFrom&&!a()&&!y(Z.sessionID);if($2&&J2&&(!M2||S2())&&(!a()||y(Z.sessionID))&&!N.sameAccountRetry){if(N.ended)await N.ended;if(N.limit)await N.limit.delivered;let q2=await H2(N.scope.sessionID,async()=>{A();let E2=J2.accountId,B2=()=>W.has(N.id)&&N.accountId===E2&&D2(Z.sessionID)===N&&N.outputStarted===M2&&(!M2||S2())&&(!a()||y(Z.sessionID))&&(!O||C.get(Z.sessionID)===!0);if(!B2()||N.sameAccountRetry)return!1;N.sameAccountRetry=!0;let U2={...N.scope,accountId:E2,error:Z.error,attempt:Z.attempt,...N.limit?{limit:N.limit.signal}:{},...M2?{continuation:"interrupted-read"}:{}},z2;try{z2=await $2(U2)}catch(C2){c("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:Z.sessionID,error:s(C2)})}if(!z2)return A(),!1;let I2={accountId:z2.accountId,input:U2,...M2?{continuation:!0}:{}};try{A()}catch(C2){throw await k2(I2),C2}if(!B2()||z2.accountId!==E2)return await k2(I2),!1;let h2=k.get(N.key);if(k.delete(N.key),h2)await R2(h2);try{A()}catch(C2){throw await k2(I2),C2}if(!B2())return await k2(I2),!1;return k.set(N.key,{request:N.request,attemptId:N.id,sessionID:N.scope.sessionID,order:++E,accountId:E2,sameAccount:I2}),N.judged=!0,Z.decision=M2?B:{retry:!0,delay:0},!0});if(A(),q2){await V({sessionID:Z.sessionID,accountId:N.accountId,kind:N.scope.kind,attempt:Z.attempt,reason:M2?"continue-same-account":"same-account",hostDecision:B,decision:Z.decision,handle:N.attempt});return}}if(y(Z.sessionID)){await T();return}N.judged=!0;let _2=N.attempt;if(_2&&!N.outputStarted){if(!N.limit){let q2=J.limitFromError?.(Z.error,_2);if(q2)x(N,q2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered}A();let{decision:A2,reason:u2}=await H2(N.scope.sessionID,async()=>{if(A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};let q2=k.get(N.key);if(k.delete(N.key),q2)await R2(q2);if(A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};let E2=B,B2,U2,z2,I2;if(N.accountId===void 0||!_2)E2={retry:!1},B2="no-account";else if(N.outputStarted)E2={retry:!1},B2="output-started";else if(a())E2={retry:!1},B2="adapter-veto";else if(N.limit){let h2={accountId:N.accountId,limit:N.limit.signal},C2,r2={...N.scope,phase:"retry",...I(N.request),hostAttempt:Z.attempt,previousAccountId:N.accountId,rerouteFrom:h2};try{C2=await J.chooseAccount(r2)}catch(S1){c("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:N.scope.sessionID,error:s(S1)})}let i2=typeof C2==="string"?C2:typeof C2==="object"&&("hold"in C2)?N.accountId:void 0;if(i(i2,r2,N.request)){if(i2!==void 0)await F2({accountId:i2,input:r2});C2=void 0}let x2=typeof C2==="object"&&"hold"in C2?C2.hold:void 0,v2=typeof C2==="object"&&"waitThenReselect"in C2?C2.waitThenReselect:void 0,H4=typeof C2==="object"&&"hostRetry"in C2?C2.hostRetry:void 0,M1=typeof C2==="string"?C2:x2?N.accountId:void 0;if(M1!==void 0)z2={accountId:M1,input:r2};try{A()}catch(S1){if(z2)await F2(z2);throw S1}if(y(Z.sessionID)){if(z2)await F2(z2);return{decision:B,reason:"host-decides"}}if(a()||H4==="veto"){if(z2)await F2(z2);if(z2=void 0,A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};N.hostRetry="veto",E2={retry:!1},B2="adapter-veto"}else if(!(z-Z.attempt>=1)){if(z2)await F2(z2);z2=void 0,B2="host-decides-last-account"}else if(v2&&Number.isFinite(v2.delayMs)&&v2.delayMs>=0&&v2.delayMs<=D1)E2={retry:!0,delay:Math.ceil(v2.delayMs)},B2="wait-then-reselect";else if(x2&&Number.isFinite(x2.delayMs)&&x2.delayMs>=0&&x2.delayMs<=D1){if(E2={retry:!0,delay:Math.ceil(x2.delayMs)},x2.target!==void 0)I2={target:x2.target,...x2.checkpoint===void 0?{}:{checkpoint:x2.checkpoint},...x2.kind===void 0?{}:{kind:x2.kind}};B2="hold"}else if(!x2&&M1!==void 0&&M1!==N.accountId)N.rerouted=!0,N.request.excluded.add(N.accountId),U2=h2,E2={retry:!0,delay:0},B2="reroute";else{if(x2&&z2)await F2(z2),z2=void 0;B2="host-decides-last-account"}}else B2="host-decides";if(Z.decision=E2,E2.retry&&N.accountId!==void 0&&W.has(N.id))k.set(N.key,{request:N.request,attemptId:N.id,sessionID:N.scope.sessionID,order:++E,accountId:N.accountId,...U2===void 0?{}:{rerouteFrom:U2},...z2===void 0?{}:{next:z2},...I2===void 0?{}:{wake:I2}});else if(z2)await F2(z2);if(!E2.retry)t(N.request);return{decision:E2,reason:B2}});A(),await V({sessionID:Z.sessionID,...N.accountId===void 0?{}:{accountId:N.accountId},kind:N.scope.kind,attempt:Z.attempt,reason:u2,hostDecision:B,decision:A2,..._2===void 0?{}:{handle:_2}})})},O2));let d2=(Z)=>{if(o(Z),C.delete(Z),!m.get(Z)?.foreignSeen)m.delete(Z);for(let B of L)if(JSON.parse(B)[0]===Z)L.delete(B);for(let B of[...W.values()]){if(B.scope.sessionID!==Z)continue;S(B,"its session was forgotten"),t(B.request),W.delete(B.id)}for(let[B,T]of k)if(T.sessionID===Z)X(B)},b2=new AbortController,w2=$.event;if(w2)(async()=>{try{for await(let Z of w2.subscribe({signal:b2.signal}))if(Z.type==="session.deleted")d2(Z.data.sessionID);else if(Z.type==="session.status"&&Z.data.status.type==="idle"){let B=Z.data.sessionID,T=++E;H2(B,async()=>{for(let[f,N]of k)if(N.sessionID===B&&N.order<T)k.delete(f),t(N.request),await R2(N)})}}catch(Z){if(!b2.signal.aborted)c("opencode2 auth stopped listening for session deletion",{error:s(Z)})}})();return{on(Z,B){let T=M.get(Z);if(!T)T=new Set,M.set(Z,T);let f=B;return T.add(f),()=>{T.delete(f)}},accountFor(Z,B){return Z2(s2(Z,B))?.accountId},forgetSession:d2,get size(){return W.size},async dispose(){if(v)return;v=!0;for(let Z of u.keys())o(Z);b2.abort();for(let Z of W.values())S(Z,"the installation was disposed");W.clear();for(let Z of k.keys())X(Z);L.clear(),C.clear(),m.clear(),M.clear(),await Promise.all(j2.values()),await Promise.all(L2.map(async(Z)=>{try{await Z.dispose()}catch(B){c("opencode2 auth hook did not dispose cleanly",{error:s(B)})}}))}}}import{createHash as r1,randomUUID as O4}from"node:crypto";import{AnthropicOAuthOriginError as T4,applyClaudeGatewayHeaders as E4,applyCustomHeaders as x4,applyRunnerTurnNotes as k4,assertHostAuthorityStable as U1,assertNotCustodyTombstone as q4,classifyGzipRejection as S4,claudeGatewayHeaderValues as A4,claudeGatewayModelUrl as R4,createDumpResponseObserver as b4,createProviderErrorRedactor as s1,createProviderErrorResponseScope as a1,decideRequestGzip as D4,dumpDirectRequest as t1,dumpRelayRequest as e1,dumpResponseArtifact as G1,encodeGzipRequestBody as w4,getRequestGzipLatch as I4,getRequestGzipLatchPath as v4,guardAnthropicStreamResponse as f4,isDumpEnabled as y4,MessageThreadTracker as g4,mergeAnthropicBetas as h4,observeAnthropicBillingResponse as $0,prepareMessageThreadRequest as m4,RELAY_PROXY_REFUSAL as Z0,relayProxyApplies as J0,remapModelId as X0,remapRequestBodyModel as l4,reportAnthropicBillingFailure as j0,requestCacheLifetimeMs as d4,requestShortestCacheLifetimeMs as u4,requestSignal as p4,resolveNativePoolPaths as c4,runWithRequestSignal as Y0,sendWithRequestGzip as i4,setDumpEnabled as V0,signRequestBody as o4,stateLayoutOfPaths as n4,stateRefusalCause as r4,stateRefusalPublicMessage as s4,stripEmptyTrailingAssistantMessages as a4,TrailingAssistantHistoryError as t4}from"@cortexkit/anthropic-auth-core";var Z1="anthropic",_0="x-common-auth-attempt",e4=["x-session-affinity","x-opencode-session","x-parent-session-id",W0,N1,o2,_0],K1=new Set(["authorization","x-api-key"]),$8="physical send before a response",Z8="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",J8=512,X8=5000,j8=500,H0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),I1=($,J="provider request failed")=>({type:H0.has($.type)?$.type:"provider_error",message:J,...$.status!==void 0?{status:$.status}:{}});class F0 extends Error{sessionID;requestKind;kind="no-account";providerID=Z1;constructor($,J){super(Z8);this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicNoAccountError"}}class z1 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=Z1;constructor($,J){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicRevokedError"}}class l2 extends Error{kind="unsupported-transport";providerID=Z1;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class P0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class L0 extends Error{kind="state-relocated";providerID=Z1;constructor($){super(s4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function _1($){let J=r4($);return J?new L0(J):void 0}var p2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function Y8($){let J=new Set;while(p2($)&&!J.has($)){if(J.add($),$.name==="AbortError")return!1;if(typeof $.code==="string"&&/^(?:ConnectionRefused|ConnectionClosed|FailedToOpenSocket|EAI_AGAIN|ECONNABORTED|ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|ENOTFOUND|EPIPE|ETIMEDOUT|UND_ERR_(?:CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT|SOCKET))$/.test($.code)||$.name==="TimeoutError"||$.name==="TypeError"&&typeof $.message==="string"&&/fetch failed|Failed to fetch|Load failed|NetworkError|ECONNRESET|socket connection was closed unexpectedly/i.test($.message))return!0;$=$.cause}return!1}function G0($){if($.status!==400&&$.status!==404||!$.body)return $;return new Response($.body.pipeThrough(new TransformStream),$)}function $1($){try{return JSON.parse($)}catch{return}}function v1($){let J={};for(let[K,Q]of Object.entries($??{}))J[K.toLowerCase()]=Q;return J}function Q0($){let J={};for(let K of e4){let Q=$.get(K);if(Q!==null&&K!==_0)J[K]=Q;$.delete(K)}return J}function V8($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function G8($){return $ instanceof t4||$ instanceof M0||$ instanceof T4?new P0($):void 0}function Q8($,J){let K=[];if($.oauth)K.push($.oauth.accessToken);for(let[Q,O]of Object.entries($.apiHeaders??{})){if(O===null||!K1.has(Q))continue;K.push(O.replace(/^Bearer\s+/i,""))}for(let Q of K1){let O=J.get(Q);if(O!==null)K.push(O.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")K.push($.dispatch.token);return[...new Set(K.filter(Boolean))]}var W8=new Set(["oauth-2025-04-20","claude-code-20250219",B0]);function M8($){let J=$.split(",").map((K)=>K.trim()).filter((K)=>K&&!W8.has(K));return h4(null,J)}function B8($,J,K){let Q=$1($);if(!p2(Q))return $;let O=a4(Q.messages),q=Object.hasOwn(Q,"fallbacks"),{droppedMarkers:D}=U0(Q,!1),F=q&&!Object.hasOwn(Q,"fallbacks"),z=l4(Q);return k4(Q,{sessionId:J,modelId:K,isOAuth:!1}),O>0||D>0||F||z?JSON.stringify(Q):$}async function U8($,J){if(!($ instanceof Promise))return"settled";let K;try{return await Promise.race([$.then(()=>"settled"),new Promise((Q)=>{K=setTimeout(()=>Q("timed-out"),J)})])}finally{if(K!==void 0)clearTimeout(K)}}function J1($){let{source:J,log:K}=$,Q=Math.max(1,$.maxPendingSends??J8),O=$.attemptEndTimeoutMs??X8,q=new WeakMap,D=$.requestGzipLatch,F=async()=>{if(D)return D;let Y=await c4();return D??=I4(v4(Y.legacyConfig,n4(Y))),D},z=new WeakSet,P=new Map,W=new WeakMap,_=new WeakMap,k=(Y)=>JSON.stringify([Y.providerID,Y.sessionID,Y.kind,Y.modelID,Y.agent,Y.accountId]),E=new Map,L=new WeakMap,C=new Map,m=new WeakMap,y=s1([]);y.dispose();let b=(Y)=>(Y&&C.get(Y)?.redactor)??y,w=(Y)=>{P2.get(Y)?.thread.fail(),P2.delete(Y);let H=C.get(Y);if(!H)return;C.delete(Y),H.redactor.dispose(),H.scope.dispose()},n=(Y,H,G,g,x=[])=>{let r=[...new Set([...Q8(H,g),...x])],p=a1(r,G);X2.set(Y,G),C.set(Y,{sessionID:H.sessionID,redactor:s1(r),scope:p}),p.settled.then(()=>{if(C.get(Y)?.scope===p)w(Y)});while(C.size>Q){let V2=C.keys().next().value;if(V2===void 0)break;w(V2)}},X2=new WeakMap,M=(Y,H)=>{let G=Y?X2.get(Y):void 0;if(!G||!H.ok)return y.redactResponse(H);let g=a1([],G),x=g.redactResponse(H);return g.dispose(),x},d=(Y,H)=>{let G=Y?C.get(Y)?.scope:void 0;if(!G)return M(Y,H);try{return G.redactResponse(H)}catch{return M(Y,H)}},v=!1,u=new Map,c=new WeakMap,s=new WeakMap,t=new WeakMap,I=(Y)=>Y.agent==="cachekeep"||Y.agent==="prime",i=async()=>{try{if(J.isDumpEnabled)return await J.isDumpEnabled()}catch{return!1}try{return y4()}catch{return!1}},j2=(Y)=>{u.delete(Y)},H2=new WeakMap,T2=new WeakMap,F2=new WeakMap,k2=(Y,H)=>{if(Y&&!H.ok)H2.set(H.headers,Y);let G=Y?.route==="oauth"&&H.ok?T2.get(Y):void 0;if(G)F2.set(H,G);return H},R2=new WeakSet,X=(Y)=>R2.has(Y)?"direct":Y.dispatch,j=(Y,H)=>{if(X(H)!=="http-relay")return!0;let G=/^req_[A-Za-z0-9_-]+$/.test(Y.get("request-id")??"");return _.set(H,G),G},V=(Y)=>new F0(Y.sessionID,Y.kind),U=new Map,h=async(Y,H)=>{if(v)throw new z1(Y.sessionID,Y.kind);let G={revoked:!1},g=U.get(Y.sessionID);if(!g)g=new Set,U.set(Y.sessionID,g);g.add(G);let x=()=>{if(p4()?.throwIfAborted(),v||G.revoked)throw new z1(Y.sessionID,Y.kind)};try{let r=await H(x);return x(),r}finally{let r=U.get(Y.sessionID);if(r?.delete(G)&&r.size===0)U.delete(Y.sessionID)}},S=(Y,H)=>{P.set(Y,H);while(P.size>Q){let G=P.keys().next().value;if(G===void 0)break;P.delete(G),K?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:Q})}},R=(Y,H)=>({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:H.route,provenance:K2.get(H)??H.provenance,dispatch:X(H)}),Z2=(Y)=>h(Y,async(H)=>{let{accountId:G,...g}=Y,x;try{x=await J.authorizeAccount(g,G)}catch(r){let p=_1(r);if(p)throw K?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:p.cause instanceof Error?p.cause.name:""}),p;throw r}return H(),W2(g,x)}),W2=(Y,H)=>{if(!H)throw V(Y);if(H.dispatch?.kind==="websocket-relay"&&!(H.route==="oauth"&&H.gateway))throw new l2;let G=H.dispatch?.kind==="http-relay"?"http-relay":"direct",g=H.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":H.dispatch.token}:void 0;if(H.route==="oauth"){if(!H.accessToken)throw V(Y);q4(H.accessToken,Z1);let p=Object.freeze({route:"oauth",provenance:H.provenance,dispatch:G});S(p,{sessionID:Y.sessionID,oauth:{accessToken:H.accessToken,credentialId:H.credentialId,...H.identity?{identity:H.identity}:{}},dispatch:H.dispatch,oauthHeaders:H.headers,...H.gateway?{gateway:H.gateway}:{}});let V2=v1(H.headers);for(let e of K1)delete V2[e];if(delete V2["anthropic-beta"],H.dispatch?.kind==="http-relay"&&H.gateway)return{headers:{...V2,"x-api-key":null},attempt:p};return{headers:g??{...V2,"x-api-key":null,authorization:`Bearer ${H.accessToken}`},attempt:p}}let x={authorization:null,"x-api-key":null,...v1(H.headers)};if(!x.authorization&&!x["x-api-key"])throw V(Y);let r=Object.freeze({route:"api",provenance:H.provenance,dispatch:G});return S(r,{sessionID:Y.sessionID,...H.baseURL?{baseURL:H.baseURL}:{},dispatch:H.dispatch,apiHeaders:x}),{headers:g??x,attempt:r}},G2=new g4,P2=new WeakMap,K2=new WeakMap,o=new WeakSet,Q2=(Y)=>h(Y,(H)=>Y2(Y,H)),Y2=async(Y,H)=>{let{request:G,attempt:g}=Y,x=g.data;E.set(k(Y),g);while(E.size>Q){let l=E.keys().next();if(!l.done)E.delete(l.value)}let r=x?P.get(x):void 0;if(x)P.delete(x);if(!x||!r||x.route==="oauth"&&!r.oauth)throw V(Y);let p=new Headers(G.headers);x4(p);let V2=Q0(p),e=G.body===null?void 0:await G.text(),D2;H();let O2=e!==void 0&&V8(G.url),L2=K0(G.url,r.baseURL!==void 0?{baseURL:r.baseURL}:{}).url?.toString()??G.url,f2=x.route==="oauth"&&G.method.toUpperCase()==="POST"?r.gateway:void 0,d2=f2?R4(L2,f2):void 0,b2=d2?f2:void 0,w2=b2?void 0:r.dispatch;if(w2?.kind==="websocket-relay")throw new l2;if(b2&&r.dispatch?.kind==="http-relay")R2.add(x);p.delete("x-relay-token");try{if(x.route==="oauth"&&r.oauth){f1(L2,b2);let{accessToken:l,identity:A}=r.oauth;for(let[J2,M2]of Object.entries(v1(r.oauthHeaders))){if(K1.has(J2))continue;if(M2===null)p.delete(J2);else p.set(J2,M2)}let $2=null;if(e!==void 0&&O2){let J2={...R(g,x),modelID:(()=>{let _2=$1(e);return X0(p2(_2)&&typeof _2.model==="string"?_2.model:Y.modelID)})(),route:"oauth",correlation:V2},M2=await J.requestOptions?.(J2)??{};if(H(),g.agent!=="cachekeep")e=await N0(e,{...M2,deferSigning:!0,onThreadCacheSlot:(_2)=>{D2=_2},...A?{identity:A}:{},sessionId:Y.sessionID,modelId:Y.modelID,isOAuth:!0,onToolNameMap:(_2)=>L.set(x,_2)});let S2=$1(e);$2=p2(S2)?S2:null}z0(p,l,{body:$2,...A?{identity:A}:{},requestClass:g.kind!=="primary"||y1(g.agent)?"auxiliary":"main"})}else{if(e!==void 0&&O2)e=B8(e,Y.sessionID,Y.modelID);p.delete("authorization"),p.delete("x-api-key");for(let[A,$2]of Object.entries(r.apiHeaders??{}))if($2===null)p.delete(A);else p.set(A,$2);if(e!==void 0&&O2&&!p.has("content-type"))p.set("content-type","application/json");let l=p.get("anthropic-beta");if(l!==null){let A=M8(l);if(A)p.set("anthropic-beta",A);else p.delete("anthropic-beta")}}}catch(l){let A=G8(l);if(!A)throw l;throw W.set(x,A.check),K?.warn("refused an Anthropic request locally; nothing was sent",{check:A.check}),A}let Z=e!==void 0?$1(e):void 0;if(await J.admitRequest?.({...R(g,x),modelID:X0(p2(Z)&&typeof Z.model==="string"?Z.model:Y.modelID)}),Q0(p),e!==void 0)p.delete("content-length");H();let B=p2(Z)&&Z.stream===!0?"event-stream":"http";if(n(x,r,B,p,A4(b2)),x.route==="oauth"&&O2&&e!==void 0)await J.onRequestPrepared?.({...R(g,x),url:L2,bodyText:e,signal:G.signal}),H();if(x.route==="oauth"&&r.oauth&&O2&&e!==void 0&&g.kind==="primary"&&!y1(g.agent)&&g.agent!=="cachekeep"&&g.agent!=="compaction"&&V2[o2]!=="1"&&!b2){let l=r.oauth.identity?.accountUuid,A,$2=await m4(G2,{session:Y.sessionID,account:r.oauth.identity?.accountUuid??Y.accountId,credential:r.oauth.credentialId,bodyText:e,replyToolNames:L.get(x),cacheSlot:D2,headers:p,signal:G.signal});e=$2.bodyText,P2.set(x,{thread:$2,beforeResend:async()=>{if(o.has(x)||!C.has(x))return!1;H(),G.signal.throwIfAborted();let J2=await Y0(G.signal,async()=>J.authorizeAccount(Y,Y.accountId));if(H(),G.signal.throwIfAborted(),!C.has(x)||J2?.route!=="oauth"||!J2.accessToken||!l||J2.identity?.accountUuid!==l)return!1;if((J2.dispatch?.kind??"direct")!==(r.dispatch?.kind??"direct"))return!1;if(await Y0(G.signal,async()=>J.admitRequest?.({...R(g,x),provenance:J2.provenance})),H(),!C.has(x))return!1;return A=J2,{credential:J2.credentialId}},resend:async(J2)=>{H(),G.signal.throwIfAborted();let M2=A;if(A=void 0,!C.has(x))throw new z1(Y.sessionID,Y.kind);if(M2?.route!=="oauth"||!M2.accessToken)throw V(Y);K2.set(x,M2.provenance);let S2=new Headers(p);S2.set("authorization",`Bearer ${M2.accessToken}`),w(x),n(x,{...r,oauth:{accessToken:M2.accessToken,credentialId:M2.credentialId,identity:M2.identity}},B,S2);let _2=M2.dispatch,A2=async(q2,E2)=>{let B2;try{U1(),B2=a(G,J2);let U2=await($.fetch??globalThis.fetch)(q2,E2);if(G.signal.aborted)U2.body?.cancel().catch(()=>{}),G.signal.throwIfAborted();if(B2){if(B2.received=!0,j(U2.headers,x))U2=$0(B2.input,U2)}if(U2.ok&&j(U2.headers,x))T2.set(x,{at:$.now?.()??Date.now()}),J.quotaFromHeaders?.(U2.headers,{...R(g,x),provenance:M2.provenance,status:U2.status});return U2}catch(U2){if(B2&&!B2.received&&_2?.kind!=="http-relay")B2.received=!0,j0(B2.input);if(G.signal.throwIfAborted(),!Y8(U2))throw U2;return Response.json({type:"error",error:{type:"api_error",message:"Connection lost while resending a rejected thread request"}},{status:502})}},u2;if(_2?.kind==="http-relay"){if(J0(_2.url))throw Error(Z0);let q2={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:L2,method:G.method,headers:Object.fromEntries(S2)},mode:"full_sync",revision:1,body:J2,next_hash:`sha256:${r1("sha256").update(J2).digest("hex")}`};u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:J2,url:L2,method:G.method,headers:S2,dispatch:"http-relay",relayUrl:_2.url,envelope:q2,relayBytes:JSON.stringify(q2).length}),u2=await A2(_2.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":_2.token},body:JSON.stringify(q2),signal:G.signal,redirect:"error"})}else{if(_2?.kind==="websocket-relay")throw new l2;u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:J2,url:L2,method:G.method,headers:S2,dispatch:"direct"}),u2=await i4({url:L2,body:J2,headers:S2,latch:await F(),send:(q2,E2)=>{return U1(),A2(L2,{method:G.method,body:q2,headers:E2,signal:G.signal,redirect:"error"})}})}return G0(u2)}}),H()}else if(x.route==="oauth"&&O2&&e!==void 0&&g.agent!=="cachekeep")e=await o4(e),H();if(w2?.kind==="http-relay"){let l=e??"";p.delete("x-relay-token");let A={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:L2,method:G.method,headers:Object.fromEntries(p)},mode:"full_sync",revision:1,body:l,next_hash:`sha256:${r1("sha256").update(l).digest("hex")}`};if(O2&&e!==void 0&&!I(g)){let S2=V2[o2]==="1"?"start":void 0,_2=JSON.stringify(A);u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:l,url:L2,method:G.method,headers:new Headers(p),dispatch:"http-relay",relayUrl:w2.url,envelope:A,relayBytes:_2.length,...S2?{tag:S2}:{}})}else j2(x);if(U1(),J0(w2.url))throw Error(Z0);let $2=p.get("x-client-request-id"),J2=new Request(w2.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":w2.token,...$2?{"x-client-request-id":$2}:{}},redirect:"error",signal:G.signal,body:JSON.stringify(A)}),M2=a(J2,e);if(M2)q.set(x,M2);return J2}let T=e;if(x.route==="oauth"&&O2&&e!==void 0&&!b2){let l=await D4({url:L2,body:e,latch:await F()});if(H(),l.gzip)T=await w4(e),p.set("content-encoding","gzip"),z.add(x),H()}if(O2&&e!==void 0&&!I(g)){let l=V2[o2]==="1"?"start":void 0;u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:e,url:L2,method:G.method,headers:new Headers(p),dispatch:"direct",...l?{tag:l}:{}})}else j2(x);if(U1(),b2&&d2)f1(d2.toString(),b2),E4(p,b2);let f=new Request(d2?.toString()??L2,{method:G.method,headers:p,redirect:x.route==="oauth"?"error":G.redirect,signal:G.signal,...T!==void 0?{body:T}:{}}),N=a(f,e);if(N)q.set(x,N);return f;function a(l,A){let $2;if(x&&O2&&A!==void 0)try{let J2=J.billingRequest?.(R(g,x));if(J2){let M2=$1(A),S2=u4(A);$2={input:{...J2,attemptId:O4(),model:p2(M2)&&typeof M2.model==="string"?M2.model:J2.model,...S2>0?{cache:{...J2.cache,ttlMs:S2}}:{}},received:!1}}}catch{}if(x?.route!=="oauth"||!O2||A===void 0)return $2;try{J.onFinalRequestPrepared?.({attemptId:g.attemptId,requestId:l.headers.get("x-client-request-id")??void 0,bodyText:A,ttlMs:d4(A)})}catch{}return $2}},N2={providerID:Z1,chooseAccount:(Y)=>h(Y,async()=>{let H=await J.chooseAccount(Y);if(typeof H==="object"&&Y.phase==="retry")return H;if(typeof H!=="string"||!H)throw V(Y);return H}),dropChoice:(Y)=>J.dropChoice?.(Y),async retrySameAccount(Y){if(!J.retrySameAccount)return;let H=k(Y),G=E.get(H);E.delete(H);let g=Y.limit??(G?N2.limitFromError?.(Y.error,G):void 0);return J.retrySameAccount({...Y,error:I1(Y.error),...g?{limit:g}:{}})},dropSameAccountRetry:(Y)=>J.dropSameAccountRetry?.({...Y,error:I1(Y.error)}),accountHeaders:Z2,rewriteRequest:Q2,rewriteHandshakeURL(){throw new l2},async rewriteResponse({response:Y,attempt:H}){let G=H.data,g=G?q.get(G):void 0;if(g){if(g.received=!0,G&&j(Y.headers,G))Y=$0(g.input,Y)}let x=G?P2.get(G):void 0,r=x?.thread.fail;if(G)P2.delete(G);if(x&&G&&j(Y.headers,G))Y=await x.thread.recover(G0(Y),x.resend,x.beforeResend),Y=x.thread.observe(Y);else x?.thread.fail();if(G&&!j(Y.headers,G)){if(G)j2(G);if(Y.status===401)return w(G),Y.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return d(G,Y)}if(G&&z.has(G))z.delete(G),S4(Y).then(async(A)=>{if(!A)return;(await F()).latchProcess(),K?.warn("gzipped request body rejected; later requests go uncompressed",{kind:A,status:Y.status})},()=>{});let p=null,V2=G?u.get(G):void 0;if(G&&V2){let A=!1;try{A=await i()}catch{A=!1}if(!A)j2(G);else{try{V0(!0)}catch{}try{if(V2.dispatch==="http-relay")p=await e1({affinity:V2.affinity,transport:"http",protocol:1,mode:"full_sync",status:Y.status,bodyText:V2.bodyText,payload:V2.envelope??{},relayBytes:V2.relayBytes??0,...V2.tag?{tag:V2.tag}:{}});else p=await t1({affinity:V2.affinity,route:V2.route,status:Y.status,bodyText:V2.bodyText,url:V2.url,method:V2.method,headers:V2.headers,...V2.tag?{tag:V2.tag}:{}})}catch{p=null}if(j2(G),p){c.set(G,p);try{await G1(p,{status:Y.status,message:null,complete:!1})}catch{}t.set(G,Promise.resolve())}}}let e=d(G,Y),D2,O2=async(A)=>{if(G)await t.get(G);if(D2){D2.fail(A),await D2.finish();return}await G1(p??null,{status:Y.status,message:null,complete:!1,incomplete_stream:A})};if(G?.route!=="oauth"||!e.body)return k2(G,G&&X2.get(G)==="event-stream"?f4(e,O2):e);let L2={...R(H,G),status:Y.status},f2=J.responseOptions?.(L2)??{},d2=G?X2.get(G)==="http":(Y.headers.get("content-type")??"").includes("application/json"),b2={...f2,requireMessageStop:!0,onIncompleteStream:O2,toolNameMap:G?L.get(G):void 0,onResponseFailure:r,onToolNameRefusal:()=>{if(!G)return;W.set(G,"response_tool_names"),w(G)},laneStartOAuthServed:!0,...d2?{responseMode:"json"}:{}};if(!G||!p)return k2(G,g1(e,b2));let w2=p,Z=Y.status,B=b4(w2,Z);D2=B;let T=(A)=>{let J2=(t.get(G)??Promise.resolve()).then(()=>A().then(()=>{return})).catch(()=>{return});t.set(G,J2)},f=f2.onMessageStart,N=f2.onMessageDelta,a=f2.onMessageResponse,l=f2.onStreamEnd;return k2(G,g1(e,{...b2,onSseEvent:B.observe,onMessageStart:(A)=>{try{f?.(A)}catch{}try{s.set(G,{...A}),T(()=>G1(w2,{status:Z,message:A,complete:!1}))}catch{}},onMessageDelta:(A)=>{try{N?.(A)}catch{}try{let $2=s.get(G)??{},J2=$2.usage&&typeof $2.usage==="object"&&!Array.isArray($2.usage)?$2.usage:{},M2={...$2,...A.usage?{usage:{...J2,...A.usage}}:{},...A.stopReason?{stop_reason:A.stopReason}:{}};T(()=>G1(w2,{status:Z,message:M2,complete:!0,reply_text_edges:B.replyTextEdges()}))}catch{}},onMessageResponse:(A)=>{try{a?.(A)}catch{}try{T(()=>G1(w2,{status:Z,message:A,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await l?.()}catch{}try{await(t.get(G)??Promise.resolve())}catch{}}}))},quotaFromHeaders(Y,H,G){let g=G.data;if(!g||!j(Y,g))return;if(g.route==="oauth"&&H>=200&&H<300)T2.set(g,{at:$.now?.()??Date.now()});return J.quotaFromHeaders?.(Y,{...R(G,g),status:H})},async limitFromResponse({status:Y,headers:H,body:G,attempt:g}){let x=g.data;if(!x||W.get(x)==="response_tool_names")return;if(!j(H,x))return J.limitFromRelayFailure?.({...R(g,x),status:Y});if(m.set(x,`provider responded with HTTP ${Y}`),!J.limitFromResponse)return;let r=H2.get(H)===x,p=b(x),V2=await J.limitFromResponse({...R(g,x),status:Y,headers:H,body:async()=>r?await G():p.redactText(await G())});if(V2)o.add(x);return V2},inspectEvent({data:Y,event:H,attempt:G}){if(G.data&&W.get(G.data)==="response_tool_names")return;let g=$1(Y);if(!p2(g))return;let x=typeof g.type==="string"?g.type:H;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let r=G.data,p=b(r),V2=p2(g.error)?g.error:{},e=typeof V2.type!=="string"?void 0:H0.has(V2.type)?V2.type:p.redactText(V2.type),D2=typeof V2.message==="string"?p.redactText(V2.message):void 0;if(r?.dispatch==="http-relay"&&_.get(r)===!1)return;let O2=r?J.limitFromStreamError?.({...R(G,r),errorType:e,message:D2}):void 0,L2={error:[e??"error",D2].filter(Boolean).join(": ").slice(0,j8),...O2?{limit:O2}:{}};if(r&&L2.error)m.set(r,L2.error);return L2},limitFromError(Y,H){let G=H.data;if(!G||W.has(G))return;let g=I1(Y,m.get(G));if(w(G),X(G)==="http-relay"&&_.get(G)===!1)return;return J.limitFromHostError?.(g,R(H,G))},async onAttemptEnd(Y,H){let G=Y.data;if(!G)return;let g=q.get(G);if(q.delete(G),g&&!g.received&&!W.has(G)&&X(G)==="direct")j0(g.input);P.delete(G);let x=u.get(G);if(x){j2(G);try{if(await i()){try{V0(!0)}catch{}try{if(x.dispatch==="http-relay"){if(H.status!==void 0)await e1({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:H.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}})}else await t1({affinity:x.affinity,route:x.route,status:H.status,error:H.status===void 0?$8:void 0,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{}}}catch{}}let r=H.error?.reason;if(r==="cancelled"||r==="abandoned"||r===void 0&&(H.status===void 0||H.status<400))w(G);let p=W.get(G),{status:V2,...e}=H,D2=J.onAttemptEnd?.(R(Y,G),{...e,...V2!==void 0&&(X(G)!=="http-relay"||_.get(G)===!0)?{status:V2}:{},...p!==void 0?{localRefusal:{check:p}}:{}});if(await U8(D2,O)==="timed-out")K?.warn("the account source did not finish recording a send",{timeoutMs:O})}};return{adapter:N2,discardUnsentBilling:(Y)=>{q.delete(Y)},acceptedResponse:(Y)=>F2.get(Y),dispose(){v=!0;for(let[Y,H]of U){for(let G of H)G.revoked=!0;J.forgetSession?.(Y)}U.clear(),P.clear(),E.clear(),u.clear();for(let Y of[...C.keys()])w(Y)},forgetSession(Y){G2.forget(Y);for(let H of U.get(Y)??[])H.revoked=!0;U.delete(Y);for(let[H,G]of E)if(G.sessionID===Y)E.delete(H);for(let[H,G]of P)if(G.sessionID===Y)P.delete(H);for(let[H,G]of[...C])if(G.sessionID===Y)w(H);for(let[H,G]of[...u])if(G.affinity===Y)u.delete(H);J.forgetSession?.(Y)},get pendingSendCount(){return P.size},get heldCredentialCount(){let Y=0;for(let H of P.values())if(H.oauth)Y++;return Y},get heldRedactorCount(){return C.size},get operationsInProgress(){let Y=0;for(let H of U.values())Y+=H.size;return Y}}}import{createHash as N8}from"node:crypto";import{setTimeout as _8}from"node:timers/promises";import{CacheKeepManager as H8,CacheKeepPrewarmError as m1,CacheKeepSessionRegistry as F8,CacheKeepWarmRefusal as F1,currentCacheKeepRealTurn as P8,getCacheKeepRegistryDirectories as L8,isCacheKeepActiveNow as C0,isCacheKeepHybridActive as Q1,isCacheKeepSubagentsEnabled as a2,isCacheKeepWarmWait as C8,logger as c2,NativeAccountRefusal as n2,nativeAccountCanServe as x0,nativeAccountRefusal as O8,readSessionCachePolicy as g2,requestCacheLifetimeMs as O0,sessionCacheActivity as T8}from"@cortexkit/anthropic-auth-core";import{CacheKeepStore as K8}from"@cortexkit/anthropic-auth-core";var H1="2.14.0";import{cacheKeepStoreDirectory as C6,legacyCacheKeepStoreDirectory as O6}from"@cortexkit/anthropic-auth-core";class h1 extends K8{constructor($,J){super({...$,pluginVersion:H1},J)}}var k0=new WeakMap;function X1($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}function E8($,J){if(!$)return"foreign-identity";try{let K=JSON.parse($);if(!Array.isArray(K))return"foreign-identity";let[Q,,O,q,D]=K;if(Q==="local"&&typeof q==="string"&&typeof D==="string")return J.some((F)=>F.binding?.storageId===q&&F.binding.rowId===D)?"foreign-identity":"account-gone";if(Q==="vault"&&typeof O==="string")return J.some((F)=>F.credentialId===O)?"foreign-identity":"account-gone"}catch{}return"foreign-identity"}function q0($,J,K){if(!K){$.hybridDisabled=!1;return}let Q=(D)=>g2(D,!0)?.keep_warm!==void 0,O=!1;for(let D of $.manager.trackedSessions())if(Q(D.id)||$.manager.hasPlannedTarget?.(D.id))O=!0;else $.manager.untrack(D.id,"disabled");if($.hybridDisabled)return;$.hybridDisabled=!0;let q=$.persistence;$.localCleanup=($.localCleanup??Promise.resolve()).then(async()=>{await q.drain(),await q.load(J,(F)=>{if(!$.hybridDisabled)return;if(F.policyState?.planned||Q(F.policyState?.ownerSessionId??F.id)){O=!0;return}return q.removed(F.id),"invalid"});let D=$.manager.trackedSessions().some((F)=>Q(F.id)||$.manager.hasPlannedTarget?.(F.id));if(!O&&!D&&$.hybridDisabled)q.clear()}).catch(()=>c2.warn("cachekeep","local restart cleanup failed"))}var T0=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2"),E0=Symbol.for("cortexkit.anthropic-auth.opencode2.legacy-turn-rules");function S0(){let $=globalThis;return $[T0]??=new Map,$[T0]}function x8($,J,K){let Q=new Map,O=new Map,q=new Set,D=0,F=new F8({...L8("opencode",J.registryDirectory),now:J.now}),z=()=>{let C;for(let m of O.values())C=m;return C},P=J.setIntervalImpl??globalThis.setInterval,W=new H8({loadStorage:async()=>{let C=z(),m=C?await C.loadStorage():null;if(C)q0(L,J.now?.()??Date.now(),!Q1(m));return m},now:J.now,setIntervalImpl:(C,m)=>P(()=>{let y=W.tick();return L.ticking=y.catch(()=>{c2.warn("cachekeep","tick failed")}),L.ticking},m),clearIntervalImpl:J.clearIntervalImpl,setTimeoutImpl:J.setTimeoutImpl,clearTimeoutImpl:J.clearTimeoutImpl,reserveWarm:(C)=>L.persistence.reserveWarm(C),settleWarm:(C)=>W.isCurrentTarget(C)?L.persistence.reserveWarm(C):Promise.resolve(!1),deferWarmReservation:!0,responseTtlMs:(C)=>k0.get(C),onTargetChanged:(C)=>L.persistence.changed(C),onTargetRemoved:(C)=>{q.delete(C),L.persistence.removed(C)},onTrackedSessionsChanged:(C)=>F.publish(O.size===0?[]:C),prepareHeaders(C,m,y){let b=z();if(!b)return;return Q.set(y.id,{target:m,attempt:y,lease:b}),new Headers({"x-native-cachekeep-attempt":String(y.id)})},fetchImpl:async(C,m)=>{let y=new Request(C,m),b=Number(y.headers.get("x-native-cachekeep-attempt")),w=Q.get(b);if(Q.delete(b),!w||w.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(q.delete(w.target.id)){let M=J.now?.()??Date.now(),d=Math.max(M,D+3000);D=d,await(J.delayImpl??_8)(Math.max(0,d-M),void 0,{signal:w.attempt.signal})}let n=w.lease.send(w.target,y,w.attempt.signal,w.attempt.onResponseHeaders),X2=n.then(()=>{},()=>{});return w.lease.inflight.add(X2),X2.then(()=>w.lease.inflight.delete(X2)),n},onComplete:({attempt:C})=>{Q.delete(C.id)}}),_,k=()=>{if(_!==void 0)clearTimeout(_);_=void 0},E=()=>{if(k(),O.size>0)return;let C=W.dropExpiredTargets();if(C===void 0){let y=S0();if(y.get($)===L)y.delete($);return}let m=J.now?.()??Date.now();if(_=setTimeout(E,Math.max(0,C-m)),typeof _==="object"&&"unref"in _)_.unref()},L={manager:W,registry:F,persistence:K,persistenceFollowsOwner:!0,prepared:Q,leases:O,nextGeneration:0,async retain(){W.stop(),W.abortWarms(),Q.clear(),await W.drain(),E()},async adopt(){if(k(),L.loading??=(async()=>{let C=z();if(!C)return;let m=await C.read(),y=J.now?.()??Date.now(),b=0;await L.persistence.load(y,(w)=>{if(!O.size||W.trackedRequest(w?.id))return;if(w.cacheExpiresAt<=y)return"expired";if(!Q1(m.policyStorage)&&!w.policyState?.planned&&g2(w.policyState?.ownerSessionId??w.id,!0)?.keep_warm===void 0)return"invalid";let n=m.accounts.find((d)=>X1(d)===w.oauthAccountIdentity);if(!n)return E8(w.oauthAccountIdentity,m.accounts);if(n.type!=="oauth"||!x0(n))return"account-gone";if(w.isSubagent&&!w.policyState?.planned&&g2(w.policyState?.ownerSessionId??w.id,!0)?.keep_warm===void 0&&!a2(m.policyStorage))return"invalid";let X2=w.nextPrewarmAt<=y?y+b++*3000:w.nextPrewarmAt,M=W.track({sessionId:w.id,url:w.url,headers:new Headers,bodyText:w.bodyText,storage:m.policyStorage,cacheMode:"hybrid",oauthAccountId:n.id,oauthAccountIdentity:w.oauthAccountIdentity,isSubagent:w.isSubagent,retained:{cacheExpiresAt:w.cacheExpiresAt,nextPrewarmAt:X2,ttlMs:w.ttlMs,lastTouchAt:w.lastTouchAt,lastTouchKind:w.lastTouchKind,policyState:w.policyState}});if(M.tracked)q.add(w.id);return M.tracked?!0:"invalid"},void 0,(w)=>O.size>0&&!W.trackedSessions().some(({id:n})=>N8("sha256").update(n).digest("hex")===w))})().catch(()=>{c2.warn("cachekeep","failed to restore tracked sessions")}),await L.loading,!O.size)return;if(W.dropExpiredTargets()===void 0)return;W.start(),F.publish(W.registrySessions?.()??W.trackedSessions()).catch(()=>{c2.warn("cachekeep","failed to publish tracked sessions")})}};return L}function A0($){let{runtime:J,source:K}=$,Q=new AbortController,O=S0(),q=O.get($.storageId),D=new h1({storageId:$.storageId,...$.persistence},q?.persistence),F=q??x8($.storageId,$,D);if(q&&!q.persistenceFollowsOwner){F.legacyPersistence??=F.persistence;let M=F.legacyPersistence;M.changed=(d)=>D.changed(d),M.removed=(d)=>D.removed(d),M.clear=()=>D.clear(),M.load=(d,v)=>D.load(d,v)}F.persistence=D,O.set($.storageId,F);let{manager:z,registry:P}=F,W=new Set,_=(M)=>{if(M.kind!=="primary"||M.agent==="cachekeep"||M.agent==="prime")return;try{if(z.beginRealTurn){for(let u of W)if(!u.active)W.delete(u);let v=z.beginRealTurn(M.sessionID);return W.add(v),v}let d=globalThis;if(!d[E0])d[E0]=!0,c2.info("cachekeep","new real-turn warming rules apply after a server restart")}catch{}return},k=new Map,E=async(M,d)=>{let v=k.get(M),u=()=>!b.stopped&&v!==void 0&&z.trackedPolicyState?.(M)===v;if(!u())return;if(!d){z.updateSubagent?.(M,!1);return}let c=()=>[...F.leases.values()].at(-1),s=c(),t=await s?.loadStorage();if(!u()||!s||c()!==s)return;if(t&&g2(M,!0)?.keep_warm===void 0&&!a2(t))z.untrack(M,"policy-refused"),k.delete(M);else z.updateSubagent?.(M,d)},L=new Map,C=(M)=>{let d=L.get(M);return L.delete(M),d?.signal?.removeEventListener("abort",d.onAbort),d},m=(M)=>{let d=C(M);try{d?.turn?.finish()}catch{}return d?.target},y=async(M,d,v,u)=>{let c=v?AbortSignal.any([Q.signal,v]):Q.signal;if(c.aborted)throw new m1("authorization",c.reason);let s=await d.text(),t;if(!z.reserveWarmDispatch&&(M.policyState?.planned||g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm!==void 0)){if(!F.plannedUnsupportedLogged)F.plannedUnsupportedLogged=!0,c2.debug("cachekeep","planned warming requires a server restart after an older owner reload");throw new F1("unsupported")}let I=JSON.parse(s),i={providerID:"anthropic",modelID:I.model,sessionID:`oc2-cachekeep:${M.id}`,agent:"cachekeep",kind:"generate"},j2=(V)=>{throw new n2(V)},H2=O0(s),T2=J1({source:{...K,quotaFromHeaders(V,U){return K.quotaFromHeaders?.(V,{...U,reportRouting:!1})},billingRequest(V){let U=K.billingRequest?.(V);return U?{...U,sessionId:M.policyState?.ownerSessionId??M.id,requestKind:"keep_warm",cache:{warming:{on:!0}}}:void 0},onRequestPrepared:void 0,onFinalRequestPrepared:({ttlMs:V})=>{H2=V},responseOptions:void 0,async requestOptions(V){return{...await K.requestOptions?.(V,j2),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(V,U){let h=await J.read();t=h.policyStorage,c.throwIfAborted();let S=h.accounts.find((Z2)=>Z2.id===U);if(S?.type!=="oauth"||!x0(S))throw new n2("account-unavailable");if(X1(S)!==M.oauthAccountIdentity)throw new n2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!a2(h.policyStorage)||!Q1(h.policyStorage)||!C0(h.policyStorage,new Date($.now?.()??Date.now()))))return;let R=await K.authorizeAccount(V,U,j2);if(R?.provenance.kind==="local"&&X1({...S,binding:R.provenance.subject.binding,accountIdentity:R.provenance.subject.binding.identity})!==M.oauthAccountIdentity)throw new n2("credential-changed");if(R?.provenance.kind==="vault"&&R.provenance.credentialId!==S.credentialId)throw new n2("credential-changed");return R},async admitRequest(V){await K.admitRequest?.(V,j2);let U=await J.read();t=U.policyStorage;let h=U.accounts.find((S)=>S.id===V.accountId);if(c.throwIfAborted(),!h)throw new n2("account-unavailable");if(X1(h)!==M.oauthAccountIdentity)throw new n2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!a2(U.policyStorage)||!Q1(U.policyStorage)||!C0(U.policyStorage,new Date($.now?.()??Date.now()))))throw Error("CacheKeep policy changed before dispatch")}}}),F2,k2,R2="authorization",X=!1,j=()=>T2.forgetSession(i.sessionID);c.addEventListener("abort",j,{once:!0});try{let V=await J.read();t=V.policyStorage;let U=M.policyState?.ownerSessionId??M.id,h=z.trackedRequest(U)?.bodyText,S=h?JSON.parse(h).model:I.model,R=z.trackedRequest(M.id)?K.peekAccount?.(U,S,V):void 0;if(R!==void 0&&R!==(M.oauthAccountId??"main"))throw new F1("routing-moved");let Z2=V.accounts.find((H)=>X1(H)===M.oauthAccountIdentity)?.id;if(!Z2)throw new n2(V.accounts.some((H)=>H.id===M.oauthAccountId)?"credential-changed":"account-unavailable");let W2=await T2.adapter.accountHeaders({...i,accountId:Z2});if(!("headers"in W2)||typeof W2.headers!=="object"||W2.headers===null||typeof W2.attempt!=="object"||W2.attempt===null||W2.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");F2={...i,accountId:Z2,attemptId:crypto.randomUUID(),transport:"http",data:W2.attempt};let G2=await T2.adapter.rewriteRequest?.({...i,accountId:Z2,attempt:F2,request:new Request(M.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(I),signal:c})});if(!G2)throw Error("CacheKeep rewrite refused");c.throwIfAborted();let P2=M.policyState?.ownerSessionId??M.id,K2=M.policyState?.planned===!0||g2(P2,!0)?.keep_warm!==void 0,o=K2?void 0:$.subagent?.(P2);if(!K2&&$.subagent&&o===void 0)throw new m1("authorization",void 0);if(o&&!a2(t))throw new F1("subagents-disabled");await z.reserveWarmDispatch?.(M),c.throwIfAborted(),R2="send";let Q2=await($.fetch??fetch)(G2);try{u?.()}catch{}R2="response",k2=Q2.status;let Y2=await T2.adapter.rewriteResponse?.({...i,accountId:Z2,attempt:F2,request:G2,response:Q2});if(!Y2)throw Error("CacheKeep response rewrite refused");if(k2=Y2.status,T2.adapter.quotaFromHeaders?.(Y2.headers,Y2.status,F2),!Y2.ok)await T2.adapter.limitFromResponse?.({status:k2,headers:Y2.headers,body:()=>Y2.clone().text(),attempt:F2});let N2=await Y2.arrayBuffer();if(Y2.ok&&!c.aborted&&!M.sourceWarm&&(z.isCurrentTarget?.(M)??!0))T8.recordPrewarm(M.id,Z2,$.now?.()??Date.now(),H2);X=!0;let Y=new Response(N2,{status:k2,headers:Y2.headers});return k0.set(Y,H2),Y}catch(V){if(V instanceof F1||C8(V))throw V;let U=O8(V);if(U)throw U;throw new m1(R2,V,k2)}finally{if(c.removeEventListener("abort",j),F2?.data&&R2==="authorization")T2.discardUnsentBilling(F2.data);try{if(F2)await T2.adapter.onAttemptEnd?.(F2,{status:k2,outputStarted:!1,...X?{}:{error:{reason:"cancelled"}}})}finally{T2.dispose(),K.forgetSession?.(i.sessionID)}}},b={generation:F.nextGeneration++,stopped:!1,loadStorage:async()=>(await J.read()).policyStorage,send:y,inflight:new Set,read:()=>J.read(),subagent:$.subagent},w=F.leases.size===0;F.leases.set(b.generation,b);let n=(w?F.adopt():F.loading??Promise.resolve()).then(()=>{if(!b.stopped)for(let M of z.trackedSessions())$.subagent?.(M.id)}),X2;return{ready:n,beginRealTurn:_,async track(M){let d=M.kind==="primary"&&M.agent!=="cachekeep"&&M.agent!=="prime"?P8():void 0;try{d??=!b.stopped?_(M):void 0}catch{}let v=(T2)=>{try{if(d?.finish(),!z.beginRealTurn&&!b.stopped&&!M.signal?.aborted&&M.kind==="primary"&&M.agent!=="prime"&&M.agent!=="cachekeep"){let F2=Reflect.get(z,"untrackRestored");if(typeof F2==="function")F2.call(z,M.sessionID)}}catch{}m(M.attemptId),c2.debug("cachekeep","tracking skipped",{session:M.sessionID,reason:T2})};if(b.stopped)return v("lease-stopped");if(M.route!=="oauth")return v("not-oauth");if(M.agent==="cachekeep"||M.agent==="prime")return v("background-agent");if(M.kind!=="primary")return v("not-primary");if(M.signal?.aborted)return v("attempt-ended");let u=C(M.attemptId);try{if(u?.turn!==d)u?.turn?.finish()}catch{}let c={sessionID:M.sessionID,signal:M.signal,onAbort:()=>m(M.attemptId),turn:d};L.set(M.attemptId,c),M.signal?.addEventListener("abort",c.onAbort,{once:!0});let s=M.admission?.snapshot??await J.read();if(b.stopped)return v("lease-stopped");let t=g2(M.sessionID,!0);if(t?.keep_warm!==void 0&&!z.reserveWarmDispatch){if(!F.plannedUnsupportedLogged)F.plannedUnsupportedLogged=!0,c2.debug("cachekeep","planned warming requires a server restart after an older owner reload");return v("planned-owner-requires-restart")}let I=Q1(s.policyStorage),i=!I&&z.trackedSessions().some(({id:T2})=>T2===M.sessionID);if(q0(F,$.now?.()??Date.now(),!I),!I){if(t?.keep_warm===void 0){if(!i)z.recordWarmingOff?.(M.sessionID);return v("hybrid-inactive")}}let j2=!1;try{j2=$.subagent?$.subagent(M.sessionID)??!1:await $.isSubagent?.(M.sessionID)??!1}catch{return v("session-lookup-failed")}if(b.stopped)return v("lease-stopped");if(t?.keep_warm===void 0&&j2&&!a2(s.policyStorage))return z.recordWarmingOff?.(M.sessionID),v("subagents-disabled");let H2=M.admission?.account??s.accounts.find((T2)=>T2.id===M.accountId);if(!H2?.accountIdentity)return v("account-identity-missing");if(M.provenance.kind==="local"&&JSON.stringify(H2.binding)!==JSON.stringify(M.provenance.subject.binding))return v("local-binding-changed");if(M.provenance.kind==="vault"&&H2.credentialId!==M.provenance.credentialId)return v("vault-credential-changed");if(L.get(M.attemptId)!==c)return v("attempt-ended");c.target={sessionId:M.sessionID,url:M.url,headers:new Headers,bodyText:M.bodyText,storage:s.policyStorage,cacheMode:"hybrid",oauthAccountId:M.accountId,oauthAccountIdentity:X1(H2),isSubagent:j2,ttlMs:O0(M.bodyText)||(g2(M.sessionID,!0)?.ttl!==void 0?0:void 0)}},onResponseHeaders(M){let d=C(M.attemptId),v=d?.target;try{if(!b.stopped&&M.status>=200&&M.status<300&&v){let u=v.sessionId;if(!u)return;let c=$.subagent?.(u);if(c!==void 0)v.isSubagent=c;if(v.isSubagent&&g2(u,!0)?.keep_warm===void 0&&!a2(v.storage)){if(d?.turn)d.turn.finish();else if(!z.untrack(u,"policy-refused"))z.recordWarmingOff?.(u);return}let s=((d?.turn)?d.turn.track.bind(d.turn):z.track.bind(z))({...v,acceptedUsage:M.acceptedUsage,...M.acceptedAt!==void 0&&{acceptedAt:M.acceptedAt},...M.ttlMs!==void 0&&{ttlMs:M.ttlMs}});if(s.tracked){for(let I of F.leases.values())I.subagent?.(u);k.delete(u);let t=z.trackedPolicyState?.(u);if(t)k.set(u,t);if(k.size>4096){let I=k.keys().next().value;if(I!==void 0)k.delete(I)}}if(s.tracked)P.publish(z.registrySessions?.()??z.trackedSessions()).catch(()=>{c2.warn("cachekeep","failed to publish tracked sessions")});return s}}finally{try{d?.turn?.finish()}catch{}}},discardAttempt(M){m(M)},warming(M){if(M.route!=="oauth")return{on:!1};return z.warming?.(M.sessionID)},recordAcceptedUsage(M,d,v){z.recordAcceptedUsage?.(M,d,v)},resolvedParent:E,forgetSession(M){k.delete(M),z.untrack(M);for(let[d,v]of L)if(v.sessionID===M)m(d)},registry:P,dispose(){if(X2)return X2;b.stopped=!0;for(let u of W)try{u.pause()}catch{}W.clear();for(let u of L.keys())C(u);Q.abort();for(let[u,c]of F.prepared)if(c.lease===b)F.prepared.delete(u);let M=F.leases.delete(b.generation)&&F.leases.size===0,d=M?F.ticking:void 0,v=M?F.retain():void 0;return X2=(async()=>{try{if(M)await v,await d;await n,await Promise.all(b.inflight),await F.persistence.drain()}finally{if(M&&F.leases.size===0)await P.dispose()}})(),X2}}}import{AsyncLocalStorage as k8}from"node:async_hooks";import{clampHostRetryMs as q8,hostRetryResponse as S8,runWithRequestSignal as A8,withCacheKeepRealTurn as R8,withSessionCacheReportHandoff as b8}from"@cortexkit/anthropic-auth-core";async function R0($,J,K){let Q=J1(J),O=new Set,q=new k8,D=new Map,F={...Q.adapter,rewriteRequest(b){let w=q.getStore();if(w)w.route=b.attempt.data?.route,w.attemptId=b.attempt.attemptId,D.set(b.attempt.attemptId,w.finish);return Q.adapter.rewriteRequest?.(b)},onAttemptEnd(b,w){let n=(async()=>{try{await Q.adapter.onAttemptEnd?.(b,w)}finally{let X2=D.get(b.attemptId);if(D.delete(b.attemptId),b.data?.route!=="oauth"||w.status===void 0||w.status>=400||w.error)try{X2?.()}catch{}}})();return O.add(n),n.finally(()=>O.delete(n)).catch(()=>{}),n}},z=async()=>{await Promise.allSettled([...O])},P=[],W=new WeakMap,_=async(b,w,n)=>{let X2=await $.session.hook(b,async(M)=>{if(b==="http.response")return b8(async()=>{let i=!1;try{let j2=await w(M);return i=!0,j2}finally{if("request"in M&&M.request instanceof Request)try{let j2="response"in M&&M.response instanceof Response?M.response:void 0;J.source.onResponseHandedToHost?.(M.request,i&&j2?Q.acceptedResponse(j2):void 0)}catch{}if("response"in M&&M.response instanceof Response)M.response=S8(M.response);if("request"in M&&M.request instanceof Request)try{W.get(M.request)?.()}catch{}}})();if(b==="retry"){let i=await w(M);if("decision"in M&&M.decision.retry)M.decision.delay=q8(M.decision.delay);return i}if(b!=="http.request")return w(M);let d="request"in M&&M.request instanceof Request?M.request.signal:void 0,v=M,u,c,s,t=()=>{try{u?.finish()}catch{}if(d?.removeEventListener("abort",t),s?.attemptId)D.delete(s.attemptId);if(c)W.delete(c)};s={finish:t};try{if(v.model.providerID==="anthropic"){if(u=J.source.beginRealTurn?.({sessionID:v.sessionID,providerID:v.model.providerID,modelID:v.model.id,agent:v.agent,kind:v.kind}),K.credential(v.request.headers)!==m2("anthropic"))t()}}catch{t()}if(d?.addEventListener("abort",t,{once:!0}),d?.aborted)t();let I=!1;try{let i=await A8(d,()=>q.run(s,()=>R8(u,async()=>w(M))));if(I=!0,u)c=v.request,W.set(c,t);return i}finally{if(!I||s.route!=="oauth")t()}},n);return P.push(X2),X2},k=new AbortController,E;try{E=await w1({session:{hook:_},event:$.event},F,{logger:J.log,gateOnPlaceholder:K})}catch(b){throw Q.dispose(),await Promise.allSettled(P.map((w)=>w.dispose())),b}let L=(b)=>{Q.forgetSession(b),E.forgetSession(b)},C=$.event,m=C?(async()=>{try{for await(let b of C.subscribe({signal:k.signal})){if(b.type==="session.deleted")L(b.data.sessionID);if(b.type==="session.idle"||b.type==="session.status"&&b.data.status.type==="idle")J.source.forgetTurn?.(b.data.sessionID)}}catch(b){if(!k.signal.aborted)J.log?.warn("stopped listening for session deletion",{error:b instanceof Error?b.name:"unknown"})}})():Promise.resolve(),y;return{installation:E,forgetSession:L,drain:z,dispose(){if(y)return y;return Q.dispose(),k.abort(),y=(async()=>{await E.dispose(),await m,await z()})(),y}}}import{effectiveRelayTransport as b0,getQuotaCheckIntervalMs as D8,logger as w8,nativeAccountCanServe as I8,oauthProfileIsFresh as v8,quotaSnapshotCheckedAt as f8,readThreeWayBoolean as y8}from"@cortexkit/anthropic-auth-core";function D0($,J){let K=new AbortController,Q,O=!1,q=async()=>{let z=await $.read();if(K.signal.throwIfAborted(),z.policyStorage.relay?.enabled===!0&&b0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="websocket")return;let P=z,W=D8(P.policyStorage);for(let _ of P.accounts){if(K.signal.aborted)return;if(!I8(_)||_.type!=="oauth")continue;if(y8(P.policyStorage.quota?.enabled,!0)&&Date.now()-f8(_.quota)>=W)await $.fetchQuota(_.id,J,K.signal,void 0,"background").catch(()=>{});if(!v8(_.profile)&&!K.signal.aborted)await $.fetchProfile(_.id,J,K.signal).catch(()=>{})}},D=()=>{if(O||Q)return Q;return Q=q().catch(()=>{if(!K.signal.aborted)w8.debug("opencode2","native background readings did not complete")}).finally(()=>{Q=void 0}),Q},F=$.vault.watch({intervalMs:60000,onRefresh:D,shouldRefresh:async()=>{let z=await $.read();return z.policyStorage.relay?.enabled!==!0||b0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="http"}});return F.ready.catch(()=>{}),{async dispose(){O=!0,F.close(),K.abort(),await Q}}}import{authorize as r8,buildCacheKeepStatusSummary as s8,buildClaudeQuotaSummary as a8,buildPrimeAccountStatuses as t8,buildPrimeStatusSummary as e8,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as $$,claudeGatewayStatusNotes as Z$,effectiveRelayTransport as J$,exchange as X$,formatNativeAccountState as j$,formatOAuthAccountTier as Y$,getCacheKeepWindow as V$,getHostClaustrumEnrollmentPaths as G$,isCacheKeepAlways as Q$,isCacheKeepHybridActive as W$,isCacheKeepPersistentlyEnabled as M$,isVaultHosted as B$,nativeAccountCanServe as U$,nativeCacheKeepAlways as z$,parseLogLevel as K$,resetClaustrumEnrollmentState as N$,setDumpEnabled as _$,VAULT_HOST_CONNECT_REFUSAL as H$}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as g8,effectiveRelayStatus as h8,formatNativeAccountState as m8,formatOAuthAccountTier as w0,getCacheKeepWindow as l8,getRoutingMode as d8,isCacheKeepAlways as u8,isCacheKeepHybridActive as p8,isPermanentRefreshError as c8,isPrimePersistentlyEnabled as i8,nativeAccountCanServe as f0,refreshBackoffActive as I0}from"@cortexkit/anthropic-auth-core";var v0=($)=>f0($)&&$.state!=="unsupported-access"?void 0:m8($)||void 0,o8=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return f0($)?"on-vault-served":"on-cold"},n8=($,J)=>typeof $==="number"&&$>J;function y0($,J){let{now:K}=J,Q=$.policyStorage,O=$.accounts.filter((W)=>W.type==="oauth"),q=O.find((W)=>W.id==="main"),D=q?v0(q):void 0,F=q?.lastQuotaRefreshError?.nextRetryAt,z=q?.lastRefreshError,P=l8(Q);return P1({main:{quota:q?.quota??null,enabled:q?.enabled,tierLabel:w0(q?.profile),quotaBackedOff:n8(F,K),quotaBackoffUntil:F,refreshBackedOff:I0(z,q?.accountIdentity,K,void 0),refreshBackoffUntil:z?.nextRetryAt,stateLine:D,quotaDated:Boolean(D)},fallbacks:O.filter((W)=>W.id!=="main"&&(W.enabled||W.source==="vault")).map((W)=>{let _=v0(W),k=o8(W);return{id:W.id,label:W.label,quota:W.quota??null,enabled:W.enabled,tierLabel:w0(W.profile),needsReauth:c8(W.lastRefreshError)&&I0(W.lastRefreshError,W.accountIdentity,K,void 0),...k==="on-vault-reauth"?{vaultReauth:!0}:{},...k==="on-vault-served"?{vaultServed:!0}:{},...k!=="off"?{custodyState:k}:{},stateLine:_,quotaDated:Boolean(_)}}),...J.activeId!==void 0&&{activeId:J.activeId},route:d8(Q),relay:h8(Q.relay),fastMode:Q.claudeFast?.enabled===!0,cacheKeep:{enabled:p8(Q),...u8(Q)?{window:"always"}:P&&{window:`${P.startHour}-${P.endHour}`},trackedSessions:J.trackedSessions},prime:i8(Q)?{enabled:!0,accounts:g8(Q,{now:K})}:void 0,lastUpdated:K})}var l1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},g0=`For first-time model access, connect Anthropic with "${O1}".
|
|
3
|
+
`)}}function b1($,J){let K=new TextDecoder,Q="",O=(D)=>{let F=F4(D);if(!F)return;try{$(F)}catch(z){J(z)}},q=()=>{for(;;){let D=/\r?\n\r?\n/.exec(Q);if(!D)return;let F=Q.slice(0,D.index);Q=Q.slice(D.index+D[0].length),O(F)}};return new TransformStream({transform(D,F){F.enqueue(D),Q+=K.decode(D,{stream:!0}),q()},flush(){if(Q+=K.decode(),q(),Q.trim()!=="")O(Q);Q=""}})}var n1=512,D1=3621000,e2="x-common-auth-attempt",s2=($,J)=>JSON.stringify([$,J]),y2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function P4($){let J=$.headers;return typeof J==="object"&&J!==null}function L4($,J){let K=$.getReader();return new ReadableStream({async pull(Q){let O;try{O=await K.read()}catch(q){J({reason:"failed",message:q instanceof Error?q.message:String(q)}),Q.error(q);return}if(O.done)J(),Q.close();else Q.enqueue(O.value)},async cancel(Q){J({reason:"cancelled",...Q===void 0?{}:{message:String(Q)}}),await K.cancel(Q)}})}function B1($,J){for(let[K,Q]of Object.entries(J)){let O=K.toLowerCase();for(let q of Object.keys($))if(q.toLowerCase()===O)delete $[q];if(Q!==null)$[K]=Q}}function C4($,J){for(let[K,Q]of Object.entries(J))if(Q===null)$.delete(K);else $.set(K,Q)}async function w1($,J,K={}){let{providerID:Q}=J,O=K.gateOnPlaceholder,q=(Z)=>O===void 0||O.credential(Z)===m2(Q),D=K.logger,F=Math.max(1,K.maxRecords??n1),z=K.hostRetryLimit??10,P=[...K.hostCredentials??[m2(Q)],...O?[m2(Q)]:[]].filter((Z)=>Z!==""),W=new Map,_=new WeakMap,k=new Map,E=0,L=new Set,C=new Map,m=new Map,y=(Z)=>{let B=m.get(Z);return B?.ownedSeen===!0&&B.foreignSeen},b=(Z,B)=>{C.set(Z,B);let T=m.get(Z)??{ownedSeen:!1,foreignSeen:!1};if(B)T.ownedSeen=!0;else T.foreignSeen=!0;m.set(Z,T)},w=(Z,B)=>{let T=O?.refuseMisplaced,f=T?[...B].filter(([,a])=>a.includes(m2(Q))):[],N=q(B)&&(!T||f.length>0);if(T){if(f.length>0&&(f.length!==1||!N))throw b(Z.sessionID,!1),new t2({kind:"placement-refused",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,message:T(f[0]?.[0]??"")})}return b(Z.sessionID,N),N},n=!1,X2=!1,M=new Map,d=0,v=!1,u=new Map,c=(Z,B)=>{try{D?.warn(Z,B)}catch{}},s=(Z)=>Z instanceof Error?Z.message:String(Z),t=(Z)=>Z.excluded.clear(),I=(Z)=>Z.excluded.size===0?{}:{excluded:[...Z.excluded]},i=(Z,B,T)=>{if(!K.enforceRequestExclusion||Z===void 0||!T.excluded.has(Z))return!1;return c("opencode2 auth ignored a chooser result for a request-excluded account",{sessionID:B.sessionID,kind:B.kind,phase:B.phase,accountId:Z}),!0},j2=new Map,H2=(Z,B)=>{let T=(j2.get(Z)??Promise.resolve()).then(B),f=T.then(()=>{},()=>{});return j2.set(Z,f),f.then(()=>{if(j2.get(Z)===f)j2.delete(Z)}),T},T2=(Z,B)=>{let T=j2.get(Z);return T?T.then(()=>T2(Z,B)):B()},F2=async(Z)=>{try{await J.dropChoice?.({...Z.input,accountId:Z.accountId})}catch(B){c("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:Z.input.sessionID,error:s(B)})}},k2=async(Z)=>{try{await J.dropSameAccountRetry?.({...Z.input,accountId:Z.accountId})}catch(B){c("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:Z.input.sessionID,error:s(B)})}},R2=async(Z)=>{if(Z.next)await F2(Z.next);if(Z.sameAccount)await k2(Z.sameAccount)},X=(Z)=>{let B=k.get(Z);if(k.delete(Z),B)H2(B.sessionID,()=>R2(B))},j=async(Z,B)=>{let T=M.get(Z);if(!T||T.size===0)return;await Promise.all([...T].map(async(f)=>{try{await f(B)}catch(N){c("opencode2 auth listener threw; the request is unaffected",{event:Z,error:s(N)})}}))},V=async(Z)=>{let B=new Set([...W.values()].filter((f)=>f.scope.sessionID===Z.sessionID).map((f)=>f.transport).filter((f)=>f!==void 0)),T=Z.handle?.transport??(B.size===1?[...B][0]:"unknown");try{D?.info?.("opencode2 auth retry decision",{sessionID:Z.sessionID,transport:T,attempt:Z.attempt,reason:Z.reason==="host-decides"&&y(Z.sessionID)?"mixed-session":Z.reason,retry:Z.decision.retry})}catch{}await j("retry",Z)},U=async(Z,B)=>{try{await J.onAttemptEnd?.(Z,B)}catch(T){c("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:Z.attemptId,error:s(T)})}},h=(Z,B)=>{if(Z.ended||!Z.attempt)return;let T={...Z.status===void 0?{}:{status:Z.status},outputStarted:Z.outputStarted,...Z.limit?{limit:Z.limit.signal}:{},...B?{error:B}:{}};if(B)Z.endError=B;if(B?.reason==="cancelled"||!B&&!Z.limit&&(Z.status===void 0||Z.status<400))t(Z.request);Z.ended=U(Z.attempt,T)},S=(Z,B)=>h(Z,{reason:"abandoned",message:B}),R=(Z)=>[...W.values()].filter((B)=>B.key===Z),Z2=(Z)=>R(Z).at(-1),W2=(Z)=>{if(W.delete(Z.id),k.get(Z.key)?.attemptId===Z.id||!R(Z.key).length)X(Z.key)},G2=(Z)=>{W.set(Z.id,Z);while(W.size>F){let B=W.values().next().value;if(B===void 0)break;S(B,"dropped to keep the record bound"),W2(B)}},P2=(Z)=>Z.accountId===void 0?void 0:{...Z.scope,accountId:Z.accountId},K2=(Z,B)=>new t2({kind:"no-account",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,...B===void 0?{}:{message:B}}),o=(Z)=>{u.get(Z)?.clear(),u.delete(Z)},Q2=async(Z,B)=>{let T=()=>K2(Z,`${Q} ${Z.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(v)throw T();let f=u.get(Z.sessionID);if(!f)f=new Set,u.set(Z.sessionID,f);let N={};f.add(N);let a=()=>{if(!f.has(N))throw T()};try{return await B(a)}finally{if(f.delete(N),f.size===0&&u.get(Z.sessionID)===f)u.delete(Z.sessionID)}},Y2=(Z,B)=>{for(let[T,f]of B)if(P.some((N)=>f.includes(N)))throw new t2({kind:"host-credential-on-wire",providerID:Q,sessionID:Z.sessionID,requestKind:Z.kind,message:`${Q} ${Z.kind} request still carries the host's placeholder credential in ${T}; the adapter's account headers must replace it`})},N2=(Z)=>{for(let B of R(Z))if(B.ended||!B.attempt)W2(B);else if(B.transport==="ws"||B.judged)S(B,"a newer attempt of its session and kind began"),W2(B)},Y=async(Z,B,T,f)=>{let N=s2(Z.sessionID,Z.kind),{input:a,accountId:l,sameAccountRetry:A,request:$2}=await T2(Z.sessionID,async()=>{T();let A2=k.get(N);k.delete(N);let u2=R(N);if(A2&&u2.some((x2)=>x2.id!==A2.attemptId&&x2.attempt&&!x2.ended))c("opencode2 auth bound a pending retry to an ambiguous concurrent request; keeping its exclusions",{sessionID:Z.sessionID,kind:Z.kind});if(!A2){let x2=new Set(u2.filter((v2)=>v2.attempt&&!v2.ended).map((v2)=>v2.request));for(let v2 of u2)if(!x2.has(v2.request))t(v2.request)}let q2=A2?.request??{excluded:new Set},E2=A2?.accountId??Z2(N)?.accountId;N2(N);let B2=A2?.next,U2=A2?.sameAccount,z2=U2!==void 0&&U2.input.modelID===Z.modelID&&U2.input.agent===Z.agent,I2=B2!==void 0&&B2.input.modelID===Z.modelID&&B2.input.agent===Z.agent,h2=A2?.wake,C2={...Z,phase:"request",...I(q2),...E2===void 0?{}:{previousAccountId:E2},...A2?.rerouteFrom?{rerouteFrom:A2.rerouteFrom}:{},...h2===void 0?{}:{wake:h2,hostAttempt:B2?.input.hostAttempt}};if(B2&&(!I2||h2!==void 0))await H2(Z.sessionID,()=>F2(B2)),T();if(U2&&!z2)await H2(Z.sessionID,()=>k2(U2)),T();if(U2?.continuation&&(!z2||y(Z.sessionID))){if(z2)await H2(Z.sessionID,()=>k2(U2));throw K2(Z)}let r2=z2?U2.accountId:I2&&h2===void 0?B2.accountId:await J.chooseAccount(C2),i2=typeof r2==="string"?r2:void 0;if(i(i2,C2,q2)){let x2=i2;if(z2&&U2)await H2(Z.sessionID,()=>k2(U2));else if(x2!==void 0)await H2(Z.sessionID,()=>F2(I2&&B2?B2:{accountId:x2,input:C2}));i2=void 0,T()}return{input:C2,accountId:i2,sameAccountRetry:z2,request:q2}});T();let J2={},M2;if(l!==void 0){let A2=await J.accountHeaders({...Z,accountId:l});if(T(),P4(A2))J2=A2.headers,M2=A2.attempt;else J2=A2}let S2=`attempt-${++d}`,_2={id:S2,key:N,scope:Z,request:$2,accountId:l,headers:J2,attempt:l===void 0?void 0:{...Z,accountId:l,attemptId:S2,transport:f,data:M2},...f===void 0?{}:{transport:f},outputStarted:!1,sameAccountRetry:A};if(G2(_2),_2.attempt)j("select",{...Z,accountId:_2.attempt.accountId,hook:B,...a.previousAccountId===void 0?{}:{previousAccountId:a.previousAccountId},...a.rerouteFrom===void 0?{}:{rerouteFrom:a.rerouteFrom},handle:_2.attempt});return _2},H=async(Z,B,T,f,N)=>{let a=s2(Z.sessionID,Z.kind),l=f===void 0?void 0:W.get(f);if(l?.key!==a)l=void 0;if(!l){if(l=Z2(a),R(a).filter(($2)=>$2.transport===void 0&&!$2.ended).length>1&&!X2)X2=!0,c("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:Z.sessionID,kind:Z.kind})}if(!l||l.transport!==void 0||l.ended)l=await Y(Z,B,N,T);else if(l.transport=T,l.attempt)l.attempt.transport=T;if(T==="ws"){for(let A of R(a))if(A!==l&&A.transport==="ws")S(A,"a newer attempt of its session and kind went out over WebSocket")}return l},G=async(Z,B)=>{try{return await B()}catch(T){throw h(Z,{reason:"failed",message:s(T)}),T}},g=(Z,B)=>{let T=R(s2(Z,B)).filter((f)=>f.transport==="ws").at(-1);return T?.attempt!==void 0&&!T.ended?T:void 0},x=(Z,B,T)=>{let f=P2(Z);if(!f||!Z.attempt||Z.limit)return;Z.limit={signal:B,delivered:j("limit",{...f,via:T,limit:B,outputStarted:Z.outputStarted,handle:Z.attempt})}},r=(Z,B,T,f)=>{let N=P2(Z);if(!N||!Z.attempt)return;j("quota",{...N,transport:B,...f===void 0?{}:{status:f},quota:T,handle:Z.attempt})},p=(Z,B,T,f)=>{let N=Z.attempt;if(!N)return;let a=J.inspectEvent?.(f===void 0?{transport:B,data:T,attempt:N}:{transport:B,data:T,event:f,attempt:N});if(!a)return;if(a.quota!==void 0)r(Z,B,a.quota);if(a.outputStarted)Z.outputStarted=!0;if(a.hostRetry==="veto")Z.hostRetry="veto";if(a.limit)x(Z,a.limit,B);if(a.error!==void 0)h(Z,{reason:"failed",message:a.error});else if(a.done)h(Z)},V2=(Z,B)=>{let T=Z.attempt;if(!T||B.accountId===Z.accountId)return;if(T.reboundFrom??=T.accountId,T.accountId=B.accountId,"data"in B)T.data=B.data;Z.accountId=B.accountId},e=(Z)=>!Z.attempt||Z.endError!==void 0||Z.status!==void 0&&Z.status>=400,D2=(Z)=>{let B=[...W.values()].filter((A)=>A.scope.sessionID===Z),T=B.filter((A)=>A.limit&&!A.rerouted).at(-1);if(T)return T;let f=B.filter((A)=>A.scope.kind==="primary"),N=f.length>0?f:B;if(N.length<=1)return N[0];let a=N.filter((A)=>!A.judged&&e(A)).at(-1);if(a)return a;let l=N.filter((A)=>A.attempt&&!A.ended);if(l.length>1)return"ambiguous";return l[0]??N.at(-1)},O2={providerID:Q},L2=[];L2.push(await $.session.hook("model.request",(Z)=>{if(O)return;return Q2(y2(Z),async(B)=>{let T=await Y(y2(Z),"model.request",B);if(B(),T.accountId===void 0)throw K2(T.scope);B1(Z.headers,{...T.headers,[e2]:T.id})})},O2)),L2.push(await $.session.hook("http.request",(Z)=>{if(O){if(!w(y2(Z),Z.request.headers))return}return Q2(y2(Z),async(B)=>{let T=Z.request.headers.get(e2)??void 0,f=O?await Y(y2(Z),"http.request",B,"http"):await H(y2(Z),"http.request","http",T,B);B();let N=P2(f),a=f.attempt;if(!N||!a)throw K2(f.scope);await G(f,async()=>{let l=Z.request;if(J.rewriteRequest){if(T!==void 0){let J2=new Headers(l.headers);J2.delete(e2),l=new Request(l,{headers:J2})}l=await J.rewriteRequest({...N,request:l,attempt:a})??l,B()}let A=new Headers(l.headers);A.delete(e2),C4(A,f.headers),Y2(f.scope,A.entries());let $2=new Request(l,{headers:A});_.set($2,f),Z.request=$2})})},O2)),L2.push(await $.session.hook("http.response",async(Z)=>{let B=_.get(Z.request);if(!B){if(O)return;if(!n)n=!0,c("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:Z.sessionID,kind:Z.kind});return}let T=Z.response;if(J.answeredBy&&B.attempt){let A=B.attempt,$2=await G(B,async()=>J.answeredBy?.({request:Z.request,response:T,attempt:A}));if($2)V2(B,$2)}let f=P2(B),N=B.attempt;if(!f||!N)return;B.status=T.status;let a=J.quotaFromHeaders?.(T.headers,T.status,N);if(a!==void 0)r(B,"http",a,T.status);if(!T.ok&&J.limitFromResponse){let A=await J.limitFromResponse({status:T.status,headers:T.headers,body:()=>T.clone().text(),attempt:N});if(A)x(B,A,"http")}if(!T.ok||!T.body)h(B);let l=T;if(T.body&&(J.inspectEvent||J.onAttemptEnd)){let A=T.body;if(J.inspectEvent)A=A.pipeThrough(b1(($2)=>p(B,"http",$2.data,$2.event),($2)=>c("opencode2 auth event inspection threw",{error:s($2)})));l=new Response(L4(A,($2)=>{if($2?.reason==="failed")B.readFailed=!0;h(B,$2)}),{status:T.status,statusText:T.statusText,headers:T.headers})}if(J.rewriteResponse)l=await J.rewriteResponse({...f,request:Z.request,response:l,attempt:N})??l;if(J.responseRetry){if(await J.responseRetry({...f,request:Z.request,response:l,attempt:N})==="veto")B.hostRetry="veto"}if(l!==T)Z.response=l},O2)),L2.push(await $.session.hook("experimental.ws.handshake",(Z)=>{if(O){let B=s2(Z.sessionID,Z.kind);if(L.delete(B),!w(y2(Z),new Headers(Z.headers)))return}return Q2(y2(Z),async(B)=>{let T;for(let l of Object.keys(Z.headers)){if(l.toLowerCase()!==e2)continue;T??=Z.headers[l],delete Z.headers[l]}let f=O?await Y(y2(Z),"experimental.ws.handshake",B,"ws"):await H(y2(Z),"experimental.ws.handshake","ws",T,B);B();let N=P2(f),a=f.attempt;if(!N||!a)throw K2(f.scope);await G(f,async()=>{if(!O?.refuseMisplaced)B1(Z.headers,f.headers);let l=J.rewriteHandshakeURL?.({...N,url:Z.url,attempt:a});if(l!==void 0)Z.url=l;if(O?.refuseMisplaced)B1(Z.headers,f.headers);if(Y2(f.scope,Object.entries(Z.headers)),O)L.add(f.key)})})},O2));let f2=J.rewriteWebSocketFrame?.bind(J);if(f2)L2.push(await $.session.hook("experimental.ws.send",async(Z)=>{let B=y2(Z);if(O&&!L.has(s2(B.sessionID,B.kind)))return;let T=g(B.sessionID,B.kind),f=await f2({...B,attempt:T?.attempt,frame:Z.frame});if(f!==void 0)Z.frame=f},O2));L2.push(await $.session.hook("experimental.ws.receive",(Z)=>{if(O&&!L.has(s2(Z.sessionID,Z.kind)))return;let B=g(Z.sessionID,Z.kind);if(!B)return;try{p(B,"ws",Z.frame)}catch(T){c("opencode2 auth frame inspection threw",{error:s(T)})}},O2)),L2.push(await $.session.hook("retry",async(Z)=>{if(O&&C.get(Z.sessionID)!==!0)return;let B=Z.decision,T=()=>V({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:B,decision:B});if(y(Z.sessionID)&&!J.retrySameAccount){await T();return}let f=D2(Z.sessionID);if(!f)return;if(f==="ambiguous"){await V({sessionID:Z.sessionID,attempt:Z.attempt,reason:"host-decides",hostDecision:B,decision:B});return}let N=f,a=()=>N.hostRetry==="veto";await Q2(N.scope,async(l)=>{let A=l,$2=J.retrySameAccount?.bind(J),J2=N.attempt,M2=N.outputStarted;if(N.transport==="ws"&&M2&&!N.ended&&!N.limit&&!(N.status!==void 0&&N.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&Z.error.type==="provider.transport")N.readFailed=!0,h(N,{reason:"failed",message:Z.error.message});if(M2&&N.readFailed&&$2&&J2&&!y(Z.sessionID)){if(!N.limit){let q2=J.limitFromError?.(Z.error,J2);if(q2)x(N,q2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered;A()}let S2=()=>N.readFailed===!0&&Z.error.type==="provider.transport"&&B.retry&&z-Z.attempt>=1&&!N.limit&&!(N.status!==void 0&&N.status>=400)&&!(Z.error.status!==void 0&&Z.error.status>=400)&&!J2?.reboundFrom&&!a()&&!y(Z.sessionID);if($2&&J2&&(!M2||S2())&&(!a()||y(Z.sessionID))&&!N.sameAccountRetry){if(N.ended)await N.ended;if(N.limit)await N.limit.delivered;let q2=await H2(N.scope.sessionID,async()=>{A();let E2=J2.accountId,B2=()=>W.has(N.id)&&N.accountId===E2&&D2(Z.sessionID)===N&&N.outputStarted===M2&&(!M2||S2())&&(!a()||y(Z.sessionID))&&(!O||C.get(Z.sessionID)===!0);if(!B2()||N.sameAccountRetry)return!1;N.sameAccountRetry=!0;let U2={...N.scope,accountId:E2,error:Z.error,attempt:Z.attempt,...N.limit?{limit:N.limit.signal}:{},...M2?{continuation:"interrupted-read"}:{}},z2;try{z2=await $2(U2)}catch(C2){c("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:Z.sessionID,error:s(C2)})}if(!z2)return A(),!1;let I2={accountId:z2.accountId,input:U2,...M2?{continuation:!0}:{}};try{A()}catch(C2){throw await k2(I2),C2}if(!B2()||z2.accountId!==E2)return await k2(I2),!1;let h2=k.get(N.key);if(k.delete(N.key),h2)await R2(h2);try{A()}catch(C2){throw await k2(I2),C2}if(!B2())return await k2(I2),!1;return k.set(N.key,{request:N.request,attemptId:N.id,sessionID:N.scope.sessionID,order:++E,accountId:E2,sameAccount:I2}),N.judged=!0,Z.decision=M2?B:{retry:!0,delay:0},!0});if(A(),q2){await V({sessionID:Z.sessionID,accountId:N.accountId,kind:N.scope.kind,attempt:Z.attempt,reason:M2?"continue-same-account":"same-account",hostDecision:B,decision:Z.decision,handle:N.attempt});return}}if(y(Z.sessionID)){await T();return}N.judged=!0;let _2=N.attempt;if(_2&&!N.outputStarted){if(!N.limit){let q2=J.limitFromError?.(Z.error,_2);if(q2)x(N,q2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered}A();let{decision:A2,reason:u2}=await H2(N.scope.sessionID,async()=>{if(A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};let q2=k.get(N.key);if(k.delete(N.key),q2)await R2(q2);if(A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};let E2=B,B2,U2,z2,I2;if(N.accountId===void 0||!_2)E2={retry:!1},B2="no-account";else if(N.outputStarted)E2={retry:!1},B2="output-started";else if(a())E2={retry:!1},B2="adapter-veto";else if(N.limit){let h2={accountId:N.accountId,limit:N.limit.signal},C2,r2={...N.scope,phase:"retry",...I(N.request),hostAttempt:Z.attempt,previousAccountId:N.accountId,rerouteFrom:h2};try{C2=await J.chooseAccount(r2)}catch(S1){c("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:N.scope.sessionID,error:s(S1)})}let i2=typeof C2==="string"?C2:typeof C2==="object"&&("hold"in C2)?N.accountId:void 0;if(i(i2,r2,N.request)){if(i2!==void 0)await F2({accountId:i2,input:r2});C2=void 0}let x2=typeof C2==="object"&&"hold"in C2?C2.hold:void 0,v2=typeof C2==="object"&&"waitThenReselect"in C2?C2.waitThenReselect:void 0,H4=typeof C2==="object"&&"hostRetry"in C2?C2.hostRetry:void 0,M1=typeof C2==="string"?C2:x2?N.accountId:void 0;if(M1!==void 0)z2={accountId:M1,input:r2};try{A()}catch(S1){if(z2)await F2(z2);throw S1}if(y(Z.sessionID)){if(z2)await F2(z2);return{decision:B,reason:"host-decides"}}if(a()||H4==="veto"){if(z2)await F2(z2);if(z2=void 0,A(),y(Z.sessionID))return{decision:B,reason:"host-decides"};N.hostRetry="veto",E2={retry:!1},B2="adapter-veto"}else if(!(z-Z.attempt>=1)){if(z2)await F2(z2);z2=void 0,B2="host-decides-last-account"}else if(v2&&Number.isFinite(v2.delayMs)&&v2.delayMs>=0&&v2.delayMs<=D1)E2={retry:!0,delay:Math.ceil(v2.delayMs)},B2="wait-then-reselect";else if(x2&&Number.isFinite(x2.delayMs)&&x2.delayMs>=0&&x2.delayMs<=D1){if(E2={retry:!0,delay:Math.ceil(x2.delayMs)},x2.target!==void 0)I2={target:x2.target,...x2.checkpoint===void 0?{}:{checkpoint:x2.checkpoint},...x2.kind===void 0?{}:{kind:x2.kind}};B2="hold"}else if(!x2&&M1!==void 0&&M1!==N.accountId)N.rerouted=!0,N.request.excluded.add(N.accountId),U2=h2,E2={retry:!0,delay:0},B2="reroute";else{if(x2&&z2)await F2(z2),z2=void 0;B2="host-decides-last-account"}}else B2="host-decides";if(Z.decision=E2,E2.retry&&N.accountId!==void 0&&W.has(N.id))k.set(N.key,{request:N.request,attemptId:N.id,sessionID:N.scope.sessionID,order:++E,accountId:N.accountId,...U2===void 0?{}:{rerouteFrom:U2},...z2===void 0?{}:{next:z2},...I2===void 0?{}:{wake:I2}});else if(z2)await F2(z2);if(!E2.retry)t(N.request);return{decision:E2,reason:B2}});A(),await V({sessionID:Z.sessionID,...N.accountId===void 0?{}:{accountId:N.accountId},kind:N.scope.kind,attempt:Z.attempt,reason:u2,hostDecision:B,decision:A2,..._2===void 0?{}:{handle:_2}})})},O2));let d2=(Z)=>{if(o(Z),C.delete(Z),!m.get(Z)?.foreignSeen)m.delete(Z);for(let B of L)if(JSON.parse(B)[0]===Z)L.delete(B);for(let B of[...W.values()]){if(B.scope.sessionID!==Z)continue;S(B,"its session was forgotten"),t(B.request),W.delete(B.id)}for(let[B,T]of k)if(T.sessionID===Z)X(B)},b2=new AbortController,w2=$.event;if(w2)(async()=>{try{for await(let Z of w2.subscribe({signal:b2.signal}))if(Z.type==="session.deleted")d2(Z.data.sessionID);else if(Z.type==="session.status"&&Z.data.status.type==="idle"){let B=Z.data.sessionID,T=++E;H2(B,async()=>{for(let[f,N]of k)if(N.sessionID===B&&N.order<T)k.delete(f),t(N.request),await R2(N)})}}catch(Z){if(!b2.signal.aborted)c("opencode2 auth stopped listening for session deletion",{error:s(Z)})}})();return{on(Z,B){let T=M.get(Z);if(!T)T=new Set,M.set(Z,T);let f=B;return T.add(f),()=>{T.delete(f)}},accountFor(Z,B){return Z2(s2(Z,B))?.accountId},forgetSession:d2,get size(){return W.size},async dispose(){if(v)return;v=!0;for(let Z of u.keys())o(Z);b2.abort();for(let Z of W.values())S(Z,"the installation was disposed");W.clear();for(let Z of k.keys())X(Z);L.clear(),C.clear(),m.clear(),M.clear(),await Promise.all(j2.values()),await Promise.all(L2.map(async(Z)=>{try{await Z.dispose()}catch(B){c("opencode2 auth hook did not dispose cleanly",{error:s(B)})}}))}}}import{createHash as r1,randomUUID as O4}from"node:crypto";import{AnthropicOAuthOriginError as T4,applyClaudeGatewayHeaders as E4,applyCustomHeaders as x4,applyRunnerTurnNotes as k4,assertHostAuthorityStable as U1,assertNotCustodyTombstone as q4,classifyGzipRejection as S4,claudeGatewayHeaderValues as A4,claudeGatewayModelUrl as R4,createDumpResponseObserver as b4,createProviderErrorRedactor as s1,createProviderErrorResponseScope as a1,decideRequestGzip as D4,dumpDirectRequest as t1,dumpRelayRequest as e1,dumpResponseArtifact as G1,encodeGzipRequestBody as w4,getRequestGzipLatch as I4,getRequestGzipLatchPath as v4,guardAnthropicStreamResponse as f4,isDumpEnabled as y4,MessageThreadTracker as g4,mergeAnthropicBetas as h4,observeAnthropicBillingResponse as $0,prepareMessageThreadRequest as m4,RELAY_PROXY_REFUSAL as Z0,relayProxyApplies as J0,remapModelId as X0,remapRequestBodyModel as l4,reportAnthropicBillingFailure as j0,requestCacheLifetimeMs as d4,requestShortestCacheLifetimeMs as u4,requestSignal as p4,resolveNativePoolPaths as c4,runWithRequestSignal as Y0,sendWithRequestGzip as i4,setDumpEnabled as V0,signRequestBody as o4,stateLayoutOfPaths as n4,stateRefusalCause as r4,stateRefusalPublicMessage as s4,stripEmptyTrailingAssistantMessages as a4,TrailingAssistantHistoryError as t4}from"@cortexkit/anthropic-auth-core";var Z1="anthropic",_0="x-common-auth-attempt",e4=["x-session-affinity","x-opencode-session","x-parent-session-id",W0,N1,o2,_0],K1=new Set(["authorization","x-api-key"]),$8="physical send before a response",Z8="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",J8=512,X8=5000,j8=500,H0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),I1=($,J="provider request failed")=>({type:H0.has($.type)?$.type:"provider_error",message:J,...$.status!==void 0?{status:$.status}:{}});class F0 extends Error{sessionID;requestKind;kind="no-account";providerID=Z1;constructor($,J){super(Z8);this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicNoAccountError"}}class z1 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=Z1;constructor($,J){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=J;this.name="NativeAnthropicRevokedError"}}class l2 extends Error{kind="unsupported-transport";providerID=Z1;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class P0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class L0 extends Error{kind="state-relocated";providerID=Z1;constructor($){super(s4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function _1($){let J=r4($);return J?new L0(J):void 0}var p2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function Y8($){let J=new Set;while(p2($)&&!J.has($)){if(J.add($),$.name==="AbortError")return!1;if(typeof $.code==="string"&&/^(?:ConnectionRefused|ConnectionClosed|FailedToOpenSocket|EAI_AGAIN|ECONNABORTED|ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|ENOTFOUND|EPIPE|ETIMEDOUT|UND_ERR_(?:CONNECT_TIMEOUT|HEADERS_TIMEOUT|BODY_TIMEOUT|SOCKET))$/.test($.code)||$.name==="TimeoutError"||$.name==="TypeError"&&typeof $.message==="string"&&/fetch failed|Failed to fetch|Load failed|NetworkError|ECONNRESET|socket connection was closed unexpectedly/i.test($.message))return!0;$=$.cause}return!1}function G0($){if($.status!==400&&$.status!==404||!$.body)return $;return new Response($.body.pipeThrough(new TransformStream),$)}function $1($){try{return JSON.parse($)}catch{return}}function v1($){let J={};for(let[K,Q]of Object.entries($??{}))J[K.toLowerCase()]=Q;return J}function Q0($){let J={};for(let K of e4){let Q=$.get(K);if(Q!==null&&K!==_0)J[K]=Q;$.delete(K)}return J}function V8($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function G8($){return $ instanceof t4||$ instanceof M0||$ instanceof T4?new P0($):void 0}function Q8($,J){let K=[];if($.oauth)K.push($.oauth.accessToken);for(let[Q,O]of Object.entries($.apiHeaders??{})){if(O===null||!K1.has(Q))continue;K.push(O.replace(/^Bearer\s+/i,""))}for(let Q of K1){let O=J.get(Q);if(O!==null)K.push(O.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")K.push($.dispatch.token);return[...new Set(K.filter(Boolean))]}var W8=new Set(["oauth-2025-04-20","claude-code-20250219",B0]);function M8($){let J=$.split(",").map((K)=>K.trim()).filter((K)=>K&&!W8.has(K));return h4(null,J)}function B8($,J,K){let Q=$1($);if(!p2(Q))return $;let O=a4(Q.messages),q=Object.hasOwn(Q,"fallbacks"),{droppedMarkers:D}=U0(Q,!1),F=q&&!Object.hasOwn(Q,"fallbacks"),z=l4(Q);return k4(Q,{sessionId:J,modelId:K,isOAuth:!1}),O>0||D>0||F||z?JSON.stringify(Q):$}async function U8($,J){if(!($ instanceof Promise))return"settled";let K;try{return await Promise.race([$.then(()=>"settled"),new Promise((Q)=>{K=setTimeout(()=>Q("timed-out"),J)})])}finally{if(K!==void 0)clearTimeout(K)}}function J1($){let{source:J,log:K}=$,Q=Math.max(1,$.maxPendingSends??J8),O=$.attemptEndTimeoutMs??X8,q=new WeakMap,D=$.requestGzipLatch,F=async()=>{if(D)return D;let Y=await c4();return D??=I4(v4(Y.legacyConfig,n4(Y))),D},z=new WeakSet,P=new Map,W=new WeakMap,_=new WeakMap,k=(Y)=>JSON.stringify([Y.providerID,Y.sessionID,Y.kind,Y.modelID,Y.agent,Y.accountId]),E=new Map,L=new WeakMap,C=new Map,m=new WeakMap,y=s1([]);y.dispose();let b=(Y)=>(Y&&C.get(Y)?.redactor)??y,w=(Y)=>{P2.get(Y)?.thread.fail(),P2.delete(Y);let H=C.get(Y);if(!H)return;C.delete(Y),H.redactor.dispose(),H.scope.dispose()},n=(Y,H,G,g,x=[])=>{let r=[...new Set([...Q8(H,g),...x])],p=a1(r,G);X2.set(Y,G),C.set(Y,{sessionID:H.sessionID,redactor:s1(r),scope:p}),p.settled.then(()=>{if(C.get(Y)?.scope===p)w(Y)});while(C.size>Q){let V2=C.keys().next().value;if(V2===void 0)break;w(V2)}},X2=new WeakMap,M=(Y,H)=>{let G=Y?X2.get(Y):void 0;if(!G||!H.ok)return y.redactResponse(H);let g=a1([],G),x=g.redactResponse(H);return g.dispose(),x},d=(Y,H)=>{let G=Y?C.get(Y)?.scope:void 0;if(!G)return M(Y,H);try{return G.redactResponse(H)}catch{return M(Y,H)}},v=!1,u=new Map,c=new WeakMap,s=new WeakMap,t=new WeakMap,I=(Y)=>Y.agent==="cachekeep"||Y.agent==="prime",i=async()=>{try{if(J.isDumpEnabled)return await J.isDumpEnabled()}catch{return!1}try{return y4()}catch{return!1}},j2=(Y)=>{u.delete(Y)},H2=new WeakMap,T2=new WeakMap,F2=new WeakMap,k2=(Y,H)=>{if(Y&&!H.ok)H2.set(H.headers,Y);let G=Y?.route==="oauth"&&H.ok?T2.get(Y):void 0;if(G)F2.set(H,G);return H},R2=new WeakSet,X=(Y)=>R2.has(Y)?"direct":Y.dispatch,j=(Y,H)=>{if(X(H)!=="http-relay")return!0;let G=/^req_[A-Za-z0-9_-]+$/.test(Y.get("request-id")??"");return _.set(H,G),G},V=(Y)=>new F0(Y.sessionID,Y.kind),U=new Map,h=async(Y,H)=>{if(v)throw new z1(Y.sessionID,Y.kind);let G={revoked:!1},g=U.get(Y.sessionID);if(!g)g=new Set,U.set(Y.sessionID,g);g.add(G);let x=()=>{if(p4()?.throwIfAborted(),v||G.revoked)throw new z1(Y.sessionID,Y.kind)};try{let r=await H(x);return x(),r}finally{let r=U.get(Y.sessionID);if(r?.delete(G)&&r.size===0)U.delete(Y.sessionID)}},S=(Y,H)=>{P.set(Y,H);while(P.size>Q){let G=P.keys().next().value;if(G===void 0)break;P.delete(G),K?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:Q})}},R=(Y,H)=>({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:H.route,provenance:K2.get(H)??H.provenance,dispatch:X(H)}),Z2=(Y)=>h(Y,async(H)=>{let{accountId:G,...g}=Y,x;try{x=await J.authorizeAccount(g,G)}catch(r){let p=_1(r);if(p)throw K?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:p.cause instanceof Error?p.cause.name:""}),p;throw r}return H(),W2(g,x)}),W2=(Y,H)=>{if(!H)throw V(Y);if(H.dispatch?.kind==="websocket-relay"&&!(H.route==="oauth"&&H.gateway))throw new l2;let G=H.dispatch?.kind==="http-relay"?"http-relay":"direct",g=H.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":H.dispatch.token}:void 0;if(H.route==="oauth"){if(!H.accessToken)throw V(Y);q4(H.accessToken,Z1);let p=Object.freeze({route:"oauth",provenance:H.provenance,dispatch:G});S(p,{sessionID:Y.sessionID,oauth:{accessToken:H.accessToken,credentialId:H.credentialId,...H.identity?{identity:H.identity}:{}},dispatch:H.dispatch,oauthHeaders:H.headers,...H.gateway?{gateway:H.gateway}:{}});let V2=v1(H.headers);for(let e of K1)delete V2[e];if(delete V2["anthropic-beta"],H.dispatch?.kind==="http-relay"&&H.gateway)return{headers:{...V2,"x-api-key":null},attempt:p};return{headers:g??{...V2,"x-api-key":null,authorization:`Bearer ${H.accessToken}`},attempt:p}}let x={authorization:null,"x-api-key":null,...v1(H.headers)};if(!x.authorization&&!x["x-api-key"])throw V(Y);let r=Object.freeze({route:"api",provenance:H.provenance,dispatch:G});return S(r,{sessionID:Y.sessionID,...H.baseURL?{baseURL:H.baseURL}:{},dispatch:H.dispatch,apiHeaders:x}),{headers:g??x,attempt:r}},G2=new g4,P2=new WeakMap,K2=new WeakMap,o=new WeakSet,Q2=(Y)=>h(Y,(H)=>Y2(Y,H)),Y2=async(Y,H)=>{let{request:G,attempt:g}=Y,x=g.data;E.set(k(Y),g);while(E.size>Q){let l=E.keys().next();if(!l.done)E.delete(l.value)}let r=x?P.get(x):void 0;if(x)P.delete(x);if(!x||!r||x.route==="oauth"&&!r.oauth)throw V(Y);let p=new Headers(G.headers);x4(p);let V2=Q0(p),e=G.body===null?void 0:await G.text(),D2;H();let O2=e!==void 0&&V8(G.url),L2=K0(G.url,r.baseURL!==void 0?{baseURL:r.baseURL}:{}).url?.toString()??G.url,f2=x.route==="oauth"&&G.method.toUpperCase()==="POST"?r.gateway:void 0,d2=f2?R4(L2,f2):void 0,b2=d2?f2:void 0,w2=b2?void 0:r.dispatch;if(w2?.kind==="websocket-relay")throw new l2;if(b2&&r.dispatch?.kind==="http-relay")R2.add(x);p.delete("x-relay-token");try{if(x.route==="oauth"&&r.oauth){f1(L2,b2);let{accessToken:l,identity:A}=r.oauth;for(let[J2,M2]of Object.entries(v1(r.oauthHeaders))){if(K1.has(J2))continue;if(M2===null)p.delete(J2);else p.set(J2,M2)}let $2=null;if(e!==void 0&&O2){let J2={...R(g,x),modelID:(()=>{let _2=$1(e);return X0(p2(_2)&&typeof _2.model==="string"?_2.model:Y.modelID)})(),route:"oauth",correlation:V2},M2=await J.requestOptions?.(J2)??{};if(H(),g.agent!=="cachekeep")e=await N0(e,{...M2,deferSigning:!0,onThreadCacheSlot:(_2)=>{D2=_2},...A?{identity:A}:{},sessionId:Y.sessionID,modelId:Y.modelID,isOAuth:!0,onToolNameMap:(_2)=>L.set(x,_2)});let S2=$1(e);$2=p2(S2)?S2:null}z0(p,l,{body:$2,...A?{identity:A}:{},requestClass:g.kind!=="primary"||y1(g.agent)?"auxiliary":"main"})}else{if(e!==void 0&&O2)e=B8(e,Y.sessionID,Y.modelID);p.delete("authorization"),p.delete("x-api-key");for(let[A,$2]of Object.entries(r.apiHeaders??{}))if($2===null)p.delete(A);else p.set(A,$2);if(e!==void 0&&O2&&!p.has("content-type"))p.set("content-type","application/json");let l=p.get("anthropic-beta");if(l!==null){let A=M8(l);if(A)p.set("anthropic-beta",A);else p.delete("anthropic-beta")}}}catch(l){let A=G8(l);if(!A)throw l;throw W.set(x,A.check),K?.warn("refused an Anthropic request locally; nothing was sent",{check:A.check}),A}let Z=e!==void 0?$1(e):void 0;if(await J.admitRequest?.({...R(g,x),modelID:X0(p2(Z)&&typeof Z.model==="string"?Z.model:Y.modelID)}),Q0(p),e!==void 0)p.delete("content-length");H();let B=p2(Z)&&Z.stream===!0?"event-stream":"http";if(n(x,r,B,p,A4(b2)),x.route==="oauth"&&O2&&e!==void 0)await J.onRequestPrepared?.({...R(g,x),url:L2,bodyText:e,signal:G.signal}),H();if(x.route==="oauth"&&r.oauth&&O2&&e!==void 0&&g.kind==="primary"&&!y1(g.agent)&&g.agent!=="cachekeep"&&g.agent!=="compaction"&&V2[o2]!=="1"&&!b2){let l=r.oauth.identity?.accountUuid,A,$2=await m4(G2,{session:Y.sessionID,account:r.oauth.identity?.accountUuid??Y.accountId,credential:r.oauth.credentialId,bodyText:e,replyToolNames:L.get(x),cacheSlot:D2,headers:p,signal:G.signal});e=$2.bodyText,P2.set(x,{thread:$2,beforeResend:async()=>{if(o.has(x)||!C.has(x))return!1;H(),G.signal.throwIfAborted();let J2=await Y0(G.signal,async()=>J.authorizeAccount(Y,Y.accountId));if(H(),G.signal.throwIfAborted(),!C.has(x)||J2?.route!=="oauth"||!J2.accessToken||!l||J2.identity?.accountUuid!==l)return!1;if((J2.dispatch?.kind??"direct")!==(r.dispatch?.kind??"direct"))return!1;if(await Y0(G.signal,async()=>J.admitRequest?.({...R(g,x),provenance:J2.provenance})),H(),!C.has(x))return!1;return A=J2,{credential:J2.credentialId}},resend:async(J2)=>{H(),G.signal.throwIfAborted();let M2=A;if(A=void 0,!C.has(x))throw new z1(Y.sessionID,Y.kind);if(M2?.route!=="oauth"||!M2.accessToken)throw V(Y);K2.set(x,M2.provenance);let S2=new Headers(p);S2.set("authorization",`Bearer ${M2.accessToken}`),w(x),n(x,{...r,oauth:{accessToken:M2.accessToken,credentialId:M2.credentialId,identity:M2.identity}},B,S2);let _2=M2.dispatch,A2=async(q2,E2)=>{let B2;try{U1(),B2=a(G,J2);let U2=await($.fetch??globalThis.fetch)(q2,E2);if(G.signal.aborted)U2.body?.cancel().catch(()=>{}),G.signal.throwIfAborted();if(B2){if(B2.received=!0,j(U2.headers,x))U2=$0(B2.input,U2)}if(U2.ok&&j(U2.headers,x))T2.set(x,{at:$.now?.()??Date.now()}),J.quotaFromHeaders?.(U2.headers,{...R(g,x),provenance:M2.provenance,status:U2.status});return U2}catch(U2){if(B2&&!B2.received&&_2?.kind!=="http-relay")B2.received=!0,j0(B2.input);if(G.signal.throwIfAborted(),!Y8(U2))throw U2;return Response.json({type:"error",error:{type:"api_error",message:"Connection lost while resending a rejected thread request"}},{status:502})}},u2;if(_2?.kind==="http-relay"){if(J0(_2.url))throw Error(Z0);let q2={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:L2,method:G.method,headers:Object.fromEntries(S2)},mode:"full_sync",revision:1,body:J2,next_hash:`sha256:${r1("sha256").update(J2).digest("hex")}`};u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:J2,url:L2,method:G.method,headers:S2,dispatch:"http-relay",relayUrl:_2.url,envelope:q2,relayBytes:JSON.stringify(q2).length}),u2=await A2(_2.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":_2.token},body:JSON.stringify(q2),signal:G.signal,redirect:"error"})}else{if(_2?.kind==="websocket-relay")throw new l2;u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:J2,url:L2,method:G.method,headers:S2,dispatch:"direct"}),u2=await i4({url:L2,body:J2,headers:S2,latch:await F(),send:(q2,E2)=>{return U1(),A2(L2,{method:G.method,body:q2,headers:E2,signal:G.signal,redirect:"error"})}})}return G0(u2)}}),H()}else if(x.route==="oauth"&&O2&&e!==void 0&&g.agent!=="cachekeep")e=await o4(e),H();if(w2?.kind==="http-relay"){let l=e??"";p.delete("x-relay-token");let A={protocol:1,type:"request",affinity:Y.sessionID,upstream:{url:L2,method:G.method,headers:Object.fromEntries(p)},mode:"full_sync",revision:1,body:l,next_hash:`sha256:${r1("sha256").update(l).digest("hex")}`};if(O2&&e!==void 0&&!I(g)){let S2=V2[o2]==="1"?"start":void 0,_2=JSON.stringify(A);u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:l,url:L2,method:G.method,headers:new Headers(p),dispatch:"http-relay",relayUrl:w2.url,envelope:A,relayBytes:_2.length,...S2?{tag:S2}:{}})}else j2(x);if(U1(),J0(w2.url))throw Error(Z0);let $2=p.get("x-client-request-id"),J2=new Request(w2.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":w2.token,...$2?{"x-client-request-id":$2}:{}},redirect:"error",signal:G.signal,body:JSON.stringify(A)}),M2=a(J2,e);if(M2)q.set(x,M2);return J2}let T=e;if(x.route==="oauth"&&O2&&e!==void 0&&!b2){let l=await D4({url:L2,body:e,latch:await F()});if(H(),l.gzip)T=await w4(e),p.set("content-encoding","gzip"),z.add(x),H()}if(O2&&e!==void 0&&!I(g)){let l=V2[o2]==="1"?"start":void 0;u.set(x,{affinity:Y.sessionID,route:Y.accountId,bodyText:e,url:L2,method:G.method,headers:new Headers(p),dispatch:"direct",...l?{tag:l}:{}})}else j2(x);if(U1(),b2&&d2)f1(d2.toString(),b2),E4(p,b2);let f=new Request(d2?.toString()??L2,{method:G.method,headers:p,redirect:x.route==="oauth"?"error":G.redirect,signal:G.signal,...T!==void 0?{body:T}:{}}),N=a(f,e);if(N)q.set(x,N);return f;function a(l,A){let $2;if(x&&O2&&A!==void 0)try{let J2=J.billingRequest?.(R(g,x));if(J2){let M2=$1(A),S2=u4(A);$2={input:{...J2,attemptId:O4(),model:p2(M2)&&typeof M2.model==="string"?M2.model:J2.model,...S2>0?{cache:{...J2.cache,ttlMs:S2}}:{}},received:!1}}}catch{}if(x?.route!=="oauth"||!O2||A===void 0)return $2;try{J.onFinalRequestPrepared?.({attemptId:g.attemptId,requestId:l.headers.get("x-client-request-id")??void 0,bodyText:A,ttlMs:d4(A)})}catch{}return $2}},N2={providerID:Z1,chooseAccount:(Y)=>h(Y,async()=>{let H=await J.chooseAccount(Y);if(typeof H==="object"&&Y.phase==="retry")return H;if(typeof H!=="string"||!H)throw V(Y);return H}),dropChoice:(Y)=>J.dropChoice?.(Y),async retrySameAccount(Y){if(!J.retrySameAccount)return;let H=k(Y),G=E.get(H);E.delete(H);let g=Y.limit??(G?N2.limitFromError?.(Y.error,G):void 0);return J.retrySameAccount({...Y,error:I1(Y.error),...g?{limit:g}:{}})},dropSameAccountRetry:(Y)=>J.dropSameAccountRetry?.({...Y,error:I1(Y.error)}),accountHeaders:Z2,rewriteRequest:Q2,rewriteHandshakeURL(){throw new l2},async rewriteResponse({response:Y,attempt:H}){let G=H.data,g=G?q.get(G):void 0;if(g){if(g.received=!0,G&&j(Y.headers,G))Y=$0(g.input,Y)}let x=G?P2.get(G):void 0,r=x?.thread.fail;if(G)P2.delete(G);if(x&&G&&j(Y.headers,G))Y=await x.thread.recover(G0(Y),x.resend,x.beforeResend),Y=x.thread.observe(Y);else x?.thread.fail();if(G&&!j(Y.headers,G)){if(G)j2(G);if(Y.status===401)return w(G),Y.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return d(G,Y)}if(G&&z.has(G))z.delete(G),S4(Y).then(async(A)=>{if(!A)return;(await F()).latchProcess(),K?.warn("gzipped request body rejected; later requests go uncompressed",{kind:A,status:Y.status})},()=>{});let p=null,V2=G?u.get(G):void 0;if(G&&V2){let A=!1;try{A=await i()}catch{A=!1}if(!A)j2(G);else{try{V0(!0)}catch{}try{if(V2.dispatch==="http-relay")p=await e1({affinity:V2.affinity,transport:"http",protocol:1,mode:"full_sync",status:Y.status,bodyText:V2.bodyText,payload:V2.envelope??{},relayBytes:V2.relayBytes??0,...V2.tag?{tag:V2.tag}:{}});else p=await t1({affinity:V2.affinity,route:V2.route,status:Y.status,bodyText:V2.bodyText,url:V2.url,method:V2.method,headers:V2.headers,...V2.tag?{tag:V2.tag}:{}})}catch{p=null}if(j2(G),p){c.set(G,p);try{await G1(p,{status:Y.status,message:null,complete:!1})}catch{}t.set(G,Promise.resolve())}}}let e=d(G,Y),D2,O2=async(A)=>{if(G)await t.get(G);if(D2){D2.fail(A),await D2.finish();return}await G1(p??null,{status:Y.status,message:null,complete:!1,incomplete_stream:A})};if(G?.route!=="oauth"||!e.body)return k2(G,G&&X2.get(G)==="event-stream"?f4(e,O2):e);let L2={...R(H,G),status:Y.status},f2=J.responseOptions?.(L2)??{},d2=G?X2.get(G)==="http":(Y.headers.get("content-type")??"").includes("application/json"),b2={...f2,requireMessageStop:!0,onIncompleteStream:O2,toolNameMap:G?L.get(G):void 0,onResponseFailure:r,onToolNameRefusal:()=>{if(!G)return;W.set(G,"response_tool_names"),w(G)},laneStartOAuthServed:!0,...d2?{responseMode:"json"}:{}};if(!G||!p)return k2(G,g1(e,b2));let w2=p,Z=Y.status,B=b4(w2,Z);D2=B;let T=(A)=>{let J2=(t.get(G)??Promise.resolve()).then(()=>A().then(()=>{return})).catch(()=>{return});t.set(G,J2)},f=f2.onMessageStart,N=f2.onMessageDelta,a=f2.onMessageResponse,l=f2.onStreamEnd;return k2(G,g1(e,{...b2,onSseEvent:B.observe,onMessageStart:(A)=>{try{f?.(A)}catch{}try{s.set(G,{...A}),T(()=>G1(w2,{status:Z,message:A,complete:!1}))}catch{}},onMessageDelta:(A)=>{try{N?.(A)}catch{}try{let $2=s.get(G)??{},J2=$2.usage&&typeof $2.usage==="object"&&!Array.isArray($2.usage)?$2.usage:{},M2={...$2,...A.usage?{usage:{...J2,...A.usage}}:{},...A.stopReason?{stop_reason:A.stopReason}:{}};T(()=>G1(w2,{status:Z,message:M2,complete:!0,reply_text_edges:B.replyTextEdges()}))}catch{}},onMessageResponse:(A)=>{try{a?.(A)}catch{}try{T(()=>G1(w2,{status:Z,message:A,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await l?.()}catch{}try{await(t.get(G)??Promise.resolve())}catch{}}}))},quotaFromHeaders(Y,H,G){let g=G.data;if(!g||!j(Y,g))return;if(g.route==="oauth"&&H>=200&&H<300)T2.set(g,{at:$.now?.()??Date.now()});return J.quotaFromHeaders?.(Y,{...R(G,g),status:H})},async limitFromResponse({status:Y,headers:H,body:G,attempt:g}){let x=g.data;if(!x||W.get(x)==="response_tool_names")return;if(!j(H,x))return J.limitFromRelayFailure?.({...R(g,x),status:Y});if(m.set(x,`provider responded with HTTP ${Y}`),!J.limitFromResponse)return;let r=H2.get(H)===x,p=b(x),V2=await J.limitFromResponse({...R(g,x),status:Y,headers:H,body:async()=>r?await G():p.redactText(await G())});if(V2)o.add(x);return V2},inspectEvent({data:Y,event:H,attempt:G}){if(G.data&&W.get(G.data)==="response_tool_names")return;let g=$1(Y);if(!p2(g))return;let x=typeof g.type==="string"?g.type:H;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let r=G.data,p=b(r),V2=p2(g.error)?g.error:{},e=typeof V2.type!=="string"?void 0:H0.has(V2.type)?V2.type:p.redactText(V2.type),D2=typeof V2.message==="string"?p.redactText(V2.message):void 0;if(r?.dispatch==="http-relay"&&_.get(r)===!1)return;let O2=r?J.limitFromStreamError?.({...R(G,r),errorType:e,message:D2}):void 0,L2={error:[e??"error",D2].filter(Boolean).join(": ").slice(0,j8),...O2?{limit:O2}:{}};if(r&&L2.error)m.set(r,L2.error);return L2},limitFromError(Y,H){let G=H.data;if(!G||W.has(G))return;let g=I1(Y,m.get(G));if(w(G),X(G)==="http-relay"&&_.get(G)===!1)return;return J.limitFromHostError?.(g,R(H,G))},async onAttemptEnd(Y,H){let G=Y.data;if(!G)return;let g=q.get(G);if(q.delete(G),g&&!g.received&&!W.has(G)&&X(G)==="direct")j0(g.input);P.delete(G);let x=u.get(G);if(x){j2(G);try{if(await i()){try{V0(!0)}catch{}try{if(x.dispatch==="http-relay"){if(H.status!==void 0)await e1({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:H.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}})}else await t1({affinity:x.affinity,route:x.route,status:H.status,error:H.status===void 0?$8:void 0,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{}}}catch{}}let r=H.error?.reason;if(r==="cancelled"||r==="abandoned"||r===void 0&&(H.status===void 0||H.status<400))w(G);let p=W.get(G),{status:V2,...e}=H,D2=J.onAttemptEnd?.(R(Y,G),{...e,...V2!==void 0&&(X(G)!=="http-relay"||_.get(G)===!0)?{status:V2}:{},...p!==void 0?{localRefusal:{check:p}}:{}});if(await U8(D2,O)==="timed-out")K?.warn("the account source did not finish recording a send",{timeoutMs:O})}};return{adapter:N2,discardUnsentBilling:(Y)=>{q.delete(Y)},acceptedResponse:(Y)=>F2.get(Y),dispose(){v=!0;for(let[Y,H]of U){for(let G of H)G.revoked=!0;J.forgetSession?.(Y)}U.clear(),P.clear(),E.clear(),u.clear();for(let Y of[...C.keys()])w(Y)},forgetSession(Y){G2.forget(Y);for(let H of U.get(Y)??[])H.revoked=!0;U.delete(Y);for(let[H,G]of E)if(G.sessionID===Y)E.delete(H);for(let[H,G]of P)if(G.sessionID===Y)P.delete(H);for(let[H,G]of[...C])if(G.sessionID===Y)w(H);for(let[H,G]of[...u])if(G.affinity===Y)u.delete(H);J.forgetSession?.(Y)},get pendingSendCount(){return P.size},get heldCredentialCount(){let Y=0;for(let H of P.values())if(H.oauth)Y++;return Y},get heldRedactorCount(){return C.size},get operationsInProgress(){let Y=0;for(let H of U.values())Y+=H.size;return Y}}}import{createHash as N8}from"node:crypto";import{setTimeout as _8}from"node:timers/promises";import{CacheKeepManager as H8,CacheKeepPrewarmError as m1,CacheKeepSessionRegistry as F8,CacheKeepWarmRefusal as F1,currentCacheKeepRealTurn as P8,getCacheKeepRegistryDirectories as L8,isCacheKeepActiveNow as C0,isCacheKeepHybridActive as Q1,isCacheKeepSubagentsEnabled as a2,isCacheKeepWarmWait as C8,logger as c2,NativeAccountRefusal as n2,nativeAccountCanServe as x0,nativeAccountRefusal as O8,readSessionCachePolicy as g2,requestCacheLifetimeMs as O0,sessionCacheActivity as T8}from"@cortexkit/anthropic-auth-core";import{CacheKeepStore as K8}from"@cortexkit/anthropic-auth-core";var H1="2.14.1";import{cacheKeepStoreDirectory as C6,legacyCacheKeepStoreDirectory as O6}from"@cortexkit/anthropic-auth-core";class h1 extends K8{constructor($,J){super({...$,pluginVersion:H1},J)}}var k0=new WeakMap;function X1($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}function E8($,J){if(!$)return"foreign-identity";try{let K=JSON.parse($);if(!Array.isArray(K))return"foreign-identity";let[Q,,O,q,D]=K;if(Q==="local"&&typeof q==="string"&&typeof D==="string")return J.some((F)=>F.binding?.storageId===q&&F.binding.rowId===D)?"foreign-identity":"account-gone";if(Q==="vault"&&typeof O==="string")return J.some((F)=>F.credentialId===O)?"foreign-identity":"account-gone"}catch{}return"foreign-identity"}function q0($,J,K){if(!K){$.hybridDisabled=!1;return}let Q=(D)=>g2(D,!0)?.keep_warm!==void 0,O=!1;for(let D of $.manager.trackedSessions())if(Q(D.id)||$.manager.hasPlannedTarget?.(D.id))O=!0;else $.manager.untrack(D.id,"disabled");if($.hybridDisabled)return;$.hybridDisabled=!0;let q=$.persistence;$.localCleanup=($.localCleanup??Promise.resolve()).then(async()=>{await q.drain(),await q.load(J,(F)=>{if(!$.hybridDisabled)return;if(F.policyState?.planned||Q(F.policyState?.ownerSessionId??F.id)){O=!0;return}return q.removed(F.id),"invalid"});let D=$.manager.trackedSessions().some((F)=>Q(F.id)||$.manager.hasPlannedTarget?.(F.id));if(!O&&!D&&$.hybridDisabled)q.clear()}).catch(()=>c2.warn("cachekeep","local restart cleanup failed"))}var T0=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2"),E0=Symbol.for("cortexkit.anthropic-auth.opencode2.legacy-turn-rules");function S0(){let $=globalThis;return $[T0]??=new Map,$[T0]}function x8($,J,K){let Q=new Map,O=new Map,q=new Set,D=0,F=new F8({...L8("opencode",J.registryDirectory),now:J.now}),z=()=>{let C;for(let m of O.values())C=m;return C},P=J.setIntervalImpl??globalThis.setInterval,W=new H8({loadStorage:async()=>{let C=z(),m=C?await C.loadStorage():null;if(C)q0(L,J.now?.()??Date.now(),!Q1(m));return m},now:J.now,setIntervalImpl:(C,m)=>P(()=>{let y=W.tick();return L.ticking=y.catch(()=>{c2.warn("cachekeep","tick failed")}),L.ticking},m),clearIntervalImpl:J.clearIntervalImpl,setTimeoutImpl:J.setTimeoutImpl,clearTimeoutImpl:J.clearTimeoutImpl,reserveWarm:(C)=>L.persistence.reserveWarm(C),settleWarm:(C)=>W.isCurrentTarget(C)?L.persistence.reserveWarm(C):Promise.resolve(!1),deferWarmReservation:!0,responseTtlMs:(C)=>k0.get(C),onTargetChanged:(C)=>L.persistence.changed(C),onTargetRemoved:(C)=>{q.delete(C),L.persistence.removed(C)},onTrackedSessionsChanged:(C)=>F.publish(O.size===0?[]:C),prepareHeaders(C,m,y){let b=z();if(!b)return;return Q.set(y.id,{target:m,attempt:y,lease:b}),new Headers({"x-native-cachekeep-attempt":String(y.id)})},fetchImpl:async(C,m)=>{let y=new Request(C,m),b=Number(y.headers.get("x-native-cachekeep-attempt")),w=Q.get(b);if(Q.delete(b),!w||w.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(q.delete(w.target.id)){let M=J.now?.()??Date.now(),d=Math.max(M,D+3000);D=d,await(J.delayImpl??_8)(Math.max(0,d-M),void 0,{signal:w.attempt.signal})}let n=w.lease.send(w.target,y,w.attempt.signal,w.attempt.onResponseHeaders),X2=n.then(()=>{},()=>{});return w.lease.inflight.add(X2),X2.then(()=>w.lease.inflight.delete(X2)),n},onComplete:({attempt:C})=>{Q.delete(C.id)}}),_,k=()=>{if(_!==void 0)clearTimeout(_);_=void 0},E=()=>{if(k(),O.size>0)return;let C=W.dropExpiredTargets();if(C===void 0){let y=S0();if(y.get($)===L)y.delete($);return}let m=J.now?.()??Date.now();if(_=setTimeout(E,Math.max(0,C-m)),typeof _==="object"&&"unref"in _)_.unref()},L={manager:W,registry:F,persistence:K,persistenceFollowsOwner:!0,prepared:Q,leases:O,nextGeneration:0,async retain(){W.stop(),W.abortWarms(),Q.clear(),await W.drain(),E()},async adopt(){if(k(),L.loading??=(async()=>{let C=z();if(!C)return;let m=await C.read(),y=J.now?.()??Date.now(),b=0;await L.persistence.load(y,(w)=>{if(!O.size||W.trackedRequest(w?.id))return;if(w.cacheExpiresAt<=y)return"expired";if(!Q1(m.policyStorage)&&!w.policyState?.planned&&g2(w.policyState?.ownerSessionId??w.id,!0)?.keep_warm===void 0)return"invalid";let n=m.accounts.find((d)=>X1(d)===w.oauthAccountIdentity);if(!n)return E8(w.oauthAccountIdentity,m.accounts);if(n.type!=="oauth"||!x0(n))return"account-gone";if(w.isSubagent&&!w.policyState?.planned&&g2(w.policyState?.ownerSessionId??w.id,!0)?.keep_warm===void 0&&!a2(m.policyStorage))return"invalid";let X2=w.nextPrewarmAt<=y?y+b++*3000:w.nextPrewarmAt,M=W.track({sessionId:w.id,url:w.url,headers:new Headers,bodyText:w.bodyText,storage:m.policyStorage,cacheMode:"hybrid",oauthAccountId:n.id,oauthAccountIdentity:w.oauthAccountIdentity,isSubagent:w.isSubagent,retained:{cacheExpiresAt:w.cacheExpiresAt,nextPrewarmAt:X2,ttlMs:w.ttlMs,lastTouchAt:w.lastTouchAt,lastTouchKind:w.lastTouchKind,policyState:w.policyState}});if(M.tracked)q.add(w.id);return M.tracked?!0:"invalid"},void 0,(w)=>O.size>0&&!W.trackedSessions().some(({id:n})=>N8("sha256").update(n).digest("hex")===w))})().catch(()=>{c2.warn("cachekeep","failed to restore tracked sessions")}),await L.loading,!O.size)return;if(W.dropExpiredTargets()===void 0)return;W.start(),F.publish(W.registrySessions?.()??W.trackedSessions()).catch(()=>{c2.warn("cachekeep","failed to publish tracked sessions")})}};return L}function A0($){let{runtime:J,source:K}=$,Q=new AbortController,O=S0(),q=O.get($.storageId),D=new h1({storageId:$.storageId,...$.persistence},q?.persistence),F=q??x8($.storageId,$,D);if(q&&!q.persistenceFollowsOwner){F.legacyPersistence??=F.persistence;let M=F.legacyPersistence;M.changed=(d)=>D.changed(d),M.removed=(d)=>D.removed(d),M.clear=()=>D.clear(),M.load=(d,v)=>D.load(d,v)}F.persistence=D,O.set($.storageId,F);let{manager:z,registry:P}=F,W=new Set,_=(M)=>{if(M.kind!=="primary"||M.agent==="cachekeep"||M.agent==="prime")return;try{if(z.beginRealTurn){for(let u of W)if(!u.active)W.delete(u);let v=z.beginRealTurn(M.sessionID);return W.add(v),v}let d=globalThis;if(!d[E0])d[E0]=!0,c2.info("cachekeep","new real-turn warming rules apply after a server restart")}catch{}return},k=new Map,E=async(M,d)=>{let v=k.get(M),u=()=>!b.stopped&&v!==void 0&&z.trackedPolicyState?.(M)===v;if(!u())return;if(!d){z.updateSubagent?.(M,!1);return}let c=()=>[...F.leases.values()].at(-1),s=c(),t=await s?.loadStorage();if(!u()||!s||c()!==s)return;if(t&&g2(M,!0)?.keep_warm===void 0&&!a2(t))z.untrack(M,"policy-refused"),k.delete(M);else z.updateSubagent?.(M,d)},L=new Map,C=(M)=>{let d=L.get(M);return L.delete(M),d?.signal?.removeEventListener("abort",d.onAbort),d},m=(M)=>{let d=C(M);try{d?.turn?.finish()}catch{}return d?.target},y=async(M,d,v,u)=>{let c=v?AbortSignal.any([Q.signal,v]):Q.signal;if(c.aborted)throw new m1("authorization",c.reason);let s=await d.text(),t;if(!z.reserveWarmDispatch&&(M.policyState?.planned||g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm!==void 0)){if(!F.plannedUnsupportedLogged)F.plannedUnsupportedLogged=!0,c2.debug("cachekeep","planned warming requires a server restart after an older owner reload");throw new F1("unsupported")}let I=JSON.parse(s),i={providerID:"anthropic",modelID:I.model,sessionID:`oc2-cachekeep:${M.id}`,agent:"cachekeep",kind:"generate"},j2=(V)=>{throw new n2(V)},H2=O0(s),T2=J1({source:{...K,quotaFromHeaders(V,U){return K.quotaFromHeaders?.(V,{...U,reportRouting:!1})},billingRequest(V){let U=K.billingRequest?.(V);return U?{...U,sessionId:M.policyState?.ownerSessionId??M.id,requestKind:"keep_warm",cache:{warming:{on:!0}}}:void 0},onRequestPrepared:void 0,onFinalRequestPrepared:({ttlMs:V})=>{H2=V},responseOptions:void 0,async requestOptions(V){return{...await K.requestOptions?.(V,j2),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(V,U){let h=await J.read();t=h.policyStorage,c.throwIfAborted();let S=h.accounts.find((Z2)=>Z2.id===U);if(S?.type!=="oauth"||!x0(S))throw new n2("account-unavailable");if(X1(S)!==M.oauthAccountIdentity)throw new n2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!a2(h.policyStorage)||!Q1(h.policyStorage)||!C0(h.policyStorage,new Date($.now?.()??Date.now()))))return;let R=await K.authorizeAccount(V,U,j2);if(R?.provenance.kind==="local"&&X1({...S,binding:R.provenance.subject.binding,accountIdentity:R.provenance.subject.binding.identity})!==M.oauthAccountIdentity)throw new n2("credential-changed");if(R?.provenance.kind==="vault"&&R.provenance.credentialId!==S.credentialId)throw new n2("credential-changed");return R},async admitRequest(V){await K.admitRequest?.(V,j2);let U=await J.read();t=U.policyStorage;let h=U.accounts.find((S)=>S.id===V.accountId);if(c.throwIfAborted(),!h)throw new n2("account-unavailable");if(X1(h)!==M.oauthAccountIdentity)throw new n2("credential-changed");if(!M.policyState?.planned&&(M.isSubagent&&g2(M.policyState?.ownerSessionId??M.id,!0)?.keep_warm===void 0&&!a2(U.policyStorage)||!Q1(U.policyStorage)||!C0(U.policyStorage,new Date($.now?.()??Date.now()))))throw Error("CacheKeep policy changed before dispatch")}}}),F2,k2,R2="authorization",X=!1,j=()=>T2.forgetSession(i.sessionID);c.addEventListener("abort",j,{once:!0});try{let V=await J.read();t=V.policyStorage;let U=M.policyState?.ownerSessionId??M.id,h=z.trackedRequest(U)?.bodyText,S=h?JSON.parse(h).model:I.model,R=z.trackedRequest(M.id)?K.peekAccount?.(U,S,V):void 0;if(R!==void 0&&R!==(M.oauthAccountId??"main"))throw new F1("routing-moved");let Z2=V.accounts.find((H)=>X1(H)===M.oauthAccountIdentity)?.id;if(!Z2)throw new n2(V.accounts.some((H)=>H.id===M.oauthAccountId)?"credential-changed":"account-unavailable");let W2=await T2.adapter.accountHeaders({...i,accountId:Z2});if(!("headers"in W2)||typeof W2.headers!=="object"||W2.headers===null||typeof W2.attempt!=="object"||W2.attempt===null||W2.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");F2={...i,accountId:Z2,attemptId:crypto.randomUUID(),transport:"http",data:W2.attempt};let G2=await T2.adapter.rewriteRequest?.({...i,accountId:Z2,attempt:F2,request:new Request(M.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(I),signal:c})});if(!G2)throw Error("CacheKeep rewrite refused");c.throwIfAborted();let P2=M.policyState?.ownerSessionId??M.id,K2=M.policyState?.planned===!0||g2(P2,!0)?.keep_warm!==void 0,o=K2?void 0:$.subagent?.(P2);if(!K2&&$.subagent&&o===void 0)throw new m1("authorization",void 0);if(o&&!a2(t))throw new F1("subagents-disabled");await z.reserveWarmDispatch?.(M),c.throwIfAborted(),R2="send";let Q2=await($.fetch??fetch)(G2);try{u?.()}catch{}R2="response",k2=Q2.status;let Y2=await T2.adapter.rewriteResponse?.({...i,accountId:Z2,attempt:F2,request:G2,response:Q2});if(!Y2)throw Error("CacheKeep response rewrite refused");if(k2=Y2.status,T2.adapter.quotaFromHeaders?.(Y2.headers,Y2.status,F2),!Y2.ok)await T2.adapter.limitFromResponse?.({status:k2,headers:Y2.headers,body:()=>Y2.clone().text(),attempt:F2});let N2=await Y2.arrayBuffer();if(Y2.ok&&!c.aborted&&!M.sourceWarm&&(z.isCurrentTarget?.(M)??!0))T8.recordPrewarm(M.id,Z2,$.now?.()??Date.now(),H2);X=!0;let Y=new Response(N2,{status:k2,headers:Y2.headers});return k0.set(Y,H2),Y}catch(V){if(V instanceof F1||C8(V))throw V;let U=O8(V);if(U)throw U;throw new m1(R2,V,k2)}finally{if(c.removeEventListener("abort",j),F2?.data&&R2==="authorization")T2.discardUnsentBilling(F2.data);try{if(F2)await T2.adapter.onAttemptEnd?.(F2,{status:k2,outputStarted:!1,...X?{}:{error:{reason:"cancelled"}}})}finally{T2.dispose(),K.forgetSession?.(i.sessionID)}}},b={generation:F.nextGeneration++,stopped:!1,loadStorage:async()=>(await J.read()).policyStorage,send:y,inflight:new Set,read:()=>J.read(),subagent:$.subagent},w=F.leases.size===0;F.leases.set(b.generation,b);let n=(w?F.adopt():F.loading??Promise.resolve()).then(()=>{if(!b.stopped)for(let M of z.trackedSessions())$.subagent?.(M.id)}),X2;return{ready:n,beginRealTurn:_,async track(M){let d=M.kind==="primary"&&M.agent!=="cachekeep"&&M.agent!=="prime"?P8():void 0;try{d??=!b.stopped?_(M):void 0}catch{}let v=(T2)=>{try{if(d?.finish(),!z.beginRealTurn&&!b.stopped&&!M.signal?.aborted&&M.kind==="primary"&&M.agent!=="prime"&&M.agent!=="cachekeep"){let F2=Reflect.get(z,"untrackRestored");if(typeof F2==="function")F2.call(z,M.sessionID)}}catch{}m(M.attemptId),c2.debug("cachekeep","tracking skipped",{session:M.sessionID,reason:T2})};if(b.stopped)return v("lease-stopped");if(M.route!=="oauth")return v("not-oauth");if(M.agent==="cachekeep"||M.agent==="prime")return v("background-agent");if(M.kind!=="primary")return v("not-primary");if(M.signal?.aborted)return v("attempt-ended");let u=C(M.attemptId);try{if(u?.turn!==d)u?.turn?.finish()}catch{}let c={sessionID:M.sessionID,signal:M.signal,onAbort:()=>m(M.attemptId),turn:d};L.set(M.attemptId,c),M.signal?.addEventListener("abort",c.onAbort,{once:!0});let s=M.admission?.snapshot??await J.read();if(b.stopped)return v("lease-stopped");let t=g2(M.sessionID,!0);if(t?.keep_warm!==void 0&&!z.reserveWarmDispatch){if(!F.plannedUnsupportedLogged)F.plannedUnsupportedLogged=!0,c2.debug("cachekeep","planned warming requires a server restart after an older owner reload");return v("planned-owner-requires-restart")}let I=Q1(s.policyStorage),i=!I&&z.trackedSessions().some(({id:T2})=>T2===M.sessionID);if(q0(F,$.now?.()??Date.now(),!I),!I){if(t?.keep_warm===void 0){if(!i)z.recordWarmingOff?.(M.sessionID);return v("hybrid-inactive")}}let j2=!1;try{j2=$.subagent?$.subagent(M.sessionID)??!1:await $.isSubagent?.(M.sessionID)??!1}catch{return v("session-lookup-failed")}if(b.stopped)return v("lease-stopped");if(t?.keep_warm===void 0&&j2&&!a2(s.policyStorage))return z.recordWarmingOff?.(M.sessionID),v("subagents-disabled");let H2=M.admission?.account??s.accounts.find((T2)=>T2.id===M.accountId);if(!H2?.accountIdentity)return v("account-identity-missing");if(M.provenance.kind==="local"&&JSON.stringify(H2.binding)!==JSON.stringify(M.provenance.subject.binding))return v("local-binding-changed");if(M.provenance.kind==="vault"&&H2.credentialId!==M.provenance.credentialId)return v("vault-credential-changed");if(L.get(M.attemptId)!==c)return v("attempt-ended");c.target={sessionId:M.sessionID,url:M.url,headers:new Headers,bodyText:M.bodyText,storage:s.policyStorage,cacheMode:"hybrid",oauthAccountId:M.accountId,oauthAccountIdentity:X1(H2),isSubagent:j2,ttlMs:O0(M.bodyText)||(g2(M.sessionID,!0)?.ttl!==void 0?0:void 0)}},onResponseHeaders(M){let d=C(M.attemptId),v=d?.target;try{if(!b.stopped&&M.status>=200&&M.status<300&&v){let u=v.sessionId;if(!u)return;let c=$.subagent?.(u);if(c!==void 0)v.isSubagent=c;if(v.isSubagent&&g2(u,!0)?.keep_warm===void 0&&!a2(v.storage)){if(d?.turn)d.turn.finish();else if(!z.untrack(u,"policy-refused"))z.recordWarmingOff?.(u);return}let s=((d?.turn)?d.turn.track.bind(d.turn):z.track.bind(z))({...v,acceptedUsage:M.acceptedUsage,...M.acceptedAt!==void 0&&{acceptedAt:M.acceptedAt},...M.ttlMs!==void 0&&{ttlMs:M.ttlMs}});if(s.tracked){for(let I of F.leases.values())I.subagent?.(u);k.delete(u);let t=z.trackedPolicyState?.(u);if(t)k.set(u,t);if(k.size>4096){let I=k.keys().next().value;if(I!==void 0)k.delete(I)}}if(s.tracked)P.publish(z.registrySessions?.()??z.trackedSessions()).catch(()=>{c2.warn("cachekeep","failed to publish tracked sessions")});return s}}finally{try{d?.turn?.finish()}catch{}}},discardAttempt(M){m(M)},warming(M){if(M.route!=="oauth")return{on:!1};return z.warming?.(M.sessionID)},recordAcceptedUsage(M,d,v){z.recordAcceptedUsage?.(M,d,v)},resolvedParent:E,forgetSession(M){k.delete(M),z.untrack(M);for(let[d,v]of L)if(v.sessionID===M)m(d)},registry:P,dispose(){if(X2)return X2;b.stopped=!0;for(let u of W)try{u.pause()}catch{}W.clear();for(let u of L.keys())C(u);Q.abort();for(let[u,c]of F.prepared)if(c.lease===b)F.prepared.delete(u);let M=F.leases.delete(b.generation)&&F.leases.size===0,d=M?F.ticking:void 0,v=M?F.retain():void 0;return X2=(async()=>{try{if(M)await v,await d;await n,await Promise.all(b.inflight),await F.persistence.drain()}finally{if(M&&F.leases.size===0)await P.dispose()}})(),X2}}}import{AsyncLocalStorage as k8}from"node:async_hooks";import{clampHostRetryMs as q8,hostRetryResponse as S8,runWithRequestSignal as A8,withCacheKeepRealTurn as R8,withSessionCacheReportHandoff as b8}from"@cortexkit/anthropic-auth-core";async function R0($,J,K){let Q=J1(J),O=new Set,q=new k8,D=new Map,F={...Q.adapter,rewriteRequest(b){let w=q.getStore();if(w)w.route=b.attempt.data?.route,w.attemptId=b.attempt.attemptId,D.set(b.attempt.attemptId,w.finish);return Q.adapter.rewriteRequest?.(b)},onAttemptEnd(b,w){let n=(async()=>{try{await Q.adapter.onAttemptEnd?.(b,w)}finally{let X2=D.get(b.attemptId);if(D.delete(b.attemptId),b.data?.route!=="oauth"||w.status===void 0||w.status>=400||w.error)try{X2?.()}catch{}}})();return O.add(n),n.finally(()=>O.delete(n)).catch(()=>{}),n}},z=async()=>{await Promise.allSettled([...O])},P=[],W=new WeakMap,_=async(b,w,n)=>{let X2=await $.session.hook(b,async(M)=>{if(b==="http.response")return b8(async()=>{let i=!1;try{let j2=await w(M);return i=!0,j2}finally{if("request"in M&&M.request instanceof Request)try{let j2="response"in M&&M.response instanceof Response?M.response:void 0;J.source.onResponseHandedToHost?.(M.request,i&&j2?Q.acceptedResponse(j2):void 0)}catch{}if("response"in M&&M.response instanceof Response)M.response=S8(M.response);if("request"in M&&M.request instanceof Request)try{W.get(M.request)?.()}catch{}}})();if(b==="retry"){let i=await w(M);if("decision"in M&&M.decision.retry)M.decision.delay=q8(M.decision.delay);return i}if(b!=="http.request")return w(M);let d="request"in M&&M.request instanceof Request?M.request.signal:void 0,v=M,u,c,s,t=()=>{try{u?.finish()}catch{}if(d?.removeEventListener("abort",t),s?.attemptId)D.delete(s.attemptId);if(c)W.delete(c)};s={finish:t};try{if(v.model.providerID==="anthropic"){if(u=J.source.beginRealTurn?.({sessionID:v.sessionID,providerID:v.model.providerID,modelID:v.model.id,agent:v.agent,kind:v.kind}),K.credential(v.request.headers)!==m2("anthropic"))t()}}catch{t()}if(d?.addEventListener("abort",t,{once:!0}),d?.aborted)t();let I=!1;try{let i=await A8(d,()=>q.run(s,()=>R8(u,async()=>w(M))));if(I=!0,u)c=v.request,W.set(c,t);return i}finally{if(!I||s.route!=="oauth")t()}},n);return P.push(X2),X2},k=new AbortController,E;try{E=await w1({session:{hook:_},event:$.event},F,{logger:J.log,gateOnPlaceholder:K})}catch(b){throw Q.dispose(),await Promise.allSettled(P.map((w)=>w.dispose())),b}let L=(b)=>{Q.forgetSession(b),E.forgetSession(b)},C=$.event,m=C?(async()=>{try{for await(let b of C.subscribe({signal:k.signal})){if(b.type==="session.deleted")L(b.data.sessionID);if(b.type==="session.idle"||b.type==="session.status"&&b.data.status.type==="idle")J.source.forgetTurn?.(b.data.sessionID)}}catch(b){if(!k.signal.aborted)J.log?.warn("stopped listening for session deletion",{error:b instanceof Error?b.name:"unknown"})}})():Promise.resolve(),y;return{installation:E,forgetSession:L,drain:z,dispose(){if(y)return y;return Q.dispose(),k.abort(),y=(async()=>{await E.dispose(),await m,await z()})(),y}}}import{effectiveRelayTransport as b0,getQuotaCheckIntervalMs as D8,logger as w8,nativeAccountCanServe as I8,oauthProfileIsFresh as v8,quotaSnapshotCheckedAt as f8,readThreeWayBoolean as y8}from"@cortexkit/anthropic-auth-core";function D0($,J){let K=new AbortController,Q,O=!1,q=async()=>{let z=await $.read();if(K.signal.throwIfAborted(),z.policyStorage.relay?.enabled===!0&&b0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="websocket")return;let P=z,W=D8(P.policyStorage);for(let _ of P.accounts){if(K.signal.aborted)return;if(!I8(_)||_.type!=="oauth")continue;if(y8(P.policyStorage.quota?.enabled,!0)&&Date.now()-f8(_.quota)>=W)await $.fetchQuota(_.id,J,K.signal,void 0,"background").catch(()=>{});if(!v8(_.profile)&&!K.signal.aborted)await $.fetchProfile(_.id,J,K.signal).catch(()=>{})}},D=()=>{if(O||Q)return Q;return Q=q().catch(()=>{if(!K.signal.aborted)w8.debug("opencode2","native background readings did not complete")}).finally(()=>{Q=void 0}),Q},F=$.vault.watch({intervalMs:60000,onRefresh:D,shouldRefresh:async()=>{let z=await $.read();return z.policyStorage.relay?.enabled!==!0||b0(z.policyStorage.relay.transport,z.policyStorage.relay.url)==="http"}});return F.ready.catch(()=>{}),{async dispose(){O=!0,F.close(),K.abort(),await Q}}}import{authorize as r8,buildCacheKeepStatusSummary as s8,buildClaudeQuotaSummary as a8,buildPrimeAccountStatuses as t8,buildPrimeStatusSummary as e8,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as $$,claudeGatewayStatusNotes as Z$,effectiveRelayTransport as J$,exchange as X$,formatNativeAccountState as j$,formatOAuthAccountTier as Y$,getCacheKeepWindow as V$,getHostClaustrumEnrollmentPaths as G$,isCacheKeepAlways as Q$,isCacheKeepHybridActive as W$,isCacheKeepPersistentlyEnabled as M$,isVaultHosted as B$,nativeAccountCanServe as U$,nativeCacheKeepAlways as z$,parseLogLevel as K$,resetClaustrumEnrollmentState as N$,setDumpEnabled as _$,VAULT_HOST_CONNECT_REFUSAL as H$}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as g8,effectiveRelayStatus as h8,formatNativeAccountState as m8,formatOAuthAccountTier as w0,getCacheKeepWindow as l8,getRoutingMode as d8,isCacheKeepAlways as u8,isCacheKeepHybridActive as p8,isPermanentRefreshError as c8,isPrimePersistentlyEnabled as i8,nativeAccountCanServe as f0,refreshBackoffActive as I0}from"@cortexkit/anthropic-auth-core";var v0=($)=>f0($)&&$.state!=="unsupported-access"?void 0:m8($)||void 0,o8=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return f0($)?"on-vault-served":"on-cold"},n8=($,J)=>typeof $==="number"&&$>J;function y0($,J){let{now:K}=J,Q=$.policyStorage,O=$.accounts.filter((W)=>W.type==="oauth"),q=O.find((W)=>W.id==="main"),D=q?v0(q):void 0,F=q?.lastQuotaRefreshError?.nextRetryAt,z=q?.lastRefreshError,P=l8(Q);return P1({main:{quota:q?.quota??null,enabled:q?.enabled,tierLabel:w0(q?.profile),quotaBackedOff:n8(F,K),quotaBackoffUntil:F,refreshBackedOff:I0(z,q?.accountIdentity,K,void 0),refreshBackoffUntil:z?.nextRetryAt,stateLine:D,quotaDated:Boolean(D)},fallbacks:O.filter((W)=>W.id!=="main"&&(W.enabled||W.source==="vault")).map((W)=>{let _=v0(W),k=o8(W);return{id:W.id,label:W.label,quota:W.quota??null,enabled:W.enabled,tierLabel:w0(W.profile),needsReauth:c8(W.lastRefreshError)&&I0(W.lastRefreshError,W.accountIdentity,K,void 0),...k==="on-vault-reauth"?{vaultReauth:!0}:{},...k==="on-vault-served"?{vaultServed:!0}:{},...k!=="off"?{custodyState:k}:{},stateLine:_,quotaDated:Boolean(_)}}),...J.activeId!==void 0&&{activeId:J.activeId},route:d8(Q),relay:h8(Q.relay),fastMode:Q.claudeFast?.enabled===!0,cacheKeep:{enabled:p8(Q),...u8(Q)?{window:"always"}:P&&{window:`${P.startHour}-${P.endHour}`},trackedSessions:J.trackedSessions},prime:i8(Q)?{enabled:!0,accounts:g8(Q,{now:K})}:void 0,lastUpdated:K})}var l1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},g0=`For first-time model access, connect Anthropic with "${O1}".
|
|
4
4
|
Run: opencode auth login anthropic --method ${C1}`,F$="No Claude accounts in the vault for this host yet. Add one with `ck auth login --provider anthropic`, then grant it to this host.",h0="The vault returned an account this plugin cannot use yet.";async function P$($){let J=new AbortController,K;try{return await Promise.race([$.vault.refresh(J.signal).then(()=>"complete",()=>"failed"),new Promise((Q)=>{K=setTimeout(()=>{Q("pending"),J.abort()},2000)})])}finally{clearTimeout(K)}}var m0=($)=>$.mode==="local"&&!$.accounts.some((J)=>J.id==="main"),L$=($)=>{let J=$.id==="main"?"main":"fallback",K=`${$.enabled?"enabled":"disabled"}, ${$.type}, ${$.source}${$.state?`, ${j$($)}`:""}`;if($.label)return`${$.label} [${J}]: ${K}
|
|
5
5
|
Route: ${$.id}`;return`${J==="main"?"Main account":`Fallback ${$.id}`}: ${K}`};function l0($){let{runtime:J,source:K}=$,Q=new Map,O=!1,q=async(_,k)=>{return J.updateSettings((E)=>({...E,[_]:{...l1(E[_]),...k}}))},D=()=>({ok:!0,text:"Native Claude settings updated."}),F=(_)=>_.outcome==="refused"||_.outcome==="failed"?{ok:!1,text:_.reason}:D(),z=async(_)=>{let k=J.getSettingsStatus?.();if(!k)return[_,`Settings file: ${await J.getSettingsPath()}`,...J.getRelayStatusNotes?.()??[]].join(`
|
|
6
6
|
`);let{file:E}=k;return[_,`Settings file: ${E.file}`,...E.missing?["Settings file is missing; a menu change recreates it when both hosts' protection can be read."]:[`Settings file state: ${E.state}`],...E.recreated?["Settings file was recreated by a menu write."]:[],...E.invalidKeys.map((L)=>`Invalid setting: ${L}`),...E.ignoredModelKeys.map(({setting:L,model:C})=>`Ignored model key: ${L}.${C}`),...E.duplicateKeys.map((L)=>`Duplicate setting: ${L}`),...Z$(E.gatewayIgnored,k.values.gateway),...J.getRelayStatusNotes?.()??[],"Settings (no model):",...Object.entries(k.values).map(([L,C])=>` ${L}: ${JSON.stringify(C)}`),...Object.entries(k.modelOverrides).flatMap(([L,C])=>(C??[]).map(({model:m,value:y})=>` ${L} [${m}]: ${JSON.stringify(y)}`))].join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "2.14.
|
|
3
|
+
"version": "2.14.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@clack/prompts": "^1.6.0",
|
|
80
|
-
"@cortexkit/anthropic-auth-core": "2.14.
|
|
80
|
+
"@cortexkit/anthropic-auth-core": "2.14.1",
|
|
81
81
|
"@cortexkit/claustrum-client": "0.18.0",
|
|
82
82
|
"@cortexkit/private-files": "0.2.2",
|
|
83
83
|
"@cortexkit/subc-client": "^0.24",
|