@cortexkit/opencode-anthropic-auth 2.2.5 → 2.2.6
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.
|
@@ -20,7 +20,7 @@ data: ${JSON.stringify(J)}
|
|
|
20
20
|
`);if(J===-1)return Y===-1?null:{index:Y,length:4};if(Y===-1||J<Y)return{index:J,length:2};return{index:Y,length:4}}function Y7($,J,Y,X){if(!J||$.disabled)return;$.pending+=J;while(!0){let V=y1($.pending);if(!V)break;let O=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let K=oJ(O);if(!K)continue;if($.events++,_9($.eventCounts,K.event??"unknown"),_9($.typeCounts,K.type),_9($.deltaTypeCounts,K.deltaType),_9($.contentBlockTypeCounts,K.contentBlockType),$.textDeltaBytes+=K.textDeltaBytes??0,$.thinkingDeltaBytes+=K.thinkingDeltaBytes??0,$.inputJsonDeltaBytes+=K.inputJsonDeltaBytes??0,$.signatureDeltaBytes+=K.signatureDeltaBytes??0,$.redactedThinkingBytes+=K.redactedThinkingBytes??0,$.last=K,X?.(K),K.dataBytes>0&&!K.type&&!K.event)$.parseErrors++}if(Q7.encode($.pending).byteLength>Y)$.pending="",$.disabled=!0,$.pendingOverflowCount++}function yX(){return{pending:"",completed:!1,disabled:!1,resyncCarry:""}}function mX($,J,Y){if(!J||$.completed)return null;if($.disabled){let V=$.resyncCarry+J,O=y1(V);if(!O)return $.resyncCarry=V.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=V.slice(O.index+O.length),!J)return null}$.pending+=J;let X=null;while(!0){let V=y1($.pending);if(!V)break;let O=$.pending.slice(0,V.index);$.pending=$.pending.slice(V.index+V.length);let K=oJ(O);if(K?.type!=="message_delta"||!K.stopReason)continue;$.completed=!0,X??=K.stopReason==="refusal"?{type:"content-filter"}:{type:"complete",finishReason:K.stopReason}}if(new TextEncoder().encode($.pending).byteLength>Y){let V=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=V.slice(-3)}return X}function cX(){return{pending:"",disabled:!1}}function X7($){let J=oJ($);if(J?.type!=="message_delta"||J.stopReason!=="max_tokens")return $;return $.replace(/("stop_reason"\s*:\s*)"max_tokens"/,'$1"end_turn"')}function pX($,J,Y,X=!1){if(!J&&!X)return"";if($.disabled)return J;if(new TextEncoder().encode($.pending+J).byteLength>Y){let O=$.pending+J;return $.pending="",$.disabled=!0,O}$.pending+=J;let V="";while(!0){let O=y1($.pending);if(!O)break;let K=$.pending.slice(0,O.index),H=$.pending.slice(O.index,O.index+O.length);$.pending=$.pending.slice(O.index+O.length),V+=X7(K),V+=H}if(X&&$.pending)V+=X7($.pending),$.pending="";return V}function lX(){return{pending:"",disabled:!1,resyncCarry:""}}function uX($,J){let Y=$?.toLowerCase(),X=J.toLowerCase();return Y==="api_error"||Y==="overloaded_error"||Y==="server_error"||Y==="internal_server_error"||X.includes("internal server error")||X.includes("server overloaded")}function dX($,J){let Y=$?`${$}: ${J}`:J,X=Error(`Anthropic stream error: ${Y}`);if(X.code="ECONNRESET",X.syscall="anthropic-sse",$)X.providerErrorType=$;return X}function iX($){let J=W7($)?"Opus 5":"Fable",Y=Error(`${J} response was blocked by the provider content filter; retrying with Opus 4.8`);return Y.code="ECONNRESET",Y.syscall="anthropic-sse",Y.providerErrorType="refusal",Y}function nX($){if(!$.includes("error"))return null;let J,Y=[];for(let q of $.split(/\r?\n/)){if(q.startsWith("event:")){J=q.slice(6).trim();continue}if(q.startsWith("data:")){let P=q.slice(5);Y.push(P.startsWith(" ")?P.slice(1):P)}}let X=Y.join(`
|
|
21
21
|
`);if(!X||X==="[DONE]")return null;let V;try{V=JSON.parse(X)}catch{return null}let O=g$(V);if(J!=="error"&&r0(O,"type")!=="error")return null;let K=g$(O?.error),H=r0(K,"type")??r0(K,"code")??void 0,w=r0(K,"message")??r0(O,"message")??H??"Anthropic stream error";if(!uX(H,w))return null;return dX(H,w)}function oX($){if(!$.includes("relay_upstream_error"))return;let J=[];for(let Y of $.split(/\r?\n/))if(Y.startsWith("data:")){let X=Y.slice(5);J.push(X.startsWith(" ")?X.slice(1):X)}if(!J.length)return;try{let Y=g$(JSON.parse(J.join(`
|
|
22
22
|
`))),X=g$(Y?.error);if(r0(X,"type")!=="relay_upstream_error")return;let V=X?.status;if(typeof V==="number"&&Number.isInteger(V))return{status:V,source:"relay_status_field"};let K=r0(X,"message")?.match(/HTTP\s+(\d{3})\b/i);return K?{status:Number(K[1]),source:"relay_message_parse"}:void 0}catch{return}}function G7($,J,Y,X){if(!J)return null;if($.disabled){let O=$.resyncCarry+J,K=y1(O);if(!K)return $.resyncCarry=O.slice(-3),null;if($.disabled=!1,$.resyncCarry="",J=O.slice(K.index+K.length),!J)return null}$.pending+=J;let V=null;while(!0){let O=y1($.pending);if(!O)break;let K=$.pending.slice(0,O.index);$.pending=$.pending.slice(O.index+O.length);let H=oX(K);if(H!==void 0)X?.(H);let w=nX(K);V??=w}if(new TextEncoder().encode($.pending).byteLength>Y){let O=$.pending;$.pending="",$.disabled=!0,$.resyncCarry=O.slice(-3)}return V}function rX($){return{sseEvents:$.events,ssePendingChars:$.pending.length,ssePendingOverflowCount:$.pendingOverflowCount,sseParseErrors:$.parseErrors,sseEventCounts:{...$.eventCounts},sseTypeCounts:{...$.typeCounts},sseDeltaTypeCounts:{...$.deltaTypeCounts},sseContentBlockTypeCounts:{...$.contentBlockTypeCounts},sseTextDeltaBytes:$.textDeltaBytes,sseThinkingDeltaBytes:$.thinkingDeltaBytes,sseInputJsonDeltaBytes:$.inputJsonDeltaBytes,sseSignatureDeltaBytes:$.signatureDeltaBytes,sseRedactedThinkingBytes:$.redactedThinkingBytes,sseLastEvent:$.last?{...$.last}:void 0}}function B7($,J={}){if(!$.body)return $;let Y=$.body.getReader(),X=new TextDecoder("utf-8",{ignoreBOM:!0}),V=new TextEncoder,O=J.responseMode==="json",K=OX(J.toolNameMap,O),H=!0,w="",q=0,P=0,c=0,a=0,u=0,s=!1,T=!1,o=F0(),R0=F0(),W0=J.perf||J.onMessageStart||J.onMessageDelta?bX():void 0,I0="",L0=0,b=!1,O0=(x0)=>{if(!x0)return;try{x0()}catch{}},m0=lX(),R=J.onContentFilter||J.onComplete?yX():void 0,s0=J.laneStart&&J.laneStartOAuthServed!==!1?cX():void 0,q1=!1,q4=!1,R4=(x0=!1)=>{if(!J.onContentFilter)return!1;if(!q1)q1=!0,q4=J.onContentFilter({completedToolUse:x0})!==!1;return q4},$1=J.serverSideFallbackModel?a3({requestedModel:J.serverSideFallbackModel,maxPendingBytes:x$,onOutcome:J.onServerSideFallbackOutcome,onRefusalAfterToolUse:J.onContentFilter?()=>R4(!0):void 0}):void 0,R1=(x0)=>{if(!R)return null;let w$=mX(R,x0,x$);if(w$?.type==="content-filter"&&J.onContentFilter)return R4()?iX(J.contentFilterModel):null;if(w$?.type==="complete")J.onComplete?.(w$.finishReason);return null},M4=(x0,w$=!1)=>s0?pX(s0,x0,x$,w$):x0,_1=()=>{if(T)return;T=!0,Y.releaseLock()},h9=async(x0)=>{try{await Y.cancel(x0)}catch{}finally{_1()}},b9=(x0={})=>({chunks:q,pulls:P,inputBytes:c,outputBytes:a,pendingChars:K.pendingLength(),sseErrorPending:m0.pending.length,sseFinishPending:R?.pending.length??0,sseFinishDisabled:R?.disabled??!1,serverFallbackPending:$1?.pendingLength()??0,rewriteMs:B$(u),totalMs:B$(F0()-R0),...W0?rX(W0):{},...x0}),f$=(x0,w$={})=>{J.perf?.(x0,b9(w$))};J.perf?.("stream_tool_prefix_wrapper_created",{status:$.status,hasBody:!0});let g9=new ReadableStream({async pull(x0){if(P++,!s)s=!0,f$("stream_tool_prefix_first_pull");while(!0){let w$=F0();try{let{done:l1,value:T$}=await Y.read(),a0=B$(F0()-w$);if(l1){let S0=X.decode();if(W0&&!O)Y7(W0,S0,x$,(M0)=>{let L1=M0.message;if(M0.type==="message_start"&&L1)O0(()=>J.onMessageStart?.(L1));if(M0.type==="message_delta"&&(M0.usage||M0.stopReason))O0(()=>J.onMessageDelta?.({...M0.usage?{usage:M0.usage}:{},...M0.stopReason?{stopReason:M0.stopReason}:{}}))});if(O){let M0=V.encode(S0).byteLength;if(L0+M0<=x$)I0+=S0,L0+=M0;else b=!0}if(O&&!b)try{let M0=JSON.parse(I0);if(M0&&typeof M0==="object"&&!Array.isArray(M0))O0(()=>J.onMessageResponse?.(M0))}catch{}let O$=F0(),P0=$1?$1.push(S0)+$1.flush():S0,M1=M4(P0,!0),j1=O?R1(M1):G7(m0,S0,x$,J.onRelayUpstreamError)??R1(M1);if(j1)throw f$("stream_tool_prefix_retryable_error",{providerErrorType:j1.providerErrorType}),await h9(j1),j1;let i1=K.push(M1,!0);if(u+=F0()-O$,i1||w){let M0=V.encode(w+i1);w="",a+=M0.byteLength,x0.enqueue(M0)}if(f$("stream_tool_prefix_rewrite",{readMs:a0}),_1(),J.onStreamEnd)try{await J.onStreamEnd()}catch{}x0.close();return}q++,c+=T$.byteLength;let b0=X.decode(T$,{stream:!0});if(H&&b0){if(H=!1,b0.charCodeAt(0)===65279)w=b0[0]??"",b0=b0.slice(1)}if(O){let S0=T$.byteLength;if(L0+S0<=x$)I0+=b0,L0+=S0;else b=!0}if(W0&&!O)Y7(W0,b0,x$,(S0)=>{let O$=S0.message;if(S0.type==="message_start"&&O$)O0(()=>J.onMessageStart?.(O$));if(S0.type==="message_delta"&&(S0.usage||S0.stopReason))O0(()=>J.onMessageDelta?.({...S0.usage?{usage:S0.usage}:{},...S0.stopReason?{stopReason:S0.stopReason}:{}}))});let y9=F0(),u1=$1?$1.push(b0):b0,d1=M4(u1),W$=O?R1(d1):G7(m0,b0,x$,J.onRelayUpstreamError)??R1(d1);if(W$)throw f$("stream_tool_prefix_retryable_error",{providerErrorType:W$.providerErrorType,readMs:a0,lastChunkBytes:T$.byteLength}),_1(),W$;let J1=K.push(d1);if(u+=F0()-y9,J1){let S0=V.encode(w+J1);w="",a+=S0.byteLength,x0.enqueue(S0)}let Z1=F0();if(q===1||q%25===0||Z1-o>5000)o=Z1,f$("stream_tool_prefix_progress",{readMs:a0,lastChunkBytes:T$.byteLength});if(J1)return}catch(l1){let T$=cJ(l1,J.toolNameMap);if(f$("stream_tool_prefix_error"),T$ instanceof D4)await pJ(Y,T$),T=!0,O0(J.onToolNameRefusal);else _1();throw T$}}},async cancel(x0){f$("stream_tool_prefix_cancel");try{await Y.cancel(x0)}finally{_1()}}});return new Response(g9,{status:$.status,statusText:$.statusText,headers:$.headers})}import{mergeNativeSettingsSection as V2,nativeCacheKeepAlways as z2,nativeSettingsRecord as K2}from"@cortexkit/anthropic-auth-core";var d7="physical send failed before a response",PW="__OPENCODE_ANTHROPIC_AUTH_COMMAND_HANDLED__",i7="~effect/http/HttpServerResponse",n7="~effect/http/Cookies",o7="~effect/http/HttpBody",qW="~effect/ErrorReporter/ignore",RW="https://api.anthropic.com/v1/messages",O8=new WeakSet;function DZ($){let J=new Response(JSON.stringify({type:"error",error:{type:"invalid_request_error",message:$}}),{status:400,headers:{"content-type":"application/json"}});return O8.add(J),J}async function r7($,J){if(!J?.aborted)return;await $.body?.cancel().catch(()=>{}),J.throwIfAborted()}function NZ($,J){return($.status!==400||!O8.has($))&&CW($.status,J)}function s7($){return h.warn("effort-history","refused uncorrelated Fable 5.1 request",{check:$.check,...$.details}),DZ($.message)}function a7($){return h.warn("transform","refused request ending on assistant history",{check:$.check,...$.details}),DZ($.message)}var MW=60000,t7=60000,_8=240,IW=_8,xW=600000;function fW($,J){return($?.accounts??[]).some((Y)=>Y.id===J&&y0(Y)&&B0(Y))}function kW($){let J=($?.accounts??[]).find((Y)=>y0(Y)&&B0(Y));if(e$($)==="fallback-first"&&J)return{activeId:J.id,route:"fallback-first"};return{activeId:"main",route:"main"}}function e7($,J){if($?.activeId==="main"||$?.activeId&&fW(J,$.activeId))return $;return kW(J)}function j8($,J,Y){let X=Date.now()-$.lastUpdated;if(!$.activeId||X<0||X>xW)return e7(Y,J);return e7($,J)}async function vW($,J,Y){let X;try{X=await J()}catch(V){return h.warn("sidebar","account storage reload failed; routing preserved",{message:V instanceof Error?V.message:String(V)}),{...$.activeId?{activeId:$.activeId,route:$.route}:Y??{activeId:"main",route:"main"},freshStorage:null}}return{...j8($,X,Y),freshStorage:X}}async function hW($){await f9()?.beforeStorageLoad?.();let J;try{J=await $()}catch{return{activeId:"main",route:"main",freshStorage:null}}finally{await f9()?.afterStorageLoad?.()}await f9()?.beforeSidebarRead?.();let Y=await z8();return{...j8(Y,J),freshStorage:J}}var bW=4,gW=25,yW=1,$8=!1;function k9(){return process.env.OPENCODE_ANTHROPIC_AUTH_PERF==="1"}function $0(){return performance.now()}function A0($){return Math.round($*10)/10}function J8($){return Math.floor(Math.random()*Math.max(0,$))}function S4($){if(typeof $==="string")return $;if($ instanceof URL)return $.toString();return $.url}function P1($,J){return J?.method??($ instanceof Request?$.method:void 0)}async function C4($,J){if(J?.body!==void 0)return J.body;if(!($ instanceof Request)||$.body===null)return;try{return await $.clone().text()}catch{return}}function mW(){if($8||!1||!k9())return;$8=!0;let $=100,J=250,Y=$0()+$;setInterval(()=>{let X=$0(),V=X-Y;if(Y=X+$,V<J)return;m$("[perf] opencode event_loop_lag",{lagMs:A0(V),thresholdMs:J})},$).unref?.()}function cW($){let J=$0(),Y={requestId:String(yW++),start:J,last:J,mark(X,V){let O=$0();if(k9())m$("[perf] opencode request stage",{requestId:Y.requestId,stage:X,deltaMs:A0(O-Y.last),totalMs:A0(O-Y.start),...V});Y.last=O},done(X,V){let O=$0();if(k9())m$("[perf] opencode request done",{requestId:Y.requestId,stage:X,deltaMs:A0(O-Y.last),totalMs:A0(O-Y.start),...V});Y.last=O}};if(k9())m$("[perf] opencode request start",{requestId:Y.requestId,...$});return Y}function L8($,J){let Y=/^msg_([0-9a-fA-F]{12})/.exec($);if(!Y)return;let X=BigInt(`0x${Y[1]}`);if(X<=0n)return;let O=`msg_${(X-1n).toString(16).padStart(12,"0")}${"z".repeat(14)}`,K=J&&O<=J?`${J}z`:O;if(K.length>128||K>=$)return;return K}async function Z8($,J,Y,X={}){let V=$.client.session,O=await Z9($.client,J),K={path:{id:J},body:{noReply:X.noReply??!0,parts:[{type:"text",text:Y,ignored:!0}]}};if(X.beforeActiveAssistant){let H=X.latestPreparedMessageId?.(),w=O?.latestUserMessageId,q=H&&(!w||H>w)?H:w,P=O?.latestAssistantMessageId?L8(O.latestAssistantMessageId,q):void 0;if(!P)return!1;K.body.messageID=P}if(O?.agent)K.body.agent=O.agent;if(O?.model)K.body.model=O.model;if(O?.variant)K.body.variant=O.variant;if(X.canSend&&!X.canSend())return!1;if(K.body.messageID)X.onPreparedMessageId?.(K.body.messageID);if(typeof V?.promptAsync==="function")return await V.promptAsync(K),!0;if(typeof V?.prompt==="function")return await Promise.resolve(V.prompt(K)),!0;throw Error("OpenCode session prompt API is unavailable for ignored replies.")}function pW(){throw Object.assign(Error(PW),{[i7]:i7,[qW]:!0,status:204,statusText:void 0,headers:{},cookies:{[n7]:n7,cookies:{}},body:{[o7]:o7,_tag:"Empty"}})}function lW($){if($.sessionID==null)return!1;let J=$.model;return J?.providerID==="anthropic"||J?.api?.npm==="@ai-sdk/anthropic"||J?.api?.npm==="@ai-sdk/google-vertex/anthropic"}function uW($){if($.some((J)=>J.includes("<use_parallel_tool_calls>")))return!1;return $.push(JW),!0}var dW={input:0,output:0,cache:{read:0,write:0}},iW=1000;function F$($){return $}function nW($,J){let Y=P4($);return`${Y} content filter detected. Switched to Opus 4.8 for a ${J}-response recovery window before trying ${Y} again.`}function oW($){let J=P4($);return`${J} recovery window complete. Returning to ${J}.`}function P4($){if(nG($))return"Opus 5.5";if(iG($))return"Opus 5";if(dG($)){if($.startsWith("claude-mythos-5-1"))return"Mythos 5.1";if($.startsWith("claude-fable-5-1"))return"Fable 5.1"}if($==="claude-fable-5"||$.startsWith("claude-fable-5-"))return"Fable 5";if($==="claude-opus-4-8"||$.startsWith("claude-opus-4-8-"))return"Opus 4.8";return $}function rW($,J){return`Anthropic safety fallback active: ${P4($)} → ${P4(J)}. Follow-up requests may remain on the fallback model for about one hour.`}function sW($){return`Anthropic safety fallback ended. Returning to ${P4($)}.`}function aW(){return{input:Q9.input,output:Q9.output,cache:{read:Q9.cacheRead,write:Q9.cacheWrite5m},tiers:[{tier:{type:"context",size:_G},input:D9.input,output:D9.output,cache:{read:D9.cacheRead,write:D9.cacheWrite5m}}]}}function tW($){let J=$["claude-opus-4-8"]??$["claude-opus-4-5"]??Object.values($)[0];if(!J)return $;return{...$,...Object.fromEntries(Object.values(KG).map((Y)=>{let X=vG(Y.id),V=X.pricing;return[Y.id,{...J,id:Y.id,name:Y.name,api:J.api?{...J.api,id:Y.id}:void 0,cost:{input:V.input,output:V.output,cache:{read:V.cacheRead,write:V.cacheWrite5m}},limit:{...J.limit??{},context:X.contextWindow,output:X.maxOutputTokens},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:X.releaseDate}]})),...$[U9]?{}:{[U9]:{...J,id:U9,name:"Claude Haiku 5.5",api:J.api?{...J.api,id:U9}:void 0,cost:aW(),limit:{...J.limit??{},context:OG,output:jG},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:LG,variants:v9()}},...$[w9]?{}:{[w9]:{...J,id:w9,name:"Claude Sonnet 5.5",api:J.api?{...J.api,id:w9}:void 0,cost:{input:T9.input,output:T9.output,cache:{read:T9.cacheRead,write:T9.cacheWrite5m}},limit:{...J.limit??{},context:UG,output:QG},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:BG,variants:v9()}},...$[B9]?{}:{[B9]:{...J,id:B9,name:"Claude Opus 5.5",api:J.api?{...J.api,id:B9}:void 0,cost:{input:F9.input,output:F9.output,cache:{read:F9.cacheRead,write:F9.cacheWrite5m}},limit:{...J.limit??{},context:NG,output:HG},capabilities:{...J.capabilities??{},reasoning:!0,attachment:!0,toolcall:!0},release_date:DG,variants:v9()}}}}var eW=["low","medium","high","xhigh","max"];function v9($=eW){return Object.fromEntries($.map((J)=>[J,{thinking:{type:"adaptive",display:"summarized"},effort:J}]))}function $2($){return Object.fromEntries(Object.entries($).map(([J,Y])=>{let X=Y.api?.id??Y.id??J,V=BW(X)?.efforts.variants;return[J,V?{...Y,variants:v9(V)}:Y]}))}function J2($){return Object.fromEntries(Object.entries($).map(([J,Y])=>[J,{...Y,cost:dW}]))}var Z2=2000,HZ="@cortexkit/opencode-anthropic-auth",A4;function Y2(){if(A4!==void 0)return A4;A4=HZ;try{let $=JSON.parse(aX(eX(tX($G(import.meta.url)),"..","package.json"),"utf8"));if($.name===HZ&&typeof $.version==="string"&&$.version.trim())A4=`${HZ}@${$.version.trim()}`}catch{}return A4}function X2(){return["The Claude menu opens in OpenCode's terminal window when the plugin's TUI part is loaded.",`In the terminal, add "${Y2()}" to the plugin list in tui.json (or rerun setup), then restart OpenCode.`,"In OpenCode Desktop, use the text menu below."].join(`
|
|
23
|
-
`)}function G2(){return process.env.OPENCODE_CLIENT==="desktop"}function Y8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var W2=async($,J={})=>{let Y={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??w7;mW();let{client:V}=$,O=globalThis.fetch,K=fG(),H=gG(yG(K)),w=600000,q=50,P=new Map;function c(){let Z=Date.now();for(let[G,W]of P)if(Z-W.createdAt>w)P.delete(G)}function a(Z,G){if(c(),P.size>=q){let W="",z=1/0;for(let[_,L]of P)if(L.createdAt<z)z=L.createdAt,W=_;if(W)P.delete(W)}P.set(Z,G)}function u(Z){c();let G=P.get(Z);if(!G)return;if(Date.now()-G.createdAt>w){P.delete(Z);return}return G}let s=await FW(K),T=JG({paths:s,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),o=T.quotaObservations,R0=null;function W0(Z){return tG(Z)}function I0(Z,G){return Z?W0(Z.binding):G?JSON.stringify([G.credentialId,G.accountIdentity,G.recordVersion]):void 0}function L0(Z,G,W,z=R0){let _=o.get(Z);if(!_||!G||_.lineage!==G||_.accountUuid!==W||w1(_.entry.quota,z,_.entry.checkedAt)<=Date.now())return;return _}function b(Z,G,W,z,_=R0){let L=L0(Z,G,W,_);if(!L)return z;if(!z)return{...L.entry,refreshAfter:w1(L.entry.quota,_,L.entry.checkedAt)};let N=L.entry.quota.source!=="headers"&&E1(z.quota)>E1(L.entry.quota)?z.quota:y7(z.quota,L.entry.quota);return{...L.entry,quota:N,refreshAfter:w1(N,_,E1(N))}}function O0(Z,G,W){if(!o.has(Z.id))return Z.quota;let z=Z.binding?W0(Z.binding):I0(void 0,W),_=E1(Z.quota);return b(Z.id,z,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:_,refreshAfter:w1(Z.quota,G,_)}:null,G)?.quota}let m0;async function R(Z=K){if(Z!==K)throw Error("Native account storage mismatch");let G=await T.read();if(R0=G.policyStorage,!m0){let _=G.accounts.find((L)=>L.id==="main")?.binding;if(_)m0={rowId:_.rowId,credentialEpoch:_.credentialEpoch}}if(G.mode!=="claustrum")return G.policyStorage;let W=G.accounts.find((_)=>_.id==="main"&&_.source==="vault"),z=F$(W?.accountIdentity);return{...G.policyStorage,claustrum:{...G.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:W?.credentialId&&z?{credentialId:W.credentialId,accountId:z,state:W.state??"cold",enabled:W.enabled}:void 0}}}async function s0(Z,G){return await T.updateSettings((W)=>V2(W,Z,G)),R()}let q1=async(Z)=>{return await T.updateSettings((G)=>({...G,claudeCache:{...K2(G.claudeCache),enabled:Z,mode:w4({...G,version:1,accounts:[]})}})),R()},q4=(Z)=>s0("claudeCache",{mode:Z}),R4=(Z)=>s0("cacheKeep",{enabled:Z}),$1=async()=>{return await T.updateSettings(z2),R()},R1=(Z,G)=>s0("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:G}),M4=(Z)=>s0("cacheKeep",{subagents:Z}),_1=(Z)=>s0("dump",{enabled:Z}),h9=(Z)=>s0("claudeFast",{enabled:Z}),b9=async(Z)=>{return await T.setLoggingLevel(Z),R()},f$=(Z,G=K)=>s0("prime",{enabled:Z}),g9=(Z,G=K)=>s0("routing",{mode:Z}),x0=(Z)=>s0("killswitch",Z),w$=(Z,G,W=K)=>T.setEnabled(Z,G),l1=(Z,G=K)=>T.remove(Z),T$=(Z,G=K,W)=>T.reorder(Z,W),a0=null;try{a0=await R()}catch{}function b0(Z){return Boolean(Z&&T4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function y9(Z=K,G=$.directory){if(Z!==K)throw Error("Native vault storage mismatch");return T.vault}let u1=TG("native-auth");async function d1(Z=K){s9?.close(),await u1.drain(),await T.drainQuotaPublications(),await Promise.all([...l9.values()].map((G)=>G.drain())),await T.drainRoutingPublications(),T.close()}function W$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function J1(Z){let G=F$(Z);if(!G)throw Error("Native wire identity requires an admitted provider account");return kG(G,G)}class Z1 extends Error{account;checkIntervalMs;constructor(Z,G){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=G}}class S0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class O$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,G,W=!1,z){super(z?.kind==="provider"&&z.status!==void 0?`Claude OAuth refresh failed: ${z.status} — ${z.classification==="invalid-grant"?"invalid_grant":"OAuth operation failed"}`:`Native OAuth authorization refused: ${G}`);this.account=Z;this.tokenRefreshFailed=W;this.failure=z}}async function P0(Z,G,W,z,_="serve",L){W$(),G?.throwIfAborted();let N=L??await T.read(),j=N.accounts.find((m)=>m.id===Z);if(j?.state==="unsupported-access")throw new S0;if(j?.source==="vault"&&!y0(j))throw new O$(j,"not-active");if(j?.type!=="oauth"||!y0(j))throw Error("Native OAuth account is unavailable");let Q=(m,J0,_0)=>{let f0=O0(m,J0,_0),w0=_==="last-main"&&Z==="main"&&e$(J0)!=="sticky-balanced";if(z&&(r$(J0)&&!a$(f0,J0,Z==="main"?void 0:Z,z)||!w0&&!I9(f0,z)))throw new Z1(m,f7(J0))};Q(j,N.policyStorage);let U;if(j.source==="vault"){let m=await T.authorizeVault(Z,G).catch((J0)=>{if(G?.throwIfAborted(),J0 instanceof sG&&["not-active","route-declined","route-unavailable"].includes(J0.code))throw new O$(j,J0.code);throw J0});U={accessToken:m.accessToken,expires:m.expiresAtMs??void 0,accountIdentity:m.accountIdentity,scopedAttempt:m}}else{let m=await T.authorizeLocal(Z,{signal:G,rejectedAccessToken:W,intent:W?"refresh":_==="last-main"?"serve":_});if(m.status!=="usable")throw new O$(j,m.status,m.status==="failed"&&m.failure.kind==="provider",m.status==="failed"?m.failure:void 0);U={accessToken:m.access,expires:m.expires,accountIdentity:m.binding.identity,localSubject:m.subject,localSource:m.source}}let C=await T.read(),f=C.accounts.find((m)=>m.id===Z);if(G?.aborted)throw G.reason??Error("Request aborted");if(!f||!y0(f)||f.source!==j.source||f.accountIdentity!==U.accountIdentity)throw Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!f.binding||f.binding.storageId!==U.localSubject.binding.storageId||f.binding.rowId!==U.localSubject.binding.rowId||f.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||f.binding.identity!==U.localSubject.binding.identity))throw Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&f.credentialId!==U.scopedAttempt.credentialId)throw Error("Native vault credential binding changed before dispatch");return Q(f,C.policyStorage,U.scopedAttempt),U}async function M1(Z,G){let z=(await T.read()).accounts.find((L)=>L.id===Z);if(z?.type!=="oauth")throw Error("Native OAuth account is unavailable");let _=z.source==="vault"?await T.authorizeVault(Z,G):await T.captureLocalSubject(Z);if(!await T.resetBackoff(Z,_))throw Error("Native reset fence changed")}let j1=new WeakMap,i1=new WeakSet;async function M0(Z,G){if(i1.has(Z))return;i1.add(Z),await T.vault.reportFailure(Z,401,G).catch(()=>{h.warn("claustrum","native auth-failure report unavailable")})}async function L1(Z,G,W){let z=await T.vault.prepareRetry(Z,W,G);return z.retry?z.receipt:void 0}let m9=r3(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),Y1=new xJ,c9=new vJ,n1=new MJ,I1=new DJ,k$=new Map,N$=new Map,E$=new Map,I4=new Map,X$=new Set,p9=new Map,x4=new Map,c$=new Map,o1=new Map,l9=new Map;async function UZ(){let Z=await T.read(),G=Z.routingPath;if(!G)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let W;if(Z.mode==="claustrum"){W=new Map;for(let _ of Z.accounts)if(_.source==="vault"&&_.accountIdentity)W.set(_.id,_.accountIdentity)}let z=l9.get(G);if(!z)z=new wW({path:G,vaultSeed:Z.routingSeed,onLockEvent:T.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),l9.set(G,z);return z.setVaultSeed(Z.routingSeed),{router:z,...W&&{accountIdentities:W}}}let k=new NW({storage:a0,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,G)=>{W$();let W=Z.kind==="main"?"main":Z.accountId;if(!W)throw Error("Quota request has no account identity");return T.fetchQuota(W,void 0,void 0,G,Z.purpose)}});function r1(Z){return["five_hour","seven_day"].some((G)=>(Z?.[G]?.remainingPercent??1)<=0)}function QZ(Z,G,W=!1){if(!Z||Z.quota?.enabled===!1||!G||e$(Z)==="sticky-balanced"||s$(Z.refresh?.mainLastRefreshError))return;let z=Date.now(),_=Z.quota?.mainLastQuotaApiError;if(_&&_.accountIdentity===G&&_.nextRetryAt!==void 0&&_.nextRetryAt>z)return{message:I7(_,z),retryAfter:Math.max(1,Math.ceil((_.nextRetryAt-z)/1000))};let L=Z.quota?.mainQuota,N=E1(L);if(L?.accountIdentity!==G||L.source==="headers"&&!W||!r1(L)||N<=0||N>z||w1(L,Z,N)<=z)return;let j=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],C=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(C)&&C>z?[C]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((j.length?Math.max(...j):z+f7(Z))-z)/1000))}}async function BZ(Z,G,W){if(XJ===Z&&H$===G)return;let z=D1!==void 0&&W!==void 0&&D1!==W;XJ=Z,H$=G,k.setMainQuotaAccountIdentity(G,!0,z)}async function s1(Z,G,W,z){let _=Z,L=p4.get(_);if(L){let j=await L.promise;return z===L.recordVersion?j:{...j,stale:!0}}let N=(async()=>{let j=++bZ,Q=e1,U=await T.read(),C=U.policyStorage,f=U.accounts.find((V1)=>V1.id==="main")?.accountIdentity,m=J1(W??f),J0=U.mode==="claustrum",_0=J0?C?.claustrum?.primaryAccount?.accountId:void 0;if(W!==void 0&&W!==f||J0&&W===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:k.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let f0=f??_0??Q,w0=C?.main?.profile?.providerAccountUuid??C?.main?.profile?.accountIdentity,k0=F$(W)??F$(m.accountUuid),N0=W?k0:Z.startsWith("sk-ant-oat")?k0??F$(w0):void 0,_$=T4(C)!=="claustrum"?"na":w0===void 0||k0===void 0?"unknown-identity":w0!==void 0&&k0!==void 0&&w0!==k0?"on-identity-mismatch":"on-vault-served";if(j!==bZ){let V1=XJ!==Z||H$!==f0;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:V1,state:_$}}if(await BZ(Z,f0,N0),Z.startsWith("sk-ant-oat")&&N0===void 0)k.clearMain();if(D1=N0,Z.startsWith("sk-ant-oat"))$4=Z;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:!1,state:_$}})();p4.set(_,{promise:N,recordVersion:z});try{return await N}finally{if(p4.get(_)?.promise===N)p4.delete(_)}}let u9=a0?.quotaHeaderFeed?.enabled===!0?new LW:null,p$=new Map,FZ=new Map,X1=new Set,G1=new AbortController,wZ=!1;function f4(Z,G){return JSON.stringify([Z,G??null])}function d9(Z){let G=Z.binding;if(Z.source!=="local"||!G)return;return JSON.stringify([G.storageId,G.rowId,G.credentialEpoch])}function i9(Z,G){return Z.lineage!==void 0&&Z.lineage===d9(G)&&(!Z.profile||Z.profile.accountIdentity===G.accountIdentity)}async function k4(Z,G){if(!Z?.profile||!q9(Z.profile,G)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function TZ(Z){if(!Z)return[];let G=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((W)=>B0(W)&&(W.enabled!==!1||Boolean(W.claustrumScopedCredentialId))).map((W)=>W.id)]);return[...new Set(p$.values())].filter((W)=>W.persistence==="failed"&&W.profile!==void 0&&G.has(W.accountId))}async function N8(Z,G,W,z){let _=G.accountId,L=W.accounts.find((Q)=>Q.id===_),N=L?.source==="local"?i9(G,L):L?.source==="vault"&&L.accountIdentity===z.accountIdentity;if(L?.type!=="oauth"||!y0(L)||L.accountIdentity!==z.accountIdentity||!N||await k4(G,Date.now())!==z)return Z;if(_==="main")return Z.main?{...Z,main:{...Z.main,profile:z}}:Z;let j=Z.accounts?.find((Q)=>Q.id===_);if(!j||!B0(j))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===_&&B0(Q)?{...Q,profile:z}:Q)}}async function EZ(Z,G,W=TZ(Z)){if(!Z||W.length===0)return Z;let z=[];for(let N of W){let j=await k4(N,Date.now());if(j)z.push({hydration:N,profile:j})}if(!z.length)return Z;let _=G??await T.read(),L=Z;for(let N of z)L=await N8(L,N.hydration,_,N.profile);return L}function H8(Z,G,W){W$();let z=!1,_=Object.assign((N,j)=>{return z=!0,O(N,j)},{preconnect:O.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:d9(Z),...W&&{deadline:W}};return L.fetched=T.fetchProfileForDisplay(Z.id,_,AbortSignal.any([G1.signal,...W?[W]:[]])).then(({profile:N,persisted:j,isCurrent:Q})=>{if(L.settled=!0,N.accountIdentity!==void 0)FZ.set(f4(Z.id,N.accountIdentity),N);if(Z.accountIdentity===void 0||N.accountIdentity===Z.accountIdentity)L.profile=N,L.isCurrent=Q,L.persistence="pending";let U=j.then(async(C)=>{if(L.persistence=C,C==="failed")h.warn("quota","failed to persist account profile",{account:Z.id});else if(C==="refused")h.debug("quota","refused account profile publication",{account:Z.id});if((C==="saved"||C==="failed")&&!G1.signal.aborted){let f=C==="failed"&&await k4(L,Date.now());if(C==="saved"||f)try{let m=await T.read();if(!G1.signal.aborted)await C$(m.policyStorage,{...$$,routingAuthoritative:!1},m)}catch{h.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});X1.add(U),U.then(()=>X1.delete(U))},(N)=>{if(L.settled=!0,L.failed=z,h.debug("quota","failed to hydrate account profile",{account:Z.id,error:N instanceof Error?N.message:String(N)}),!z&&p$.get(G)===L)p$.delete(G)}),X1.add(L.fetched),L.fetched.then(()=>X1.delete(L.fetched)),L}function D8(Z,G){let W=[G,Z.deadline].filter((_)=>_!==void 0);if(!W.length)return Z.fetched;let z=AbortSignal.any(W);if(z.aborted)return Promise.resolve();return new Promise((_)=>{let L=()=>{z.removeEventListener("abort",L),_()};z.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function SZ(Z,G){return q9(Z.profile,G)&&$W(Z.profile,Z.accountIdentity)}async function v4(Z){let G=await T.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return G;let W=Date.now(),z=[],_=new Map;for(let j of G.accounts){if(j.type!=="oauth"||!y0(j)||SZ(j,W))continue;let Q=f4(j.id,j.accountIdentity),U=p$.get(Q);if(U&&j.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==d9(j)))U=void 0;if(!U&&j.accountIdentity!==void 0){let C=p$.get(f4(j.id));if(C&&i9(C,j))U=C,_.set(j.id,C)}if(U?.failed)continue;if(!U&&q9(FZ.get(Q),W))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!q9(U.profile,W)){if(Z?.aborted||G1.signal.aborted)continue;U=H8(j,Q,Z),p$.set(Q,U)}if(j.accountIdentity===void 0)_.set(j.id,U);z.push(D8(U,Z))}if(!z.length)return G;await Promise.all(z);let L=await T.read(),N=Date.now();for(let j of L.accounts){if(j.type!=="oauth"||!y0(j))continue;let Q=f4(j.id,j.accountIdentity),U=_.get(j.id);if(U&&j.accountIdentity!==void 0&&!p$.has(Q)&&i9(U,j))p$.set(Q,U);if(SZ(j,N))continue;let C=await k4(p$.get(Q),N);if(!C||C.accountIdentity!==j.accountIdentity)continue;if(j.profile=C,j.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=C}else for(let f of L.policyStorage.accounts)if(f.id===j.id&&B0(f))f.profile=C}return L}async function U8(Z,G,W,z){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await v4(W)).policyStorage}let CZ=new Set;async function Q8(Z,G,W){let _=(await T.read()).accounts.find((U)=>U.id===Z.accountId);if(!_||!Z.anthropicAccountUuid||_.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...y7(_.quota,G.quota),accountIdentity:_.accountIdentity};if(!(Z.scopedAttempt?await T.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await T.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(k.getMain(Z.mainQuotaIdentity?.quotaKey)===W)k.clearMain()}else if(k.getAllFallbacks().get(Z.accountId)===W)k.clearFallback(Z.accountId);return h.debug("quota","native quota publication refused",{accountId:Z.accountId}),null}let j=await T.read(),Q=j.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==_.source)return null;if(Z.localSubject&&Q.binding?.credentialEpoch!==Z.localSubject.binding.credentialEpoch)return null;if(Z.scopedAttempt&&Q.credentialId!==Z.scopedAttempt.credentialId)return null;return{...G,quota:Q.quota,refreshAfter:w1(Q.quota,j.policyStorage,G.checkedAt)}}function B8(Z){h.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function F8(Z){let G=Z instanceof Error?Z.name:typeof Z,W=Z instanceof Error?Z.message:String(Z),z=`${G}:${W}`;if(CZ.has(z))return;CZ.add(z),h.warn("quota","failed to normalize response quota headers",{error:W})}function w8(Z){if(!Z||typeof Z!=="object")return;let G=Z,W=G.credential_id;if(typeof W==="string"&&W&&W!=="main")return W;let z=G.vault;if(z&&typeof z==="object"){let _=z.credential_id;if(typeof _==="string"&&_&&_!=="main")return _}return}async function T8(Z,G){if(!u9)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let W=await R(K)??o$(),_=(await W1?.())?.type==="oauth",L=Z.accountId==="main"?W.main:W.accounts.find((m)=>m.id===Z.accountId),N=w8(L),j=wG({storage:W,mainOAuthConfigured:_}),Q=G.checkedAt,U={five_hour:G.quota.five_hour,seven_day:G.quota.seven_day,bindingWindow:G.quota.bindingWindow,fallbackAdvised:G.quota.fallbackAdvised,scoped:G.quota.scoped,extraUsage:G.quota.extraUsage,fieldSources:G.quota.fieldSources},C=N??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),f=N?{identity_source:"credential_id",credential_id:N,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"?{identity_source:"none",schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C};await u9.publish(f)}function E8(Z){h.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function AZ(Z,G){try{if(!rG(Z)){h.trace("quota","skipped non-quota response headers",{account:G.accountId});return}let W=eG(Z),z=G.accountId==="main"?G.mainQuotaIdentity:void 0;if(G.accountId==="main"){if(!z||k.getMainQuotaIdentityGeneration()!==z.generation){h.trace("quota","discarded stale main quota headers",{boundIdentity:z?.quotaKey,currentGeneration:k.getMainQuotaIdentityGeneration()});return}}let _=G.accountId==="main"?k.getMain(z?.quotaKey):k.getAllFallbacks().get(G.accountId),L=W.checkedAt??Date.now(),N=I0(G.localSubject,G.scopedAttempt),j=N&&G.anthropicAccountUuid?{lineage:N,accountUuid:G.anthropicAccountUuid,entry:{quota:{...W,accountIdentity:G.anthropicAccountUuid},checkedAt:L,refreshAfter:L},generalExhausted:["five_hour","seven_day"].some((Q)=>{let U=Z.get(Q==="five_hour"?"anthropic-ratelimit-unified-5h-utilization":"anthropic-ratelimit-unified-7d-utilization");return W[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(j){if(o.delete(G.accountId),o.size>=iW){let Q=o.keys().next().value;if(Q!==void 0)o.delete(Q)}o.set(G.accountId,j)}(async()=>{let Q=!1;try{let U;try{U=await Q8(G,{quota:W,checkedAt:L,refreshAfter:L},_)}catch(f){B8(f);return}if(U===null)return;if(G.accountId==="main"&&k.getMainQuotaIdentityGeneration()!==z?.generation)return;let C=U;if(j&&o.get(G.accountId)===j)j.entry=C,Q=!0;if(G.accountId==="main")k.setMain(z?.quotaKey,C);else k.setFallback(G.accountId,C,{authLineageId:G.authLineageId});f1().catch(()=>{}),await T8(G,C),h.debug("quota","harvested response quota",{account:G.accountId,fiveHourPercent:C.quota.five_hour?.usedPercent,sevenDayPercent:C.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&j&&o.get(G.accountId)===j)o.delete(G.accountId),h.debug("quota","discarded pending response quota",{accountId:G.accountId})}})().catch(E8),h.trace("quota","response quota awaiting publication",{account:G.accountId})}catch(W){F8(W)}}let PZ=Promise.resolve();function N1(Z=!1,G=!1,W,z){let _=PZ.then(()=>S8(Z,G,W,z));return PZ=_.then(()=>{},()=>{}),_}async function S8(Z,G,W,z){let _=await T.read(),L=new Set;if(!Z&&!G&&_.policyStorage.quota?.enabled===!1)return L;for(let N of _.accounts){if(N.id==="main"||N.type!=="oauth")continue;if(!y0(N)){if(G)L.add(N.id);continue}if(!Z&&w1(N.quota,_.policyStorage,E1(N.quota))>Date.now()&&(!W||A1(N.quota,_.policyStorage,Date.now(),W)))continue;try{if(!await k.refreshFallback(N.id,"",_.policyStorage.accounts.find((Q)=>Q.id===N.id&&B0(Q)),Z?void 0:z))L.add(N.id),h.debug("quota","fallback quota preflight returned no reading",{accountId:N.id,requiredByPolicy:G})}catch(j){if(G&&T1(j))throw j;L.add(N.id),x3(N.id,G,j)}}return f1().catch(()=>{}),L}let n9={refreshQuotaForDueAccounts:async()=>{await N1()},refreshQuotaForAllAccounts:async(Z)=>{await N1(!0)},refreshAccount:async(Z,G,W)=>{let z=await P0(Z.id,void 0,W?.force?Z.access:void 0);return{...Z,access:z.accessToken,expires:z.expires}},refreshAccountQuota:async(Z,G)=>{W$();let W=await T.fetchQuota(Z.id);return{account:{...Z,quota:W},fetched:!0}},getUsableFallbackAccounts:async(Z,G)=>{Z=Z??null;let W=[],z=Z?.accounts.some((_)=>B0(_)&&o.has(_.id))?(await T.read()).accounts:[];for(let _ of Z?.accounts??[]){if(!B0(_)||!y0(_))continue;let L=z.find((Q)=>Q.id===_.id),N=k.getFallback(_.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:_)?.quota??L?.quota??_.quota,j=L&&Z?O0({...L,quota:N},Z):N;if(!p1(j,Z)||!I9(j,G?.modelId)||r$(Z)&&!a$(j,Z,_.id,G?.modelId))continue;if(b0(Z)){if(z4(_.id,Z))W.push(_);continue}try{let Q=await P0(_.id,void 0,void 0,G?.modelId);W.push({..._,access:Q.accessToken,expires:Q.expires})}catch(Q){if(T1(Q))throw Q}}return W}};async function o9(){W$();let Z=await T.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let G of Z.accounts){if(G.id==="main"||G.type!=="oauth"||!y0(G))continue;try{let W=await P0(G.id);if(C1(G.lastRefreshError,G.accountIdentity,Date.now(),void 0))continue;if(W.localSource!=="rotated"&&W.localSource!=="adopted"&&(!W.expires||W.expires-Date.now()<=gZ(Z.policyStorage)))await P0(G.id,void 0,void 0,void 0,"refresh")}catch{}}await N1(!1,!1,void 0,"background")}let r9=a0!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,qZ=new Set;async function C8(){let Z=await T.read(),G=new Set(Z.accounts.filter((z)=>z.id!=="main"&&z.source==="vault"&&z.type==="oauth"&&y0(z)).map((z)=>z.id)),W=[...G].some((z)=>!qZ.has(z));if(qZ=G,W)await N1(!1,!1,void 0,"background");await f1()}let s9=r9&&b0(a0)?T.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:C8,setInterval:Y.setInterval,clearInterval:Y.clearInterval}):void 0,A8=r9?(s9?s9.ready.then(()=>o9()):o9()).catch(()=>{}):Promise.resolve(),a9=r9?Y.setInterval(()=>{o9().catch(()=>{})},MG+J8(t7)):null;a9?.unref?.();let P8=(Z,G)=>{let W=SJ({id:Z,role:"fallback"},G);return W==="na"?"off":W},t9=new UJ,q8=new QJ,l$=new WeakMap,a1=new Map;async function e9(Z){let G=(Z.get("anthropic-beta")??"").split(",").map((W)=>W.trim()).filter(Boolean).sort();return{betas:G,betasHash:await FG(G.join(","))}}function RZ(Z){try{if(!Z.request)return;let G=G3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(z)=>h.warn("cache-diagnostics",z),message:Z.message,receivedAt:Z.receivedAt});if(!G.record||!G.messageId){h.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}h.debug("cache-diagnostics",W3(G.record));let W=q8.capture(Z.betasHash,Z.betas);if(W)h.debug("cache-diagnostics",W);if(G.canary)h.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:G.canary.messageId,previous_message_id:G.canary.previousMessageId});if(Z.trackSessionId)t9.capture(Z.trackSessionId,G.messageId,Z.receivedAt)}catch(G){h.debug("cache-diagnostics","response observation failed",{status:Z.status,error:G instanceof Error?G.message:String(G)})}}function MZ(Z,G,W=!0){let z=l$.get(Z);if(!z)return;if(G&&typeof G==="object"&&!Array.isArray(G)&&!W)z.messageStart=G;z.dumpWrite=z.dumpWrite.then(()=>eJ(z.dump,{status:z.status,message:G,complete:W})).catch(()=>{}),RZ({...z,message:G,receivedAt:Date.now()})}function R8(Z,G){let W=l$.get(Z);if(!W)return;let z=W.messageStart??{},_=z.usage&&typeof z.usage==="object"&&!Array.isArray(z.usage)?z.usage:{},L={...z,...G.usage?{usage:{..._,...G.usage}}:{},...G.stopReason?{stop_reason:G.stopReason}:{}};W.dumpWrite=W.dumpWrite.then(()=>eJ(W.dump,{status:W.status,message:L,complete:!0})).catch(()=>{})}function IZ(Z,G){let W=Promise.resolve(eJ(G.dump,{status:G.status,message:null,complete:!1})).catch(()=>{});l$.set(Z,{...G,dumpWrite:W})}let u$=null,h4=null;function b4(Z){return Z!==null&&typeof Z==="object"&&EJ(Z)==="R"}function M8(Z){let G=aJ("anthropic");if(!Z||typeof Z!=="object")return!1;let W=Z;return W.type===G.type&&W.access===G.access&&W.refresh===G.refresh&&W.expires===G.expires}async function I8(){if(h4){let Z=await h4();return pG("opencode",Z===void 0?{}:{anthropic:Z}).kind}if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("OpenCode logins cannot be checked while OPENCODE_AUTH_CONTENT is set");return DW("opencode",W8())}async function xZ(){if(await S1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await I8()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let x8={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await xZ(),{url:"",instructions:"Claude requests use the credential vault this host is connected to. OpenCode stores only a placeholder, never a credential.",method:"auto",callback:async()=>{await xZ();let Z=aJ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},$J=new zG({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||hG("opencode")}),g4=[],x1=new Map,t1=new VG({loadStorage:()=>R(K),setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,onTrackedSessionsChanged:async(Z)=>{await $J.publish(Z),g4=await $J.list(Z)},prepareBody:(Z,G)=>{if(!new Headers(G.headers).get("anthropic-beta")?.split(",").map((W)=>W.trim()).includes(V4))return Z;try{let W=JSON.parse(Z),z=t9.previousFor(G.id),_=z?.messageId??null;return r4(W,_),a1.set(G.id,{sessionId:G.id,previousMessageId:_,...z?{previousMessageReceivedAt:z.receivedAt}:{},isSubagent:G.isSubagent,ttlSent:s4(W),accountId:G.oauthAccountId??"main",synthetic:!0,requestedModel:typeof W.model==="string"?W.model:void 0}),JSON.stringify(W)}catch{return Z}},onResponse:async({target:Z,bodyText:G,status:W,data:z,receivedAt:_,attempt:L})=>{let N=x1.get(L.id);if(W===401&&N?.scopedAttempt)await M0(N.scopedAttempt,"direct");let j=a1.get(Z.id);if(!j?.betasHash||!j.betas){a1.delete(Z.id);return}try{let Q=JSON.parse(G),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,C=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===j.previousMessageId?j.previousMessageId:void 0;if(C===void 0)return;RZ({source:"prewarm_cachekeep",accountId:j.accountId,synthetic:j.synthetic,betasHash:j.betasHash,betas:j.betas,requestedModel:j.requestedModel,request:{...j,previousMessageId:C,ttlSent:s4(Q)},trackSessionId:Z.id,status:W,message:z,receivedAt:_})}catch{}finally{a1.delete(Z.id)}},onComplete:({attempt:Z})=>{x1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:G,attempt:W})=>{let z=x1.get(W.id);if(!z)return;let _;try{let j=JSON.parse(Z.bodyText);if(typeof j.model==="string")_=j.model}catch{}if(z.scopedAttempt&&!await L1(z.scopedAttempt,"cachekeep",W.signal))return;let L=await P0(Z.oauthAccountId??"main",W.signal,z.scopedAttempt?void 0:z.accessToken,_);if(L.accountIdentity!==z.accountIdentity||Boolean(L.scopedAttempt)!==Boolean(z.scopedAttempt))return;if(z.scopedAttempt&&(!L.scopedAttempt||L.scopedAttempt.credentialId!==z.scopedAttempt.credentialId||L.scopedAttempt.recordVersion<=z.scopedAttempt.recordVersion))return;if(!z.scopedAttempt&&L.accessToken===z.accessToken)return;let N=new Headers(G);return N.set("authorization",`Bearer ${L.accessToken}`),x1.set(W.id,L),N},prepareHeaders:async(Z,G,W)=>{let z=G.oauthAccountId??"main",_;try{let Q=JSON.parse(G.bodyText);if(typeof Q.model==="string")_=Q.model}catch{}let L=await P0(z,W.signal,void 0,_),N=L.accessToken;x1.set(W.id,L);try{let Q=JSON.parse(G.bodyText),U=J1(L.accountIdentity);if(Z.delete("anthropic-beta"),m1(Z,N,{body:Q,identity:U}),Z.set("anthropic-beta",g7(Z.get("anthropic-beta"),[WG])),Q.speed==="fast")N9(Z);let C=a1.get(G.id);if(C){let{betas:f,betasHash:m}=await e9(Z);C.betas=f,C.betasHash=m}}catch{m1(Z,N)}let j=await P0(z,W.signal,void 0,_);if(j.accountIdentity!==L.accountIdentity||Boolean(j.scopedAttempt)!==Boolean(L.scopedAttempt))throw Error("CacheKeep credential authority changed before dispatch");return Z.set("authorization",`Bearer ${j.accessToken}`),x1.set(W.id,j),Z}});async function f8(Z){if(!u$||!(await u$()).active)throw Error("Native main OAuth activation is not available");let G=await P0("main",Z);return{...G,credentialAccountId:F$(G.accountIdentity)}}async function k8(){let Z=await f8();if((await s1(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let W=await k.refreshMainWithMetadata(H$,Z.accessToken);return{quota:W.quota,fresh:W.fetched}}async function v8(Z){W$();let G=await R(K),W=G?.accounts.find((_)=>_.id===Z&&y0(_)&&B0(_));if(!W||!G)throw Error(`prime: OAuth account ${Z} is unavailable`);let z=await n9.refreshAccountQuota(W,G);return{quota:z.account.quota??{},fresh:z.fetched}}let JJ=new Map;async function h8(Z){let G=performance.now(),W,z,_,L="",N;try{if(Z==="main"&&(!u$||!(await u$()).active))throw Error("Native main OAuth activation is not available");let j=await P0(Z,void 0,void 0,T7);if(W=j.accessToken,_=j.scopedAttempt,z=T7,!W)return{ok:!1,error:"prime: no access token available"};let Q=GG(),U=J1(j.accountIdentity),C=await H9(JSON.stringify(Q),{identity:U}),f=new Headers({"content-type":"application/json"});m1(f,W,{body:JSON.parse(C),identity:U,requestClass:"auxiliary"}),f.delete("content-length"),f.delete("transfer-encoding");let m=Q4(RW,{baseURL:""}),J0=m.url?.toString()??m.input.toString(),_0=AbortSignal.timeout(30000),f0={method:"POST",headers:f,body:C,signal:_0},w0=await P0(Z,_0,void 0,z);if(w0.accountIdentity!==j.accountIdentity||Boolean(w0.scopedAttempt)!==Boolean(j.scopedAttempt))throw Error("Prime credential authority changed before dispatch");_=w0.scopedAttempt,L=w0.accessToken,f.set("authorization",`Bearer ${L}`);let k0=async()=>{let Q0=E9([L],"http");return N=Q0,Q0.redactResponse(await fetch(J0,f0))},N0=await k0();if(N0.status===401&&_&&!_0.aborted){let Q0;try{Q0=await L1(_,"prime",_0)}catch{}if(Q0){N?.dispose(),await N0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:_.recordVersion,newVersion:Q0.recordVersion}),w0=await P0(Z,_0,void 0,z);let v0=w0.scopedAttempt;if(!v0||v0.credentialId!==_.credentialId||v0.accountIdentity!==_.accountIdentity||v0.recordVersion<=_.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");_=v0,L=v0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}if(N0.status===401&&!w0.scopedAttempt&&!_0.aborted){let Q0=w0.accessToken,v0=await P0(Z,_0,Q0,z).catch(()=>{return});if(v0&&v0.accessToken!==Q0&&v0.accountIdentity===j.accountIdentity&&!v0.scopedAttempt){if(N?.dispose(),await N0.body?.cancel().catch(()=>{}),w0=await P0(Z,_0,void 0,z),w0.scopedAttempt||w0.accountIdentity!==j.accountIdentity)throw Error("Prime local authority changed before retry");L=w0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}let _$=Math.round(performance.now()-G);if(!N0.ok){let Q0;try{Q0=await N0.text().catch(()=>"")||`HTTP ${N0.status}`}finally{N?.dispose()}if(N0.status===401&&_)await M0(_,"direct");return{ok:!1,status:N0.status,ms:_$,error:Q0}}let D$=(await N0.json().catch(()=>null))?.usage,U$=D$&&(Number.isFinite(D$.input_tokens)||Number.isFinite(D$.output_tokens))?{inputTokens:Number.isFinite(D$.input_tokens)?D$.input_tokens:void 0,outputTokens:Number.isFinite(D$.output_tokens)?D$.output_tokens:void 0}:void 0;return JJ.set(Z,w0),{ok:!0,status:N0.status,ms:_$,...U$&&{usage:U$}}}catch(j){N?.dispose();let Q=E9([L],"http"),U=Q.redactError(j);return Q.dispose(),{ok:!1,...j instanceof O$&&j.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-G),error:U instanceof Error?U.message:String(U)}}}let fZ={storagePath:K,loadStorage:()=>R(K),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!u$||!(await u$()).active))return;let G=await P0(Z),W=G.scopedAttempt??G.localSubject;if(!W)return;let z=await T.getOrCreateAuthLineage(Z,W);return z?t$(z):void 0},refreshQuota:async(Z)=>{if(Z==="main")return k8();return v8(Z)},sendPrime:h8,recordSuccess:async(Z,G)=>{let W=JJ.get(Z);JJ.delete(Z);let z=W?.scopedAttempt??W?.localSubject;if(!z||!await T.incrementPrimeUsage(Z,z,G))throw Error("Prime usage publication lost its native credential fence");let _=(await T.read()).accounts.find((L)=>L.id===Z)?.prime;if(!_)throw Error("Prime usage counters are unavailable after publication");return _},setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,setTimeoutImpl:Y.setTimeout,clearTimeoutImpl:Y.clearTimeout},kZ=I3(K,()=>new ZW(fZ),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(fZ)}),H1=kZ.manager;if(P9(a0))H1.start();async function y4(){return g4=await $J.list(t1.trackedSessions()),g4}let vZ=J.cacheKeepAggregateRefreshIntervalMs??1e4,ZJ=vZ>0?Y.setInterval(()=>{y4().catch(()=>{})},vZ):void 0;if(ZJ?.unref?.(),x9({enabled:A9(a0),mode:w4(a0)}),jZ(WZ(a0)),LZ(zZ(a0)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)SW(XZ(a0)??"info");let YJ=null,b8=async()=>{G1.abort();while(X1.size)await Promise.all([...X1]);try{await d1(K)}catch(Z){h.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{k.close()}catch{}try{await u9?.dispose()}catch(Z){h.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(U1)Y.clearInterval(U1),U1=null}catch(Z){h.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(a9)Y.clearInterval(a9)}catch(Z){h.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(ZJ!==void 0)Y.clearInterval(ZJ)}catch(Z){h.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{t1.stop()}catch(Z){h.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{kZ.release()}catch(Z){h.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!YJ)return;try{await YJ.release()}catch(Z){h.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},$$={activeId:"main",route:"main"},g8=V8(),S$=new Map;function m4(Z,G){if(k.updateStorage(Z),k.seedMainFromStorage(Z,H$),!G.skipFallbackQuotaSeed)k.seedFallbacksFromAccounts((Z?.accounts??[]).filter(B0));let W=k.getMain(H$),z=k.getLastApiError(),_=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,N=b0(Z)&&!y0(L)?ZZ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:W?.quota??null,enabled:L?.enabled,tierLabel:B4(Z?.main?.profile),quotaBackedOff:k.isBackedOff(),quotaBackoffUntil:z?.nextRetryAt,refreshBackedOff:_?C1(_,e1??Z?.mainAccountId,Date.now(),G.mainRefreshToken?t$(G.mainRefreshToken):void 0):!1,refreshBackoffUntil:_?.nextRetryAt,stateLine:N,quotaDated:Boolean(N)},fallbacks:(Z?.accounts??[]).filter((j)=>B0(j)&&(j.enabled!==!1||Boolean(j.claustrumScopedCredentialId))).map((j)=>{let Q=z4(j.id,Z),U=P8(j.id,Z),C=j.claustrumScopedCredentialId&&!Q?ZZ({source:"vault",enabled:j.enabled!==!1,state:j.claustrumScopedState}):void 0;return{id:j.id,label:j.label,tierLabel:B4(j.profile),quota:G.skipFallbackQuotaSeed?null:k.getFallback(j.id,j)?.quota??j.quota??null,needsReauth:j.lastRefreshError!=null&&C1(j.lastRefreshError,j.id,Date.now(),t$(j.refresh))&&s$(j.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:j.enabled!==!1,stateLine:C,quotaDated:Boolean(C)}}),activeId:G.activeId,route:G.route,relay:AG(Z?.relay),fastMode:VZ(),cacheKeep:{enabled:v7(Z),window:k7(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:g4.length},prime:P9(Z)?{enabled:!0,accounts:H1.stats(Z)}:void 0,fableRecoveries:S$.size>0?[...S$.values()]:void 0,lastUpdated:Date.now()}}function C$(Z,G,W){let z=G.routingAuthoritative!==!1;if(z)$$={activeId:G.activeId,route:G.route};function _(L){return K8(L,g8,{routingAuthoritative:z,resolvePreservedRouting:z?void 0:async(N)=>{let j=await vW(N,()=>R(K),{activeId:L.activeId,route:L.route}),Q=await EZ(j.freshStorage,W);return{activeId:j.activeId,route:j.route,state:m4(Q,{...G,activeId:j.activeId,route:j.route})}},onRoutingResolved:z?void 0:(N)=>{$$=N}}).catch((N)=>h.warn("sidebar","state write failed",{error:N instanceof Error?N.message:String(N)}))}if(z){let L=TZ(Z);if(L.length>0)return EZ(Z,W,L).then((N)=>_(m4(N,G))).catch(()=>{return h.debug("quota","failed to recheck account profile for sidebar"),_(m4(Z,G))})}return _(m4(Z,G))}async function hZ(){return{storage:await R(K),access:void 0}}async function f1(){await y4().catch(()=>{});let{storage:Z,access:G}=await hZ();C$(Z,{activeId:$$.activeId,route:$$.route,mainAccessToken:G,mainRefreshToken:void 0,routingAuthoritative:!1})}function y8(Z,G,W){if(!G)return;if(Z?.quota?.enabled!==!0)return;let z=W?.quotaKey??H$;if(k.getMain(z))return;if(GJ)return;GJ=!0,k.refreshMain(z,G,W?.generation).then(()=>f1()).catch(()=>{}).finally(()=>{GJ=!1})}let W1=null,c4,e1,H$,$4,D1,XJ,bZ=0,p4=new Map,GJ=!1,U1=null,l4=0;function gZ(Z){let G=Z?.refresh?.refreshBeforeExpiryMinutes??IW;return Math.max(_8,G)*60000}function m8(Z){return Z?.refresh?.enabled!==!1}async function yZ(Z=!1){let G=new Map;if(Z){if(u$&&(await u$()).active)try{await T.fetchQuota("main")}catch{G.set("main","Native primary usage refresh unavailable")}await N1(!0)}let W=await v4(AbortSignal.timeout(3000));k.updateStorage(W.policyStorage),k.seedMainFromStorage(W.policyStorage,H$),k.seedFallbacksFromAccounts(W.policyStorage.accounts.filter(B0));let z=[],_=W.accounts.find((N)=>N.id==="main"&&N.type==="oauth");if(_)z.push({name:_.label??"OpenCode anthropic",role:"main",quota:_.quota,tierLabel:B4(_.profile),error:G.get("main")??_.lastQuotaRefreshError?.message});z.push(...XG(W.policyStorage,G));let L=Math.max(0,...W.accounts.map((N)=>E1(N.quota)));return YG({accounts:z,refreshedAt:L||void 0})}async function WJ(Z){await y4().catch(()=>{}),await C$(Z,{activeId:$$.activeId,route:$$.route,routingAuthoritative:!1})}function J4(Z,G,W,z){if(S$.delete(Z.sessionId),S$.set(Z.sessionId,{...Z,changedAt:Date.now()}),S$.size>128){let _=S$.keys().next().value;if(_)S$.delete(_)}if(C$(G,{activeId:$$.activeId,route:$$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1}),z)pZ(Z.sessionId,z)}function mZ(Z,G){let W=c$.get(Z)??new Set;W.delete(G),W.add(G);while(W.size>4){let z=W.values().next().value;if(typeof z!=="string")break;W.delete(z)}c$.delete(Z),c$.set(Z,W);while(c$.size>128){let z=c$.keys().next().value;if(typeof z!=="string")break;c$.delete(z)}}function cZ(Z,G){return typeof G==="string"&&c$.get(Z)?.has(G)===!0}function pZ(Z,G){if(V9(Z))return;N$.delete(Z),N$.set(Z,[G]);while(N$.size>128){let W=N$.keys().next().value;if(W)N$.delete(W);else break}if(X$.has(Z))VJ(Z)}function VJ(Z,G=0){if(!N$.has(Z)||o1.has(Z))return;o1.set(Z,G);let W=()=>{if(o1.get(Z)!==G)return;o1.delete(Z),c8(Z,G)};if(G===0)setImmediate(W);else setTimeout(W,gW*G)}function zJ(Z,G){if(G+1<bW)VJ(Z,G+1)}async function c8(Z,G){if(!X$.has(Z)||!N$.has(Z))return;let W=$.client.session;if(typeof W?.status==="function")try{let z=await Promise.resolve(W.status()),_=z!==null&&typeof z==="object"?z:void 0,L=_&&Object.hasOwn(_,"data")?_.data:_;if(L===null||typeof L!=="object"||Array.isArray(L)){zJ(Z,G);return}let N=L[Z];if(N!==void 0&&(!N||typeof N!=="object"||N.type!=="idle")){zJ(Z,G);return}}catch{zJ(Z,G);return}if(!X$.has(Z))return;await p8(Z)}function p8(Z){let G=I4.get(Z);if(G)return G;let W=(async()=>{while(!0){let z=N$.get(Z),_=z?.[0];if(!_){N$.delete(Z);return}try{let L=()=>N$.get(Z)===z&&z[0]===_;if(!await Z8($,Z,_,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>X$.has(Z)&&L(),onPreparedMessageId:(j)=>mZ(Z,j),latestPreparedMessageId:()=>[...c$.get(Z)??[]].at(-1)})){if(X$.has(Z)&&!L())continue;return}if(L())z.shift()}catch(L){h.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return I4.set(Z,W),W.finally(()=>{if(I4.get(Z)===W)I4.delete(Z)}),W}function l8(Z,G,W,z){if(G.fallback&&G.targetModel){let _=k$.get(Z.recoveryKey);k$.delete(Z.recoveryKey),k$.set(Z.recoveryKey,G.targetModel);while(k$.size>128){let N=k$.keys().next().value;if(N)k$.delete(N);else break}let L=S$.get(Z.sessionId);if(_===G.targetModel&&L?.mode==="server"&&b$(L.requestedModelId)===b$(Z.requestedModel)&&L.targetModelId===G.targetModel)return;h.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:G.targetModel,handoff:G.handoff}),J4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:G.targetModel},W,z,rW(Z.requestedModel,G.targetModel));return}if(G.stopReason==="refusal"||!k$.delete(Z.recoveryKey))return;h.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),J4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},W,z,sW(Z.requestedModel))}function u8(Z,G,W){if(!Z)return;for(let z of k$.keys())if(z.startsWith(`${Z}\x00`))k$.delete(z);if(!S$.delete(Z))return;C$(G,{activeId:$$.activeId,route:$$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1})}async function KJ(Z){let G=XW(Z);if(G.type==="enable"||G.type==="disable"){let L=G.type==="enable",N=await q1(L),j=w4(N);return x9({enabled:L,mode:j}),h.info("commands","cache enabled changed",{enabled:L}),JZ({argumentsText:Z,enabled:L,mode:j,settingsPath:await T.getSettingsPath()})}if(G.type==="mode"){let L=await q4(G.mode),N=A9(L);return x9({enabled:N,mode:G.mode}),h.info("commands","cache mode changed",{mode:G.mode}),JZ({argumentsText:Z,enabled:N,mode:G.mode,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=A9(W),_=w4(W);return x9({enabled:z,mode:_}),JZ({argumentsText:Z,enabled:z,mode:_})}async function Z4(Z){let G=GW(Z),W=await R(K);if(G.type==="window")W=await R1(G.startHour,G.endHour),h.info("commands","cachekeep schedule changed",{schedule:`${G.startHour}-${G.endHour}`});else if(G.type==="always")W=await $1(),h.info("commands","cachekeep schedule changed",{schedule:"always"});else if(G.type==="disable")W=await R4(!1),h.info("commands","cachekeep enabled changed",{enabled:!1});else if(G.type==="subagents")W=await M4(G.enabled),h.info("commands","cachekeep subagents changed",{subagents:G.enabled});let z=x7(W),_=await y4(),L=_.length?Math.min(..._.map((N)=>N.nextPrewarmAt)):void 0;return qG({argumentsText:Z,enabled:lG(W),always:k7(W),window:z,hybridActive:v7(W),trackedSessions:_.length,trackedSessionDetails:_,nextPrewarmAt:L})}async function lZ(Z){let G=WW(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await _1(_),jZ(_),h.info("commands","dump changed",{enabled:_}),S7({argumentsText:Z,enabled:_,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=WZ(W);return jZ(z),S7({argumentsText:Z,enabled:z})}async function uZ(Z){let G=VW(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await h9(_),LZ(_),h.info("commands","fast mode changed",{enabled:_}),C7({argumentsText:Z,enabled:_,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=zZ(W);return LZ(z),C7({argumentsText:Z,enabled:z})}async function dZ(Z,G){if(zW(Z).type==="fire"){if(!G)return`## Claude Start Failed
|
|
23
|
+
`)}function G2(){return process.env.OPENCODE_CLIENT==="desktop"}function Y8(){return process.env.OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE?.trim()||process.env.CLAUSTRUM_SUBC_CONNECTION?.trim()||void 0}var W2=async($,J={})=>{let Y={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,setInterval:globalThis.setInterval,clearInterval:globalThis.clearInterval,...J},X=J.authorize??w7;mW();let{client:V}=$,O=globalThis.fetch,K=fG(),H=gG(yG(K)),w=600000,q=50,P=new Map;function c(){let Z=Date.now();for(let[G,W]of P)if(Z-W.createdAt>w)P.delete(G)}function a(Z,G){if(c(),P.size>=q){let W="",z=1/0;for(let[_,L]of P)if(L.createdAt<z)z=L.createdAt,W=_;if(W)P.delete(W)}P.set(Z,G)}function u(Z){c();let G=P.get(Z);if(!G)return;if(Date.now()-G.createdAt>w){P.delete(Z);return}return G}let s=await FW(K),T=JG({paths:s,host:"opencode",local:J.nativeLocal,vault:J.claustrumScopedConnect?{connect:J.claustrumScopedConnect}:void 0}),o=T.quotaObservations,R0=null;function W0(Z){return tG(Z)}function I0(Z,G){return Z?W0(Z.binding):G?JSON.stringify([G.credentialId,G.accountIdentity,G.recordVersion]):void 0}function L0(Z,G,W,z=R0){let _=o.get(Z);if(!_||!G||_.lineage!==G||_.accountUuid!==W||w1(_.entry.quota,z,_.entry.checkedAt)<=Date.now())return;return _}function b(Z,G,W,z,_=R0){let L=L0(Z,G,W,_);if(!L)return z;if(!z)return{...L.entry,refreshAfter:w1(L.entry.quota,_,L.entry.checkedAt)};let N=L.entry.quota.source!=="headers"&&E1(z.quota)>E1(L.entry.quota)?z.quota:y7(z.quota,L.entry.quota);return{...L.entry,quota:N,refreshAfter:w1(N,_,E1(N))}}function O0(Z,G,W){if(!o.has(Z.id))return Z.quota;let z=Z.binding?W0(Z.binding):I0(void 0,W),_=E1(Z.quota);return b(Z.id,z,Z.accountIdentity,Z.quota?{quota:Z.quota,checkedAt:_,refreshAfter:w1(Z.quota,G,_)}:null,G)?.quota}let m0;async function R(Z=K){if(Z!==K)throw Error("Native account storage mismatch");let G=await T.read();if(R0=G.policyStorage,!m0){let _=G.accounts.find((L)=>L.id==="main")?.binding;if(_)m0={rowId:_.rowId,credentialEpoch:_.credentialEpoch}}if(G.mode!=="claustrum")return G.policyStorage;let W=G.accounts.find((_)=>_.id==="main"&&_.source==="vault"),z=F$(W?.accountIdentity);return{...G.policyStorage,claustrum:{...G.policyStorage.claustrum,mode:"claustrum",scopedRoster:!0,primaryAccount:W?.credentialId&&z?{credentialId:W.credentialId,accountId:z,state:W.state??"cold",enabled:W.enabled}:void 0}}}async function s0(Z,G){return await T.updateSettings((W)=>V2(W,Z,G)),R()}let q1=async(Z)=>{return await T.updateSettings((G)=>({...G,claudeCache:{...K2(G.claudeCache),enabled:Z,mode:w4({...G,version:1,accounts:[]})}})),R()},q4=(Z)=>s0("claudeCache",{mode:Z}),R4=(Z)=>s0("cacheKeep",{enabled:Z}),$1=async()=>{return await T.updateSettings(z2),R()},R1=(Z,G)=>s0("cacheKeep",{enabled:!0,always:!1,startHour:Z,endHour:G}),M4=(Z)=>s0("cacheKeep",{subagents:Z}),_1=(Z)=>s0("dump",{enabled:Z}),h9=(Z)=>s0("claudeFast",{enabled:Z}),b9=async(Z)=>{return await T.setLoggingLevel(Z),R()},f$=(Z,G=K)=>s0("prime",{enabled:Z}),g9=(Z,G=K)=>s0("routing",{mode:Z}),x0=(Z)=>s0("killswitch",Z),w$=(Z,G,W=K)=>T.setEnabled(Z,G),l1=(Z,G=K)=>T.remove(Z),T$=(Z,G=K,W)=>T.reorder(Z,W),a0=null;try{a0=await R()}catch{}function b0(Z){return Boolean(Z&&T4(Z)==="claustrum"&&Z.claustrum?.scopedRoster===!0)}function y9(Z=K,G=$.directory){if(Z!==K)throw Error("Native vault storage mismatch");return T.vault}let u1=TG("native-auth");async function d1(Z=K){s9?.close(),await u1.drain(),await T.drainQuotaPublications(),await Promise.all([...l9.values()].map((G)=>G.drain())),await T.drainRoutingPublications(),T.close()}function W$(){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native OAuth cannot serve while OPENCODE_AUTH_CONTENT is set")}function J1(Z){let G=F$(Z);if(!G)throw Error("Native wire identity requires an admitted provider account");return kG(G,G)}class Z1 extends Error{account;checkIntervalMs;constructor(Z,G){super("OAuth account cannot serve the requested model under current quota policy");this.account=Z;this.checkIntervalMs=G}}class S0 extends Error{constructor(){super("Native OAuth requires a Claude Pro/Max credential. An API key belongs in OpenCode stock Anthropic authentication.")}}class O$ extends Error{account;tokenRefreshFailed;failure;constructor(Z,G,W=!1,z){super(z?.kind==="provider"&&z.status!==void 0?`Claude OAuth refresh failed: ${z.status} — ${z.classification==="invalid-grant"?"invalid_grant":"OAuth operation failed"}`:`Native OAuth authorization refused: ${G}`);this.account=Z;this.tokenRefreshFailed=W;this.failure=z}}async function P0(Z,G,W,z,_="serve",L){W$(),G?.throwIfAborted();let N=L??await T.read(),j=N.accounts.find((m)=>m.id===Z);if(j?.state==="unsupported-access")throw new S0;if(j?.source==="vault"&&!y0(j))throw new O$(j,"not-active");if(j?.type!=="oauth"||!y0(j))throw Error("Native OAuth account is unavailable");let Q=(m,J0,_0)=>{let f0=O0(m,J0,_0),w0=_==="last-main"&&Z==="main"&&e$(J0)!=="sticky-balanced";if(z&&(r$(J0)&&!a$(f0,J0,Z==="main"?void 0:Z,z)||!w0&&!I9(f0,z)))throw new Z1(m,f7(J0))};Q(j,N.policyStorage);let U;if(j.source==="vault"){let m=await T.authorizeVault(Z,G).catch((J0)=>{if(G?.throwIfAborted(),J0 instanceof sG&&["not-active","route-declined","route-unavailable"].includes(J0.code))throw new O$(j,J0.code);throw J0});U={accessToken:m.accessToken,expires:m.expiresAtMs??void 0,accountIdentity:m.accountIdentity,scopedAttempt:m}}else{let m=await T.authorizeLocal(Z,{signal:G,rejectedAccessToken:W,intent:W?"refresh":_==="last-main"?"serve":_});if(m.status!=="usable")throw new O$(j,m.status,m.status==="failed"&&m.failure.kind==="provider",m.status==="failed"?m.failure:void 0);U={accessToken:m.access,expires:m.expires,accountIdentity:m.binding.identity,localSubject:m.subject,localSource:m.source}}let C=await T.read(),f=C.accounts.find((m)=>m.id===Z);if(G?.aborted)throw G.reason??Error("Request aborted");if(!f||!y0(f)||f.source!==j.source||f.accountIdentity!==U.accountIdentity)throw Error("Native OAuth account changed before dispatch");if(U.localSubject&&(!f.binding||f.binding.storageId!==U.localSubject.binding.storageId||f.binding.rowId!==U.localSubject.binding.rowId||f.binding.credentialEpoch!==U.localSubject.binding.credentialEpoch||f.binding.identity!==U.localSubject.binding.identity))throw Error("Native local account binding changed before dispatch");if(U.scopedAttempt&&f.credentialId!==U.scopedAttempt.credentialId)throw Error("Native vault credential binding changed before dispatch");return Q(f,C.policyStorage,U.scopedAttempt),U}async function M1(Z,G){let z=(await T.read()).accounts.find((L)=>L.id===Z);if(z?.type!=="oauth")throw Error("Native OAuth account is unavailable");let _=z.source==="vault"?await T.authorizeVault(Z,G):await T.captureLocalSubject(Z);if(!await T.resetBackoff(Z,_))throw Error("Native reset fence changed")}let j1=new WeakMap,i1=new WeakSet;async function M0(Z,G){if(i1.has(Z))return;i1.add(Z),await T.vault.reportFailure(Z,401,G).catch(()=>{h.warn("claustrum","native auth-failure report unavailable")})}async function L1(Z,G,W){let z=await T.vault.prepareRetry(Z,W,G);return z.retry?z.receipt:void 0}let m9=r3(process.env.OPENCODE_ANTHROPIC_AUTH_FALLBACK_MODE),Y1=new xJ,c9=new vJ,n1=new MJ,I1=new DJ,k$=new Map,N$=new Map,E$=new Map,I4=new Map,X$=new Set,p9=new Map,x4=new Map,c$=new Map,o1=new Map,l9=new Map;async function UZ(){let Z=await T.read(),G=Z.routingPath;if(!G)throw Error(Z.mode==="claustrum"?"Vault routing storage is unavailable":"Native routing storage is unavailable");let W;if(Z.mode==="claustrum"){W=new Map;for(let _ of Z.accounts)if(_.source==="vault"&&_.accountIdentity)W.set(_.id,_.accountIdentity)}let z=l9.get(G);if(!z)z=new wW({path:G,vaultSeed:Z.routingSeed,onLockEvent:T.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),l9.set(G,z);return z.setVaultSeed(Z.routingSeed),{router:z,...W&&{accountIdentities:W}}}let k=new NW({storage:a0,pauseBetweenQuotaCalls:J.quotaCallPause,fetchQuotaSnapshot:(Z,G)=>{W$();let W=Z.kind==="main"?"main":Z.accountId;if(!W)throw Error("Quota request has no account identity");return T.fetchQuota(W,void 0,void 0,G,Z.purpose)}});function r1(Z){return["five_hour","seven_day"].some((G)=>(Z?.[G]?.remainingPercent??1)<=0)}function QZ(Z,G,W=!1){if(!Z||Z.quota?.enabled===!1||!G||e$(Z)==="sticky-balanced"||s$(Z.refresh?.mainLastRefreshError))return;let z=Date.now(),_=Z.quota?.mainLastQuotaApiError;if(_&&_.accountIdentity===G&&_.nextRetryAt!==void 0&&_.nextRetryAt>z)return{message:I7(_,z),retryAfter:Math.max(1,Math.ceil((_.nextRetryAt-z)/1000))};let L=Z.quota?.mainQuota,N=E1(L);if(L?.accountIdentity!==G||L.source==="headers"&&!W||!r1(L)||N<=0||N>z||w1(L,Z,N)<=z)return;let j=["five_hour","seven_day"].flatMap((Q)=>{let U=L[Q],C=U?.resetsAt?Date.parse(U.resetsAt):Number.NaN;return U&&U.remainingPercent<=0&&Number.isFinite(C)&&C>z?[C]:[]});return{message:"Claude OAuth quota is exhausted for this account.",retryAfter:Math.max(1,Math.ceil(((j.length?Math.max(...j):z+f7(Z))-z)/1000))}}async function BZ(Z,G,W){if(XJ===Z&&H$===G)return;let z=D1!==void 0&&W!==void 0&&D1!==W;XJ=Z,H$=G,k.setMainQuotaAccountIdentity(G,!0,z)}async function s1(Z,G,W,z){let _=Z,L=p4.get(_);if(L){let j=await L.promise;return z===L.recordVersion?j:{...j,stale:!0}}let N=(async()=>{let j=++bZ,Q=e1,U=await T.read(),C=U.policyStorage,f=U.accounts.find((V1)=>V1.id==="main")?.accountIdentity,m=J1(W??f),J0=U.mode==="claustrum",_0=J0?C?.claustrum?.primaryAccount?.accountId:void 0;if(W!==void 0&&W!==f||J0&&W===void 0)return{quotaKey:void 0,providerAccountUuid:void 0,generation:k.getMainQuotaIdentityGeneration(),stale:!0,state:"on-identity-mismatch"};let f0=f??_0??Q,w0=C?.main?.profile?.providerAccountUuid??C?.main?.profile?.accountIdentity,k0=F$(W)??F$(m.accountUuid),N0=W?k0:Z.startsWith("sk-ant-oat")?k0??F$(w0):void 0,_$=T4(C)!=="claustrum"?"na":w0===void 0||k0===void 0?"unknown-identity":w0!==void 0&&k0!==void 0&&w0!==k0?"on-identity-mismatch":"on-vault-served";if(j!==bZ){let V1=XJ!==Z||H$!==f0;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:V1,state:_$}}if(await BZ(Z,f0,N0),Z.startsWith("sk-ant-oat")&&N0===void 0)k.clearMain();if(D1=N0,Z.startsWith("sk-ant-oat"))$4=Z;return{quotaKey:f0,providerAccountUuid:N0,generation:k.getMainQuotaIdentityGeneration(),stale:!1,state:_$}})();p4.set(_,{promise:N,recordVersion:z});try{return await N}finally{if(p4.get(_)?.promise===N)p4.delete(_)}}let u9=a0?.quotaHeaderFeed?.enabled===!0?new LW:null,p$=new Map,FZ=new Map,X1=new Set,G1=new AbortController,wZ=!1;function f4(Z,G){return JSON.stringify([Z,G??null])}function d9(Z){let G=Z.binding;if(Z.source!=="local"||!G)return;return JSON.stringify([G.storageId,G.rowId,G.credentialEpoch])}function i9(Z,G){return Z.lineage!==void 0&&Z.lineage===d9(G)&&(!Z.profile||Z.profile.accountIdentity===G.accountIdentity)}async function k4(Z,G){if(!Z?.profile||!q9(Z.profile,G)||!await Z.isCurrent?.())return;return Z.persistence==="refused"?void 0:Z.profile}function TZ(Z){if(!Z)return[];let G=new Set([...Z.main?["main"]:[],...(Z.accounts??[]).filter((W)=>B0(W)&&(W.enabled!==!1||Boolean(W.claustrumScopedCredentialId))).map((W)=>W.id)]);return[...new Set(p$.values())].filter((W)=>W.persistence==="failed"&&W.profile!==void 0&&G.has(W.accountId))}async function N8(Z,G,W,z){let _=G.accountId,L=W.accounts.find((Q)=>Q.id===_),N=L?.source==="local"?i9(G,L):L?.source==="vault"&&L.accountIdentity===z.accountIdentity;if(L?.type!=="oauth"||!y0(L)||L.accountIdentity!==z.accountIdentity||!N||await k4(G,Date.now())!==z)return Z;if(_==="main")return Z.main?{...Z,main:{...Z.main,profile:z}}:Z;let j=Z.accounts?.find((Q)=>Q.id===_);if(!j||!B0(j))return Z;return{...Z,accounts:Z.accounts.map((Q)=>Q.id===_&&B0(Q)?{...Q,profile:z}:Q)}}async function EZ(Z,G,W=TZ(Z)){if(!Z||W.length===0)return Z;let z=[];for(let N of W){let j=await k4(N,Date.now());if(j)z.push({hydration:N,profile:j})}if(!z.length)return Z;let _=G??await T.read(),L=Z;for(let N of z)L=await N8(L,N.hydration,_,N.profile);return L}function H8(Z,G,W){W$();let z=!1,_=Object.assign((N,j)=>{return z=!0,O(N,j)},{preconnect:O.preconnect}),L={accountId:Z.id,fetched:Promise.resolve(),lineage:d9(Z),...W&&{deadline:W}};return L.fetched=T.fetchProfileForDisplay(Z.id,_,AbortSignal.any([G1.signal,...W?[W]:[]])).then(({profile:N,persisted:j,isCurrent:Q})=>{if(L.settled=!0,N.accountIdentity!==void 0)FZ.set(f4(Z.id,N.accountIdentity),N);if(Z.accountIdentity===void 0||N.accountIdentity===Z.accountIdentity)L.profile=N,L.isCurrent=Q,L.persistence="pending";let U=j.then(async(C)=>{if(L.persistence=C,C==="failed")h.warn("quota","failed to persist account profile",{account:Z.id});else if(C==="refused")h.debug("quota","refused account profile publication",{account:Z.id});if((C==="saved"||C==="failed")&&!G1.signal.aborted){let f=C==="failed"&&await k4(L,Date.now());if(C==="saved"||f)try{let m=await T.read();if(!G1.signal.aborted)await C$(m.policyStorage,{...$$,routingAuthoritative:!1},m)}catch{h.debug("quota","failed to publish account profile to sidebar",{account:Z.id})}}});X1.add(U),U.then(()=>X1.delete(U))},(N)=>{if(L.settled=!0,L.failed=z,h.debug("quota","failed to hydrate account profile",{account:Z.id,error:N instanceof Error?N.message:String(N)}),!z&&p$.get(G)===L)p$.delete(G)}),X1.add(L.fetched),L.fetched.then(()=>X1.delete(L.fetched)),L}function D8(Z,G){let W=[G,Z.deadline].filter((_)=>_!==void 0);if(!W.length)return Z.fetched;let z=AbortSignal.any(W);if(z.aborted)return Promise.resolve();return new Promise((_)=>{let L=()=>{z.removeEventListener("abort",L),_()};z.addEventListener("abort",L,{once:!0}),Z.fetched.then(L)})}function SZ(Z,G){return q9(Z.profile,G)&&$W(Z.profile,Z.accountIdentity)}async function v4(Z){let G=await T.read();if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return G;let W=Date.now(),z=[],_=new Map;for(let j of G.accounts){if(j.type!=="oauth"||!y0(j)||SZ(j,W))continue;let Q=f4(j.id,j.accountIdentity),U=p$.get(Q);if(U&&j.accountIdentity===void 0&&(U.lineage===void 0||U.lineage!==d9(j)))U=void 0;if(!U&&j.accountIdentity!==void 0){let C=p$.get(f4(j.id));if(C&&i9(C,j))U=C,_.set(j.id,C)}if(U?.failed)continue;if(!U&&q9(FZ.get(Q),W))continue;if(!U||!U.profile&&(U.deadline?.aborted||U.settled)||U.profile&&!q9(U.profile,W)){if(Z?.aborted||G1.signal.aborted)continue;U=H8(j,Q,Z),p$.set(Q,U)}if(j.accountIdentity===void 0)_.set(j.id,U);z.push(D8(U,Z))}if(!z.length)return G;await Promise.all(z);let L=await T.read(),N=Date.now();for(let j of L.accounts){if(j.type!=="oauth"||!y0(j))continue;let Q=f4(j.id,j.accountIdentity),U=_.get(j.id);if(U&&j.accountIdentity!==void 0&&!p$.has(Q)&&i9(U,j))p$.set(Q,U);if(SZ(j,N))continue;let C=await k4(p$.get(Q),N);if(!C||C.accountIdentity!==j.accountIdentity)continue;if(j.profile=C,j.id==="main"){if(L.policyStorage.main)L.policyStorage.main.profile=C}else for(let f of L.policyStorage.accounts)if(f.id===j.id&&B0(f))f.profile=C}return L}async function U8(Z,G,W,z){if(process.env.OPENCODE_ANTHROPIC_AUTH_DISABLE_PROFILE_HYDRATION==="1")return Z;return(await v4(W)).policyStorage}let CZ=new Set;async function Q8(Z,G,W){let _=(await T.read()).accounts.find((U)=>U.id===Z.accountId);if(!_||!Z.anthropicAccountUuid||_.accountIdentity!==Z.anthropicAccountUuid)return null;let L={...y7(_.quota,G.quota),accountIdentity:_.accountIdentity};if(!(Z.scopedAttempt?await T.vault.publish(Z.scopedAttempt,{quota:L}):Z.localSubject?await T.publishLocal(Z.localSubject,{quota:L}):!1)){if(Z.accountId==="main"){if(k.getMain(Z.mainQuotaIdentity?.quotaKey)===W)k.clearMain()}else if(k.getAllFallbacks().get(Z.accountId)===W)k.clearFallback(Z.accountId);return h.debug("quota","native quota publication refused",{accountId:Z.accountId}),h.warn("quota","Quota publication discarded"),null}let j=await T.read(),Q=j.accounts.find((U)=>U.id===Z.accountId);if(!Q?.quota||Q.accountIdentity!==Z.anthropicAccountUuid||Q.source!==_.source)return null;if(Z.localSubject&&Q.binding?.credentialEpoch!==Z.localSubject.binding.credentialEpoch)return null;if(Z.scopedAttempt&&Q.credentialId!==Z.scopedAttempt.credentialId)return null;return{...G,quota:Q.quota,refreshAfter:w1(Q.quota,j.policyStorage,G.checkedAt)}}function B8(Z){h.warn("quota","failed to persist harvested response quota",{error:Z instanceof Error?Z.message:String(Z)})}function F8(Z){let G=Z instanceof Error?Z.name:typeof Z,W=Z instanceof Error?Z.message:String(Z),z=`${G}:${W}`;if(CZ.has(z))return;CZ.add(z),h.warn("quota","failed to normalize response quota headers",{error:W})}function w8(Z){if(!Z||typeof Z!=="object")return;let G=Z,W=G.credential_id;if(typeof W==="string"&&W&&W!=="main")return W;let z=G.vault;if(z&&typeof z==="object"){let _=z.credential_id;if(typeof _==="string"&&_&&_!=="main")return _}return}async function T8(Z,G){if(!u9)return;if(Z.accountId==="main"&&!Z.mainQuotaIdentity?.quotaKey)return;let W=await R(K)??o$(),_=(await W1?.())?.type==="oauth",L=Z.accountId==="main"?W.main:W.accounts.find((m)=>m.id===Z.accountId),N=w8(L),j=wG({storage:W,mainOAuthConfigured:_}),Q=G.checkedAt,U={five_hour:G.quota.five_hour,seven_day:G.quota.seven_day,bindingWindow:G.quota.bindingWindow,fallbackAdvised:G.quota.fallbackAdvised,scoped:G.quota.scoped,extraUsage:G.quota.extraUsage,fieldSources:G.quota.fieldSources},C=N??(Z.accountId==="main"?Z.mainQuotaIdentity?.quotaKey??"main":Z.accountId),f=N?{identity_source:"credential_id",credential_id:N,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"&&Z.mainQuotaIdentity?.quotaKey?{identity_source:"account_ref",account_ref:Z.mainQuotaIdentity.quotaKey,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:Z.accountId==="main"?{identity_source:"none",schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C}:{identity_source:"account_ref",account_ref:Z.accountId,schema_version:R9,provider:"anthropic",configured_account_count:j,observed_at_ms:Q,anthropic_account_uuid:Z.anthropicAccountUuid??null,quota:U,accountKey:C};await u9.publish(f)}function E8(Z){h.debug("quota","failed to publish quota header feed",{error:Z instanceof Error?Z.message:String(Z)})}function AZ(Z,G){try{if(!rG(Z)){h.trace("quota","skipped non-quota response headers",{account:G.accountId});return}let W=eG(Z),z=G.accountId==="main"?G.mainQuotaIdentity:void 0;if(G.accountId==="main"){if(!z||k.getMainQuotaIdentityGeneration()!==z.generation){h.trace("quota","discarded stale main quota headers",{boundIdentity:z?.quotaKey,currentGeneration:k.getMainQuotaIdentityGeneration()});return}}let _=G.accountId==="main"?k.getMain(z?.quotaKey):k.getAllFallbacks().get(G.accountId),L=W.checkedAt??Date.now(),N=I0(G.localSubject,G.scopedAttempt),j=N&&G.anthropicAccountUuid?{lineage:N,accountUuid:G.anthropicAccountUuid,entry:{quota:{...W,accountIdentity:G.anthropicAccountUuid},checkedAt:L,refreshAfter:L},generalExhausted:["five_hour","seven_day"].some((Q)=>{let U=Z.get(Q==="five_hour"?"anthropic-ratelimit-unified-5h-utilization":"anthropic-ratelimit-unified-7d-utilization");return W[Q]!==void 0&&U!==null&&Number.isFinite(Number(U))&&Number(U)>=1})}:void 0;if(j){if(o.delete(G.accountId),o.size>=iW){let Q=o.keys().next().value;if(Q!==void 0)o.delete(Q)}o.set(G.accountId,j)}(async()=>{let Q=!1;try{let U;try{U=await Q8(G,{quota:W,checkedAt:L,refreshAfter:L},_)}catch(f){B8(f);return}if(U===null)return;if(G.accountId==="main"&&k.getMainQuotaIdentityGeneration()!==z?.generation)return;let C=U;if(j&&o.get(G.accountId)===j)j.entry=C,Q=!0;if(G.accountId==="main")k.setMain(z?.quotaKey,C);else k.setFallback(G.accountId,C,{authLineageId:G.authLineageId});f1().catch(()=>{}),await T8(G,C),h.debug("quota","harvested response quota",{account:G.accountId,fiveHourPercent:C.quota.five_hour?.usedPercent,sevenDayPercent:C.quota.seven_day?.usedPercent,source:"headers"})}finally{if(!Q&&j&&o.get(G.accountId)===j)o.delete(G.accountId),h.debug("quota","discarded pending response quota",{accountId:G.accountId})}})().catch(E8),h.trace("quota","response quota awaiting publication",{account:G.accountId})}catch(W){F8(W)}}let PZ=Promise.resolve();function N1(Z=!1,G=!1,W,z){let _=PZ.then(()=>S8(Z,G,W,z));return PZ=_.then(()=>{},()=>{}),_}async function S8(Z,G,W,z){let _=await T.read(),L=new Set;if(!Z&&!G&&_.policyStorage.quota?.enabled===!1)return L;for(let N of _.accounts){if(N.id==="main"||N.type!=="oauth")continue;if(!y0(N)){if(G)L.add(N.id);continue}if(!Z&&w1(N.quota,_.policyStorage,E1(N.quota))>Date.now()&&(!W||A1(N.quota,_.policyStorage,Date.now(),W)))continue;try{if(!await k.refreshFallback(N.id,"",_.policyStorage.accounts.find((Q)=>Q.id===N.id&&B0(Q)),Z?void 0:z))L.add(N.id),h.debug("quota","fallback quota preflight returned no reading",{accountId:N.id,requiredByPolicy:G})}catch(j){if(G&&T1(j))throw j;L.add(N.id),x3(N.id,G,j)}}return f1().catch(()=>{}),L}let n9={refreshQuotaForDueAccounts:async()=>{await N1()},refreshQuotaForAllAccounts:async(Z)=>{await N1(!0)},refreshAccount:async(Z,G,W)=>{let z=await P0(Z.id,void 0,W?.force?Z.access:void 0);return{...Z,access:z.accessToken,expires:z.expires}},refreshAccountQuota:async(Z,G)=>{W$();let W=await T.fetchQuota(Z.id);return{account:{...Z,quota:W},fetched:!0}},getUsableFallbackAccounts:async(Z,G)=>{Z=Z??null;let W=[],z=Z?.accounts.some((_)=>B0(_)&&o.has(_.id))?(await T.read()).accounts:[];for(let _ of Z?.accounts??[]){if(!B0(_)||!y0(_))continue;let L=z.find((Q)=>Q.id===_.id),N=k.getFallback(_.id,L?.binding?{authLineageId:JSON.stringify(L.binding)}:_)?.quota??L?.quota??_.quota,j=L&&Z?O0({...L,quota:N},Z):N;if(!p1(j,Z)||!I9(j,G?.modelId)||r$(Z)&&!a$(j,Z,_.id,G?.modelId))continue;if(b0(Z)){if(z4(_.id,Z))W.push(_);continue}try{let Q=await P0(_.id,void 0,void 0,G?.modelId);W.push({..._,access:Q.accessToken,expires:Q.expires})}catch(Q){if(T1(Q))throw Q}}return W}};async function o9(){W$();let Z=await T.read();if(Z.mode==="local"&&Z.policyStorage.refresh?.enabled!==!1)for(let G of Z.accounts){if(G.id==="main"||G.type!=="oauth"||!y0(G))continue;try{let W=await P0(G.id);if(C1(G.lastRefreshError,G.accountIdentity,Date.now(),void 0))continue;if(W.localSource!=="rotated"&&W.localSource!=="adopted"&&(!W.expires||W.expires-Date.now()<=gZ(Z.policyStorage)))await P0(G.id,void 0,void 0,void 0,"refresh")}catch{}}await N1(!1,!1,void 0,"background")}let r9=a0!==null&&process.env.OPENCODE_AUTH_CONTENT===void 0,qZ=new Set;async function C8(){let Z=await T.read(),G=new Set(Z.accounts.filter((z)=>z.id!=="main"&&z.source==="vault"&&z.type==="oauth"&&y0(z)).map((z)=>z.id)),W=[...G].some((z)=>!qZ.has(z));if(qZ=G,W)await N1(!1,!1,void 0,"background");await f1()}let s9=r9&&b0(a0)?T.vault.watch({intervalMs:J.scopedRosterPollIntervalMs??2000,shouldRefresh:()=>process.env.OPENCODE_AUTH_CONTENT===void 0,onRefresh:C8,setInterval:Y.setInterval,clearInterval:Y.clearInterval}):void 0,A8=r9?(s9?s9.ready.then(()=>o9()):o9()).catch(()=>{}):Promise.resolve(),a9=r9?Y.setInterval(()=>{o9().catch(()=>{})},MG+J8(t7)):null;a9?.unref?.();let P8=(Z,G)=>{let W=SJ({id:Z,role:"fallback"},G);return W==="na"?"off":W},t9=new UJ,q8=new QJ,l$=new WeakMap,a1=new Map;async function e9(Z){let G=(Z.get("anthropic-beta")??"").split(",").map((W)=>W.trim()).filter(Boolean).sort();return{betas:G,betasHash:await FG(G.join(","))}}function RZ(Z){try{if(!Z.request)return;let G=G3({request:Z.request,source:Z.source,accountId:Z.accountId,synthetic:Z.synthetic,betasHash:Z.betasHash,requestedModel:Z.requestedModel,onWarning:(z)=>h.warn("cache-diagnostics",z),message:Z.message,receivedAt:Z.receivedAt});if(!G.record||!G.messageId){h.debug("cache-diagnostics","skipped invalid response envelope",{status:Z.status});return}h.debug("cache-diagnostics",W3(G.record));let W=q8.capture(Z.betasHash,Z.betas);if(W)h.debug("cache-diagnostics",W);if(G.canary)h.warn("cache-diagnostics","short-gap previous_message_not_found",{message_id:G.canary.messageId,previous_message_id:G.canary.previousMessageId});if(Z.trackSessionId)t9.capture(Z.trackSessionId,G.messageId,Z.receivedAt)}catch(G){h.debug("cache-diagnostics","response observation failed",{status:Z.status,error:G instanceof Error?G.message:String(G)})}}function MZ(Z,G,W=!0){let z=l$.get(Z);if(!z)return;if(G&&typeof G==="object"&&!Array.isArray(G)&&!W)z.messageStart=G;z.dumpWrite=z.dumpWrite.then(()=>eJ(z.dump,{status:z.status,message:G,complete:W})).catch(()=>{}),RZ({...z,message:G,receivedAt:Date.now()})}function R8(Z,G){let W=l$.get(Z);if(!W)return;let z=W.messageStart??{},_=z.usage&&typeof z.usage==="object"&&!Array.isArray(z.usage)?z.usage:{},L={...z,...G.usage?{usage:{..._,...G.usage}}:{},...G.stopReason?{stop_reason:G.stopReason}:{}};W.dumpWrite=W.dumpWrite.then(()=>eJ(W.dump,{status:W.status,message:L,complete:!0})).catch(()=>{})}function IZ(Z,G){let W=Promise.resolve(eJ(G.dump,{status:G.status,message:null,complete:!1})).catch(()=>{});l$.set(Z,{...G,dumpWrite:W})}let u$=null,h4=null;function b4(Z){return Z!==null&&typeof Z==="object"&&EJ(Z)==="R"}function M8(Z){let G=aJ("anthropic");if(!Z||typeof Z!=="object")return!1;let W=Z;return W.type===G.type&&W.access===G.access&&W.refresh===G.refresh&&W.expires===G.expires}async function I8(){if(h4){let Z=await h4();return pG("opencode",Z===void 0?{}:{anthropic:Z}).kind}if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("OpenCode logins cannot be checked while OPENCODE_AUTH_CONTENT is set");return DW("opencode",W8())}async function xZ(){if(await S1("opencode")!=="claustrum")throw Error("This host is not connected to the credential vault; run setup to connect it first");if(await I8()!=="absent")throw Error("OpenCode already holds an Anthropic login; remove it before choosing the vault login")}let x8={label:"Claude via credential vault",type:"oauth",authorize:async()=>{return await xZ(),{url:"",instructions:"Claude requests use the credential vault this host is connected to. OpenCode stores only a placeholder, never a credential.",method:"auto",callback:async()=>{await xZ();let Z=aJ("anthropic");return{type:"success",access:Z.access,refresh:Z.refresh,expires:Z.expires}}}}},$J=new zG({directory:process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||hG("opencode")}),g4=[],x1=new Map,t1=new VG({loadStorage:()=>R(K),setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,onTrackedSessionsChanged:async(Z)=>{await $J.publish(Z),g4=await $J.list(Z)},prepareBody:(Z,G)=>{if(!new Headers(G.headers).get("anthropic-beta")?.split(",").map((W)=>W.trim()).includes(V4))return Z;try{let W=JSON.parse(Z),z=t9.previousFor(G.id),_=z?.messageId??null;return r4(W,_),a1.set(G.id,{sessionId:G.id,previousMessageId:_,...z?{previousMessageReceivedAt:z.receivedAt}:{},isSubagent:G.isSubagent,ttlSent:s4(W),accountId:G.oauthAccountId??"main",synthetic:!0,requestedModel:typeof W.model==="string"?W.model:void 0}),JSON.stringify(W)}catch{return Z}},onResponse:async({target:Z,bodyText:G,status:W,data:z,receivedAt:_,attempt:L})=>{let N=x1.get(L.id);if(W===401&&N?.scopedAttempt)await M0(N.scopedAttempt,"direct");let j=a1.get(Z.id);if(!j?.betasHash||!j.betas){a1.delete(Z.id);return}try{let Q=JSON.parse(G),U=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q.diagnostics:void 0,C=U&&typeof U==="object"&&!Array.isArray(U)&&U.previous_message_id===j.previousMessageId?j.previousMessageId:void 0;if(C===void 0)return;RZ({source:"prewarm_cachekeep",accountId:j.accountId,synthetic:j.synthetic,betasHash:j.betasHash,betas:j.betas,requestedModel:j.requestedModel,request:{...j,previousMessageId:C,ttlSent:s4(Q)},trackSessionId:Z.id,status:W,message:z,receivedAt:_})}catch{}finally{a1.delete(Z.id)}},onComplete:({attempt:Z})=>{x1.delete(Z.id)},retryOnUnauthorized:async({target:Z,headers:G,attempt:W})=>{let z=x1.get(W.id);if(!z)return;let _;try{let j=JSON.parse(Z.bodyText);if(typeof j.model==="string")_=j.model}catch{}if(z.scopedAttempt&&!await L1(z.scopedAttempt,"cachekeep",W.signal))return;let L=await P0(Z.oauthAccountId??"main",W.signal,z.scopedAttempt?void 0:z.accessToken,_);if(L.accountIdentity!==z.accountIdentity||Boolean(L.scopedAttempt)!==Boolean(z.scopedAttempt))return;if(z.scopedAttempt&&(!L.scopedAttempt||L.scopedAttempt.credentialId!==z.scopedAttempt.credentialId||L.scopedAttempt.recordVersion<=z.scopedAttempt.recordVersion))return;if(!z.scopedAttempt&&L.accessToken===z.accessToken)return;let N=new Headers(G);return N.set("authorization",`Bearer ${L.accessToken}`),x1.set(W.id,L),N},prepareHeaders:async(Z,G,W)=>{let z=G.oauthAccountId??"main",_;try{let Q=JSON.parse(G.bodyText);if(typeof Q.model==="string")_=Q.model}catch{}let L=await P0(z,W.signal,void 0,_),N=L.accessToken;x1.set(W.id,L);try{let Q=JSON.parse(G.bodyText),U=J1(L.accountIdentity);if(Z.delete("anthropic-beta"),m1(Z,N,{body:Q,identity:U}),Z.set("anthropic-beta",g7(Z.get("anthropic-beta"),[WG])),Q.speed==="fast")N9(Z);let C=a1.get(G.id);if(C){let{betas:f,betasHash:m}=await e9(Z);C.betas=f,C.betasHash=m}}catch{m1(Z,N)}let j=await P0(z,W.signal,void 0,_);if(j.accountIdentity!==L.accountIdentity||Boolean(j.scopedAttempt)!==Boolean(L.scopedAttempt))throw Error("CacheKeep credential authority changed before dispatch");return Z.set("authorization",`Bearer ${j.accessToken}`),x1.set(W.id,j),Z}});async function f8(Z){if(!u$||!(await u$()).active)throw Error("Native main OAuth activation is not available");let G=await P0("main",Z);return{...G,credentialAccountId:F$(G.accountIdentity)}}async function k8(){let Z=await f8();if((await s1(Z.accessToken,void 0,Z.credentialAccountId)).stale&&Z.credentialAccountId!==void 0)throw Error("Main account identity changed before the prime refresh");let W=await k.refreshMainWithMetadata(H$,Z.accessToken);return{quota:W.quota,fresh:W.fetched}}async function v8(Z){W$();let G=await R(K),W=G?.accounts.find((_)=>_.id===Z&&y0(_)&&B0(_));if(!W||!G)throw Error(`prime: OAuth account ${Z} is unavailable`);let z=await n9.refreshAccountQuota(W,G);return{quota:z.account.quota??{},fresh:z.fetched}}let JJ=new Map;async function h8(Z){let G=performance.now(),W,z,_,L="",N;try{if(Z==="main"&&(!u$||!(await u$()).active))throw Error("Native main OAuth activation is not available");let j=await P0(Z,void 0,void 0,T7);if(W=j.accessToken,_=j.scopedAttempt,z=T7,!W)return{ok:!1,error:"prime: no access token available"};let Q=GG(),U=J1(j.accountIdentity),C=await H9(JSON.stringify(Q),{identity:U}),f=new Headers({"content-type":"application/json"});m1(f,W,{body:JSON.parse(C),identity:U,requestClass:"auxiliary"}),f.delete("content-length"),f.delete("transfer-encoding");let m=Q4(RW,{baseURL:""}),J0=m.url?.toString()??m.input.toString(),_0=AbortSignal.timeout(30000),f0={method:"POST",headers:f,body:C,signal:_0},w0=await P0(Z,_0,void 0,z);if(w0.accountIdentity!==j.accountIdentity||Boolean(w0.scopedAttempt)!==Boolean(j.scopedAttempt))throw Error("Prime credential authority changed before dispatch");_=w0.scopedAttempt,L=w0.accessToken,f.set("authorization",`Bearer ${L}`);let k0=async()=>{let Q0=E9([L],"http");return N=Q0,Q0.redactResponse(await fetch(J0,f0))},N0=await k0();if(N0.status===401&&_&&!_0.aborted){let Q0;try{Q0=await L1(_,"prime",_0)}catch{}if(Q0){N?.dispose(),await N0.body?.cancel().catch(()=>{}),h.info("claustrum","retrying Prime after scoped credential rotation",{accountId:Z,previousVersion:_.recordVersion,newVersion:Q0.recordVersion}),w0=await P0(Z,_0,void 0,z);let v0=w0.scopedAttempt;if(!v0||v0.credentialId!==_.credentialId||v0.accountIdentity!==_.accountIdentity||v0.recordVersion<=_.recordVersion)throw Error("Prime vault retry lost its strict newer receipt");_=v0,L=v0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}if(N0.status===401&&!w0.scopedAttempt&&!_0.aborted){let Q0=w0.accessToken,v0=await P0(Z,_0,Q0,z).catch(()=>{return});if(v0&&v0.accessToken!==Q0&&v0.accountIdentity===j.accountIdentity&&!v0.scopedAttempt){if(N?.dispose(),await N0.body?.cancel().catch(()=>{}),w0=await P0(Z,_0,void 0,z),w0.scopedAttempt||w0.accountIdentity!==j.accountIdentity)throw Error("Prime local authority changed before retry");L=w0.accessToken,f.set("authorization",`Bearer ${L}`),N0=await k0()}}let _$=Math.round(performance.now()-G);if(!N0.ok){let Q0;try{Q0=await N0.text().catch(()=>"")||`HTTP ${N0.status}`}finally{N?.dispose()}if(N0.status===401&&_)await M0(_,"direct");return{ok:!1,status:N0.status,ms:_$,error:Q0}}let D$=(await N0.json().catch(()=>null))?.usage,U$=D$&&(Number.isFinite(D$.input_tokens)||Number.isFinite(D$.output_tokens))?{inputTokens:Number.isFinite(D$.input_tokens)?D$.input_tokens:void 0,outputTokens:Number.isFinite(D$.output_tokens)?D$.output_tokens:void 0}:void 0;return JJ.set(Z,w0),{ok:!0,status:N0.status,ms:_$,...U$&&{usage:U$}}}catch(j){N?.dispose();let Q=E9([L],"http"),U=Q.redactError(j);return Q.dispose(),{ok:!1,...j instanceof O$&&j.tokenRefreshFailed&&{reason:"token-refresh"},ms:Math.round(performance.now()-G),error:U instanceof Error?U.message:String(U)}}}let fZ={storagePath:K,loadStorage:()=>R(K),getAccountFingerprint:async(Z)=>{if(Z==="main"&&(!u$||!(await u$()).active))return;let G=await P0(Z),W=G.scopedAttempt??G.localSubject;if(!W)return;let z=await T.getOrCreateAuthLineage(Z,W);return z?t$(z):void 0},refreshQuota:async(Z)=>{if(Z==="main")return k8();return v8(Z)},sendPrime:h8,recordSuccess:async(Z,G)=>{let W=JJ.get(Z);JJ.delete(Z);let z=W?.scopedAttempt??W?.localSubject;if(!z||!await T.incrementPrimeUsage(Z,z,G))throw Error("Prime usage publication lost its native credential fence");let _=(await T.read()).accounts.find((L)=>L.id===Z)?.prime;if(!_)throw Error("Prime usage counters are unavailable after publication");return _},setIntervalImpl:Y.setInterval,clearIntervalImpl:Y.clearInterval,setTimeoutImpl:Y.setTimeout,clearTimeoutImpl:Y.clearTimeout},kZ=I3(K,()=>new ZW(fZ),{slot:$.directory??"default",rebind:(Z)=>Z.updateOptions(fZ)}),H1=kZ.manager;if(P9(a0))H1.start();async function y4(){return g4=await $J.list(t1.trackedSessions()),g4}let vZ=J.cacheKeepAggregateRefreshIntervalMs??1e4,ZJ=vZ>0?Y.setInterval(()=>{y4().catch(()=>{})},vZ):void 0;if(ZJ?.unref?.(),x9({enabled:A9(a0),mode:w4(a0)}),jZ(WZ(a0)),LZ(zZ(a0)),!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)SW(XZ(a0)??"info");let YJ=null,b8=async()=>{G1.abort();while(X1.size)await Promise.all([...X1]);try{await d1(K)}catch(Z){h.warn("claustrum","failed to close scoped runtime",{error:Z instanceof Error?Z.message:String(Z)})}try{k.close()}catch{}try{await u9?.dispose()}catch(Z){h.warn("quota-header-feed","failed to dispose",{error:Z instanceof Error?Z.message:String(Z)})}try{if(U1)Y.clearInterval(U1),U1=null}catch(Z){h.warn("main-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(a9)Y.clearInterval(a9)}catch(Z){h.warn("fallback-background","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{if(ZJ!==void 0)Y.clearInterval(ZJ)}catch(Z){h.warn("cachekeep","failed to stop aggregate refresh",{error:Z instanceof Error?Z.message:String(Z)})}try{t1.stop()}catch(Z){h.warn("cachekeep","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}try{kZ.release()}catch(Z){h.warn("prime","failed to release slot",{error:Z instanceof Error?Z.message:String(Z)})}if(!YJ)return;try{await YJ.release()}catch(Z){h.warn("rpc","failed to stop",{error:Z instanceof Error?Z.message:String(Z)})}},$$={activeId:"main",route:"main"},g8=V8(),S$=new Map;function m4(Z,G){if(k.updateStorage(Z),k.seedMainFromStorage(Z,H$),!G.skipFallbackQuotaSeed)k.seedFallbacksFromAccounts((Z?.accounts??[]).filter(B0));let W=k.getMain(H$),z=k.getLastApiError(),_=Z?.refresh?.mainLastRefreshError,L=Z?.claustrum?.primaryAccount,N=b0(Z)&&!y0(L)?ZZ({source:"vault",enabled:L?.enabled,state:L?.state}):void 0;return{main:{quota:W?.quota??null,enabled:L?.enabled,tierLabel:B4(Z?.main?.profile),quotaBackedOff:k.isBackedOff(),quotaBackoffUntil:z?.nextRetryAt,refreshBackedOff:_?C1(_,e1??Z?.mainAccountId,Date.now(),G.mainRefreshToken?t$(G.mainRefreshToken):void 0):!1,refreshBackoffUntil:_?.nextRetryAt,stateLine:N,quotaDated:Boolean(N)},fallbacks:(Z?.accounts??[]).filter((j)=>B0(j)&&(j.enabled!==!1||Boolean(j.claustrumScopedCredentialId))).map((j)=>{let Q=z4(j.id,Z),U=P8(j.id,Z),C=j.claustrumScopedCredentialId&&!Q?ZZ({source:"vault",enabled:j.enabled!==!1,state:j.claustrumScopedState}):void 0;return{id:j.id,label:j.label,tierLabel:B4(j.profile),quota:G.skipFallbackQuotaSeed?null:k.getFallback(j.id,j)?.quota??j.quota??null,needsReauth:j.lastRefreshError!=null&&C1(j.lastRefreshError,j.id,Date.now(),t$(j.refresh))&&s$(j.lastRefreshError),vaultReauth:U==="on-vault-reauth",vaultServed:Q,custodyState:U,enabled:j.enabled!==!1,stateLine:C,quotaDated:Boolean(C)}}),activeId:G.activeId,route:G.route,relay:AG(Z?.relay),fastMode:VZ(),cacheKeep:{enabled:v7(Z),window:k7(Z)?"always":Z?.cacheKeep?.startHour!=null&&Z?.cacheKeep?.endHour!=null?`${Z.cacheKeep.startHour}-${Z.cacheKeep.endHour}`:void 0,trackedSessions:g4.length},prime:P9(Z)?{enabled:!0,accounts:H1.stats(Z)}:void 0,fableRecoveries:S$.size>0?[...S$.values()]:void 0,lastUpdated:Date.now()}}function C$(Z,G,W){let z=G.routingAuthoritative!==!1;if(z)$$={activeId:G.activeId,route:G.route};function _(L){return K8(L,g8,{routingAuthoritative:z,resolvePreservedRouting:z?void 0:async(N)=>{let j=await vW(N,()=>R(K),{activeId:L.activeId,route:L.route}),Q=await EZ(j.freshStorage,W);return{activeId:j.activeId,route:j.route,state:m4(Q,{...G,activeId:j.activeId,route:j.route})}},onRoutingResolved:z?void 0:(N)=>{$$=N}}).catch((N)=>h.warn("sidebar","state write failed",{error:N instanceof Error?N.message:String(N)}))}if(z){let L=TZ(Z);if(L.length>0)return EZ(Z,W,L).then((N)=>_(m4(N,G))).catch(()=>{return h.debug("quota","failed to recheck account profile for sidebar"),_(m4(Z,G))})}return _(m4(Z,G))}async function hZ(){return{storage:await R(K),access:void 0}}async function f1(){await y4().catch(()=>{});let{storage:Z,access:G}=await hZ();C$(Z,{activeId:$$.activeId,route:$$.route,mainAccessToken:G,mainRefreshToken:void 0,routingAuthoritative:!1})}function y8(Z,G,W){if(!G)return;if(Z?.quota?.enabled!==!0)return;let z=W?.quotaKey??H$;if(k.getMain(z))return;if(GJ)return;GJ=!0,k.refreshMain(z,G,W?.generation).then(()=>f1()).catch(()=>{}).finally(()=>{GJ=!1})}let W1=null,c4,e1,H$,$4,D1,XJ,bZ=0,p4=new Map,GJ=!1,U1=null,l4=0;function gZ(Z){let G=Z?.refresh?.refreshBeforeExpiryMinutes??IW;return Math.max(_8,G)*60000}function m8(Z){return Z?.refresh?.enabled!==!1}async function yZ(Z=!1){let G=new Map;if(Z){if(u$&&(await u$()).active)try{await T.fetchQuota("main")}catch{G.set("main","Native primary usage refresh unavailable")}await N1(!0)}let W=await v4(AbortSignal.timeout(3000));k.updateStorage(W.policyStorage),k.seedMainFromStorage(W.policyStorage,H$),k.seedFallbacksFromAccounts(W.policyStorage.accounts.filter(B0));let z=[],_=W.accounts.find((N)=>N.id==="main"&&N.type==="oauth");if(_)z.push({name:_.label??"OpenCode anthropic",role:"main",quota:_.quota,tierLabel:B4(_.profile),error:G.get("main")??_.lastQuotaRefreshError?.message});z.push(...XG(W.policyStorage,G));let L=Math.max(0,...W.accounts.map((N)=>E1(N.quota)));return YG({accounts:z,refreshedAt:L||void 0})}async function WJ(Z){await y4().catch(()=>{}),await C$(Z,{activeId:$$.activeId,route:$$.route,routingAuthoritative:!1})}function J4(Z,G,W,z){if(S$.delete(Z.sessionId),S$.set(Z.sessionId,{...Z,changedAt:Date.now()}),S$.size>128){let _=S$.keys().next().value;if(_)S$.delete(_)}if(C$(G,{activeId:$$.activeId,route:$$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1}),z)pZ(Z.sessionId,z)}function mZ(Z,G){let W=c$.get(Z)??new Set;W.delete(G),W.add(G);while(W.size>4){let z=W.values().next().value;if(typeof z!=="string")break;W.delete(z)}c$.delete(Z),c$.set(Z,W);while(c$.size>128){let z=c$.keys().next().value;if(typeof z!=="string")break;c$.delete(z)}}function cZ(Z,G){return typeof G==="string"&&c$.get(Z)?.has(G)===!0}function pZ(Z,G){if(V9(Z))return;N$.delete(Z),N$.set(Z,[G]);while(N$.size>128){let W=N$.keys().next().value;if(W)N$.delete(W);else break}if(X$.has(Z))VJ(Z)}function VJ(Z,G=0){if(!N$.has(Z)||o1.has(Z))return;o1.set(Z,G);let W=()=>{if(o1.get(Z)!==G)return;o1.delete(Z),c8(Z,G)};if(G===0)setImmediate(W);else setTimeout(W,gW*G)}function zJ(Z,G){if(G+1<bW)VJ(Z,G+1)}async function c8(Z,G){if(!X$.has(Z)||!N$.has(Z))return;let W=$.client.session;if(typeof W?.status==="function")try{let z=await Promise.resolve(W.status()),_=z!==null&&typeof z==="object"?z:void 0,L=_&&Object.hasOwn(_,"data")?_.data:_;if(L===null||typeof L!=="object"||Array.isArray(L)){zJ(Z,G);return}let N=L[Z];if(N!==void 0&&(!N||typeof N!=="object"||N.type!=="idle")){zJ(Z,G);return}}catch{zJ(Z,G);return}if(!X$.has(Z))return;await p8(Z)}function p8(Z){let G=I4.get(Z);if(G)return G;let W=(async()=>{while(!0){let z=N$.get(Z),_=z?.[0];if(!_){N$.delete(Z);return}try{let L=()=>N$.get(Z)===z&&z[0]===_;if(!await Z8($,Z,_,{noReply:!0,beforeActiveAssistant:!0,canSend:()=>X$.has(Z)&&L(),onPreparedMessageId:(j)=>mZ(Z,j),latestPreparedMessageId:()=>[...c$.get(Z)??[]].at(-1)})){if(X$.has(Z)&&!L())continue;return}if(L())z.shift()}catch(L){h.warn("fable-fallback","Desktop notification failed",{session:Z,error:L instanceof Error?L.message:String(L)})}}})();return I4.set(Z,W),W.finally(()=>{if(I4.get(Z)===W)I4.delete(Z)}),W}function l8(Z,G,W,z){if(G.fallback&&G.targetModel){let _=k$.get(Z.recoveryKey);k$.delete(Z.recoveryKey),k$.set(Z.recoveryKey,G.targetModel);while(k$.size>128){let N=k$.keys().next().value;if(N)k$.delete(N);else break}let L=S$.get(Z.sessionId);if(_===G.targetModel&&L?.mode==="server"&&b$(L.requestedModelId)===b$(Z.requestedModel)&&L.targetModelId===G.targetModel)return;h.info("fable-fallback","Anthropic server-side safety fallback active",{session:Z.sessionId,requestedModel:Z.requestedModel,targetModel:G.targetModel,handoff:G.handoff}),J4({sessionId:Z.sessionId,mode:"server",remaining:0,requestedModelId:Z.requestedModel,targetModelId:G.targetModel},W,z,rW(Z.requestedModel,G.targetModel));return}if(G.stopReason==="refusal"||!k$.delete(Z.recoveryKey))return;h.info("fable-fallback","Anthropic server-side safety fallback ended",{session:Z.sessionId,requestedModel:Z.requestedModel}),J4({sessionId:Z.sessionId,mode:"fable",remaining:0,requestedModelId:Z.requestedModel},W,z,sW(Z.requestedModel))}function u8(Z,G,W){if(!Z)return;for(let z of k$.keys())if(z.startsWith(`${Z}\x00`))k$.delete(z);if(!S$.delete(Z))return;C$(G,{activeId:$$.activeId,route:$$.route,mainAccessToken:W.access,mainRefreshToken:W.refresh,routingAuthoritative:!1})}async function KJ(Z){let G=XW(Z);if(G.type==="enable"||G.type==="disable"){let L=G.type==="enable",N=await q1(L),j=w4(N);return x9({enabled:L,mode:j}),h.info("commands","cache enabled changed",{enabled:L}),JZ({argumentsText:Z,enabled:L,mode:j,settingsPath:await T.getSettingsPath()})}if(G.type==="mode"){let L=await q4(G.mode),N=A9(L);return x9({enabled:N,mode:G.mode}),h.info("commands","cache mode changed",{mode:G.mode}),JZ({argumentsText:Z,enabled:N,mode:G.mode,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=A9(W),_=w4(W);return x9({enabled:z,mode:_}),JZ({argumentsText:Z,enabled:z,mode:_})}async function Z4(Z){let G=GW(Z),W=await R(K);if(G.type==="window")W=await R1(G.startHour,G.endHour),h.info("commands","cachekeep schedule changed",{schedule:`${G.startHour}-${G.endHour}`});else if(G.type==="always")W=await $1(),h.info("commands","cachekeep schedule changed",{schedule:"always"});else if(G.type==="disable")W=await R4(!1),h.info("commands","cachekeep enabled changed",{enabled:!1});else if(G.type==="subagents")W=await M4(G.enabled),h.info("commands","cachekeep subagents changed",{subagents:G.enabled});let z=x7(W),_=await y4(),L=_.length?Math.min(..._.map((N)=>N.nextPrewarmAt)):void 0;return qG({argumentsText:Z,enabled:lG(W),always:k7(W),window:z,hybridActive:v7(W),trackedSessions:_.length,trackedSessionDetails:_,nextPrewarmAt:L})}async function lZ(Z){let G=WW(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await _1(_),jZ(_),h.info("commands","dump changed",{enabled:_}),S7({argumentsText:Z,enabled:_,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=WZ(W);return jZ(z),S7({argumentsText:Z,enabled:z})}async function uZ(Z){let G=VW(Z);if(G.type==="enable"||G.type==="disable"){let _=G.type==="enable";return await h9(_),LZ(_),h.info("commands","fast mode changed",{enabled:_}),C7({argumentsText:Z,enabled:_,settingsPath:await T.getSettingsPath()})}let W=await R(K),z=zZ(W);return LZ(z),C7({argumentsText:Z,enabled:z})}async function dZ(Z,G){if(zW(Z).type==="fire"){if(!G)return`## Claude Start Failed
|
|
24
24
|
|
|
25
25
|
- OpenCode did not provide a session ID.`;try{return await P3($.client,G),P7({argumentsText:Z}).text}catch(z){return`## Claude Start Failed
|
|
26
26
|
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{p as a}from"./index-
|
|
1
|
+
import{p as a}from"./index-0tb7qc58.js";import"./index-6chd6jnr.js";import"./index-hazrk5c3.js";import"./index-b1dvkp15.js";import"./index-20d6rmjj.js";import"./index-ppdrzs41.js";import"./index-62x1p34p.js";export{a as AnthropicAuthPlugin};
|
package/dist/v2/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as k2,b as
|
|
1
|
+
import{a as k2,b as h$,c as l$,d as W$,e as Q$,f as D2,g as R2,h as H$,i as U$,j as d$,k as B$,l as K$,m as M$,n as z$,o as _$,p as s$}from"../index-0tb7qc58.js";import"../index-6chd6jnr.js";import"../index-hazrk5c3.js";import{u as n$}from"../index-jvhs8sxv.js";import{v as i$,w as c$,y as o$}from"../index-0kxy8k2c.js";import"../index-b1dvkp15.js";import"../index-20d6rmjj.js";import"../index-ppdrzs41.js";import"../index-62x1p34p.js";import{acquireNativeAccountRuntime as xX,authorize as AX,createNativeUi as qX,disconnectNativeVaultForHost as kX,exchange as DX,logger as u$,readNativeEnrollmentMode as bX,resolveNativePoolPaths as wX}from"@cortexkit/anthropic-auth-core";class O2 extends Error{kind;providerID;sessionID;requestKind;constructor(X){super(X.message??`${X.providerID} ${X.requestKind} request refused (${X.kind})`);this.name="OpenCode2AuthError",this.kind=X.kind,this.providerID=X.providerID,this.sessionID=X.sessionID,this.requestKind=X.requestKind}}function M2(X){return`common-auth-placeholder.${X}`}function $$(X){let J=M2(X.integrationID);return{type:"oauth",methodID:X.methodID,access:J,refresh:J,expires:X.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function v2(X,J){if(X?.type!=="oauth")return!1;let M=J===void 0?void 0:M2(J),V=(F)=>M===void 0?F.startsWith("common-auth-placeholder."):F===M;return V(X.access)&&V(X.refresh)}var X$="No browser sign-in: this connects the plugin to the accounts in its vault.";async function h2(X,J){let M=J.now??Date.now,{integrationID:V}=J,F=(T)=>$$({integrationID:V,methodID:T,now:M()}),L=async(T,K)=>{return await J.onLogin(T,{integrationID:V,methodID:K}),F(K)},P=(T)=>async(K)=>{let Y=T.method.id,B=await T.authorize(K),W={url:B.url,instructions:B.instructions,...B.expiresAt===void 0?{}:{expiresAt:B.expiresAt}};if(B.mode==="auto")return{...W,mode:"auto",callback:B.callback.then((O)=>L(O,Y))};let U=B.callback;return{...W,mode:"code",callback:async(O)=>L(await U(O),Y)}};return X.integration.transform((T)=>{let K=J.label===void 0?{}:{label:()=>J.label};for(let W of J.methods)T.method.update({integrationID:V,method:W.method,authorize:P(W),refresh:async(U)=>{if(!v2(U,V))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return F(U.methodID)},...K});let Y=J.vault;if(Y===void 0)return;let B=Y.method.id;T.method.update({integrationID:V,method:Y.method,authorize:async()=>({url:"",instructions:Y.instructions??X$,mode:"auto",callback:Promise.resolve().then(()=>Y.activate({integrationID:V,methodID:B})).then(()=>F(B))}),refresh:async(W)=>{if(!v2(W,V)||W.methodID!==B)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return F(B)},...K})})}function a$(X){let J=[],M;for(let V of X.split(/\r?\n/))if(V.startsWith("data:"))J.push(V.slice(5).replace(/^ /,""));else if(V.startsWith("event:"))M=V.slice(6).trim();if(J.length===0)return;return M===void 0?{data:J.join(`
|
|
2
2
|
`)}:{event:M,data:J.join(`
|
|
3
|
-
`)}}function m2(X,J){let M=new TextDecoder,G="",F=(P)=>{let T=s$(P);if(!T)return;try{X(T)}catch(K){J(K)}},C=()=>{for(;;){let P=/\r?\n\r?\n/.exec(G);if(!P)return;let T=G.slice(0,P.index);G=G.slice(P.index+P[0].length),F(T)}};return new TransformStream({transform(P,T){T.enqueue(P),G+=M.decode(P,{stream:!0}),C()},flush(){if(G+=M.decode(),C(),G.trim()!=="")F(G);G=""}})}var J$=512,C2="x-common-auth-attempt",z2=(X,J)=>JSON.stringify([X,J]),Q2=(X)=>({providerID:X.model.providerID,modelID:X.model.id,sessionID:X.sessionID,agent:X.agent,kind:X.kind});function a$(X){let J=X.headers;return typeof J==="object"&&J!==null}function t$(X,J){let M=X.getReader();return new ReadableStream({async pull(G){let F;try{F=await M.read()}catch(C){J({reason:"failed",message:C instanceof Error?C.message:String(C)}),G.error(C);return}if(F.done)J(),G.close();else G.enqueue(F.value)},async cancel(G){J({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await M.cancel(G)}})}function l2(X,J){for(let[M,G]of Object.entries(J)){let F=M.toLowerCase();for(let C of Object.keys(X))if(C.toLowerCase()===F)delete X[C];if(G!==null)X[M]=G}}function e$(X,J){for(let[M,G]of Object.entries(J))if(G===null)X.delete(M);else X.set(M,G)}async function d2(X,J,M={}){let{providerID:G}=J,F=M.gateOnPlaceholder,C=($)=>F===void 0||F.credential($)===M2(G),P=M.logger,T=Math.max(1,M.maxRecords??J$),K=[...M.hostCredentials??[M2(G)],...F?[M2(G)]:[]].filter(($)=>$!==""),Y=new Map,B=new WeakMap,V=new Map,U=new Set,O=new Map,q=!1,x=!1,m=new Map,w=0,o=!1,r=new Map,i=($,Q)=>{try{P?.warn($,Q)}catch{}},s=($)=>$ instanceof Error?$.message:String($),Z=new Map,W=($,Q)=>{let _=(Z.get($)??Promise.resolve()).then(Q),N=_.then(()=>{},()=>{});return Z.set($,N),N.then(()=>{if(Z.get($)===N)Z.delete($)}),_},j=($,Q)=>{let _=Z.get($);return _?_.then(()=>j($,Q)):Q()},A=async($)=>{try{await J.dropChoice?.({...$.input,accountId:$.accountId})}catch(Q){i("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:$.input.sessionID,error:s(Q)})}},R=($)=>{let Q=V.get($);if(V.delete($),Q?.next){let _=Q.next;W(Q.sessionID,()=>A(_))}},b=async($,Q)=>{let _=m.get($);if(!_||_.size===0)return;await Promise.all([..._].map(async(N)=>{try{await N(Q)}catch(I){i("opencode2 auth listener threw; the request is unaffected",{event:$,error:s(I)})}}))},y=async($,Q)=>{try{await J.onAttemptEnd?.($,Q)}catch(_){i("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:$.attemptId,error:s(_)})}},d=($,Q)=>{if($.ended||!$.attempt)return;let _={...$.status===void 0?{}:{status:$.status},outputStarted:$.outputStarted,...$.limit?{limit:$.limit.signal}:{},...Q?{error:Q}:{}};if(Q)$.endError=Q;$.ended=y($.attempt,_)},p=($,Q)=>d($,{reason:"abandoned",message:Q}),f=($)=>[...Y.values()].filter((Q)=>Q.key===$),c=($)=>f($).at(-1),l=($)=>{if(Y.delete($.id),V.get($.key)?.attemptId===$.id||!f($.key).length)R($.key)},H=($)=>{Y.set($.id,$);while(Y.size>T){let Q=Y.values().next().value;if(Q===void 0)break;p(Q,"dropped to keep the record bound"),l(Q)}},z=($)=>$.accountId===void 0?void 0:{...$.scope,accountId:$.accountId},L=($,Q)=>new O2({kind:"no-account",providerID:G,sessionID:$.sessionID,requestKind:$.kind,...Q===void 0?{}:{message:Q}}),E=($)=>{r.get($)?.clear(),r.delete($)},S=async($,Q)=>{let _=()=>L($,`${G} ${$.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(o)throw _();let N=r.get($.sessionID);if(!N)N=new Set,r.set($.sessionID,N);let I={};N.add(I);let v=()=>{if(!N.has(I))throw _()};try{return await Q(v)}finally{if(N.delete(I),N.size===0&&r.get($.sessionID)===N)r.delete($.sessionID)}},D=($,Q)=>{for(let[_,N]of Q)if(K.some((I)=>N.includes(I)))throw new O2({kind:"host-credential-on-wire",providerID:G,sessionID:$.sessionID,requestKind:$.kind,message:`${G} ${$.kind} request still carries the host's placeholder credential in ${_}; the adapter's account headers must replace it`})},g=($)=>{for(let Q of f($))if(Q.ended||!Q.attempt)l(Q);else if(Q.transport==="ws"||Q.judged)p(Q,"a newer attempt of its session and kind began"),l(Q)},n=async($,Q,_,N)=>{let I=z2($.sessionID,$.kind),{input:v,accountId:k}=await j($.sessionID,async()=>{_();let e=V.get(I);V.delete(I);let L2=e?.accountId??c(I)?.accountId;g(I);let X2=e?.next,T2=X2!==void 0&&X2.input.modelID===$.modelID&&X2.input.agent===$.agent,U2={...$,phase:"request",...L2===void 0?{}:{previousAccountId:L2},...e?.rerouteFrom?{rerouteFrom:e.rerouteFrom}:{}};if(X2&&!T2)await W($.sessionID,()=>A(X2)),_();let A2=T2?X2.accountId:await J.chooseAccount(U2);return{input:U2,accountId:A2}});_();let h={},a;if(k!==void 0){let e=await J.accountHeaders({...$,accountId:k});if(_(),a$(e))h=e.headers,a=e.attempt;else h=e}let V2=`attempt-${++w}`,G2={id:V2,key:I,scope:$,accountId:k,headers:h,attempt:k===void 0?void 0:{...$,accountId:k,attemptId:V2,transport:N,data:a},...N===void 0?{}:{transport:N},outputStarted:!1};if(H(G2),G2.attempt)b("select",{...$,accountId:G2.attempt.accountId,hook:Q,...v.previousAccountId===void 0?{}:{previousAccountId:v.previousAccountId},...v.rerouteFrom===void 0?{}:{rerouteFrom:v.rerouteFrom},handle:G2.attempt});return G2},u=async($,Q,_,N,I)=>{let v=z2($.sessionID,$.kind),k=N===void 0?void 0:Y.get(N);if(k?.key!==v)k=void 0;if(!k){if(k=c(v),f(v).filter((a)=>a.transport===void 0&&!a.ended).length>1&&!x)x=!0,i("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:$.sessionID,kind:$.kind})}if(!k||k.transport!==void 0||k.ended)k=await n($,Q,I,_);else if(k.transport=_,k.attempt)k.attempt.transport=_;if(_==="ws"){for(let h of f(v))if(h!==k&&h.transport==="ws")p(h,"a newer attempt of its session and kind went out over WebSocket")}return k},J2=async($,Q)=>{try{return await Q()}catch(_){throw d($,{reason:"failed",message:s(_)}),_}},j2=($,Q)=>{let _=f(z2($,Q)).filter((N)=>N.transport==="ws").at(-1);return _?.attempt!==void 0&&!_.ended?_:void 0},Z2=($,Q,_)=>{let N=z($);if(!N||!$.attempt||$.limit)return;$.limit={signal:Q,delivered:b("limit",{...N,via:_,limit:Q,outputStarted:$.outputStarted,handle:$.attempt})}},N2=($,Q,_,N)=>{let I=z($);if(!I||!$.attempt)return;b("quota",{...I,transport:Q,...N===void 0?{}:{status:N},quota:_,handle:$.attempt})},$2=($,Q,_,N)=>{let I=$.attempt;if(!I)return;let v=J.inspectEvent?.(N===void 0?{transport:Q,data:_,attempt:I}:{transport:Q,data:_,event:N,attempt:I});if(!v)return;if(v.quota!==void 0)N2($,Q,v.quota);if(v.outputStarted)$.outputStarted=!0;if(v.limit)Z2($,v.limit,Q);if(v.error!==void 0)d($,{reason:"failed",message:v.error});else if(v.done)d($)},t=($,Q)=>{let _=$.attempt;if(!_||Q.accountId===$.accountId)return;if(_.reboundFrom??=_.accountId,_.accountId=Q.accountId,"data"in Q)_.data=Q.data;$.accountId=Q.accountId},B2=($)=>!$.attempt||$.endError!==void 0||$.status!==void 0&&$.status>=400,K2=($)=>{let Q=[...Y.values()].filter((h)=>h.scope.sessionID===$),_=Q.filter((h)=>h.limit&&!h.rerouted).at(-1);if(_)return _;let N=Q.filter((h)=>h.scope.kind==="primary"),I=N.length>0?N:Q;if(I.length<=1)return I[0];let v=I.filter((h)=>!h.judged&&B2(h)).at(-1);if(v)return v;let k=I.filter((h)=>h.attempt&&!h.ended);if(k.length>1)return"ambiguous";return k[0]??I.at(-1)},Y2={providerID:G},W2=[];W2.push(await X.session.hook("model.request",($)=>{if(F)return;return S(Q2($),async(Q)=>{let _=await n(Q2($),"model.request",Q);if(Q(),_.accountId===void 0)throw L(_.scope);l2($.headers,{..._.headers,[C2]:_.id})})},Y2)),W2.push(await X.session.hook("http.request",($)=>{if(F){let Q=C($.request.headers);if(O.set($.sessionID,Q),!Q)return}return S(Q2($),async(Q)=>{let _=$.request.headers.get(C2)??void 0,N=F?await n(Q2($),"http.request",Q,"http"):await u(Q2($),"http.request","http",_,Q);Q();let I=z(N),v=N.attempt;if(!I||!v)throw L(N.scope);await J2(N,async()=>{let k=$.request;if(J.rewriteRequest){if(_!==void 0){let V2=new Headers(k.headers);V2.delete(C2),k=new Request(k,{headers:V2})}k=await J.rewriteRequest({...I,request:k,attempt:v})??k,Q()}let h=new Headers(k.headers);h.delete(C2),e$(h,N.headers),D(N.scope,h.entries());let a=new Request(k,{headers:h});B.set(a,N),$.request=a})})},Y2)),W2.push(await X.session.hook("http.response",async($)=>{let Q=B.get($.request);if(!Q){if(F)return;if(!q)q=!0,i("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:$.sessionID,kind:$.kind});return}let _=$.response;if(J.answeredBy&&Q.attempt){let h=Q.attempt,a=await J2(Q,async()=>J.answeredBy?.({request:$.request,response:_,attempt:h}));if(a)t(Q,a)}let N=z(Q),I=Q.attempt;if(!N||!I)return;Q.status=_.status;let v=J.quotaFromHeaders?.(_.headers,_.status,I);if(v!==void 0)N2(Q,"http",v,_.status);if(!_.ok&&J.limitFromResponse){let h=await J.limitFromResponse({status:_.status,headers:_.headers,body:()=>_.clone().text(),attempt:I});if(h)Z2(Q,h,"http")}if(!_.ok||!_.body)d(Q);let k=_;if(_.body&&(J.inspectEvent||J.onAttemptEnd)){let h=_.body;if(J.inspectEvent)h=h.pipeThrough(m2((a)=>$2(Q,"http",a.data,a.event),(a)=>i("opencode2 auth event inspection threw",{error:s(a)})));k=new Response(t$(h,(a)=>d(Q,a)),{status:_.status,statusText:_.statusText,headers:_.headers})}if(J.rewriteResponse)k=await J.rewriteResponse({...N,request:$.request,response:k,attempt:I})??k;if(k!==_)$.response=k},Y2)),W2.push(await X.session.hook("experimental.ws.handshake",($)=>{if(F){let Q=C(new Headers($.headers)),_=z2($.sessionID,$.kind);if(O.set($.sessionID,Q),U.delete(_),!Q)return}return S(Q2($),async(Q)=>{let _;for(let k of Object.keys($.headers)){if(k.toLowerCase()!==C2)continue;_??=$.headers[k],delete $.headers[k]}let N=F?await n(Q2($),"experimental.ws.handshake",Q,"ws"):await u(Q2($),"experimental.ws.handshake","ws",_,Q);Q();let I=z(N),v=N.attempt;if(!I||!v)throw L(N.scope);await J2(N,async()=>{l2($.headers,N.headers);let k=J.rewriteHandshakeURL?.({...I,url:$.url,attempt:v});if(k!==void 0)$.url=k;if(D(N.scope,Object.entries($.headers)),F)U.add(N.key)})})},Y2));let H2=J.rewriteWebSocketFrame?.bind(J);if(H2)W2.push(await X.session.hook("experimental.ws.send",async($)=>{let Q=Q2($);if(F&&!U.has(z2(Q.sessionID,Q.kind)))return;let _=j2(Q.sessionID,Q.kind),N=await H2({...Q,attempt:_?.attempt,frame:$.frame});if(N!==void 0)$.frame=N},Y2));W2.push(await X.session.hook("experimental.ws.receive",($)=>{if(F&&!U.has(z2($.sessionID,$.kind)))return;let Q=j2($.sessionID,$.kind);if(!Q)return;try{$2(Q,"ws",$.frame)}catch(_){i("opencode2 auth frame inspection threw",{error:s(_)})}},Y2)),W2.push(await X.session.hook("retry",async($)=>{if(F&&O.get($.sessionID)!==!0)return;let Q=K2($.sessionID);if(!Q)return;let _=$.decision;if(Q==="ambiguous"){await b("retry",{sessionID:$.sessionID,attempt:$.attempt,reason:"host-decides",hostDecision:_,decision:_});return}let N=Q;await S(N.scope,async(I)=>{let v=I;N.judged=!0;let k=N.attempt;if(k&&!N.outputStarted){if(!N.limit){let V2=J.limitFromError?.($.error,k);if(V2)Z2(N,V2,"error")}if(N.ended)await N.ended;if(N.limit)await N.limit.delivered}v();let{decision:h,reason:a}=await W(N.scope.sessionID,async()=>{v();let V2=V.get(N.key);if(V.delete(N.key),V2?.next)await A(V2.next);v();let G2=_,e,L2,X2;if(N.accountId===void 0||!k)G2={retry:!1},e="no-account";else if(N.outputStarted)G2={retry:!1},e="output-started";else if(N.limit){let T2={accountId:N.accountId,limit:N.limit.signal},U2,A2={...N.scope,phase:"retry",previousAccountId:N.accountId,rerouteFrom:T2};try{U2=await J.chooseAccount(A2)}catch(g2){i("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:N.scope.sessionID,error:s(g2)})}if(U2!==void 0)X2={accountId:U2,input:A2};try{v()}catch(g2){if(X2)await A(X2);throw g2}if(U2!==void 0&&U2!==N.accountId)N.rerouted=!0,L2=T2,G2={retry:!0,delay:0},e="reroute";else e="host-decides-last-account"}else e="host-decides";if($.decision=G2,G2.retry&&N.accountId!==void 0&&Y.has(N.id))V.set(N.key,{attemptId:N.id,sessionID:N.scope.sessionID,accountId:N.accountId,...L2===void 0?{}:{rerouteFrom:L2},...X2===void 0?{}:{next:X2}});else if(X2)await A(X2);return{decision:G2,reason:e}});v(),await b("retry",{sessionID:$.sessionID,...N.accountId===void 0?{}:{accountId:N.accountId},kind:N.scope.kind,attempt:$.attempt,reason:a,hostDecision:_,decision:h,...k===void 0?{}:{handle:k}})})},Y2));let t2=($)=>{E($),O.delete($);for(let Q of U)if(JSON.parse(Q)[0]===$)U.delete(Q);for(let Q of[...Y.values()]){if(Q.scope.sessionID!==$)continue;p(Q,"its session was forgotten"),Y.delete(Q.id)}for(let[Q,_]of V)if(_.sessionID===$)R(Q)},f2=new AbortController,e2=X.event;if(e2)(async()=>{try{for await(let $ of e2.subscribe({signal:f2.signal}))if($.type==="session.deleted")t2($.data.sessionID)}catch($){if(!f2.signal.aborted)i("opencode2 auth stopped listening for session deletion",{error:s($)})}})();return{on($,Q){let _=m.get($);if(!_)_=new Set,m.set($,_);let N=Q;return _.add(N),()=>{_.delete(N)}},accountFor($,Q){return c(z2($,Q))?.accountId},forgetSession:t2,get size(){return Y.size},async dispose(){if(o)return;o=!0;for(let $ of r.keys())E($);f2.abort();for(let $ of Y.values())p($,"the installation was disposed");Y.clear();for(let $ of V.keys())R($);U.clear(),O.clear(),m.clear(),await Promise.all(Z.values()),await Promise.all(W2.map(async($)=>{try{await $.dispose()}catch(Q){i("opencode2 auth hook did not dispose cleanly",{error:s(Q)})}}))}}}import{CacheKeepManager as S1,CacheKeepSessionRegistry as R1,getDefaultCacheKeepRegistryDirectory as x1,isCacheKeepActiveNow as F$,isCacheKeepHybridActive as i2,isCacheKeepSubagentsEnabled as c2,logger as A1}from"@cortexkit/anthropic-auth-core";import{createHash as $1}from"node:crypto";import{applyCustomHeaders as X1,assertNotCustodyTombstone as J1,classifyGzipRejection as Z1,createProviderErrorRedactor as Z$,createProviderErrorResponseScope as Y$,decideRequestGzip as Y1,encodeGzipRequestBody as G1,getAccountStoragePath as j1,getRequestGzipLatch as W1,getRequestGzipLatchPath as V1,mergeAnthropicBetas as Q1,remapModelId as G$,remapRequestBodyModel as H1,stripEmptyTrailingAssistantMessages as U1,TrailingAssistantHistoryError as B1}from"@cortexkit/anthropic-auth-core";var S2="anthropic",N$="x-common-auth-attempt",K1=["x-session-affinity","x-opencode-session","x-parent-session-id",V$,k2,R2,N$],q2=new Set(["authorization","x-api-key"]),M1="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",z1=512,_1=5000,N1=500,j$=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"]);class L$ extends Error{sessionID;requestKind;kind="no-account";providerID=S2;constructor(X,J){super(M1);this.sessionID=X;this.requestKind=J;this.name="NativeAnthropicNoAccountError"}}class u2 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=S2;constructor(X,J){super("request refused: its session was closed while it was being prepared");this.sessionID=X;this.requestKind=J;this.name="NativeAnthropicRevokedError"}}class F2 extends Error{kind="unsupported-transport";providerID=S2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class C$ extends Error{kind="local-invalid-request";status=400;check;constructor(X){super(X.message,{cause:X});this.name="NativeAnthropicLocalRefusal",this.check=X.check}}var _2=(X)=>typeof X==="object"&&X!==null&&!Array.isArray(X);function E2(X){try{return JSON.parse(X)}catch{return}}function p2(X){let J={};for(let[M,G]of Object.entries(X??{}))J[M.toLowerCase()]=G;return J}function W$(X){let J={};for(let M of K1){let G=X.get(M);if(G!==null&&M!==N$)J[M]=G;X.delete(M)}return J}function L1(X){try{return new URL(X).pathname.endsWith("/messages")}catch{return!1}}function C1(X){return X instanceof B1||X instanceof Q$?new C$(X):void 0}function F1(X,J){let M=[];if(X.oauth)M.push(X.oauth.accessToken);for(let[G,F]of Object.entries(X.apiHeaders??{})){if(F===null||!q2.has(G))continue;M.push(F.replace(/^Bearer\s+/i,""))}for(let G of q2){let F=J.get(G);if(F!==null)M.push(F.replace(/^Bearer\s+/i,""))}if(X.dispatch?.kind==="http-relay")M.push(X.dispatch.token);return[...new Set(M.filter(Boolean))]}var P1=new Set(["oauth-2025-04-20","claude-code-20250219",U$]);function T1(X){let J=X.split(",").map((M)=>M.trim()).filter((M)=>M&&!P1.has(M));return Q1(null,J)}function O1(X){let J=E2(X);if(!_2(J))return X;let M=U1(J.messages),G=Object.hasOwn(J,"fallbacks"),{droppedMarkers:F}=B$(J,!1),C=G&&!Object.hasOwn(J,"fallbacks"),P=H1(J);return M>0||F>0||C||P?JSON.stringify(J):X}async function E1(X,J){if(!(X instanceof Promise))return"settled";let M;try{return await Promise.race([X.then(()=>"settled"),new Promise((G)=>{M=setTimeout(()=>G("timed-out"),J)})])}finally{if(M!==void 0)clearTimeout(M)}}function P2(X){let{source:J,log:M}=X,G=Math.max(1,X.maxPendingSends??z1),F=X.attemptEndTimeoutMs??_1,C=X.requestGzipLatch??W1(V1(j1())),P=new WeakSet,T=new Map,K=new WeakMap,Y=new WeakMap,B=new WeakMap,V=new Map,U=new WeakMap,O=Z$([]);O.dispose();let q=(H)=>(H&&V.get(H)?.redactor)??O,x=(H)=>{let z=V.get(H);if(!z)return;V.delete(H),z.redactor.dispose(),z.scope.dispose()},m=(H,z,L,E)=>{let S=F1(z,E),D=Y$(S,L);w.set(H,L),V.set(H,{sessionID:z.sessionID,redactor:Z$(S),scope:D}),D.settled.then(()=>x(H));while(V.size>G){let g=V.keys().next().value;if(g===void 0)break;x(g)}},w=new WeakMap,o=(H,z)=>{let L=H?w.get(H):void 0;if(!L||!z.ok)return O.redactResponse(z);let E=Y$([],L),S=E.redactResponse(z);return E.dispose(),S},r=(H,z)=>{let L=H?V.get(H)?.scope:void 0;if(!L)return o(H,z);try{return L.redactResponse(z)}catch{return o(H,z)}},i=!1,s=new WeakMap,Z=(H,z)=>{if(H&&!z.ok)s.set(z.headers,H);return z},W=(H,z)=>{if(z.dispatch!=="http-relay")return!0;let L=/^req_[A-Za-z0-9_-]+$/.test(H.get("request-id")??"");return Y.set(z,L),L},j=(H)=>new L$(H.sessionID,H.kind),A=new Map,R=async(H,z)=>{if(i)throw new u2(H.sessionID,H.kind);let L={revoked:!1},E=A.get(H.sessionID);if(!E)E=new Set,A.set(H.sessionID,E);E.add(L);let S=()=>{if(i||L.revoked)throw new u2(H.sessionID,H.kind)};try{let D=await z(S);return S(),D}finally{let D=A.get(H.sessionID);if(D?.delete(L)&&D.size===0)A.delete(H.sessionID)}},b=(H,z)=>{T.set(H,z);while(T.size>G){let L=T.keys().next().value;if(L===void 0)break;T.delete(L),M?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:G})}},y=(H,z)=>({providerID:H.providerID,modelID:H.modelID,sessionID:H.sessionID,agent:H.agent,kind:H.kind,accountId:H.accountId,attemptId:H.attemptId,transport:H.transport,route:z.route,provenance:z.provenance,dispatch:z.dispatch}),d=(H)=>R(H,async(z)=>{let{accountId:L,...E}=H,S=await J.authorizeAccount(E,L);return z(),p(E,S)}),p=(H,z)=>{if(!z)throw j(H);if(z.dispatch?.kind==="websocket-relay")throw new F2;let L=z.dispatch?.kind==="http-relay"?"http-relay":"direct",E=z.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":z.dispatch.token}:void 0;if(z.route==="oauth"){if(!z.accessToken)throw j(H);J1(z.accessToken,S2);let g=Object.freeze({route:"oauth",provenance:z.provenance,dispatch:L});b(g,{sessionID:H.sessionID,oauth:{accessToken:z.accessToken,...z.identity?{identity:z.identity}:{}},dispatch:z.dispatch,oauthHeaders:z.headers});let n=p2(z.headers);for(let u of q2)delete n[u];return delete n["anthropic-beta"],{headers:E??{...n,"x-api-key":null,authorization:`Bearer ${z.accessToken}`},attempt:g}}let S={authorization:null,"x-api-key":null,...p2(z.headers)};if(!S.authorization&&!S["x-api-key"])throw j(H);let D=Object.freeze({route:"api",provenance:z.provenance,dispatch:L});return b(D,{sessionID:H.sessionID,...z.baseURL?{baseURL:z.baseURL}:{},dispatch:z.dispatch,apiHeaders:S}),{headers:E??S,attempt:D}},f=(H)=>R(H,(z)=>c(H,z)),c=async(H,z)=>{let{request:L,attempt:E}=H,S=E.data,D=S?T.get(S):void 0;if(S)T.delete(S);if(!S||!D||S.route==="oauth"&&!D.oauth)throw j(H);let g=new Headers(L.headers);X1(g);let n=W$(g),u=L.body===null?void 0:await L.text();z();let J2=u!==void 0&&L1(L.url);try{if(S.route==="oauth"&&D.oauth){let{accessToken:$2,identity:t}=D.oauth;for(let[K2,Y2]of Object.entries(p2(D.oauthHeaders))){if(q2.has(K2))continue;if(Y2===null)g.delete(K2);else g.set(K2,Y2)}let B2=null;if(u!==void 0&&J2){let K2={...y(E,S),modelID:(()=>{let H2=E2(u);return G$(_2(H2)&&typeof H2.model==="string"?H2.model:H.modelID)})(),route:"oauth",correlation:n},Y2=await J.requestOptions?.(K2)??{};z(),u=await z$(u,{...Y2,...t?{identity:t}:{},sessionId:H.sessionID,onToolNameMap:(H2)=>B.set(S,H2)});let W2=E2(u);B2=_2(W2)?W2:null}K$(g,$2,{body:B2,...t?{identity:t}:{},requestClass:H$(E.agent)?"auxiliary":"main"})}else{if(u!==void 0&&J2)u=O1(u);g.delete("authorization"),g.delete("x-api-key");for(let[t,B2]of Object.entries(D.apiHeaders??{}))if(B2===null)g.delete(t);else g.set(t,B2);if(u!==void 0&&J2&&!g.has("content-type"))g.set("content-type","application/json");let $2=g.get("anthropic-beta");if($2!==null){let t=T1($2);if(t)g.set("anthropic-beta",t);else g.delete("anthropic-beta")}}}catch($2){let t=C1($2);if(!t)throw $2;throw K.set(S,t.check),M?.warn("refused an Anthropic request locally; nothing was sent",{check:t.check}),t}let j2=u!==void 0?E2(u):void 0;if(await J.admitRequest?.({...y(E,S),modelID:G$(_2(j2)&&typeof j2.model==="string"?j2.model:H.modelID)}),W$(g),u!==void 0)g.delete("content-length");z(),m(S,D,_2(j2)&&j2.stream===!0?"event-stream":"http",g);let Z2=M$(L.url,D.baseURL!==void 0?{baseURL:D.baseURL}:{}).url?.toString()??L.url;if(S.route==="oauth"&&J2&&u!==void 0)await J.onRequestPrepared?.({...y(E,S),url:Z2,bodyText:u}),z();if(D.dispatch?.kind==="http-relay"){let $2=u??"";g.delete("x-relay-token");let t={protocol:1,type:"request",affinity:H.sessionID,upstream:{url:Z2,method:L.method,headers:Object.fromEntries(g)},mode:"full_sync",revision:1,body:$2,next_hash:`sha256:${$1("sha256").update($2).digest("hex")}`};return new Request(D.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":D.dispatch.token},redirect:"error",signal:L.signal,body:JSON.stringify(t)})}let N2=u;if(S.route==="oauth"&&J2&&u!==void 0){let $2=await Y1({url:Z2,body:u,latch:C});if(z(),$2.gzip)N2=await G1(u),g.set("content-encoding","gzip"),P.add(S),z()}return new Request(Z2,{method:L.method,headers:g,redirect:L.redirect,signal:L.signal,...N2!==void 0?{body:N2}:{}})};return{adapter:{providerID:S2,chooseAccount:(H)=>R(H,async()=>{let z=await J.chooseAccount(H);if(!z)throw j(H);return z}),dropChoice:(H)=>J.dropChoice?.(H),accountHeaders:d,rewriteRequest:f,rewriteHandshakeURL(){throw new F2},rewriteResponse({response:H,attempt:z}){let L=z.data;if(L&&!W(H.headers,L)){if(H.status===401)return x(L),H.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return r(L,H)}if(L&&P.has(L))P.delete(L),Z1(H).then((n)=>{if(!n)return;C.latchProcess(),M?.warn("gzipped request body rejected; later requests go uncompressed",{kind:n,status:H.status})},()=>{});let E=r(L,H);if(L?.route!=="oauth"||!E.body)return Z(L,E);let S={...y(z,L),status:H.status},D=J.responseOptions?.(S)??{},g=(H.headers.get("content-type")??"").includes("application/json");return Z(L,_$(E,{...D,toolNameMap:B.get(L),onToolNameRefusal:()=>{K.set(L,"response_tool_names"),x(L)},laneStartOAuthServed:!0,...g?{responseMode:"json"}:{}}))},quotaFromHeaders(H,z,L){let E=L.data;if(!E||!W(H,E))return;return J.quotaFromHeaders?.(H,{...y(L,E),status:z})},async limitFromResponse({status:H,headers:z,body:L,attempt:E}){let S=E.data;if(!S||K.get(S)==="response_tool_names")return;if(!W(z,S))return J.limitFromRelayFailure?.({...y(E,S),status:H});if(U.set(S,`provider responded with HTTP ${H}`),!J.limitFromResponse)return;let D=s.get(z)===S,g=q(S);return J.limitFromResponse({...y(E,S),status:H,headers:z,body:async()=>D?await L():g.redactText(await L())})},inspectEvent({data:H,event:z,attempt:L}){if(L.data&&K.get(L.data)==="response_tool_names")return;let E=E2(H);if(!_2(E))return;let S=typeof E.type==="string"?E.type:z;if(S==="content_block_start"||S==="content_block_delta")return{outputStarted:!0};if(S==="message_stop")return{done:!0};if(S!=="error")return;let D=L.data,g=q(D),n=_2(E.error)?E.error:{},u=typeof n.type!=="string"?void 0:j$.has(n.type)?n.type:g.redactText(n.type),J2=typeof n.message==="string"?g.redactText(n.message):void 0;if(D?.dispatch==="http-relay"&&Y.get(D)===!1)return;let j2=D?J.limitFromStreamError?.({...y(L,D),errorType:u,message:J2}):void 0,Z2={error:[u??"error",J2].filter(Boolean).join(": ").slice(0,N1),...j2?{limit:j2}:{}};if(D&&Z2.error)U.set(D,Z2.error);return Z2},limitFromError(H,z){let L=z.data;if(!L||K.has(L))return;let E={type:j$.has(H.type)?H.type:"provider_error",message:U.get(L)??"provider request failed",...H.status!==void 0?{status:H.status}:{}};if(x(L),L.dispatch==="http-relay"&&Y.get(L)===!1)return;return J.limitFromHostError?.(E,y(z,L))},async onAttemptEnd(H,z){let L=H.data;if(!L)return;T.delete(L);let E=z.error?.reason;if(E==="cancelled"||E==="abandoned"||E===void 0&&(z.status===void 0||z.status<400))x(L);let S=K.get(L),{status:D,...g}=z,n=J.onAttemptEnd?.(y(H,L),{...g,...D!==void 0&&(L.dispatch!=="http-relay"||Y.get(L)===!0)?{status:D}:{},...S!==void 0?{localRefusal:{check:S}}:{}});if(await E1(n,F)==="timed-out")M?.warn("the account source did not finish recording a send",{timeoutMs:F})}},dispose(){i=!0;for(let[H,z]of A){for(let L of z)L.revoked=!0;J.forgetSession?.(H)}A.clear(),T.clear();for(let H of[...V.keys()])x(H)},forgetSession(H){for(let z of A.get(H)??[])z.revoked=!0;A.delete(H);for(let[z,L]of T)if(L.sessionID===H)T.delete(z);for(let[z,L]of[...V])if(L.sessionID===H)x(z);J.forgetSession?.(H)},get pendingSendCount(){return T.size},get heldCredentialCount(){let H=0;for(let z of T.values())if(z.oauth)H++;return H},get heldRedactorCount(){return V.size},get operationsInProgress(){let H=0;for(let z of A.values())H+=z.size;return H}}}function x2(X){return JSON.stringify([X.source,X.accountIdentity,X.credentialId,X.binding?.storageId,X.binding?.rowId,X.binding?.credentialEpoch])}function P$(X){let{runtime:J,source:M}=X,G=new AbortController,F=!1,C=new R1({directory:X.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||x1("opencode"),now:X.now}),P=new Map,T=async(V,U,O)=>{let q=O?AbortSignal.any([G.signal,O]):G.signal;q.throwIfAborted();let x=JSON.parse(await U.text()),m={providerID:"anthropic",modelID:x.model,sessionID:`oc2-cachekeep:${V.id}`,agent:"cachekeep",kind:"generate"},w=P2({source:{...M,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(Z){return{...await M.requestOptions?.(Z),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(Z,W){let j=await J.read();q.throwIfAborted();let A=j.accounts.find((b)=>b.id===W);if(A?.type!=="oauth"||x2(A)!==V.oauthAccountIdentity||V.isSubagent&&!c2(j.policyStorage)||!i2(j.policyStorage)||!F$(j.policyStorage,new Date(X.now?.()??Date.now())))return;let R=await M.authorizeAccount(Z,W);if(R?.provenance.kind==="local"&&x2({...A,binding:R.provenance.subject.binding,accountIdentity:R.provenance.subject.binding.identity})!==V.oauthAccountIdentity)return;if(R?.provenance.kind==="vault"&&R.provenance.credentialId!==A.credentialId)return;return R},async admitRequest(Z){await M.admitRequest?.(Z);let W=await J.read(),j=W.accounts.find((A)=>A.id===Z.accountId);if(q.throwIfAborted(),!j||x2(j)!==V.oauthAccountIdentity||V.isSubagent&&!c2(W.policyStorage)||!i2(W.policyStorage)||!F$(W.policyStorage,new Date(X.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),o,r,i=!1,s=()=>w.forgetSession(m.sessionID);q.addEventListener("abort",s,{once:!0});try{let Z=(await J.read()).accounts.find((y)=>x2(y)===V.oauthAccountIdentity)?.id;if(!Z)throw Error("CacheKeep account is unavailable");let W=await w.adapter.accountHeaders({...m,accountId:Z});if(!("headers"in W)||typeof W.headers!=="object"||W.headers===null||typeof W.attempt!=="object"||W.attempt===null||W.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");o={...m,accountId:Z,attemptId:crypto.randomUUID(),transport:"http",data:W.attempt};let j=await w.adapter.rewriteRequest?.({...m,accountId:Z,attempt:o,request:new Request(V.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(x),signal:q})});if(!j)throw Error("CacheKeep rewrite refused");q.throwIfAborted();let A=await(X.fetch??fetch)(j),R=await w.adapter.rewriteResponse?.({...m,accountId:Z,attempt:o,request:j,response:A});if(!R)throw Error("CacheKeep response rewrite refused");if(r=R.status,w.adapter.quotaFromHeaders?.(R.headers,R.status,o),!R.ok)await w.adapter.limitFromResponse?.({status:r,headers:R.headers,body:()=>R.clone().text(),attempt:o});let b=await R.arrayBuffer();return i=!0,new Response(b,{status:r,headers:R.headers})}catch{throw Error("Native CacheKeep was not completed")}finally{q.removeEventListener("abort",s);try{if(o)await w.adapter.onAttemptEnd?.(o,{status:r,outputStarted:!1,...i?{}:{error:{reason:"cancelled"}}})}finally{w.dispose(),M.forgetSession?.(m.sessionID)}}},K=X.setIntervalImpl??globalThis.setInterval,Y=new S1({loadStorage:async()=>F?null:(await J.read()).policyStorage,now:X.now,setIntervalImpl:(V,U)=>K(()=>Y.tick().catch(()=>{A1.warn("cachekeep","tick failed")}),U),clearIntervalImpl:X.clearIntervalImpl,onTrackedSessionsChanged:(V)=>C.publish(F?[]:V),prepareHeaders(V,U,O){if(F)return;return P.set(O.id,{target:U,attempt:O}),new Headers({"x-native-cachekeep-attempt":String(O.id)})},fetchImpl:async(V,U)=>{let O=new Request(V,U),q=Number(O.headers.get("x-native-cachekeep-attempt")),x=P.get(q);if(P.delete(q),!x)throw Error("CacheKeep attempt is unavailable");return T(x.target,O,x.attempt.signal)},onComplete:({attempt:V})=>{P.delete(V.id)}}),B;return{async track(V){if(F||V.route!=="oauth"||V.agent==="cachekeep"||V.agent==="prime"||V.kind!=="primary")return;let U=await J.read();if(F||!i2(U.policyStorage))return;let O=!1;try{O=await X.isSubagent?.(V.sessionID)??!1}catch{return}if(F||O&&!c2(U.policyStorage))return;let q=U.accounts.find((x)=>x.id===V.accountId);if(!q?.accountIdentity)return;if(V.provenance.kind==="local"&&JSON.stringify(q.binding)!==JSON.stringify(V.provenance.subject.binding))return;if(V.provenance.kind==="vault"&&q.credentialId!==V.provenance.credentialId)return;Y.track({sessionId:V.sessionID,url:V.url,headers:new Headers,bodyText:V.bodyText,storage:U.policyStorage,cacheMode:"hybrid",oauthAccountId:V.accountId,oauthAccountIdentity:x2(q),isSubagent:O}),await C.publish(Y.trackedSessions())},registry:C,dispose(){if(B)return B;return F=!0,Y.stop(),G.abort(),B=(async()=>{try{await Y.tick()}finally{P.clear(),await C.dispose()}})(),B}}}async function T$(X,J,M){let G=P2(J),F=[],C=async(U,O,q)=>{let x=await X.session.hook(U,O,q);return F.push(x),x},P=new AbortController,T;try{T=await d2({session:{hook:C},event:X.event},G.adapter,{logger:J.log,gateOnPlaceholder:M})}catch(U){throw G.dispose(),await Promise.allSettled(F.map((O)=>O.dispose())),U}let K=(U)=>{G.forgetSession(U),T.forgetSession(U)},Y=X.event,B=Y?(async()=>{try{for await(let U of Y.subscribe({signal:P.signal}))if(U.type==="session.deleted")K(U.data.sessionID)}catch(U){if(!P.signal.aborted)J.log?.warn("stopped listening for session deletion",{error:U instanceof Error?U.name:"unknown"})}})():Promise.resolve(),V;return{installation:T,forgetSession:K,dispose(){if(V)return V;return G.dispose(),P.abort(),V=(async()=>{await T.dispose(),await B})(),V}}}import{effectiveRelayTransport as O$,getQuotaCheckIntervalMs as q1,logger as k1,nativeAccountCanServe as D1,oauthProfileIsFresh as b1,quotaSnapshotCheckedAt as w1}from"@cortexkit/anthropic-auth-core";function E$(X,J){let M=new AbortController,G,F=!1,C=async()=>{let K=await X.read();if(M.signal.throwIfAborted(),K.policyStorage.relay?.enabled===!0&&O$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="websocket")return;let Y=K,B=q1(Y.policyStorage);for(let V of Y.accounts){if(M.signal.aborted)return;if(!D1(V)||V.type!=="oauth")continue;if(Y.policyStorage.quota?.enabled!==!1&&Date.now()-w1(V.quota)>=B)await X.fetchQuota(V.id,J,M.signal,void 0,"background").catch(()=>{});if(!b1(V.profile)&&!M.signal.aborted)await X.fetchProfile(V.id,J,M.signal).catch(()=>{})}},P=()=>{if(F||G)return G;return G=C().catch(()=>{if(!M.signal.aborted)k1.debug("opencode2","native background readings did not complete")}).finally(()=>{G=void 0}),G},T=X.vault.watch({intervalMs:60000,onRefresh:P,shouldRefresh:async()=>{let K=await X.read();return K.policyStorage.relay?.enabled!==!0||O$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){F=!0,T.close(),M.abort(),await G}}}import{authorize as i1,buildCacheKeepStatusSummary as c1,buildClaudeQuotaSummary as o1,buildPrimeAccountStatuses as n1,buildPrimeStatusSummary as r1,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as s1,exchange as a1,formatNativeAccountState as t1,formatOAuthAccountTier as e1,getCacheKeepWindow as $X,getHostClaustrumEnrollmentPaths as XX,isCacheKeepAlways as JX,isCacheKeepHybridActive as ZX,isCacheKeepPersistentlyEnabled as YX,nativeAccountCanServe as GX,resetClaustrumEnrollmentState as jX}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as y1,effectiveRelayStatus as I1,formatNativeAccountState as f1,formatOAuthAccountTier as S$,getCacheKeepWindow as g1,getRoutingMode as v1,isCacheKeepAlways as h1,isCacheKeepHybridActive as m1,isPermanentRefreshError as l1,isPrimePersistentlyEnabled as d1,nativeAccountCanServe as A$,refreshBackoffActive as R$}from"@cortexkit/anthropic-auth-core";var x$=(X)=>A$(X)&&X.state!=="unsupported-access"?void 0:f1(X)||void 0,p1=(X)=>{if(X.source!=="vault")return"off";if(X.state==="needs_reauth")return"on-vault-reauth";return A$(X)?"on-vault-served":"on-cold"},u1=(X,J)=>typeof X==="number"&&X>J;function q$(X,J){let{now:M}=J,G=X.policyStorage,F=X.accounts.filter((B)=>B.type==="oauth"),C=F.find((B)=>B.id==="main"),P=C?x$(C):void 0,T=C?.lastQuotaRefreshError?.nextRetryAt,K=C?.lastRefreshError,Y=g1(G);return{main:{quota:C?.quota??null,enabled:C?.enabled,tierLabel:S$(C?.profile),quotaBackedOff:u1(T,M),quotaBackoffUntil:T,refreshBackedOff:R$(K,C?.accountIdentity,M,void 0),refreshBackoffUntil:K?.nextRetryAt,stateLine:P,quotaDated:Boolean(P)},fallbacks:F.filter((B)=>B.id!=="main"&&(B.enabled||B.source==="vault")).map((B)=>{let V=x$(B),U=p1(B);return{id:B.id,label:B.label,quota:B.quota??null,enabled:B.enabled,tierLabel:S$(B.profile),needsReauth:l1(B.lastRefreshError)&&R$(B.lastRefreshError,B.accountIdentity,M,void 0),...U==="on-vault-reauth"?{vaultReauth:!0}:{},...U==="on-vault-served"?{vaultServed:!0}:{},...U!=="off"?{custodyState:U}:{},stateLine:V,quotaDated:Boolean(V)}}),activeId:J.activeId,route:v1(G),relay:I1(G.relay),fastMode:G.claudeFast?.enabled===!0,cacheKeep:{enabled:m1(G),window:h1(G)?"always":Y?`${Y.startHour}-${Y.endHour}`:void 0,trackedSessions:J.trackedSessions},prime:d1(G)?{enabled:!0,accounts:y1(G,{now:M})}:void 0,lastUpdated:M}}var o2=(X)=>X!==null&&typeof X==="object"&&!Array.isArray(X)?X:{};function k$(X){let{runtime:J,source:M}=X,G=new Map,F=!1,C=async(Y,B)=>{await J.updateSettings((V)=>({...V,[Y]:{...o2(V[Y]),...B}}))},P=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(Y,B)=>{if(F)throw Error("Native menu is closed");switch(B.signal?.throwIfAborted(),Y.action){case"enable":case"disable":return await J.setEnabled(Y.values.id,Y.action==="enable"),P();case"remove":return await J.remove(Y.values.id),P();case"move-up":case"move-down":{let U=(await J.read()).accounts.map((w)=>w.id),O=U.indexOf(Y.values.id),q=O+(Y.action==="move-up"?-1:1);if(O<0||q<0||q>=U.length)return{ok:!1,text:"Account cannot move in that direction."};let x=U[O],m=U[q];if(x===void 0||m===void 0)return{ok:!1,text:"Account order changed."};return U[O]=m,U[q]=x,await J.reorder(U),P()}case"add-apikey":return await J.addApi(Y.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let V=new AbortController;G.get(Y.sessionId)?.active.abort();let U={active:V,auth:void 0};G.set(Y.sessionId,U);let O=await i1("max");if(F||V.signal.aborted||B.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return U.auth=O,{ok:!0,text:`Open ${O.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let V=G.get(Y.sessionId);if(!V?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let U=await a1(Y.values.code,V.auth.verifier,V.auth.redirectUri,V.auth.state);if(V.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),F||U.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await J.loginOAuth({routeId:crypto.randomUUID(),credential:U,label:Y.values.label}),V.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),F)return{ok:!1,text:"Sign-in cancelled."};return G.delete(Y.sessionId),{ok:!0,text:"OAuth account stored in the native account pool."}}case"reset-backoff":{let V=await J.read();for(let U of V.accounts){if(B.signal?.throwIfAborted(),U.type!=="oauth")continue;let O=U.source==="vault"?await J.authorizeVault(U.id,B.signal):await J.captureLocalSubject(U.id);await J.resetBackoff(U.id,O)}return P()}case"enrollment-reset":{let V=await jX(XX("opencode"),s1);return{ok:V==="reset",text:V==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":V==="refused-pending"?"An enrollment request may still be in progress. Quit OpenCode and run setup again; it picks up the same request.":"Only terminal enrollment state may be reset; active enrollment was left unchanged."}}case"quota-refresh":{let U=(await J.read()).accounts.filter((x)=>x.type==="oauth"&&GX(x)),O=await Promise.allSettled(U.map((x)=>J.fetchQuota(x.id,void 0,B.signal)));return{ok:O.every((x)=>x.status==="fulfilled"),text:`${O.filter((x)=>x.status==="fulfilled").length}/${U.length} native quota readings refreshed.`}}case"routing-reset":return await M.resetRouting(Y.sessionId),P();case"routing-mode":return await C("routing",{mode:Y.values.mode}),P();case"killswitch-on":case"killswitch-off":return await C("killswitch",{enabled:Y.action==="killswitch-on"}),P();case"killswitch-set":return await J.updateSettings((V)=>{let U=o2(V.killswitch),O={...o2(U.accounts)},q=U.main;for(let x of Y.values.entries){let m={five_hour:x.fh,seven_day:x.sd,...x.scoped!==void 0?{scoped:x.scoped}:{}};if(x.account==="main"||x.account==="all")q=m;if(x.account==="all")for(let w of Object.keys(O))O[w]=m;else if(x.account!=="main")O[x.account]=m}return{...V,killswitch:{...U,main:q,accounts:O}}}),P();case"cache-on":case"cache-off":return await C("claudeCache",{enabled:Y.action==="cache-on"}),P();case"cache-mode":return await C("claudeCache",{mode:Y.values.mode}),P();case"cachekeep-always":return await C("cacheKeep",{enabled:!0,always:!0}),P();case"cachekeep-off":return await C("cacheKeep",{enabled:!1}),P();case"cachekeep-window":return await C("cacheKeep",{enabled:!0,always:!1,startHour:Y.values.startHour,endHour:Y.values.endHour}),P();case"cachekeep-subagents":return await C("cacheKeep",{subagents:Y.values.enabled==="on"}),P();case"dump-on":case"dump-off":return await C("dump",{enabled:Y.action==="dump-on"}),P();case"logging-level":return await C("logging",{level:Y.values.level}),P();case"fast-on":case"fast-off":return await C("claudeFast",{enabled:Y.action==="fast-on"}),P();case"prime-on":case"prime-off":return await C("prime",{enabled:Y.action==="prime-on"}),P();case"start-fire":return await K(Y.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},K=(Y)=>X.start(Y,D2);return{dispatch:T,async readStatus(Y){let B=await J.read();if(Y==="account")return B.accounts.map((U)=>`${U.id}${U.label?` (${U.label})`:""}: ${U.type}, ${U.source}, ${U.enabled?"enabled":"disabled"}${U.state?`, ${t1(U)}`:""}${U.accountIdentity?`, ${U.accountIdentity}`:""}`).join(`
|
|
4
|
-
`)||"No native Claude accounts.";if(Y==="quota")return o1({accounts:B.accounts.filter((U)=>U.type==="oauth").map((U)=>({name:U.label??U.id,role:U.id==="main"?"main":"fallback",enabled:U.enabled,quota:U.quota,tierLabel:e1(U.profile),lastRefreshedAt:U.lastRefreshedAt,error:U.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(Y==="prime")return r1({enabled:B.policyStorage.prime?.enabled===!0,accounts:n1(B.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(Y==="cachekeep"){let U=await X.cacheKeepRegistry?.list()??[];return c1({enabled:YX(B.policyStorage),always:JX(B.policyStorage),hybridActive:ZX(B.policyStorage),trackedSessionDetails:U,window:$X(B.policyStorage),trackedSessions:U.length,nextPrewarmAt:U.length?Math.min(...U.map((O)=>O.nextPrewarmAt)):void 0})}let V={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(B.settings[V[Y]]??{})},async readSidebar(Y){let[B,V]=await Promise.all([J.read(),X.cacheKeepRegistry?.list()??[]]);return q$(B,{activeId:M.servedAccount(Y),trackedSessions:V.length,now:Date.now()})},forgetSession(Y){G.get(Y)?.active.abort(),G.delete(Y)},close(){F=!0;for(let Y of G.values())Y.active.abort();G.clear()}}}import{resolveClaudeModelCapabilities as WX}from"@cortexkit/anthropic-auth-core";function D$(){let X=new Map;return{install:(M)=>M.model.transform((G)=>{X.clear();for(let F of G.list("anthropic")){X.set(String(F.id),String(F.modelID));let C=WX(F.modelID)?.efforts.variants;if(!C)continue;G.update("anthropic",String(F.id),(P)=>{let T=P.variants.filter((K)=>!C.some((Y)=>Y===String(K.id)));P.variants=[...T,...C.map((K)=>({id:K,settings:{effort:K,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(M)=>X.get(M)??M}}function b$(X){return X.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??X.get("x-api-key")??void 0}import{buildPrimeRequestBody as w$,effectiveRelayTransport as y$,nativeAccountCanServe as VX,PrimeManager as QX}from"@cortexkit/anthropic-auth-core";var I$=(X)=>X!==null&&typeof X==="object"&&!Array.isArray(X)?X:{};function f$(X){let{runtime:J,source:M}=X,G=new AbortController,F=new Set,C=(K)=>({providerID:"anthropic",modelID:w$().model,sessionID:`oc2-prime:${K}`,agent:"prime",kind:"generate"}),P=async(K)=>{let Y=C(K),B=P2({source:M}),V=performance.now();try{for(let U=0;U<3;U++){if(G.signal.throwIfAborted(),(await J.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let q=await B.adapter.accountHeaders({...Y,accountId:K});if(!("headers"in q)||typeof q.headers!=="object"||q.headers===null||typeof q.attempt!=="object"||q.attempt===null)throw Error("Native Prime authorization refused");let x={...Y,accountId:K,attemptId:crypto.randomUUID(),transport:"http",data:q.attempt},m,w=!1,o=!1,r=(i)=>{o=!0,i.body?.cancel().catch(()=>{})};try{let i=await B.adapter.rewriteRequest?.({...Y,accountId:K,attempt:x,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w$()),signal:G.signal})});if(!i)throw Error("Native Prime rewrite refused");let s=new Headers(i.headers);for(let[d,p]of Object.entries(q.headers))if(p===null)s.delete(d);else s.set(d,p);let Z=new Request(i,{headers:s}),W=await(X.fetch??fetch)(Z),j=await B.adapter.rewriteResponse?.({...Y,accountId:K,request:Z,response:W,attempt:x})??W;m=j.status,B.adapter.quotaFromHeaders?.(j.headers,j.status,x);let A=j.ok?void 0:await B.adapter.limitFromResponse?.({status:j.status,headers:j.headers,body:()=>j.clone().text(),attempt:x});if(A&&/^(vault-newer|local-newer|relay-direct):/.test(A.reason)&&U<2){r(j);let d={...Y,phase:"retry",rerouteFrom:{accountId:K,limit:A}};if(await M.chooseAccount(d)!==K)throw Error("Native Prime retry changed account");continue}if(!j.ok)return r(j),{ok:!1,status:m,ms:performance.now()-V,error:"Native Prime upstream refused the request"};let R=I$(await j.json()),b=I$(R.usage),y={inputTokens:typeof b.input_tokens==="number"?b.input_tokens:void 0,outputTokens:typeof b.output_tokens==="number"?b.output_tokens:void 0};if(x.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(j.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await M.recordPrime(q.attempt.provenance,y),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:m,ms:performance.now()-V,usage:y}}finally{await B.adapter.onAttemptEnd?.(x,{status:m,outputStarted:!1,...w?{}:{error:{reason:o?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-V}}finally{B.dispose()}},T=new QX({storagePath:X.paths.legacyConfig,loadStorage:async()=>(await J.read()).policyStorage,async getAccountFingerprint(K){let Y=await J.read(),B=Y.accounts.find((U)=>U.id===K);if(!VX(B)||B?.type!=="oauth")return;if(Y.policyStorage.relay?.enabled===!0&&y$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")return;if(B.source==="vault"){let U=await J.authorizeVault(K,G.signal);return J.getOrCreateAuthLineage(K,U)}let V=await J.authorizeLocal(K,{signal:G.signal});return V.status==="usable"?J.getOrCreateAuthLineage(K,V.subject):void 0},async refreshQuota(K){let Y=await J.read();if(Y.policyStorage.relay?.enabled===!0&&y$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await J.fetchQuota(K,X.fetch,G.signal),fresh:!0}},sendPrime(K){let Y=P(K);return F.add(Y),Y.finally(()=>F.delete(Y)),Y},async recordSuccess(K){let Y=(await J.read()).accounts.find((B)=>B.id===K);if(!Y?.prime)throw Error("Native Prime counters are unavailable");return Y.prime}});return T.start(),{manager:T,async dispose(){T.stop(),G.abort(),await Promise.allSettled(F)}}}import{createNativeUsagePublisher as HX,effectiveRelayTransport as UX,getClaudeCodeIdentityForVerifiedAccount as b2,getQuotaCheckIntervalMs as BX,getRoutingMode as g$,isQuotaBearingHeaderFrame as KX,mergeHeaderQuotaForPersistence as MX,NativeVaultNoAccountError as zX,nativeAccountCanServe as n2,nativeAccountPolicy as w2,normalizeQuotaHeaders as _X,quotaSnapshotCheckedAt as NX,quotaSnapshotHasStandardWindows as LX,readNativeAccountsForRequest as CX,remapModelId as r2,StickySessionRouter as FX,shouldFallbackStatus as PX,stickyQuotaSnapshotIsFresh as y2,stickyRouteFamilyForModel as TX}from"@cortexkit/anthropic-auth-core";var s2=(X)=>["five_hour","seven_day"].some((J)=>(X?.[J]?.remainingPercent??1)<=0);function h$(X){let{runtime:J}=X,M=HX("native-auth"),G=new Map,F=(Z)=>{let W=Z.routingPath;if(!W)throw Error("Native routing storage is unavailable");let j=G.get(W);if(!j)j=new FX({path:W,vaultSeed:Z.routingSeed,onLockEvent:J.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),G.set(W,j);return j.setVaultSeed(Z.routingSeed),j},C=new WeakMap,P=new Map,T=new Map,K=new Map,Y=new Map,B=new WeakSet,V=!1,U=()=>{while(P.size>512){let Z=P.keys().next();if(!Z.done)P.delete(Z.value)}},O=(Z,W)=>JSON.stringify([Z.sessionID,Z.kind,Z.modelID,W]),q=(Z)=>{if(V)throw Error("Native Anthropic source is closed");let W=K.get(Z.sessionID);if(!W){W=new AbortController,K.set(Z.sessionID,W);while(K.size>512){let j=K.keys().next();if(!j.done)i.forgetSession?.(j.value)}}return W},x=(Z,W,j)=>n2(Z)&&(Z.type==="api"||w2(Z,W,r2(j)).status==="allowed"),m=async(Z,W,j,A)=>{let R=await J.read();A.signal.throwIfAborted(),w(R);let b=R.accounts.find((y)=>y.id===Z);if(!b||b.type!==j||!x(b,R,W))return!1;if(j==="api"){let y=R.accounts.find((d)=>d.id==="main"&&d.type==="oauth");return!!y&&y2(y.quota,R.policyStorage)&&s2(y.quota)}return!0},w=(Z)=>{let W=Z.policyStorage.relay;if(W?.enabled===!0&&UX(W.transport,W.url)==="websocket")throw new F2},o=async(Z,W)=>{if(w(Z),W||Z.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let j=await J.getRelayConfig();if(!j)throw Error("request refused: native HTTP relay configuration is unavailable");if(j.transport!=="http")throw new F2;return{dispatch:{kind:"http-relay",url:j.url,token:j.token},relayFallback:j.fallbackToDirect}};async function r(Z,W,j){if(Z.kind==="local")await J.publishLocal(Z.subject,j);else if(Z.kind==="vault"&&W.receipt)await J.vault.publish(W.receipt,j);else if(Z.kind==="api"&&j.lastUsed!==void 0)await J.publishApi(Z.subject,{lastUsed:j.lastUsed})}let i={async chooseAccount(Z){let W=q(Z);X.onOwnedRequest?.();let j=await J.read();W.signal.throwIfAborted(),w(j);let A=r2(await X.resolveModelId?.(Z)??Z.modelID);if(W.signal.throwIfAborted(),j.mode==="claustrum")j=await CX(J,W.signal),W.signal.throwIfAborted();if(j.policyStorage.quota?.enabled!==!1){let f=!1;for(let c of j.accounts){if(!n2(c)||c.type!=="oauth")continue;if(LX(c.quota)?y2(c.quota,j.policyStorage,Date.now(),A):Date.now()-NX(c.quota)<BX(j.policyStorage))continue;try{await J.fetchQuota(c.id,X.fetch,W.signal,void 0,"admission"),f=!0}catch{W.signal.throwIfAborted()}}if(f)j=await J.read();W.signal.throwIfAborted()}let R=Z.rerouteFrom?P.get(Z.rerouteFrom.limit.reason):void 0;if(Z.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(Z.rerouteFrom.limit.reason)&&!R)return;if(R&&Z.rerouteFrom){let f=j.accounts.find((H)=>H.id===R.accountId);if(!f||!x(f,j,A))return;P.delete(Z.rerouteFrom.limit.reason);let c=O(Z,R.accountId),l=T.get(c)??[];return l.push(R),T.set(c,l),R.accountId}let b=[];for(let f of j.accounts){if(f.type!=="oauth"||!x(f,j,A))continue;if(f.source==="local"){let c=await J.authorizeLocal(f.id,{signal:W.signal,policy:(l,H)=>w2(l,H,A)});if(W.signal.throwIfAborted(),c.status!=="usable")continue}b.push(f)}let y=b.filter((f)=>f.id!==Z.rerouteFrom?.accountId);if(g$(j.policyStorage)==="sticky-balanced"){let f=y.map((l,H)=>({accountId:l.id,order:H,quota:l.quota??{kind:"unknown"}})),c=await F(j).resolve({sessionId:Z.sessionID,family:TX(A),modelId:A,affinityModelId:Z.modelID,candidates:f,retainAccountIds:new Set(y.map((l)=>l.id)),...j.mode==="claustrum"?{accountIdentities:new Map(j.accounts.flatMap((l)=>l.accountIdentity?[[l.id,l.accountIdentity]]:[]))}:{},storage:j.policyStorage,inputBytes:1,preferredAccountId:Z.previousAccountId,preserveOnNoCandidate:!0});if(W.signal.throwIfAborted(),c)return c.accountId}else{let c=g$(j.policyStorage)==="fallback-first"?[...y.filter((l)=>l.id!=="main"),...y.filter((l)=>l.id==="main")]:[...y.filter((l)=>l.id==="main"),...y.filter((l)=>l.id!=="main")];if(c[0])return c[0].id}if(j.mode==="claustrum")throw new zX;let d=j.accounts.find((f)=>f.id==="main"&&f.type==="oauth");if(!d)return;let p=d.quota;if(Z.rerouteFrom?.limit.status===429||!y2(p,j.policyStorage))try{p=await J.fetchQuota("main",X.fetch,W.signal)}catch{return}if(W.signal.throwIfAborted(),!s2(p))return;return j.accounts.find((f)=>f.type==="api"&&n2(f)&&f.id!==Z.rerouteFrom?.accountId)?.id},dropChoice(Z){let W=O(Z,Z.accountId),j=T.get(W);if(j?.shift(),j?.length===0)T.delete(W)},async authorizeAccount(Z,W){let j=q(Z),A=await J.read();j.signal.throwIfAborted(),w(A);let R=r2(await X.resolveModelId?.(Z)??Z.modelID);j.signal.throwIfAborted();let b=A.accounts.find((E)=>E.id===W);if(!b||!x(b,A,R))return;let y=O(Z,W),d=T.get(y),p=d?.shift();if(d?.length===0)T.delete(y);let{dispatch:f,relayFallback:c}=await o(A,p?.direct===!0);if(j.signal.throwIfAborted(),p?.auth){if(!await m(W,R,p.auth.route,j))return;let E=C.get(p.auth.provenance);if(E?.receipt?.expiresAtMs!==void 0&&E.receipt.expiresAtMs!==null&&E.receipt.expiresAtMs<Date.now()+300000)return;if(E)C.set(p.auth.provenance,{...E,scope:{...Z,modelID:R},account:b,active:j,relayFallback:c});return Y.set(Z.sessionID,W),{...p.auth,dispatch:f}}let l={scope:{...Z,modelID:R},active:j,account:b,retry:p?.retry??!1,relayFallback:c,quota:b.quota};if(b.type==="api"){let E=A.accounts.find((n)=>n.id==="main"&&n.type==="oauth");if(!E||!y2(E.quota,A.policyStorage)||!s2(E.quota))return;let S=await J.authorizeApi(W,j.signal);if(j.signal.throwIfAborted(),!await m(W,R,"api",j))return;let D={kind:"api",subject:S.subject};return C.set(D,l),Y.set(Z.sessionID,W),{route:"api",headers:S.authHeader==="authorization-bearer"?{authorization:`Bearer ${S.apiKey}`}:{"x-api-key":S.apiKey},baseURL:S.baseURL,provenance:D,dispatch:f}}if(b.source==="vault"){let E=await J.authorizeVault(W,j.signal);if(j.signal.throwIfAborted(),!await m(W,R,"oauth",j))return;let S={kind:"vault",credentialId:E.credentialId,recordVersion:E.recordVersion};C.set(S,{...l,receipt:E});let D=E.assertedAccountIdentity;if(!D)return;return Y.set(Z.sessionID,W),{route:"oauth",accessToken:E.accessToken,provenance:S,dispatch:f,identity:b2(D,D)}}let H=await J.authorizeLocal(W,{signal:j.signal,policy:(E,S)=>w2(E,S,R)});if(j.signal.throwIfAborted(),H.status!=="usable")return;if(!await m(W,R,"oauth",j))return;let z={kind:"local",subject:H.subject};C.set(z,{...l,access:H.access}),Y.set(Z.sessionID,W);let L=H.subject.binding.identity;return{route:"oauth",accessToken:H.access,provenance:z,dispatch:f,identity:b2(L,L)}},async requestOptions(Z){let W=q(Z),j=await J.read();W.signal.throwIfAborted();let A=j.accounts.find((b)=>b.id===Z.accountId);if(!A||!x(A,j,Z.modelID))throw Error("request refused: native account is ineligible for this model");let R=C.get(Z.provenance);if(R)C.set(Z.provenance,{...R,scope:{...R.scope,modelID:Z.modelID}});return X.requestOptions(Z,j)},async admitRequest(Z){let W=C.get(Z.provenance);if(!W||!await m(Z.accountId,Z.modelID,Z.route,W.active))throw Error("request refused: native account policy changed before dispatch");C.set(Z.provenance,{...W,scope:{...W.scope,modelID:Z.modelID}})},onRequestPrepared:(Z)=>X.onRequestPrepared?.(Z),responseOptions(Z){return X.responseOptions?.({...Z,modelID:C.get(Z.provenance)?.scope.modelID??Z.modelID})},quotaFromHeaders(Z,W){let j=C.get(W.provenance),A=v$(Z);if(A)X.onRequestId?.(W,A);if(!j||W.route!=="oauth"||!KX(Z))return;let R=W.provenance.kind==="local"?W.provenance.subject.binding.identity:j.receipt?.assertedAccountIdentity,b={..._X(Z),...R?{accountIdentity:R}:{}};j.quota=MX(j.quota,b);let y=M.observe(r(W.provenance,j,{quota:j.quota}));return s.set(W.provenance,y),b},async limitFromResponse(Z){let W=C.get(Z.provenance);if(!W)return;if(Z.status===401&&W.receipt){if(!B.has(W.receipt))B.add(W.receipt),await J.vault.reportFailure(W.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(W.retry||W.active.signal.aborted)return;let A=W.active,R=await J.vault.prepareRetry(W.receipt,A.signal);if(A.signal.throwIfAborted(),!R.retry)return;let b=R.receipt,y=b.assertedAccountIdentity;if(!y)return;let d={kind:"vault",credentialId:b.credentialId,recordVersion:b.recordVersion};C.set(d,{...W,receipt:b,retry:!0});let p=`vault-newer:${Z.attemptId}`;return P.set(p,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:b.accessToken,provenance:d,identity:b2(y,y)}}),U(),{reason:p,status:401}}if(Z.status===401&&Z.provenance.kind==="local"&&W.access&&!W.retry){if(W.active.signal.aborted)return;let A=W.active,R=await J.authorizeLocal(Z.accountId,{rejectedAccessToken:W.access,signal:A.signal,policy:(p,f)=>w2(p,f,W.scope.modelID)});if(A.signal.throwIfAborted(),R.status!=="usable"||R.access===W.access)return;let b={kind:"local",subject:R.subject};C.set(b,{...W,access:R.access,retry:!0});let y=R.subject.binding.identity,d=`local-newer:${Z.attemptId}`;return P.set(d,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:R.access,provenance:b,identity:b2(y,y)}}),U(),{reason:d,status:401}}let j=await J.read();if(PX(Z.status,j.policyStorage))return{reason:`provider-${Z.status}`,status:Z.status};return},limitFromRelayFailure(Z){let W=C.get(Z.provenance);if(!W?.relayFallback||W.active.signal.aborted||!(Z.status===401||Z.status>=500))return;let j=`relay-direct:${Z.attemptId}`;return P.set(j,{sessionID:Z.sessionID,accountId:Z.accountId,direct:!0,retry:!1}),U(),{reason:j}},limitFromStreamError(Z){return Z.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(Z,W){let j=C.get(W.provenance);if(W.dispatch==="http-relay"&&j?.relayFallback&&!j.active.signal.aborted&&Z.status===void 0){let A=`relay-direct:${W.attemptId}`;return P.set(A,{sessionID:W.sessionID,accountId:W.accountId,direct:!0,retry:!1}),U(),{reason:A}}return},async onAttemptEnd(Z,W){let j=C.get(Z.provenance);if(!j)return;try{if(await s.get(Z.provenance),W.status===401&&j.receipt&&!B.has(j.receipt))B.add(j.receipt),await J.vault.reportFailure(j.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(!W.localRefusal&&W.status!==void 0)M.publish(()=>r(Z.provenance,j,{lastUsed:Date.now()}))}finally{C.delete(Z.provenance),s.delete(Z.provenance)}},forgetSession(Z){K.get(Z)?.abort(),K.delete(Z),Y.delete(Z);for(let[W,j]of P)if(j.sessionID===Z)P.delete(W);for(let[W,j]of T)if(j[0]?.sessionID===Z)T.delete(W);X.onForgetSession?.(Z)},servedAccount:(Z)=>Y.get(Z),resetRouting:async(Z)=>F(await J.read()).clear(Z),async recordPrime(Z,W){let j=C.get(Z);if(!j||j.active.signal.aborted)return!1;if(Z.kind==="local")return J.incrementPrimeUsage(j.account.id,Z.subject,W);if(Z.kind==="vault"&&j.receipt)return J.incrementPrimeUsage(j.account.id,j.receipt,W);return!1},drainRoutingPublications:()=>Promise.all([J.drainRoutingPublications(),...[...G.values()].map((Z)=>Z.drain())]).then(()=>{}),close(){V=!0;for(let Z of K.values())Z.abort();return K.clear(),T.clear(),P.clear(),Promise.all([M.drain(),i.drainRoutingPublications()]).then(()=>{})}},s=new WeakMap;return i}import{remapModelId as OX}from"@cortexkit/anthropic-auth-core";function d$(){let X=new m$,J=new Map,M=new Map,G=new Map,F=new Set,C=new Set,P=new Map,T=(K)=>{while(K.size>512){let Y=K.keys().next();if(!Y.done)K.delete(Y.value)}};return{async install(K){let Y=[];try{Y.push(await K.session.hook("context",(B)=>{let V=B.messages.map((O)=>{return{info:{id:O.id,sessionID:B.sessionID,role:O.role,agent:B.agent,model:{providerID:B.model.providerID,modelID:B.model.id}},parts:O.content.map((q)=>({type:q.type,...q.type==="text"?{text:q.text}:{}}))}});X.observeMessages(V);let U=B.messages.findLast((O)=>O.role==="user"&&O.id);if(U?.id)J.set(B.sessionID,U.id);if(U?.content.some((O)=>O.type==="text"&&O.text===D2))F.add(B.sessionID);else F.delete(B.sessionID);T(J)},{providerID:"anthropic"})),Y.push(await K.session.hook("model.request",(B)=>{if(B.kind!=="primary")return;let V=J.get(B.sessionID);if(!V)return;if(X.markHeaders({sessionId:B.sessionID,messageId:V,agent:B.agent,headers:B.headers}),F.has(B.sessionID))B.headers[R2]="1"},{providerID:"anthropic"}))}catch(B){throw await Promise.allSettled(Y.map((V)=>V.dispose())),B}return{dispose:async()=>{await Promise.all(Y.map((B)=>B.dispose()))}}},requestOptions(K,Y){let B=X.resolveHeader(K.correlation[k2]);if(B)M.set(K.attemptId,B),T(M);P.set(K.attemptId,K.sessionID),T(P);let V=K.correlation[R2]==="1";if(V)C.add(K.attemptId);return{cache1hEnabled:K.agent!=="compaction"&&K.agent!=="title"&&(Y.policyStorage.claudeCache?.enabled??!0),cache1hMode:Y.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:Y.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:Y.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:Y.policyStorage.turnEndNote,serverSideFallbackEnabled:l$(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:V,billingLineage:B?{promptId:B.promptId,previousRequestId:B.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:G.get(K.sessionID)}},responseOptions(K){return{serverSideFallbackModel:OX(K.modelID),laneStart:C.has(K.attemptId),onMessageStart(Y){if(K.kind==="primary"&&typeof Y.id==="string")G.set(K.sessionID,Y.id),T(G)},onStreamEnd(){M.delete(K.attemptId),C.delete(K.attemptId),P.delete(K.attemptId)}}},onRequestId(K,Y){X.commit(M.get(K.attemptId),Y)},forgetSession(K){X.clearSession(K),J.delete(K),G.delete(K),F.delete(K);for(let[Y,B]of P)if(B===K)M.delete(Y),C.delete(Y),P.delete(Y)}}}var I2="cortexkit-anthropic-auth",DX='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',bX="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",wX="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function yX(X){let J=X.authorize??SX,M=X.exchange??AX,G=()=>{if(!X.isActive())throw Error("Claude authentication setup is closed")},F=async()=>{let T;try{T=await X.readMode()}catch{throw Error(wX)}return G(),T},C=async()=>{if(await F()!=="local")throw Error(DX)};return{integrationID:"anthropic",methods:[{method:{id:u$,type:"oauth",label:i$},async authorize(){G(),await C();let T=await J("max");return G(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(K)=>{G();let Y=await M(K,T.verifier,T.redirectUri,T.state);if(!X.isActive()||Y.type!=="success")throw Error("Claude sign-in did not complete");return{access:Y.access,refresh:Y.refresh,expires:Y.expires}}}}}],vault:{method:{id:c$,type:"oauth",label:"Claude vault accounts"},async activate(){if(G(),await F()!=="claustrum")throw Error(bX)}},async onLogin(T){G(),await C(),await X.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),G()},label:"Claude native account pool"}}function IX(X){return{readMode:()=>qX("opencode",X),disconnectVault:()=>xX({host:"opencode",env:X})}}function a2(X={}){return{id:I2,setup:(J)=>n$(J,X)}}async function n$(X,J={}){let M=J.paths??await kX(),G=EX({paths:M,host:"opencode",local:J.local,vault:J.vault}),F=IX(J.vault?.env??process.env),C=!0,P=d$(),T=D$(),K,Y,B,V=h$({runtime:G,paths:M,fetch:J.fetch,requestOptions:P.requestOptions,responseOptions:P.responseOptions,onRequestId:P.onRequestId,onForgetSession:P.forgetSession,onRequestPrepared:async(w)=>{try{await B?.track(w)}catch{p$.warn("cachekeep","live request tracking failed")}},resolveModelId:async(w)=>T.modelId(w.modelID),onOwnedRequest:()=>{K??=E$(G,J.fetch),Y??=f$({runtime:G,paths:M,source:V,fetch:J.fetch})}});B=P$({...J.cacheKeep,runtime:G,source:V,fetch:J.fetch,isSubagent:async(w)=>Boolean((await X.session.get({sessionID:w})).parentID)});let U=k$({runtime:G,source:V,cacheKeepRegistry:B.registry,start:async(w,o)=>{await X.session.synthetic({sessionID:w,text:o,description:"Claude lane start",resume:!0})}}),O=[],q=await T$(X,{source:V,log:{warn:(w,o)=>p$.warn("opencode2",w,o)}},{credential:b$}).catch(async(w)=>{throw U.close(),await B?.dispose(),await V.close(),await G.drainQuotaPublications(),G.close(),w}),x,m=()=>{if(x)return x;return C=!1,U.close(),V.close(),x=(async()=>{await Promise.allSettled([q.dispose(),K?.dispose(),Y?.dispose(),B?.dispose(),...O.map((w)=>w.dispose())]),await V.close(),await G.drainQuotaPublications(),G.close()})(),x};try{O.push(await P.install(X)),O.push(await T.install(X)),O.push(await h2(X,yX({isActive:()=>C,readMode:F.readMode,runtime:G})));let w={host:"opencode",dispatch:U.dispatch,readStatus:(r)=>U.readStatus(r),readAccounts:()=>G.read(),readMode:F.readMode,disconnectVault:F.disconnectVault,interactive:!0},o=RX(w);return O.push(await o$(X,o,U)),m}catch(w){throw await m(),w}}var aJ={id:I2,setup:a2().setup,server:r$};export{n$ as setupAnthropicAuth,aJ as default,a2 as createAnthropicAuthPlugin,I2 as ANTHROPIC_AUTH_PLUGIN_ID};
|
|
3
|
+
`)}}function m2(X,J){let M=new TextDecoder,V="",F=(P)=>{let T=a$(P);if(!T)return;try{X(T)}catch(K){J(K)}},L=()=>{for(;;){let P=/\r?\n\r?\n/.exec(V);if(!P)return;let T=V.slice(0,P.index);V=V.slice(P.index+P[0].length),F(T)}};return new TransformStream({transform(P,T){T.enqueue(P),V+=M.decode(P,{stream:!0}),L()},flush(){if(V+=M.decode(),L(),V.trim()!=="")F(V);V=""}})}var J$=512,L2="x-common-auth-attempt",z2=(X,J)=>JSON.stringify([X,J]),Q2=(X)=>({providerID:X.model.providerID,modelID:X.model.id,sessionID:X.sessionID,agent:X.agent,kind:X.kind});function t$(X){let J=X.headers;return typeof J==="object"&&J!==null}function e$(X,J){let M=X.getReader();return new ReadableStream({async pull(V){let F;try{F=await M.read()}catch(L){J({reason:"failed",message:L instanceof Error?L.message:String(L)}),V.error(L);return}if(F.done)J(),V.close();else V.enqueue(F.value)},async cancel(V){J({reason:"cancelled",...V===void 0?{}:{message:String(V)}}),await M.cancel(V)}})}function l2(X,J){for(let[M,V]of Object.entries(J)){let F=M.toLowerCase();for(let L of Object.keys(X))if(L.toLowerCase()===F)delete X[L];if(V!==null)X[M]=V}}function $1(X,J){for(let[M,V]of Object.entries(J))if(V===null)X.delete(M);else X.set(M,V)}async function d2(X,J,M={}){let{providerID:V}=J,F=M.gateOnPlaceholder,L=($)=>F===void 0||F.credential($)===M2(V),P=M.logger,T=Math.max(1,M.maxRecords??J$),K=[...M.hostCredentials??[M2(V)],...F?[M2(V)]:[]].filter(($)=>$!==""),Y=new Map,B=new WeakMap,W=new Map,U=new Set,O=new Map,q=!1,A=!1,m=new Map,w=0,c=!1,r=new Map,o=($,Q)=>{try{P?.warn($,Q)}catch{}},s=($)=>$ instanceof Error?$.message:String($),Z=new Map,j=($,Q)=>{let _=(Z.get($)??Promise.resolve()).then(Q),C=_.then(()=>{},()=>{});return Z.set($,C),C.then(()=>{if(Z.get($)===C)Z.delete($)}),_},G=($,Q)=>{let _=Z.get($);return _?_.then(()=>G($,Q)):Q()},x=async($)=>{try{await J.dropChoice?.({...$.input,accountId:$.accountId})}catch(Q){o("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:$.input.sessionID,error:s(Q)})}},E=($)=>{let Q=W.get($);if(W.delete($),Q?.next){let _=Q.next;j(Q.sessionID,()=>x(_))}},D=async($,Q)=>{let _=m.get($);if(!_||_.size===0)return;await Promise.all([..._].map(async(C)=>{try{await C(Q)}catch(f){o("opencode2 auth listener threw; the request is unaffected",{event:$,error:s(f)})}}))},y=async($,Q)=>{try{await J.onAttemptEnd?.($,Q)}catch(_){o("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:$.attemptId,error:s(_)})}},l=($,Q)=>{if($.ended||!$.attempt)return;let _={...$.status===void 0?{}:{status:$.status},outputStarted:$.outputStarted,...$.limit?{limit:$.limit.signal}:{},...Q?{error:Q}:{}};if(Q)$.endError=Q;$.ended=y($.attempt,_)},p=($,Q)=>l($,{reason:"abandoned",message:Q}),I=($)=>[...Y.values()].filter((Q)=>Q.key===$),u=($)=>I($).at(-1),d=($)=>{if(Y.delete($.id),W.get($.key)?.attemptId===$.id||!I($.key).length)E($.key)},H=($)=>{Y.set($.id,$);while(Y.size>T){let Q=Y.values().next().value;if(Q===void 0)break;p(Q,"dropped to keep the record bound"),d(Q)}},z=($)=>$.accountId===void 0?void 0:{...$.scope,accountId:$.accountId},N=($,Q)=>new O2({kind:"no-account",providerID:V,sessionID:$.sessionID,requestKind:$.kind,...Q===void 0?{}:{message:Q}}),S=($)=>{r.get($)?.clear(),r.delete($)},R=async($,Q)=>{let _=()=>N($,`${V} ${$.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(c)throw _();let C=r.get($.sessionID);if(!C)C=new Set,r.set($.sessionID,C);let f={};C.add(f);let v=()=>{if(!C.has(f))throw _()};try{return await Q(v)}finally{if(C.delete(f),C.size===0&&r.get($.sessionID)===C)r.delete($.sessionID)}},b=($,Q)=>{for(let[_,C]of Q)if(K.some((f)=>C.includes(f)))throw new O2({kind:"host-credential-on-wire",providerID:V,sessionID:$.sessionID,requestKind:$.kind,message:`${V} ${$.kind} request still carries the host's placeholder credential in ${_}; the adapter's account headers must replace it`})},g=($)=>{for(let Q of I($))if(Q.ended||!Q.attempt)d(Q);else if(Q.transport==="ws"||Q.judged)p(Q,"a newer attempt of its session and kind began"),d(Q)},n=async($,Q,_,C)=>{let f=z2($.sessionID,$.kind),{input:v,accountId:k}=await G($.sessionID,async()=>{_();let e=W.get(f);W.delete(f);let N2=e?.accountId??u(f)?.accountId;g(f);let X2=e?.next,T2=X2!==void 0&&X2.input.modelID===$.modelID&&X2.input.agent===$.agent,U2={...$,phase:"request",...N2===void 0?{}:{previousAccountId:N2},...e?.rerouteFrom?{rerouteFrom:e.rerouteFrom}:{}};if(X2&&!T2)await j($.sessionID,()=>x(X2)),_();let A2=T2?X2.accountId:await J.chooseAccount(U2);return{input:U2,accountId:A2}});_();let h={},a;if(k!==void 0){let e=await J.accountHeaders({...$,accountId:k});if(_(),t$(e))h=e.headers,a=e.attempt;else h=e}let W2=`attempt-${++w}`,G2={id:W2,key:f,scope:$,accountId:k,headers:h,attempt:k===void 0?void 0:{...$,accountId:k,attemptId:W2,transport:C,data:a},...C===void 0?{}:{transport:C},outputStarted:!1};if(H(G2),G2.attempt)D("select",{...$,accountId:G2.attempt.accountId,hook:Q,...v.previousAccountId===void 0?{}:{previousAccountId:v.previousAccountId},...v.rerouteFrom===void 0?{}:{rerouteFrom:v.rerouteFrom},handle:G2.attempt});return G2},i=async($,Q,_,C,f)=>{let v=z2($.sessionID,$.kind),k=C===void 0?void 0:Y.get(C);if(k?.key!==v)k=void 0;if(!k){if(k=u(v),I(v).filter((a)=>a.transport===void 0&&!a.ended).length>1&&!A)A=!0,o("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:$.sessionID,kind:$.kind})}if(!k||k.transport!==void 0||k.ended)k=await n($,Q,f,_);else if(k.transport=_,k.attempt)k.attempt.transport=_;if(_==="ws"){for(let h of I(v))if(h!==k&&h.transport==="ws")p(h,"a newer attempt of its session and kind went out over WebSocket")}return k},J2=async($,Q)=>{try{return await Q()}catch(_){throw l($,{reason:"failed",message:s(_)}),_}},V2=($,Q)=>{let _=I(z2($,Q)).filter((C)=>C.transport==="ws").at(-1);return _?.attempt!==void 0&&!_.ended?_:void 0},Z2=($,Q,_)=>{let C=z($);if(!C||!$.attempt||$.limit)return;$.limit={signal:Q,delivered:D("limit",{...C,via:_,limit:Q,outputStarted:$.outputStarted,handle:$.attempt})}},C2=($,Q,_,C)=>{let f=z($);if(!f||!$.attempt)return;D("quota",{...f,transport:Q,...C===void 0?{}:{status:C},quota:_,handle:$.attempt})},$2=($,Q,_,C)=>{let f=$.attempt;if(!f)return;let v=J.inspectEvent?.(C===void 0?{transport:Q,data:_,attempt:f}:{transport:Q,data:_,event:C,attempt:f});if(!v)return;if(v.quota!==void 0)C2($,Q,v.quota);if(v.outputStarted)$.outputStarted=!0;if(v.limit)Z2($,v.limit,Q);if(v.error!==void 0)l($,{reason:"failed",message:v.error});else if(v.done)l($)},t=($,Q)=>{let _=$.attempt;if(!_||Q.accountId===$.accountId)return;if(_.reboundFrom??=_.accountId,_.accountId=Q.accountId,"data"in Q)_.data=Q.data;$.accountId=Q.accountId},B2=($)=>!$.attempt||$.endError!==void 0||$.status!==void 0&&$.status>=400,K2=($)=>{let Q=[...Y.values()].filter((h)=>h.scope.sessionID===$),_=Q.filter((h)=>h.limit&&!h.rerouted).at(-1);if(_)return _;let C=Q.filter((h)=>h.scope.kind==="primary"),f=C.length>0?C:Q;if(f.length<=1)return f[0];let v=f.filter((h)=>!h.judged&&B2(h)).at(-1);if(v)return v;let k=f.filter((h)=>h.attempt&&!h.ended);if(k.length>1)return"ambiguous";return k[0]??f.at(-1)},Y2={providerID:V},j2=[];j2.push(await X.session.hook("model.request",($)=>{if(F)return;return R(Q2($),async(Q)=>{let _=await n(Q2($),"model.request",Q);if(Q(),_.accountId===void 0)throw N(_.scope);l2($.headers,{..._.headers,[L2]:_.id})})},Y2)),j2.push(await X.session.hook("http.request",($)=>{if(F){let Q=L($.request.headers);if(O.set($.sessionID,Q),!Q)return}return R(Q2($),async(Q)=>{let _=$.request.headers.get(L2)??void 0,C=F?await n(Q2($),"http.request",Q,"http"):await i(Q2($),"http.request","http",_,Q);Q();let f=z(C),v=C.attempt;if(!f||!v)throw N(C.scope);await J2(C,async()=>{let k=$.request;if(J.rewriteRequest){if(_!==void 0){let W2=new Headers(k.headers);W2.delete(L2),k=new Request(k,{headers:W2})}k=await J.rewriteRequest({...f,request:k,attempt:v})??k,Q()}let h=new Headers(k.headers);h.delete(L2),$1(h,C.headers),b(C.scope,h.entries());let a=new Request(k,{headers:h});B.set(a,C),$.request=a})})},Y2)),j2.push(await X.session.hook("http.response",async($)=>{let Q=B.get($.request);if(!Q){if(F)return;if(!q)q=!0,o("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:$.sessionID,kind:$.kind});return}let _=$.response;if(J.answeredBy&&Q.attempt){let h=Q.attempt,a=await J2(Q,async()=>J.answeredBy?.({request:$.request,response:_,attempt:h}));if(a)t(Q,a)}let C=z(Q),f=Q.attempt;if(!C||!f)return;Q.status=_.status;let v=J.quotaFromHeaders?.(_.headers,_.status,f);if(v!==void 0)C2(Q,"http",v,_.status);if(!_.ok&&J.limitFromResponse){let h=await J.limitFromResponse({status:_.status,headers:_.headers,body:()=>_.clone().text(),attempt:f});if(h)Z2(Q,h,"http")}if(!_.ok||!_.body)l(Q);let k=_;if(_.body&&(J.inspectEvent||J.onAttemptEnd)){let h=_.body;if(J.inspectEvent)h=h.pipeThrough(m2((a)=>$2(Q,"http",a.data,a.event),(a)=>o("opencode2 auth event inspection threw",{error:s(a)})));k=new Response(e$(h,(a)=>l(Q,a)),{status:_.status,statusText:_.statusText,headers:_.headers})}if(J.rewriteResponse)k=await J.rewriteResponse({...C,request:$.request,response:k,attempt:f})??k;if(k!==_)$.response=k},Y2)),j2.push(await X.session.hook("experimental.ws.handshake",($)=>{if(F){let Q=L(new Headers($.headers)),_=z2($.sessionID,$.kind);if(O.set($.sessionID,Q),U.delete(_),!Q)return}return R(Q2($),async(Q)=>{let _;for(let k of Object.keys($.headers)){if(k.toLowerCase()!==L2)continue;_??=$.headers[k],delete $.headers[k]}let C=F?await n(Q2($),"experimental.ws.handshake",Q,"ws"):await i(Q2($),"experimental.ws.handshake","ws",_,Q);Q();let f=z(C),v=C.attempt;if(!f||!v)throw N(C.scope);await J2(C,async()=>{l2($.headers,C.headers);let k=J.rewriteHandshakeURL?.({...f,url:$.url,attempt:v});if(k!==void 0)$.url=k;if(b(C.scope,Object.entries($.headers)),F)U.add(C.key)})})},Y2));let H2=J.rewriteWebSocketFrame?.bind(J);if(H2)j2.push(await X.session.hook("experimental.ws.send",async($)=>{let Q=Q2($);if(F&&!U.has(z2(Q.sessionID,Q.kind)))return;let _=V2(Q.sessionID,Q.kind),C=await H2({...Q,attempt:_?.attempt,frame:$.frame});if(C!==void 0)$.frame=C},Y2));j2.push(await X.session.hook("experimental.ws.receive",($)=>{if(F&&!U.has(z2($.sessionID,$.kind)))return;let Q=V2($.sessionID,$.kind);if(!Q)return;try{$2(Q,"ws",$.frame)}catch(_){o("opencode2 auth frame inspection threw",{error:s(_)})}},Y2)),j2.push(await X.session.hook("retry",async($)=>{if(F&&O.get($.sessionID)!==!0)return;let Q=K2($.sessionID);if(!Q)return;let _=$.decision;if(Q==="ambiguous"){await D("retry",{sessionID:$.sessionID,attempt:$.attempt,reason:"host-decides",hostDecision:_,decision:_});return}let C=Q;await R(C.scope,async(f)=>{let v=f;C.judged=!0;let k=C.attempt;if(k&&!C.outputStarted){if(!C.limit){let W2=J.limitFromError?.($.error,k);if(W2)Z2(C,W2,"error")}if(C.ended)await C.ended;if(C.limit)await C.limit.delivered}v();let{decision:h,reason:a}=await j(C.scope.sessionID,async()=>{v();let W2=W.get(C.key);if(W.delete(C.key),W2?.next)await x(W2.next);v();let G2=_,e,N2,X2;if(C.accountId===void 0||!k)G2={retry:!1},e="no-account";else if(C.outputStarted)G2={retry:!1},e="output-started";else if(C.limit){let T2={accountId:C.accountId,limit:C.limit.signal},U2,A2={...C.scope,phase:"retry",previousAccountId:C.accountId,rerouteFrom:T2};try{U2=await J.chooseAccount(A2)}catch(g2){o("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:C.scope.sessionID,error:s(g2)})}if(U2!==void 0)X2={accountId:U2,input:A2};try{v()}catch(g2){if(X2)await x(X2);throw g2}if(U2!==void 0&&U2!==C.accountId)C.rerouted=!0,N2=T2,G2={retry:!0,delay:0},e="reroute";else e="host-decides-last-account"}else e="host-decides";if($.decision=G2,G2.retry&&C.accountId!==void 0&&Y.has(C.id))W.set(C.key,{attemptId:C.id,sessionID:C.scope.sessionID,accountId:C.accountId,...N2===void 0?{}:{rerouteFrom:N2},...X2===void 0?{}:{next:X2}});else if(X2)await x(X2);return{decision:G2,reason:e}});v(),await D("retry",{sessionID:$.sessionID,...C.accountId===void 0?{}:{accountId:C.accountId},kind:C.scope.kind,attempt:$.attempt,reason:a,hostDecision:_,decision:h,...k===void 0?{}:{handle:k}})})},Y2));let t2=($)=>{S($),O.delete($);for(let Q of U)if(JSON.parse(Q)[0]===$)U.delete(Q);for(let Q of[...Y.values()]){if(Q.scope.sessionID!==$)continue;p(Q,"its session was forgotten"),Y.delete(Q.id)}for(let[Q,_]of W)if(_.sessionID===$)E(Q)},f2=new AbortController,e2=X.event;if(e2)(async()=>{try{for await(let $ of e2.subscribe({signal:f2.signal}))if($.type==="session.deleted")t2($.data.sessionID)}catch($){if(!f2.signal.aborted)o("opencode2 auth stopped listening for session deletion",{error:s($)})}})();return{on($,Q){let _=m.get($);if(!_)_=new Set,m.set($,_);let C=Q;return _.add(C),()=>{_.delete(C)}},accountFor($,Q){return u(z2($,Q))?.accountId},forgetSession:t2,get size(){return Y.size},async dispose(){if(c)return;c=!0;for(let $ of r.keys())S($);f2.abort();for(let $ of Y.values())p($,"the installation was disposed");Y.clear();for(let $ of W.keys())E($);U.clear(),O.clear(),m.clear(),await Promise.all(Z.values()),await Promise.all(j2.map(async($)=>{try{await $.dispose()}catch(Q){o("opencode2 auth hook did not dispose cleanly",{error:s(Q)})}}))}}}import{CacheKeepManager as R1,CacheKeepSessionRegistry as x1,getDefaultCacheKeepRegistryDirectory as A1,isCacheKeepActiveNow as F$,isCacheKeepHybridActive as i2,isCacheKeepSubagentsEnabled as c2,logger as q1}from"@cortexkit/anthropic-auth-core";import{createHash as X1}from"node:crypto";import{applyCustomHeaders as J1,assertNotCustodyTombstone as Z1,classifyGzipRejection as Y1,createProviderErrorRedactor as Z$,createProviderErrorResponseScope as Y$,decideRequestGzip as G1,encodeGzipRequestBody as V1,getAccountStoragePath as j1,getRequestGzipLatch as W1,getRequestGzipLatchPath as Q1,mergeAnthropicBetas as H1,remapModelId as G$,remapRequestBodyModel as U1,stripEmptyTrailingAssistantMessages as B1,TrailingAssistantHistoryError as K1}from"@cortexkit/anthropic-auth-core";var S2="anthropic",C$="x-common-auth-attempt",M1=["x-session-affinity","x-opencode-session","x-parent-session-id",W$,k2,R2,C$],q2=new Set(["authorization","x-api-key"]),z1="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",_1=512,C1=5000,N1=500,V$=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"]);class N$ extends Error{sessionID;requestKind;kind="no-account";providerID=S2;constructor(X,J){super(z1);this.sessionID=X;this.requestKind=J;this.name="NativeAnthropicNoAccountError"}}class u2 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=S2;constructor(X,J){super("request refused: its session was closed while it was being prepared");this.sessionID=X;this.requestKind=J;this.name="NativeAnthropicRevokedError"}}class F2 extends Error{kind="unsupported-transport";providerID=S2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class L$ extends Error{kind="local-invalid-request";status=400;check;constructor(X){super(X.message,{cause:X});this.name="NativeAnthropicLocalRefusal",this.check=X.check}}var _2=(X)=>typeof X==="object"&&X!==null&&!Array.isArray(X);function E2(X){try{return JSON.parse(X)}catch{return}}function p2(X){let J={};for(let[M,V]of Object.entries(X??{}))J[M.toLowerCase()]=V;return J}function j$(X){let J={};for(let M of M1){let V=X.get(M);if(V!==null&&M!==C$)J[M]=V;X.delete(M)}return J}function L1(X){try{return new URL(X).pathname.endsWith("/messages")}catch{return!1}}function F1(X){return X instanceof K1||X instanceof Q$?new L$(X):void 0}function P1(X,J){let M=[];if(X.oauth)M.push(X.oauth.accessToken);for(let[V,F]of Object.entries(X.apiHeaders??{})){if(F===null||!q2.has(V))continue;M.push(F.replace(/^Bearer\s+/i,""))}for(let V of q2){let F=J.get(V);if(F!==null)M.push(F.replace(/^Bearer\s+/i,""))}if(X.dispatch?.kind==="http-relay")M.push(X.dispatch.token);return[...new Set(M.filter(Boolean))]}var T1=new Set(["oauth-2025-04-20","claude-code-20250219",U$]);function O1(X){let J=X.split(",").map((M)=>M.trim()).filter((M)=>M&&!T1.has(M));return H1(null,J)}function E1(X){let J=E2(X);if(!_2(J))return X;let M=B1(J.messages),V=Object.hasOwn(J,"fallbacks"),{droppedMarkers:F}=B$(J,!1),L=V&&!Object.hasOwn(J,"fallbacks"),P=U1(J);return M>0||F>0||L||P?JSON.stringify(J):X}async function S1(X,J){if(!(X instanceof Promise))return"settled";let M;try{return await Promise.race([X.then(()=>"settled"),new Promise((V)=>{M=setTimeout(()=>V("timed-out"),J)})])}finally{if(M!==void 0)clearTimeout(M)}}function P2(X){let{source:J,log:M}=X,V=Math.max(1,X.maxPendingSends??_1),F=X.attemptEndTimeoutMs??C1,L=X.requestGzipLatch??W1(Q1(j1())),P=new WeakSet,T=new Map,K=new WeakMap,Y=new WeakMap,B=new WeakMap,W=new Map,U=new WeakMap,O=Z$([]);O.dispose();let q=(H)=>(H&&W.get(H)?.redactor)??O,A=(H)=>{let z=W.get(H);if(!z)return;W.delete(H),z.redactor.dispose(),z.scope.dispose()},m=(H,z,N,S)=>{let R=P1(z,S),b=Y$(R,N);w.set(H,N),W.set(H,{sessionID:z.sessionID,redactor:Z$(R),scope:b}),b.settled.then(()=>A(H));while(W.size>V){let g=W.keys().next().value;if(g===void 0)break;A(g)}},w=new WeakMap,c=(H,z)=>{let N=H?w.get(H):void 0;if(!N||!z.ok)return O.redactResponse(z);let S=Y$([],N),R=S.redactResponse(z);return S.dispose(),R},r=(H,z)=>{let N=H?W.get(H)?.scope:void 0;if(!N)return c(H,z);try{return N.redactResponse(z)}catch{return c(H,z)}},o=!1,s=new WeakMap,Z=(H,z)=>{if(H&&!z.ok)s.set(z.headers,H);return z},j=(H,z)=>{if(z.dispatch!=="http-relay")return!0;let N=/^req_[A-Za-z0-9_-]+$/.test(H.get("request-id")??"");return Y.set(z,N),N},G=(H)=>new N$(H.sessionID,H.kind),x=new Map,E=async(H,z)=>{if(o)throw new u2(H.sessionID,H.kind);let N={revoked:!1},S=x.get(H.sessionID);if(!S)S=new Set,x.set(H.sessionID,S);S.add(N);let R=()=>{if(o||N.revoked)throw new u2(H.sessionID,H.kind)};try{let b=await z(R);return R(),b}finally{let b=x.get(H.sessionID);if(b?.delete(N)&&b.size===0)x.delete(H.sessionID)}},D=(H,z)=>{T.set(H,z);while(T.size>V){let N=T.keys().next().value;if(N===void 0)break;T.delete(N),M?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:V})}},y=(H,z)=>({providerID:H.providerID,modelID:H.modelID,sessionID:H.sessionID,agent:H.agent,kind:H.kind,accountId:H.accountId,attemptId:H.attemptId,transport:H.transport,route:z.route,provenance:z.provenance,dispatch:z.dispatch}),l=(H)=>E(H,async(z)=>{let{accountId:N,...S}=H,R=await J.authorizeAccount(S,N);return z(),p(S,R)}),p=(H,z)=>{if(!z)throw G(H);if(z.dispatch?.kind==="websocket-relay")throw new F2;let N=z.dispatch?.kind==="http-relay"?"http-relay":"direct",S=z.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":z.dispatch.token}:void 0;if(z.route==="oauth"){if(!z.accessToken)throw G(H);Z1(z.accessToken,S2);let g=Object.freeze({route:"oauth",provenance:z.provenance,dispatch:N});D(g,{sessionID:H.sessionID,oauth:{accessToken:z.accessToken,...z.identity?{identity:z.identity}:{}},dispatch:z.dispatch,oauthHeaders:z.headers});let n=p2(z.headers);for(let i of q2)delete n[i];return delete n["anthropic-beta"],{headers:S??{...n,"x-api-key":null,authorization:`Bearer ${z.accessToken}`},attempt:g}}let R={authorization:null,"x-api-key":null,...p2(z.headers)};if(!R.authorization&&!R["x-api-key"])throw G(H);let b=Object.freeze({route:"api",provenance:z.provenance,dispatch:N});return D(b,{sessionID:H.sessionID,...z.baseURL?{baseURL:z.baseURL}:{},dispatch:z.dispatch,apiHeaders:R}),{headers:S??R,attempt:b}},I=(H)=>E(H,(z)=>u(H,z)),u=async(H,z)=>{let{request:N,attempt:S}=H,R=S.data,b=R?T.get(R):void 0;if(R)T.delete(R);if(!R||!b||R.route==="oauth"&&!b.oauth)throw G(H);let g=new Headers(N.headers);J1(g);let n=j$(g),i=N.body===null?void 0:await N.text();z();let J2=i!==void 0&&L1(N.url);try{if(R.route==="oauth"&&b.oauth){let{accessToken:$2,identity:t}=b.oauth;for(let[K2,Y2]of Object.entries(p2(b.oauthHeaders))){if(q2.has(K2))continue;if(Y2===null)g.delete(K2);else g.set(K2,Y2)}let B2=null;if(i!==void 0&&J2){let K2={...y(S,R),modelID:(()=>{let H2=E2(i);return G$(_2(H2)&&typeof H2.model==="string"?H2.model:H.modelID)})(),route:"oauth",correlation:n},Y2=await J.requestOptions?.(K2)??{};z(),i=await z$(i,{...Y2,...t?{identity:t}:{},sessionId:H.sessionID,onToolNameMap:(H2)=>B.set(R,H2)});let j2=E2(i);B2=_2(j2)?j2:null}K$(g,$2,{body:B2,...t?{identity:t}:{},requestClass:H$(S.agent)?"auxiliary":"main"})}else{if(i!==void 0&&J2)i=E1(i);g.delete("authorization"),g.delete("x-api-key");for(let[t,B2]of Object.entries(b.apiHeaders??{}))if(B2===null)g.delete(t);else g.set(t,B2);if(i!==void 0&&J2&&!g.has("content-type"))g.set("content-type","application/json");let $2=g.get("anthropic-beta");if($2!==null){let t=O1($2);if(t)g.set("anthropic-beta",t);else g.delete("anthropic-beta")}}}catch($2){let t=F1($2);if(!t)throw $2;throw K.set(R,t.check),M?.warn("refused an Anthropic request locally; nothing was sent",{check:t.check}),t}let V2=i!==void 0?E2(i):void 0;if(await J.admitRequest?.({...y(S,R),modelID:G$(_2(V2)&&typeof V2.model==="string"?V2.model:H.modelID)}),j$(g),i!==void 0)g.delete("content-length");z(),m(R,b,_2(V2)&&V2.stream===!0?"event-stream":"http",g);let Z2=M$(N.url,b.baseURL!==void 0?{baseURL:b.baseURL}:{}).url?.toString()??N.url;if(R.route==="oauth"&&J2&&i!==void 0)await J.onRequestPrepared?.({...y(S,R),url:Z2,bodyText:i}),z();if(b.dispatch?.kind==="http-relay"){let $2=i??"";g.delete("x-relay-token");let t={protocol:1,type:"request",affinity:H.sessionID,upstream:{url:Z2,method:N.method,headers:Object.fromEntries(g)},mode:"full_sync",revision:1,body:$2,next_hash:`sha256:${X1("sha256").update($2).digest("hex")}`};return new Request(b.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":b.dispatch.token},redirect:"error",signal:N.signal,body:JSON.stringify(t)})}let C2=i;if(R.route==="oauth"&&J2&&i!==void 0){let $2=await G1({url:Z2,body:i,latch:L});if(z(),$2.gzip)C2=await V1(i),g.set("content-encoding","gzip"),P.add(R),z()}return new Request(Z2,{method:N.method,headers:g,redirect:N.redirect,signal:N.signal,...C2!==void 0?{body:C2}:{}})};return{adapter:{providerID:S2,chooseAccount:(H)=>E(H,async()=>{let z=await J.chooseAccount(H);if(!z)throw G(H);return z}),dropChoice:(H)=>J.dropChoice?.(H),accountHeaders:l,rewriteRequest:I,rewriteHandshakeURL(){throw new F2},rewriteResponse({response:H,attempt:z}){let N=z.data;if(N&&!j(H.headers,N)){if(H.status===401)return A(N),H.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return r(N,H)}if(N&&P.has(N))P.delete(N),Y1(H).then((n)=>{if(!n)return;L.latchProcess(),M?.warn("gzipped request body rejected; later requests go uncompressed",{kind:n,status:H.status})},()=>{});let S=r(N,H);if(N?.route!=="oauth"||!S.body)return Z(N,S);let R={...y(z,N),status:H.status},b=J.responseOptions?.(R)??{},g=(H.headers.get("content-type")??"").includes("application/json");return Z(N,_$(S,{...b,toolNameMap:B.get(N),onToolNameRefusal:()=>{K.set(N,"response_tool_names"),A(N)},laneStartOAuthServed:!0,...g?{responseMode:"json"}:{}}))},quotaFromHeaders(H,z,N){let S=N.data;if(!S||!j(H,S))return;return J.quotaFromHeaders?.(H,{...y(N,S),status:z})},async limitFromResponse({status:H,headers:z,body:N,attempt:S}){let R=S.data;if(!R||K.get(R)==="response_tool_names")return;if(!j(z,R))return J.limitFromRelayFailure?.({...y(S,R),status:H});if(U.set(R,`provider responded with HTTP ${H}`),!J.limitFromResponse)return;let b=s.get(z)===R,g=q(R);return J.limitFromResponse({...y(S,R),status:H,headers:z,body:async()=>b?await N():g.redactText(await N())})},inspectEvent({data:H,event:z,attempt:N}){if(N.data&&K.get(N.data)==="response_tool_names")return;let S=E2(H);if(!_2(S))return;let R=typeof S.type==="string"?S.type:z;if(R==="content_block_start"||R==="content_block_delta")return{outputStarted:!0};if(R==="message_stop")return{done:!0};if(R!=="error")return;let b=N.data,g=q(b),n=_2(S.error)?S.error:{},i=typeof n.type!=="string"?void 0:V$.has(n.type)?n.type:g.redactText(n.type),J2=typeof n.message==="string"?g.redactText(n.message):void 0;if(b?.dispatch==="http-relay"&&Y.get(b)===!1)return;let V2=b?J.limitFromStreamError?.({...y(N,b),errorType:i,message:J2}):void 0,Z2={error:[i??"error",J2].filter(Boolean).join(": ").slice(0,N1),...V2?{limit:V2}:{}};if(b&&Z2.error)U.set(b,Z2.error);return Z2},limitFromError(H,z){let N=z.data;if(!N||K.has(N))return;let S={type:V$.has(H.type)?H.type:"provider_error",message:U.get(N)??"provider request failed",...H.status!==void 0?{status:H.status}:{}};if(A(N),N.dispatch==="http-relay"&&Y.get(N)===!1)return;return J.limitFromHostError?.(S,y(z,N))},async onAttemptEnd(H,z){let N=H.data;if(!N)return;T.delete(N);let S=z.error?.reason;if(S==="cancelled"||S==="abandoned"||S===void 0&&(z.status===void 0||z.status<400))A(N);let R=K.get(N),{status:b,...g}=z,n=J.onAttemptEnd?.(y(H,N),{...g,...b!==void 0&&(N.dispatch!=="http-relay"||Y.get(N)===!0)?{status:b}:{},...R!==void 0?{localRefusal:{check:R}}:{}});if(await S1(n,F)==="timed-out")M?.warn("the account source did not finish recording a send",{timeoutMs:F})}},dispose(){o=!0;for(let[H,z]of x){for(let N of z)N.revoked=!0;J.forgetSession?.(H)}x.clear(),T.clear();for(let H of[...W.keys()])A(H)},forgetSession(H){for(let z of x.get(H)??[])z.revoked=!0;x.delete(H);for(let[z,N]of T)if(N.sessionID===H)T.delete(z);for(let[z,N]of[...W])if(N.sessionID===H)A(z);J.forgetSession?.(H)},get pendingSendCount(){return T.size},get heldCredentialCount(){let H=0;for(let z of T.values())if(z.oauth)H++;return H},get heldRedactorCount(){return W.size},get operationsInProgress(){let H=0;for(let z of x.values())H+=z.size;return H}}}function x2(X){return JSON.stringify([X.source,X.accountIdentity,X.credentialId,X.binding?.storageId,X.binding?.rowId,X.binding?.credentialEpoch])}function P$(X){let{runtime:J,source:M}=X,V=new AbortController,F=!1,L=new x1({directory:X.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||A1("opencode"),now:X.now}),P=new Map,T=async(W,U,O)=>{let q=O?AbortSignal.any([V.signal,O]):V.signal;q.throwIfAborted();let A=JSON.parse(await U.text()),m={providerID:"anthropic",modelID:A.model,sessionID:`oc2-cachekeep:${W.id}`,agent:"cachekeep",kind:"generate"},w=P2({source:{...M,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(Z){return{...await M.requestOptions?.(Z),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(Z,j){let G=await J.read();q.throwIfAborted();let x=G.accounts.find((D)=>D.id===j);if(x?.type!=="oauth"||x2(x)!==W.oauthAccountIdentity||W.isSubagent&&!c2(G.policyStorage)||!i2(G.policyStorage)||!F$(G.policyStorage,new Date(X.now?.()??Date.now())))return;let E=await M.authorizeAccount(Z,j);if(E?.provenance.kind==="local"&&x2({...x,binding:E.provenance.subject.binding,accountIdentity:E.provenance.subject.binding.identity})!==W.oauthAccountIdentity)return;if(E?.provenance.kind==="vault"&&E.provenance.credentialId!==x.credentialId)return;return E},async admitRequest(Z){await M.admitRequest?.(Z);let j=await J.read(),G=j.accounts.find((x)=>x.id===Z.accountId);if(q.throwIfAborted(),!G||x2(G)!==W.oauthAccountIdentity||W.isSubagent&&!c2(j.policyStorage)||!i2(j.policyStorage)||!F$(j.policyStorage,new Date(X.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),c,r,o=!1,s=()=>w.forgetSession(m.sessionID);q.addEventListener("abort",s,{once:!0});try{let Z=(await J.read()).accounts.find((y)=>x2(y)===W.oauthAccountIdentity)?.id;if(!Z)throw Error("CacheKeep account is unavailable");let j=await w.adapter.accountHeaders({...m,accountId:Z});if(!("headers"in j)||typeof j.headers!=="object"||j.headers===null||typeof j.attempt!=="object"||j.attempt===null||j.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");c={...m,accountId:Z,attemptId:crypto.randomUUID(),transport:"http",data:j.attempt};let G=await w.adapter.rewriteRequest?.({...m,accountId:Z,attempt:c,request:new Request(W.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(A),signal:q})});if(!G)throw Error("CacheKeep rewrite refused");q.throwIfAborted();let x=await(X.fetch??fetch)(G),E=await w.adapter.rewriteResponse?.({...m,accountId:Z,attempt:c,request:G,response:x});if(!E)throw Error("CacheKeep response rewrite refused");if(r=E.status,w.adapter.quotaFromHeaders?.(E.headers,E.status,c),!E.ok)await w.adapter.limitFromResponse?.({status:r,headers:E.headers,body:()=>E.clone().text(),attempt:c});let D=await E.arrayBuffer();return o=!0,new Response(D,{status:r,headers:E.headers})}catch{throw Error("Native CacheKeep was not completed")}finally{q.removeEventListener("abort",s);try{if(c)await w.adapter.onAttemptEnd?.(c,{status:r,outputStarted:!1,...o?{}:{error:{reason:"cancelled"}}})}finally{w.dispose(),M.forgetSession?.(m.sessionID)}}},K=X.setIntervalImpl??globalThis.setInterval,Y=new R1({loadStorage:async()=>F?null:(await J.read()).policyStorage,now:X.now,setIntervalImpl:(W,U)=>K(()=>Y.tick().catch(()=>{q1.warn("cachekeep","tick failed")}),U),clearIntervalImpl:X.clearIntervalImpl,onTrackedSessionsChanged:(W)=>L.publish(F?[]:W),prepareHeaders(W,U,O){if(F)return;return P.set(O.id,{target:U,attempt:O}),new Headers({"x-native-cachekeep-attempt":String(O.id)})},fetchImpl:async(W,U)=>{let O=new Request(W,U),q=Number(O.headers.get("x-native-cachekeep-attempt")),A=P.get(q);if(P.delete(q),!A)throw Error("CacheKeep attempt is unavailable");return T(A.target,O,A.attempt.signal)},onComplete:({attempt:W})=>{P.delete(W.id)}}),B;return{async track(W){if(F||W.route!=="oauth"||W.agent==="cachekeep"||W.agent==="prime"||W.kind!=="primary")return;let U=await J.read();if(F||!i2(U.policyStorage))return;let O=!1;try{O=await X.isSubagent?.(W.sessionID)??!1}catch{return}if(F||O&&!c2(U.policyStorage))return;let q=U.accounts.find((A)=>A.id===W.accountId);if(!q?.accountIdentity)return;if(W.provenance.kind==="local"&&JSON.stringify(q.binding)!==JSON.stringify(W.provenance.subject.binding))return;if(W.provenance.kind==="vault"&&q.credentialId!==W.provenance.credentialId)return;Y.track({sessionId:W.sessionID,url:W.url,headers:new Headers,bodyText:W.bodyText,storage:U.policyStorage,cacheMode:"hybrid",oauthAccountId:W.accountId,oauthAccountIdentity:x2(q),isSubagent:O}),await L.publish(Y.trackedSessions())},registry:L,dispose(){if(B)return B;return F=!0,Y.stop(),V.abort(),B=(async()=>{try{await Y.tick()}finally{P.clear(),await L.dispose()}})(),B}}}async function T$(X,J,M){let V=P2(J),F=[],L=async(U,O,q)=>{let A=await X.session.hook(U,O,q);return F.push(A),A},P=new AbortController,T;try{T=await d2({session:{hook:L},event:X.event},V.adapter,{logger:J.log,gateOnPlaceholder:M})}catch(U){throw V.dispose(),await Promise.allSettled(F.map((O)=>O.dispose())),U}let K=(U)=>{V.forgetSession(U),T.forgetSession(U)},Y=X.event,B=Y?(async()=>{try{for await(let U of Y.subscribe({signal:P.signal}))if(U.type==="session.deleted")K(U.data.sessionID)}catch(U){if(!P.signal.aborted)J.log?.warn("stopped listening for session deletion",{error:U instanceof Error?U.name:"unknown"})}})():Promise.resolve(),W;return{installation:T,forgetSession:K,dispose(){if(W)return W;return V.dispose(),P.abort(),W=(async()=>{await T.dispose(),await B})(),W}}}import{effectiveRelayTransport as O$,getQuotaCheckIntervalMs as k1,logger as D1,nativeAccountCanServe as b1,oauthProfileIsFresh as w1,quotaSnapshotCheckedAt as y1}from"@cortexkit/anthropic-auth-core";function E$(X,J){let M=new AbortController,V,F=!1,L=async()=>{let K=await X.read();if(M.signal.throwIfAborted(),K.policyStorage.relay?.enabled===!0&&O$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="websocket")return;let Y=K,B=k1(Y.policyStorage);for(let W of Y.accounts){if(M.signal.aborted)return;if(!b1(W)||W.type!=="oauth")continue;if(Y.policyStorage.quota?.enabled!==!1&&Date.now()-y1(W.quota)>=B)await X.fetchQuota(W.id,J,M.signal,void 0,"background").catch(()=>{});if(!w1(W.profile)&&!M.signal.aborted)await X.fetchProfile(W.id,J,M.signal).catch(()=>{})}},P=()=>{if(F||V)return V;return V=L().catch(()=>{if(!M.signal.aborted)D1.debug("opencode2","native background readings did not complete")}).finally(()=>{V=void 0}),V},T=X.vault.watch({intervalMs:60000,onRefresh:P,shouldRefresh:async()=>{let K=await X.read();return K.policyStorage.relay?.enabled!==!0||O$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){F=!0,T.close(),M.abort(),await V}}}import{authorize as c1,buildCacheKeepStatusSummary as o1,buildClaudeQuotaSummary as n1,buildPrimeAccountStatuses as r1,buildPrimeStatusSummary as s1,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as a1,exchange as t1,formatNativeAccountState as e1,formatOAuthAccountTier as $X,getCacheKeepWindow as XX,getHostClaustrumEnrollmentPaths as JX,isCacheKeepAlways as ZX,isCacheKeepHybridActive as YX,isCacheKeepPersistentlyEnabled as GX,nativeAccountCanServe as VX,resetClaustrumEnrollmentState as jX}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as I1,effectiveRelayStatus as f1,formatNativeAccountState as g1,formatOAuthAccountTier as S$,getCacheKeepWindow as v1,getRoutingMode as h1,isCacheKeepAlways as m1,isCacheKeepHybridActive as l1,isPermanentRefreshError as d1,isPrimePersistentlyEnabled as p1,nativeAccountCanServe as A$,refreshBackoffActive as R$}from"@cortexkit/anthropic-auth-core";var x$=(X)=>A$(X)&&X.state!=="unsupported-access"?void 0:g1(X)||void 0,u1=(X)=>{if(X.source!=="vault")return"off";if(X.state==="needs_reauth")return"on-vault-reauth";return A$(X)?"on-vault-served":"on-cold"},i1=(X,J)=>typeof X==="number"&&X>J;function q$(X,J){let{now:M}=J,V=X.policyStorage,F=X.accounts.filter((B)=>B.type==="oauth"),L=F.find((B)=>B.id==="main"),P=L?x$(L):void 0,T=L?.lastQuotaRefreshError?.nextRetryAt,K=L?.lastRefreshError,Y=v1(V);return{main:{quota:L?.quota??null,enabled:L?.enabled,tierLabel:S$(L?.profile),quotaBackedOff:i1(T,M),quotaBackoffUntil:T,refreshBackedOff:R$(K,L?.accountIdentity,M,void 0),refreshBackoffUntil:K?.nextRetryAt,stateLine:P,quotaDated:Boolean(P)},fallbacks:F.filter((B)=>B.id!=="main"&&(B.enabled||B.source==="vault")).map((B)=>{let W=x$(B),U=u1(B);return{id:B.id,label:B.label,quota:B.quota??null,enabled:B.enabled,tierLabel:S$(B.profile),needsReauth:d1(B.lastRefreshError)&&R$(B.lastRefreshError,B.accountIdentity,M,void 0),...U==="on-vault-reauth"?{vaultReauth:!0}:{},...U==="on-vault-served"?{vaultServed:!0}:{},...U!=="off"?{custodyState:U}:{},stateLine:W,quotaDated:Boolean(W)}}),activeId:J.activeId,route:h1(V),relay:f1(V.relay),fastMode:V.claudeFast?.enabled===!0,cacheKeep:{enabled:l1(V),window:m1(V)?"always":Y?`${Y.startHour}-${Y.endHour}`:void 0,trackedSessions:J.trackedSessions},prime:p1(V)?{enabled:!0,accounts:I1(V,{now:M})}:void 0,lastUpdated:M}}var o2=(X)=>X!==null&&typeof X==="object"&&!Array.isArray(X)?X:{};function k$(X){let{runtime:J,source:M}=X,V=new Map,F=!1,L=async(Y,B)=>{await J.updateSettings((W)=>({...W,[Y]:{...o2(W[Y]),...B}}))},P=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(Y,B)=>{if(F)throw Error("Native menu is closed");switch(B.signal?.throwIfAborted(),Y.action){case"enable":case"disable":return await J.setEnabled(Y.values.id,Y.action==="enable"),P();case"remove":return await J.remove(Y.values.id),P();case"move-up":case"move-down":{let U=(await J.read()).accounts.map((w)=>w.id),O=U.indexOf(Y.values.id),q=O+(Y.action==="move-up"?-1:1);if(O<0||q<0||q>=U.length)return{ok:!1,text:"Account cannot move in that direction."};let A=U[O],m=U[q];if(A===void 0||m===void 0)return{ok:!1,text:"Account order changed."};return U[O]=m,U[q]=A,await J.reorder(U),P()}case"add-apikey":return await J.addApi(Y.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let W=new AbortController;V.get(Y.sessionId)?.active.abort();let U={active:W,auth:void 0};V.set(Y.sessionId,U);let O=await c1("max");if(F||W.signal.aborted||B.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return U.auth=O,{ok:!0,text:`Open ${O.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let W=V.get(Y.sessionId);if(!W?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let U=await t1(Y.values.code,W.auth.verifier,W.auth.redirectUri,W.auth.state);if(W.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),F||U.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await J.loginOAuth({routeId:crypto.randomUUID(),credential:U,label:Y.values.label}),W.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),F)return{ok:!1,text:"Sign-in cancelled."};return V.delete(Y.sessionId),{ok:!0,text:"OAuth account stored in the native account pool."}}case"reset-backoff":{let W=await J.read();for(let U of W.accounts){if(B.signal?.throwIfAborted(),U.type!=="oauth")continue;let O=U.source==="vault"?await J.authorizeVault(U.id,B.signal):await J.captureLocalSubject(U.id);await J.resetBackoff(U.id,O)}return P()}case"enrollment-reset":{let W=await jX(JX("opencode"),a1);return{ok:W==="reset",text:W==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":W==="refused-pending"?"An enrollment request may still be in progress. Quit OpenCode and run setup again; it picks up the same request.":"Only terminal enrollment state may be reset; active enrollment was left unchanged."}}case"quota-refresh":{let U=(await J.read()).accounts.filter((A)=>A.type==="oauth"&&VX(A)),O=await Promise.allSettled(U.map((A)=>J.fetchQuota(A.id,void 0,B.signal)));return{ok:O.every((A)=>A.status==="fulfilled"),text:`${O.filter((A)=>A.status==="fulfilled").length}/${U.length} native quota readings refreshed.`}}case"routing-reset":return await M.resetRouting(Y.sessionId),P();case"routing-mode":return await L("routing",{mode:Y.values.mode}),P();case"killswitch-on":case"killswitch-off":return await L("killswitch",{enabled:Y.action==="killswitch-on"}),P();case"killswitch-set":return await J.updateSettings((W)=>{let U=o2(W.killswitch),O={...o2(U.accounts)},q=U.main;for(let A of Y.values.entries){let m={five_hour:A.fh,seven_day:A.sd,...A.scoped!==void 0?{scoped:A.scoped}:{}};if(A.account==="main"||A.account==="all")q=m;if(A.account==="all")for(let w of Object.keys(O))O[w]=m;else if(A.account!=="main")O[A.account]=m}return{...W,killswitch:{...U,main:q,accounts:O}}}),P();case"cache-on":case"cache-off":return await L("claudeCache",{enabled:Y.action==="cache-on"}),P();case"cache-mode":return await L("claudeCache",{mode:Y.values.mode}),P();case"cachekeep-always":return await L("cacheKeep",{enabled:!0,always:!0}),P();case"cachekeep-off":return await L("cacheKeep",{enabled:!1}),P();case"cachekeep-window":return await L("cacheKeep",{enabled:!0,always:!1,startHour:Y.values.startHour,endHour:Y.values.endHour}),P();case"cachekeep-subagents":return await L("cacheKeep",{subagents:Y.values.enabled==="on"}),P();case"dump-on":case"dump-off":return await L("dump",{enabled:Y.action==="dump-on"}),P();case"logging-level":return await L("logging",{level:Y.values.level}),P();case"fast-on":case"fast-off":return await L("claudeFast",{enabled:Y.action==="fast-on"}),P();case"prime-on":case"prime-off":return await L("prime",{enabled:Y.action==="prime-on"}),P();case"start-fire":return await K(Y.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},K=(Y)=>X.start(Y,D2);return{dispatch:T,async readStatus(Y){let B=await J.read();if(Y==="account")return B.accounts.map((U)=>`${U.id}${U.label?` (${U.label})`:""}: ${U.type}, ${U.source}, ${U.enabled?"enabled":"disabled"}${U.state?`, ${e1(U)}`:""}${U.accountIdentity?`, ${U.accountIdentity}`:""}`).join(`
|
|
4
|
+
`)||"No native Claude accounts.";if(Y==="quota")return n1({accounts:B.accounts.filter((U)=>U.type==="oauth").map((U)=>({name:U.label??U.id,role:U.id==="main"?"main":"fallback",enabled:U.enabled,quota:U.quota,tierLabel:$X(U.profile),lastRefreshedAt:U.lastRefreshedAt,error:U.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(Y==="prime")return s1({enabled:B.policyStorage.prime?.enabled===!0,accounts:r1(B.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(Y==="cachekeep"){let U=await X.cacheKeepRegistry?.list()??[];return o1({enabled:GX(B.policyStorage),always:ZX(B.policyStorage),hybridActive:YX(B.policyStorage),trackedSessionDetails:U,window:XX(B.policyStorage),trackedSessions:U.length,nextPrewarmAt:U.length?Math.min(...U.map((O)=>O.nextPrewarmAt)):void 0})}let W={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(B.settings[W[Y]]??{})},async readSidebar(Y){let[B,W]=await Promise.all([J.read(),X.cacheKeepRegistry?.list()??[]]);return q$(B,{activeId:M.servedAccount(Y),trackedSessions:W.length,now:Date.now()})},forgetSession(Y){V.get(Y)?.active.abort(),V.delete(Y)},close(){F=!0;for(let Y of V.values())Y.active.abort();V.clear()}}}import{resolveClaudeModelCapabilities as WX}from"@cortexkit/anthropic-auth-core";function D$(){let X=new Map;return{install:(M)=>M.model.transform((V)=>{X.clear();for(let F of V.list("anthropic")){X.set(String(F.id),String(F.modelID));let L=WX(F.modelID)?.efforts.variants;if(!L)continue;V.update("anthropic",String(F.id),(P)=>{let T=P.variants.filter((K)=>!L.some((Y)=>Y===String(K.id)));P.variants=[...T,...L.map((K)=>({id:K,settings:{effort:K,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(M)=>X.get(M)??M}}function b$(X){return X.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??X.get("x-api-key")??void 0}import{buildPrimeRequestBody as w$,effectiveRelayTransport as y$,nativeAccountCanServe as QX,PrimeManager as HX}from"@cortexkit/anthropic-auth-core";var I$=(X)=>X!==null&&typeof X==="object"&&!Array.isArray(X)?X:{};function f$(X){let{runtime:J,source:M}=X,V=new AbortController,F=new Set,L=(K)=>({providerID:"anthropic",modelID:w$().model,sessionID:`oc2-prime:${K}`,agent:"prime",kind:"generate"}),P=async(K)=>{let Y=L(K),B=P2({source:M}),W=performance.now();try{for(let U=0;U<3;U++){if(V.signal.throwIfAborted(),(await J.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let q=await B.adapter.accountHeaders({...Y,accountId:K});if(!("headers"in q)||typeof q.headers!=="object"||q.headers===null||typeof q.attempt!=="object"||q.attempt===null)throw Error("Native Prime authorization refused");let A={...Y,accountId:K,attemptId:crypto.randomUUID(),transport:"http",data:q.attempt},m,w=!1,c=!1,r=(o)=>{c=!0,o.body?.cancel().catch(()=>{})};try{let o=await B.adapter.rewriteRequest?.({...Y,accountId:K,attempt:A,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w$()),signal:V.signal})});if(!o)throw Error("Native Prime rewrite refused");let s=new Headers(o.headers);for(let[l,p]of Object.entries(q.headers))if(p===null)s.delete(l);else s.set(l,p);let Z=new Request(o,{headers:s}),j=await(X.fetch??fetch)(Z),G=await B.adapter.rewriteResponse?.({...Y,accountId:K,request:Z,response:j,attempt:A})??j;m=G.status,B.adapter.quotaFromHeaders?.(G.headers,G.status,A);let x=G.ok?void 0:await B.adapter.limitFromResponse?.({status:G.status,headers:G.headers,body:()=>G.clone().text(),attempt:A});if(x&&/^(vault-newer|local-newer|relay-direct):/.test(x.reason)&&U<2){r(G);let l={...Y,phase:"retry",rerouteFrom:{accountId:K,limit:x}};if(await M.chooseAccount(l)!==K)throw Error("Native Prime retry changed account");continue}if(!G.ok)return r(G),{ok:!1,status:m,ms:performance.now()-W,error:"Native Prime upstream refused the request"};let E=I$(await G.json()),D=I$(E.usage),y={inputTokens:typeof D.input_tokens==="number"?D.input_tokens:void 0,outputTokens:typeof D.output_tokens==="number"?D.output_tokens:void 0};if(A.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(G.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await M.recordPrime(q.attempt.provenance,y),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:m,ms:performance.now()-W,usage:y}}finally{await B.adapter.onAttemptEnd?.(A,{status:m,outputStarted:!1,...w?{}:{error:{reason:c?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-W}}finally{B.dispose()}},T=new HX({storagePath:X.paths.legacyConfig,loadStorage:async()=>(await J.read()).policyStorage,async getAccountFingerprint(K){let Y=await J.read(),B=Y.accounts.find((U)=>U.id===K);if(!QX(B)||B?.type!=="oauth")return;if(Y.policyStorage.relay?.enabled===!0&&y$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")return;if(B.source==="vault"){let U=await J.authorizeVault(K,V.signal);return J.getOrCreateAuthLineage(K,U)}let W=await J.authorizeLocal(K,{signal:V.signal});return W.status==="usable"?J.getOrCreateAuthLineage(K,W.subject):void 0},async refreshQuota(K){let Y=await J.read();if(Y.policyStorage.relay?.enabled===!0&&y$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await J.fetchQuota(K,X.fetch,V.signal),fresh:!0}},sendPrime(K){let Y=P(K);return F.add(Y),Y.finally(()=>F.delete(Y)),Y},async recordSuccess(K){let Y=(await J.read()).accounts.find((B)=>B.id===K);if(!Y?.prime)throw Error("Native Prime counters are unavailable");return Y.prime}});return T.start(),{manager:T,async dispose(){T.stop(),V.abort(),await Promise.allSettled(F)}}}import{createNativeUsagePublisher as UX,effectiveRelayTransport as BX,getClaudeCodeIdentityForVerifiedAccount as b2,getQuotaCheckIntervalMs as KX,getRoutingMode as g$,isQuotaBearingHeaderFrame as MX,logger as zX,mergeHeaderQuotaForPersistence as _X,NativeVaultNoAccountError as CX,nativeAccountCanServe as n2,nativeAccountPolicy as w2,nativeLocalQuotaLineage as NX,nativePollQuotaGenerallyExhausted as LX,normalizeQuotaHeaders as FX,quotaSnapshotCheckedAt as v$,quotaSnapshotHasStandardWindows as PX,readNativeAccountsForRequest as TX,remapModelId as r2,StickySessionRouter as OX,shouldFallbackStatus as EX,stickyQuotaSnapshotIsFresh as y2,stickyRouteFamilyForModel as SX}from"@cortexkit/anthropic-auth-core";var s2=(X)=>["five_hour","seven_day"].some((J)=>(X?.[J]?.remainingPercent??1)<=0);function m$(X){let{runtime:J}=X,M=UX("native-auth"),V=new Map,F=(Z)=>{let j=Z.routingPath;if(!j)throw Error("Native routing storage is unavailable");let G=V.get(j);if(!G)G=new OX({path:j,vaultSeed:Z.routingSeed,onLockEvent:J.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),V.set(j,G);return G.setVaultSeed(Z.routingSeed),G},L=new WeakMap,P=new Map,T=new Map,K=new Map,Y=new Map,B=new WeakSet,W=!1,U=()=>{while(P.size>512){let Z=P.keys().next();if(!Z.done)P.delete(Z.value)}},O=(Z,j)=>JSON.stringify([Z.sessionID,Z.kind,Z.modelID,j]),q=(Z)=>{if(W)throw Error("Native Anthropic source is closed");let j=K.get(Z.sessionID);if(!j){j=new AbortController,K.set(Z.sessionID,j);while(K.size>512){let G=K.keys().next();if(!G.done)s.forgetSession?.(G.value)}}return j},A=(Z,j,G)=>n2(Z)&&(Z.type==="api"||w2(Z,j,r2(G)).status==="allowed"),m=async(Z,j,G,x)=>{let E=await J.read();x.signal.throwIfAborted(),w(E);let D=E.accounts.find((y)=>y.id===Z);if(!D||D.type!==G||!A(D,E,j))return!1;if(G==="api"){let y=E.accounts.find((l)=>l.id==="main"&&l.type==="oauth");return!!y&&y2(y.quota,E.policyStorage)&&s2(y.quota)}return!0},w=(Z)=>{let j=Z.policyStorage.relay;if(j?.enabled===!0&&BX(j.transport,j.url)==="websocket")throw new F2},c=async(Z,j)=>{if(w(Z),j||Z.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let G=await J.getRelayConfig();if(!G)throw Error("request refused: native HTTP relay configuration is unavailable");if(G.transport!=="http")throw new F2;return{dispatch:{kind:"http-relay",url:G.url,token:G.token},relayFallback:G.fallbackToDirect}};async function r(Z,j,G){if(Z.kind==="local"){let x=await J.publishLocal(Z.subject,G);if(!x&&G.quota)zX.warn("quota","Quota publication discarded");return x}if(Z.kind==="vault"&&j.receipt)await J.vault.publish(j.receipt,G);else if(Z.kind==="api"&&G.lastUsed!==void 0)await J.publishApi(Z.subject,{lastUsed:G.lastUsed});return!0}function o(Z,j,G){if(Z.kind!=="local")return;let x=Z.subject.binding,E=v$(G),D={lineage:NX(x),accountUuid:x.identity,entry:{quota:G,checkedAt:E,refreshAfter:E},generalExhausted:LX(G),routeBeforeSave:!0};return J.quotaObservations.hold(j.account.id,D)?D:void 0}let s={async chooseAccount(Z){let j=q(Z);X.onOwnedRequest?.();let G=await J.read();j.signal.throwIfAborted(),w(G);let x=r2(await X.resolveModelId?.(Z)??Z.modelID);if(j.signal.throwIfAborted(),G.mode==="claustrum")G=await TX(J,j.signal),j.signal.throwIfAborted();if(G.policyStorage.quota?.enabled!==!1){let I=!1;for(let u of G.accounts){if(!n2(u)||u.type!=="oauth")continue;if(PX(u.quota)?y2(u.quota,G.policyStorage,Date.now(),x):Date.now()-v$(u.quota)<KX(G.policyStorage))continue;try{await J.fetchQuota(u.id,X.fetch,j.signal,void 0,"admission"),I=!0}catch{j.signal.throwIfAborted()}}if(I)G=await J.read();j.signal.throwIfAborted()}let E=Z.rerouteFrom?P.get(Z.rerouteFrom.limit.reason):void 0;if(Z.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(Z.rerouteFrom.limit.reason)&&!E)return;if(E&&Z.rerouteFrom){let I=G.accounts.find((H)=>H.id===E.accountId);if(!I||!A(I,G,x))return;P.delete(Z.rerouteFrom.limit.reason);let u=O(Z,E.accountId),d=T.get(u)??[];return d.push(E),T.set(u,d),E.accountId}let D=[];for(let I of G.accounts){if(I.type!=="oauth"||!A(I,G,x))continue;if(I.source==="local"){let u=await J.authorizeLocal(I.id,{signal:j.signal,policy:(d,H)=>w2(d,H,x)});if(j.signal.throwIfAborted(),u.status!=="usable")continue}D.push(I)}let y=D.filter((I)=>I.id!==Z.rerouteFrom?.accountId);if(g$(G.policyStorage)==="sticky-balanced"){let I=y.map((d,H)=>({accountId:d.id,order:H,quota:d.quota??{kind:"unknown"}})),u=await F(G).resolve({sessionId:Z.sessionID,family:SX(x),modelId:x,affinityModelId:Z.modelID,candidates:I,retainAccountIds:new Set(y.map((d)=>d.id)),...G.mode==="claustrum"?{accountIdentities:new Map(G.accounts.flatMap((d)=>d.accountIdentity?[[d.id,d.accountIdentity]]:[]))}:{},storage:G.policyStorage,inputBytes:1,preferredAccountId:Z.previousAccountId,preserveOnNoCandidate:!0});if(j.signal.throwIfAborted(),u)return u.accountId}else{let u=g$(G.policyStorage)==="fallback-first"?[...y.filter((d)=>d.id!=="main"),...y.filter((d)=>d.id==="main")]:[...y.filter((d)=>d.id==="main"),...y.filter((d)=>d.id!=="main")];if(u[0])return u[0].id}if(G.mode==="claustrum")throw new CX;let l=G.accounts.find((I)=>I.id==="main"&&I.type==="oauth");if(!l)return;let p=l.quota;if(Z.rerouteFrom?.limit.status===429||!y2(p,G.policyStorage))try{p=await J.fetchQuota("main",X.fetch,j.signal)}catch{return}if(j.signal.throwIfAborted(),!s2(p))return;return G.accounts.find((I)=>I.type==="api"&&n2(I)&&I.id!==Z.rerouteFrom?.accountId)?.id},dropChoice(Z){let j=O(Z,Z.accountId),G=T.get(j);if(G?.shift(),G?.length===0)T.delete(j)},async authorizeAccount(Z,j){let G=q(Z),x=await J.read();G.signal.throwIfAborted(),w(x);let E=r2(await X.resolveModelId?.(Z)??Z.modelID);G.signal.throwIfAborted();let D=x.accounts.find((S)=>S.id===j);if(!D||!A(D,x,E))return;let y=O(Z,j),l=T.get(y),p=l?.shift();if(l?.length===0)T.delete(y);let{dispatch:I,relayFallback:u}=await c(x,p?.direct===!0);if(G.signal.throwIfAborted(),p?.auth){if(!await m(j,E,p.auth.route,G))return;let S=L.get(p.auth.provenance);if(S?.receipt?.expiresAtMs!==void 0&&S.receipt.expiresAtMs!==null&&S.receipt.expiresAtMs<Date.now()+300000)return;if(S)L.set(p.auth.provenance,{...S,scope:{...Z,modelID:E},account:D,active:G,relayFallback:u});return Y.set(Z.sessionID,j),{...p.auth,dispatch:I}}let d={scope:{...Z,modelID:E},active:G,account:D,retry:p?.retry??!1,relayFallback:u,quota:D.quota};if(D.type==="api"){let S=x.accounts.find((n)=>n.id==="main"&&n.type==="oauth");if(!S||!y2(S.quota,x.policyStorage)||!s2(S.quota))return;let R=await J.authorizeApi(j,G.signal);if(G.signal.throwIfAborted(),!await m(j,E,"api",G))return;let b={kind:"api",subject:R.subject};return L.set(b,d),Y.set(Z.sessionID,j),{route:"api",headers:R.authHeader==="authorization-bearer"?{authorization:`Bearer ${R.apiKey}`}:{"x-api-key":R.apiKey},baseURL:R.baseURL,provenance:b,dispatch:I}}if(D.source==="vault"){let S=await J.authorizeVault(j,G.signal);if(G.signal.throwIfAborted(),!await m(j,E,"oauth",G))return;let R={kind:"vault",credentialId:S.credentialId,recordVersion:S.recordVersion};L.set(R,{...d,receipt:S});let b=S.assertedAccountIdentity;if(!b)return;return Y.set(Z.sessionID,j),{route:"oauth",accessToken:S.accessToken,provenance:R,dispatch:I,identity:b2(b,b)}}let H=await J.authorizeLocal(j,{signal:G.signal,policy:(S,R)=>w2(S,R,E)});if(G.signal.throwIfAborted(),H.status!=="usable")return;if(!await m(j,E,"oauth",G))return;let z={kind:"local",subject:H.subject};L.set(z,{...d,access:H.access}),Y.set(Z.sessionID,j);let N=H.subject.binding.identity;return{route:"oauth",accessToken:H.access,provenance:z,dispatch:I,identity:b2(N,N)}},async requestOptions(Z){let j=q(Z),G=await J.read();j.signal.throwIfAborted();let x=G.accounts.find((D)=>D.id===Z.accountId);if(!x||!A(x,G,Z.modelID))throw Error("request refused: native account is ineligible for this model");let E=L.get(Z.provenance);if(E)L.set(Z.provenance,{...E,scope:{...E.scope,modelID:Z.modelID}});return X.requestOptions(Z,G)},async admitRequest(Z){let j=L.get(Z.provenance);if(!j||!await m(Z.accountId,Z.modelID,Z.route,j.active))throw Error("request refused: native account policy changed before dispatch");L.set(Z.provenance,{...j,scope:{...j.scope,modelID:Z.modelID}})},onRequestPrepared:(Z)=>X.onRequestPrepared?.(Z),responseOptions(Z){return X.responseOptions?.({...Z,modelID:L.get(Z.provenance)?.scope.modelID??Z.modelID})},quotaFromHeaders(Z,j){let G=L.get(j.provenance),x=h$(Z);if(x)X.onRequestId?.(j,x);if(!G||j.route!=="oauth"||!MX(Z))return;let E=j.provenance.kind==="local"?j.provenance.subject.binding.identity:G.receipt?.assertedAccountIdentity,D={...FX(Z),...E?{accountIdentity:E}:{}},y=_X(G.quota,D);G.quota=y;let l=o(j.provenance,G,y),p=G.account.id,I=()=>{if(l)J.quotaObservations.forget(p,l)};return M.observe(r(j.provenance,G,{quota:y}).then((u)=>{if(!u)I()},(u)=>{throw I(),u})),D},async limitFromResponse(Z){let j=L.get(Z.provenance);if(!j)return;if(Z.status===401&&j.receipt){if(!B.has(j.receipt))B.add(j.receipt),await J.vault.reportFailure(j.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(j.retry||j.active.signal.aborted)return;let x=j.active,E=await J.vault.prepareRetry(j.receipt,x.signal);if(x.signal.throwIfAborted(),!E.retry)return;let D=E.receipt,y=D.assertedAccountIdentity;if(!y)return;let l={kind:"vault",credentialId:D.credentialId,recordVersion:D.recordVersion};L.set(l,{...j,receipt:D,retry:!0});let p=`vault-newer:${Z.attemptId}`;return P.set(p,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:D.accessToken,provenance:l,identity:b2(y,y)}}),U(),{reason:p,status:401}}if(Z.status===401&&Z.provenance.kind==="local"&&j.access&&!j.retry){if(j.active.signal.aborted)return;let x=j.active,E=await J.authorizeLocal(Z.accountId,{rejectedAccessToken:j.access,signal:x.signal,policy:(p,I)=>w2(p,I,j.scope.modelID)});if(x.signal.throwIfAborted(),E.status!=="usable"||E.access===j.access)return;let D={kind:"local",subject:E.subject};L.set(D,{...j,access:E.access,retry:!0});let y=E.subject.binding.identity,l=`local-newer:${Z.attemptId}`;return P.set(l,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:E.access,provenance:D,identity:b2(y,y)}}),U(),{reason:l,status:401}}let G=await J.read();if(EX(Z.status,G.policyStorage))return{reason:`provider-${Z.status}`,status:Z.status};return},limitFromRelayFailure(Z){let j=L.get(Z.provenance);if(!j?.relayFallback||j.active.signal.aborted||!(Z.status===401||Z.status>=500))return;let G=`relay-direct:${Z.attemptId}`;return P.set(G,{sessionID:Z.sessionID,accountId:Z.accountId,direct:!0,retry:!1}),U(),{reason:G}},limitFromStreamError(Z){return Z.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(Z,j){let G=L.get(j.provenance);if(j.dispatch==="http-relay"&&G?.relayFallback&&!G.active.signal.aborted&&Z.status===void 0){let x=`relay-direct:${j.attemptId}`;return P.set(x,{sessionID:j.sessionID,accountId:j.accountId,direct:!0,retry:!1}),U(),{reason:x}}return},async onAttemptEnd(Z,j){let G=L.get(Z.provenance);if(!G)return;try{if(j.status===401&&G.receipt&&!B.has(G.receipt))B.add(G.receipt),await J.vault.reportFailure(G.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(!j.localRefusal&&j.status!==void 0)M.publish(()=>r(Z.provenance,G,{lastUsed:Date.now()}))}finally{L.delete(Z.provenance)}},forgetSession(Z){K.get(Z)?.abort(),K.delete(Z),Y.delete(Z);for(let[j,G]of P)if(G.sessionID===Z)P.delete(j);for(let[j,G]of T)if(G[0]?.sessionID===Z)T.delete(j);X.onForgetSession?.(Z)},servedAccount:(Z)=>Y.get(Z),resetRouting:async(Z)=>F(await J.read()).clear(Z),async recordPrime(Z,j){let G=L.get(Z);if(!G||G.active.signal.aborted)return!1;if(Z.kind==="local")return J.incrementPrimeUsage(G.account.id,Z.subject,j);if(Z.kind==="vault"&&G.receipt)return J.incrementPrimeUsage(G.account.id,G.receipt,j);return!1},drainRoutingPublications:()=>Promise.all([J.drainRoutingPublications(),...[...V.values()].map((Z)=>Z.drain())]).then(()=>{}),close(){W=!0;for(let Z of K.values())Z.abort();return K.clear(),T.clear(),P.clear(),Promise.all([M.drain(),s.drainRoutingPublications()]).then(()=>{})}};return s}import{remapModelId as RX}from"@cortexkit/anthropic-auth-core";function p$(){let X=new l$,J=new Map,M=new Map,V=new Map,F=new Set,L=new Set,P=new Map,T=(K)=>{while(K.size>512){let Y=K.keys().next();if(!Y.done)K.delete(Y.value)}};return{async install(K){let Y=[];try{Y.push(await K.session.hook("context",(B)=>{let W=B.messages.map((O)=>{return{info:{id:O.id,sessionID:B.sessionID,role:O.role,agent:B.agent,model:{providerID:B.model.providerID,modelID:B.model.id}},parts:O.content.map((q)=>({type:q.type,...q.type==="text"?{text:q.text}:{}}))}});X.observeMessages(W);let U=B.messages.findLast((O)=>O.role==="user"&&O.id);if(U?.id)J.set(B.sessionID,U.id);if(U?.content.some((O)=>O.type==="text"&&O.text===D2))F.add(B.sessionID);else F.delete(B.sessionID);T(J)},{providerID:"anthropic"})),Y.push(await K.session.hook("model.request",(B)=>{if(B.kind!=="primary")return;let W=J.get(B.sessionID);if(!W)return;if(X.markHeaders({sessionId:B.sessionID,messageId:W,agent:B.agent,headers:B.headers}),F.has(B.sessionID))B.headers[R2]="1"},{providerID:"anthropic"}))}catch(B){throw await Promise.allSettled(Y.map((W)=>W.dispose())),B}return{dispose:async()=>{await Promise.all(Y.map((B)=>B.dispose()))}}},requestOptions(K,Y){let B=X.resolveHeader(K.correlation[k2]);if(B)M.set(K.attemptId,B),T(M);P.set(K.attemptId,K.sessionID),T(P);let W=K.correlation[R2]==="1";if(W)L.add(K.attemptId);return{cache1hEnabled:K.agent!=="compaction"&&K.agent!=="title"&&(Y.policyStorage.claudeCache?.enabled??!0),cache1hMode:Y.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:Y.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:Y.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:Y.policyStorage.turnEndNote,serverSideFallbackEnabled:d$(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:W,billingLineage:B?{promptId:B.promptId,previousRequestId:B.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:V.get(K.sessionID)}},responseOptions(K){return{serverSideFallbackModel:RX(K.modelID),laneStart:L.has(K.attemptId),onMessageStart(Y){if(K.kind==="primary"&&typeof Y.id==="string")V.set(K.sessionID,Y.id),T(V)},onStreamEnd(){M.delete(K.attemptId),L.delete(K.attemptId),P.delete(K.attemptId)}}},onRequestId(K,Y){X.commit(M.get(K.attemptId),Y)},forgetSession(K){X.clearSession(K),J.delete(K),V.delete(K),F.delete(K);for(let[Y,B]of P)if(B===K)M.delete(Y),L.delete(Y),P.delete(Y)}}}var I2="cortexkit-anthropic-auth",yX='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',IX="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",fX="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function gX(X){let J=X.authorize??AX,M=X.exchange??DX,V=()=>{if(!X.isActive())throw Error("Claude authentication setup is closed")},F=async()=>{let T;try{T=await X.readMode()}catch{throw Error(fX)}return V(),T},L=async()=>{if(await F()!=="local")throw Error(yX)};return{integrationID:"anthropic",methods:[{method:{id:i$,type:"oauth",label:c$},async authorize(){V(),await L();let T=await J("max");return V(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(K)=>{V();let Y=await M(K,T.verifier,T.redirectUri,T.state);if(!X.isActive()||Y.type!=="success")throw Error("Claude sign-in did not complete");return{access:Y.access,refresh:Y.refresh,expires:Y.expires}}}}}],vault:{method:{id:o$,type:"oauth",label:"Claude vault accounts"},async activate(){if(V(),await F()!=="claustrum")throw Error(IX)}},async onLogin(T){V(),await L(),await X.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),V()},label:"Claude native account pool"}}function vX(X){return{readMode:()=>bX("opencode",X),disconnectVault:()=>kX({host:"opencode",env:X})}}function a2(X={}){return{id:I2,setup:(J)=>r$(J,X)}}async function r$(X,J={}){let M=J.paths??await wX(),V=xX({paths:M,host:"opencode",local:J.local,vault:J.vault}),F=vX(J.vault?.env??process.env),L=!0,P=p$(),T=D$(),K,Y,B,W=m$({runtime:V,paths:M,fetch:J.fetch,requestOptions:P.requestOptions,responseOptions:P.responseOptions,onRequestId:P.onRequestId,onForgetSession:P.forgetSession,onRequestPrepared:async(w)=>{try{await B?.track(w)}catch{u$.warn("cachekeep","live request tracking failed")}},resolveModelId:async(w)=>T.modelId(w.modelID),onOwnedRequest:()=>{K??=E$(V,J.fetch),Y??=f$({runtime:V,paths:M,source:W,fetch:J.fetch})}});B=P$({...J.cacheKeep,runtime:V,source:W,fetch:J.fetch,isSubagent:async(w)=>Boolean((await X.session.get({sessionID:w})).parentID)});let U=k$({runtime:V,source:W,cacheKeepRegistry:B.registry,start:async(w,c)=>{await X.session.synthetic({sessionID:w,text:c,description:"Claude lane start",resume:!0})}}),O=[],q=await T$(X,{source:W,log:{warn:(w,c)=>u$.warn("opencode2",w,c)}},{credential:b$}).catch(async(w)=>{throw U.close(),await B?.dispose(),await W.close(),await V.drainQuotaPublications(),V.close(),w}),A,m=()=>{if(A)return A;return L=!1,U.close(),W.close(),A=(async()=>{await Promise.allSettled([q.dispose(),K?.dispose(),Y?.dispose(),B?.dispose(),...O.map((w)=>w.dispose())]),await W.close(),await V.drainQuotaPublications(),V.close()})(),A};try{O.push(await P.install(X)),O.push(await T.install(X)),O.push(await h2(X,gX({isActive:()=>L,readMode:F.readMode,runtime:V})));let w={host:"opencode",dispatch:U.dispatch,readStatus:(r)=>U.readStatus(r),readAccounts:()=>V.read(),readMode:F.readMode,disconnectVault:F.disconnectVault,interactive:!0},c=qX(w);return O.push(await n$(X,c,U)),m}catch(w){throw await m(),w}}var $Z={id:I2,setup:a2().setup,server:s$};export{r$ as setupAnthropicAuth,$Z as default,a2 as createAnthropicAuthPlugin,I2 as ANTHROPIC_AUTH_PLUGIN_ID};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.6",
|
|
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.2.
|
|
80
|
+
"@cortexkit/anthropic-auth-core": "2.2.6",
|
|
81
81
|
"@cortexkit/claustrum-client": "0.12.0",
|
|
82
82
|
"@cortexkit/private-files": "0.2.1",
|
|
83
83
|
"@cortexkit/subc-client": "^0.22.0",
|