@cortexkit/opencode-anthropic-auth 2.2.4 → 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-79frmfve.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};
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};
@@ -152,6 +152,8 @@ export interface NativeAnthropicAttemptOutcome extends AttemptOutcome {
152
152
  export interface NativeAnthropicSource<Q, P> {
153
153
  /** Picks the account for one request; `undefined` refuses it. */
154
154
  readonly chooseAccount: (input: ChooseAccountInput) => Promise<string | undefined> | string | undefined;
155
+ /** Discards one queued choice that the installer will not authorize. */
156
+ readonly dropChoice?: (input: AccountRequest) => Promise<void> | void;
155
157
  /**
156
158
  * The credential for one send with the chosen account; `undefined` refuses
157
159
  * the request before anything is sent.
@@ -218,7 +220,9 @@ export interface NativeAnthropicAdapterDeps<Q, P> {
218
220
  readonly requestGzipLatch?: RequestGzipLatch;
219
221
  }
220
222
  export interface NativeAnthropicAdapter<Q, P> {
221
- readonly adapter: OpenCode2AuthAdapter<Q, NativeAnthropicAttemptData<P>>;
223
+ readonly adapter: OpenCode2AuthAdapter<Q, NativeAnthropicAttemptData<P>> & {
224
+ readonly dropChoice: (input: AccountRequest) => Promise<void> | void;
225
+ };
222
226
  /**
223
227
  * Drops the session's authorized sends that have not been rewritten yet,
224
228
  * revokes its choices, authorizations and rewrites still in progress so