@cortexkit/opencode-anthropic-auth 2.4.5 → 2.4.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.
- package/dist/cli.js +1 -1
- package/dist/{index-sg0knfec.js → index-2ra790fx.js} +1 -1
- package/dist/{index-naff9h33.js → index-a0jxsmac.js} +1 -1
- package/dist/{index-gvswxab8.js → index-crx0xd9j.js} +1 -1
- package/dist/{index-j2cv839v.js → index-d4e8qj37.js} +1 -1
- package/dist/index-eq1kbq5z.js +2 -0
- package/dist/{index-hc7bm3yf.js → index-jc8zwxvw.js} +1 -1
- package/dist/{index-71temqvq.js → index-n8xr16kr.js} +1 -1
- package/dist/{index-m4dazzyf.js → index-qqs4ec18.js} +1 -1
- package/dist/index-zxyjjr82.js +45 -0
- package/dist/index.js +1 -1
- package/dist/routing-relay.d.ts +22 -0
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/v2/server.js +9 -9
- package/dist/v2/tui.js +1 -1
- package/package.json +2 -2
- package/dist/index-61bbefpq.js +0 -2
- package/dist/index-y35yxsnq.js +0 -45
package/dist/rpc/rpc-client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ka as s}from"../index-crx0xd9j.js";import"../index-n8xr16kr.js";async function i(e,o,t,n){let r=await s(e,n);if(!r)return null;let a=new AbortController,l=setTimeout(()=>a.abort(),2000);try{let p=await fetch(`http://127.0.0.1:${r.port}/rpc/${o}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r.token}`},body:JSON.stringify(t),signal:a.signal});if(!p.ok)return null;return await p.json()}catch{return null}finally{clearTimeout(l)}}function c(e,o){return{async pending(t,n){return(await i(e,"pending-notifications",{lastReceivedId:t,sessionId:n},o))?.messages??[]},async apply(t){return await i(e,"apply",{...t},o)??{text:"apply failed",knobs:{}}},async applyMenu(t){if(t.command!=="claude"||!t.sessionId?.trim())throw TypeError("A claude menu sessionId is required");let n=await i(e,"apply-menu",{...t},o);if(!n)throw Error("Menu apply unavailable; outcome unknown");return n}}}export{c as createRpcClient};
|
package/dist/rpc/rpc-dir.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{v as a,w as b}from"../index-jc8zwxvw.js";import"../index-n8xr16kr.js";export{a as tmpdir,b as getRpcDir};
|
package/dist/sidebar-state.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as
|
|
1
|
+
import{$ as r,K as a,L as b,M as c,N as d,O as e,P as f,Q as g,R as h,S as i,T as j,U as k,V as l,W as m,X as n,Y as o,Z as p,_ as q,aa as s,ba as t,ca as u,da as v,ea as w,fa as x,ga as y,ha as z,ia as A}from"./index-d4e8qj37.js";import"./index-n8xr16kr.js";export{i as setSidebarState,r as scopedQuotaShortNames,k as resolveActiveAccount,s as quotaLabelColumnWidth,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,w as getCollapsedQuotaSummary,x as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,u as fitQuotaRow,v as fitPaceLine,j as drainSidebarWrites,A as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,z as SEVEN_DAY_MS,t as QUOTA_BAR_MIN_CELLS,y as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
|
package/dist/tui-preferences.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./index-
|
|
1
|
+
import"./index-n8xr16kr.js";import{readFileSync as S,statSync as b,watch as F}from"node:fs";import{mkdir as g,readFile as I,rename as T,writeFile as y}from"node:fs/promises";import{homedir as h}from"node:os";import{basename as v,dirname as _,join as N}from"node:path";import{clearTimeout as D,setTimeout as P}from"node:timers";import{applyEdits as f,modify as m,parse as p}from"jsonc-parser";var c="OPENCODE_TUI_PREFERENCES_FILE",u="tui-preferences.jsonc";function K(){let Q=process.env[c];if(Q)return Q;let q=process.env.OPENCODE_CONFIG_DIR||N(process.env.XDG_CONFIG_HOME||N(h(),".config"),"opencode");return N(q,u)}function H(Q){return typeof Q==="object"&&Q!==null&&!Array.isArray(Q)}async function Zq(){try{let Q=await I(K(),"utf8"),q=[],J=p(Q,q,{allowTrailingComma:!0});if(q.length>0)return{};return H(J)?J:{}}catch{return{}}}var s="anthropic-auth",d=160,k={forceToTop:!1,order:d,startCollapsed:!1,rememberCollapsed:!0,collapsed:null,pollMs:1500,refreshDebounceMs:200,header:{label:"CLAUDE",showVersion:!0},sections:{quota:!0,fallbackAccounts:!0,routing:!0,cache:!0,health:!0,pacing:!0},appearance:{barWidth:10,barFilledChar:"█",barEmptyChar:"░",warnThreshold:50,errorThreshold:80}};function z(Q,q){return typeof Q==="boolean"?Q:q}function B(Q,q,J,Z){if(typeof Q!=="number"||!Number.isFinite(Q))return q;return Math.min(Math.max(Math.round(Q),J),Z)}function o(Q,q,J){if(typeof Q!=="string"||Q.length===0)return q;return Q.slice(0,J)}function x(Q,q){if(typeof Q!=="string")return q;return[...Q][0]??q}function $q(Q){let q=Q[s];if(!H(q))return structuredClone(k);let J=k,Z=H(q.header)?q.header:{},X=H(q.sections)?q.sections:{},$=H(q.appearance)?q.appearance:{},Y=B($.warnThreshold,J.appearance.warnThreshold,0,99),G=Math.max(B($.errorThreshold,J.appearance.errorThreshold,0,100),Math.min(Y+1,100));return{forceToTop:z(q.forceToTop,J.forceToTop),order:B(q.order,J.order,-1e4,1e4),startCollapsed:z(q.startCollapsed,J.startCollapsed),rememberCollapsed:z(q.rememberCollapsed,J.rememberCollapsed),collapsed:typeof q.collapsed==="boolean"?q.collapsed:null,pollMs:B(q.pollMs,J.pollMs,500,30000),refreshDebounceMs:B(q.refreshDebounceMs,J.refreshDebounceMs,50,5000),header:{label:o(Z.label,J.header.label,20),showVersion:z(Z.showVersion,J.header.showVersion)},sections:{quota:z(X.quota,J.sections.quota),fallbackAccounts:z(X.fallbackAccounts,J.sections.fallbackAccounts),routing:z(X.routing,J.sections.routing),cache:z(X.cache,J.sections.cache),health:z(X.health,J.sections.health),pacing:z(X.pacing,J.sections.pacing)},appearance:{barWidth:B($.barWidth,J.appearance.barWidth,4,40),barFilledChar:x($.barFilledChar,J.appearance.barFilledChar),barEmptyChar:x($.barEmptyChar,J.appearance.barEmptyChar),warnThreshold:Y,errorThreshold:G}}}var n=-1e5;function zq(Q,q,J){let Z=Q[q];if(!H(Z))return J;if(Z.forceToTop===!0)return n+Object.keys(Q).indexOf(q);return B(Z.order,J,-1e4,1e4)}var i=`// Shared preferences for opencode TUI plugins.
|
|
2
2
|
// One top-level key per plugin (short name). See each plugin's README for
|
|
3
3
|
// its supported settings. This file is safe to hand-edit; plugins update
|
|
4
4
|
// individual keys in place and preserve comments.
|
package/dist/v2/server.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{a as t2,b as
|
|
2
|
-
`)}:{event:
|
|
3
|
-
`)}}function H0($,Z){let V=new TextDecoder,Y="",M=(O)=>{let C=p1(O);if(!C)return;try{$(C)}catch(N){Z(N)}},_=()=>{for(;;){let O=/\r?\n\r?\n/.exec(Y);if(!O)return;let C=Y.slice(0,O.index);Y=Y.slice(O.index+O[0].length),M(C)}};return new TransformStream({transform(O,C){C.enqueue(O),Y+=V.decode(O,{stream:!0}),_()},flush(){if(Y+=V.decode(),_(),Y.trim()!=="")M(Y);Y=""}})}var A0=512,w0=1200000,v2="x-common-auth-attempt",w2=($,Z)=>JSON.stringify([$,Z]),E2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function c1($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function i1($,Z){let V=$.getReader();return new ReadableStream({async pull(Y){let M;try{M=await V.read()}catch(_){Z({reason:"failed",message:_ instanceof Error?_.message:String(_)}),Y.error(_);return}if(M.done)Z(),Y.close();else Y.enqueue(M.value)},async cancel(Y){Z({reason:"cancelled",...Y===void 0?{}:{message:String(Y)}}),await V.cancel(Y)}})}function r2($,Z){for(let[V,Y]of Object.entries(Z)){let M=V.toLowerCase();for(let _ of Object.keys($))if(_.toLowerCase()===M)delete $[_];if(Y!==null)$[V]=Y}}function o1($,Z){for(let[V,Y]of Object.entries(Z))if(Y===null)$.delete(V);else $.set(V,Y)}async function N0($,Z,V={}){let{providerID:Y}=Z,M=V.gateOnPlaceholder,_=(j)=>M===void 0||M.credential(j)===k2(Y),O=V.logger,C=Math.max(1,V.maxRecords??A0),N=[...V.hostCredentials??[k2(Y)],...M?[k2(Y)]:[]].filter((j)=>j!==""),X=new Map,B=new WeakMap,z=new Map,F=0,L=new Set,R=new Map,E=new Map,b=(j)=>{let Q=E.get(j);return Q?.ownedSeen===!0&&Q.foreignSeen},w=(j,Q)=>{R.set(j,Q);let P=E.get(j)??{ownedSeen:!1,foreignSeen:!1};if(Q)P.ownedSeen=!0;else P.foreignSeen=!0;E.set(j,P)},f=(j,Q)=>{let P=M?.refuseMisplaced,k=P?[...Q].filter(([,p])=>p.includes(k2(Y))):[],T=_(Q)&&(!P||k.length>0);if(P){if(k.length>0&&(k.length!==1||!T))throw w(j.sessionID,!1),new f2({kind:"placement-refused",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,message:P(k[0]?.[0]??"")})}return w(j.sessionID,T),T},v=!1,i=!1,a=new Map,Y2=0,j2=!1,e=new Map,u=(j,Q)=>{try{O?.warn(j,Q)}catch{}},J=(j)=>j instanceof Error?j.message:String(j),W=new Map,U=(j,Q)=>{let P=(W.get(j)??Promise.resolve()).then(Q),k=P.then(()=>{},()=>{});return W.set(j,k),k.then(()=>{if(W.get(j)===k)W.delete(j)}),P},q=(j,Q)=>{let P=W.get(j);return P?P.then(()=>q(j,Q)):Q()},A=async(j)=>{try{await Z.dropChoice?.({...j.input,accountId:j.accountId})}catch(Q){u("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:j.input.sessionID,error:J(Q)})}},y=async(j)=>{try{await Z.dropSameAccountRetry?.({...j.input,accountId:j.accountId})}catch(Q){u("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:j.input.sessionID,error:J(Q)})}},I=async(j)=>{if(j.next)await A(j.next);if(j.sameAccount)await y(j.sameAccount)},n=(j)=>{let Q=z.get(j);if(z.delete(j),Q)U(Q.sessionID,()=>I(Q))},d=async(j,Q)=>{let P=a.get(j);if(!P||P.size===0)return;await Promise.all([...P].map(async(k)=>{try{await k(Q)}catch(T){u("opencode2 auth listener threw; the request is unaffected",{event:j,error:J(T)})}}))},m=async(j,Q)=>{try{await Z.onAttemptEnd?.(j,Q)}catch(P){u("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:j.attemptId,error:J(P)})}},r=(j,Q)=>{if(j.ended||!j.attempt)return;let P={...j.status===void 0?{}:{status:j.status},outputStarted:j.outputStarted,...j.limit?{limit:j.limit.signal}:{},...Q?{error:Q}:{}};if(Q)j.endError=Q;j.ended=m(j.attempt,P)},l=(j,Q)=>r(j,{reason:"abandoned",message:Q}),M2=(j)=>[...X.values()].filter((Q)=>Q.key===j),L2=(j)=>M2(j).at(-1),x2=(j)=>{if(X.delete(j.id),z.get(j.key)?.attemptId===j.id||!M2(j.key).length)n(j.key)},y2=(j)=>{X.set(j.id,j);while(X.size>C){let Q=X.values().next().value;if(Q===void 0)break;l(Q,"dropped to keep the record bound"),x2(Q)}},s=(j)=>j.accountId===void 0?void 0:{...j.scope,accountId:j.accountId},G=(j,Q)=>new f2({kind:"no-account",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,...Q===void 0?{}:{message:Q}}),K=(j)=>{e.get(j)?.clear(),e.delete(j)},H=async(j,Q)=>{let P=()=>G(j,`${Y} ${j.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw P();let k=e.get(j.sessionID);if(!k)k=new Set,e.set(j.sessionID,k);let T={};k.add(T);let p=()=>{if(!k.has(T))throw P()};try{return await Q(p)}finally{if(k.delete(T),k.size===0&&e.get(j.sessionID)===k)e.delete(j.sessionID)}},x=(j,Q)=>{for(let[P,k]of Q)if(N.some((T)=>k.includes(T)))throw new f2({kind:"host-credential-on-wire",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,message:`${Y} ${j.kind} request still carries the host's placeholder credential in ${P}; the adapter's account headers must replace it`})},S=(j)=>{for(let Q of M2(j))if(Q.ended||!Q.attempt)x2(Q);else if(Q.transport==="ws"||Q.judged)l(Q,"a newer attempt of its session and kind began"),x2(Q)},g=async(j,Q,P,k)=>{let T=w2(j.sessionID,j.kind),{input:p,accountId:D,sameAccountRetry:c}=await q(j.sessionID,async()=>{P();let U2=z.get(T);z.delete(T);let H2=U2?.accountId??L2(T)?.accountId;S(T);let B2=U2?.next,_2=U2?.sameAccount,G2=_2!==void 0&&_2.input.modelID===j.modelID&&_2.input.agent===j.agent,T2=B2!==void 0&&B2.input.modelID===j.modelID&&B2.input.agent===j.agent,C2={...j,phase:"request",...H2===void 0?{}:{previousAccountId:H2},...U2?.rerouteFrom?{rerouteFrom:U2.rerouteFrom}:{}};if(B2&&!T2)await U(j.sessionID,()=>A(B2)),P();if(_2&&!G2)await U(j.sessionID,()=>y(_2)),P();let O2=G2?_2.accountId:T2?B2.accountId:await Z.chooseAccount(C2);return{input:C2,accountId:typeof O2==="string"?O2:void 0,sameAccountRetry:G2}});P();let X2={},P2;if(D!==void 0){let U2=await Z.accountHeaders({...j,accountId:D});if(P(),c1(U2))X2=U2.headers,P2=U2.attempt;else X2=U2}let o2=`attempt-${++Y2}`,A2={id:o2,key:T,scope:j,accountId:D,headers:X2,attempt:D===void 0?void 0:{...j,accountId:D,attemptId:o2,transport:k,data:P2},...k===void 0?{}:{transport:k},outputStarted:!1,sameAccountRetry:c};if(y2(A2),A2.attempt)d("select",{...j,accountId:A2.attempt.accountId,hook:Q,...p.previousAccountId===void 0?{}:{previousAccountId:p.previousAccountId},...p.rerouteFrom===void 0?{}:{rerouteFrom:p.rerouteFrom},handle:A2.attempt});return A2},h=async(j,Q,P,k,T)=>{let p=w2(j.sessionID,j.kind),D=k===void 0?void 0:X.get(k);if(D?.key!==p)D=void 0;if(!D){if(D=L2(p),M2(p).filter((X2)=>X2.transport===void 0&&!X2.ended).length>1&&!i)i=!0,u("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:j.sessionID,kind:j.kind})}if(!D||D.transport!==void 0||D.ended)D=await g(j,Q,T,P);else if(D.transport=P,D.attempt)D.attempt.transport=P;if(P==="ws"){for(let c of M2(p))if(c!==D&&c.transport==="ws")l(c,"a newer attempt of its session and kind went out over WebSocket")}return D},$2=async(j,Q)=>{try{return await Q()}catch(P){throw r(j,{reason:"failed",message:J(P)}),P}},o=(j,Q)=>{let P=M2(w2(j,Q)).filter((k)=>k.transport==="ws").at(-1);return P?.attempt!==void 0&&!P.ended?P:void 0},V2=(j,Q,P)=>{let k=s(j);if(!k||!j.attempt||j.limit)return;j.limit={signal:Q,delivered:d("limit",{...k,via:P,limit:Q,outputStarted:j.outputStarted,handle:j.attempt})}},z2=(j,Q,P,k)=>{let T=s(j);if(!T||!j.attempt)return;d("quota",{...T,transport:Q,...k===void 0?{}:{status:k},quota:P,handle:j.attempt})},K2=(j,Q,P,k)=>{let T=j.attempt;if(!T)return;let p=Z.inspectEvent?.(k===void 0?{transport:Q,data:P,attempt:T}:{transport:Q,data:P,event:k,attempt:T});if(!p)return;if(p.quota!==void 0)z2(j,Q,p.quota);if(p.outputStarted)j.outputStarted=!0;if(p.limit)V2(j,p.limit,Q);if(p.error!==void 0)r(j,{reason:"failed",message:p.error});else if(p.done)r(j)},q2=(j,Q)=>{let P=j.attempt;if(!P||Q.accountId===j.accountId)return;if(P.reboundFrom??=P.accountId,P.accountId=Q.accountId,"data"in Q)P.data=Q.data;j.accountId=Q.accountId},J2=(j)=>!j.attempt||j.endError!==void 0||j.status!==void 0&&j.status>=400,Z2=(j)=>{let Q=[...X.values()].filter((c)=>c.scope.sessionID===j),P=Q.filter((c)=>c.limit&&!c.rerouted).at(-1);if(P)return P;let k=Q.filter((c)=>c.scope.kind==="primary"),T=k.length>0?k:Q;if(T.length<=1)return T[0];let p=T.filter((c)=>!c.judged&&J2(c)).at(-1);if(p)return p;let D=T.filter((c)=>c.attempt&&!c.ended);if(D.length>1)return"ambiguous";return D[0]??T.at(-1)},Q2={providerID:Y},W2=[];W2.push(await $.session.hook("model.request",(j)=>{if(M)return;return H(E2(j),async(Q)=>{let P=await g(E2(j),"model.request",Q);if(Q(),P.accountId===void 0)throw G(P.scope);r2(j.headers,{...P.headers,[v2]:P.id})})},Q2)),W2.push(await $.session.hook("http.request",(j)=>{if(M){if(!f(E2(j),j.request.headers))return}return H(E2(j),async(Q)=>{let P=j.request.headers.get(v2)??void 0,k=M?await g(E2(j),"http.request",Q,"http"):await h(E2(j),"http.request","http",P,Q);Q();let T=s(k),p=k.attempt;if(!T||!p)throw G(k.scope);await $2(k,async()=>{let D=j.request;if(Z.rewriteRequest){if(P!==void 0){let P2=new Headers(D.headers);P2.delete(v2),D=new Request(D,{headers:P2})}D=await Z.rewriteRequest({...T,request:D,attempt:p})??D,Q()}let c=new Headers(D.headers);c.delete(v2),o1(c,k.headers),x(k.scope,c.entries());let X2=new Request(D,{headers:c});B.set(X2,k),j.request=X2})})},Q2)),W2.push(await $.session.hook("http.response",async(j)=>{let Q=B.get(j.request);if(!Q){if(M)return;if(!v)v=!0,u("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:j.sessionID,kind:j.kind});return}let P=j.response;if(Z.answeredBy&&Q.attempt){let c=Q.attempt,X2=await $2(Q,async()=>Z.answeredBy?.({request:j.request,response:P,attempt:c}));if(X2)q2(Q,X2)}let k=s(Q),T=Q.attempt;if(!k||!T)return;Q.status=P.status;let p=Z.quotaFromHeaders?.(P.headers,P.status,T);if(p!==void 0)z2(Q,"http",p,P.status);if(!P.ok&&Z.limitFromResponse){let c=await Z.limitFromResponse({status:P.status,headers:P.headers,body:()=>P.clone().text(),attempt:T});if(c)V2(Q,c,"http")}if(!P.ok||!P.body)r(Q);let D=P;if(P.body&&(Z.inspectEvent||Z.onAttemptEnd)){let c=P.body;if(Z.inspectEvent)c=c.pipeThrough(H0((X2)=>K2(Q,"http",X2.data,X2.event),(X2)=>u("opencode2 auth event inspection threw",{error:J(X2)})));D=new Response(i1(c,(X2)=>r(Q,X2)),{status:P.status,statusText:P.statusText,headers:P.headers})}if(Z.rewriteResponse)D=await Z.rewriteResponse({...k,request:j.request,response:D,attempt:T})??D;if(D!==P)j.response=D},Q2)),W2.push(await $.session.hook("experimental.ws.handshake",(j)=>{if(M){let Q=w2(j.sessionID,j.kind);if(L.delete(Q),!f(E2(j),new Headers(j.headers)))return}return H(E2(j),async(Q)=>{let P;for(let D of Object.keys(j.headers)){if(D.toLowerCase()!==v2)continue;P??=j.headers[D],delete j.headers[D]}let k=M?await g(E2(j),"experimental.ws.handshake",Q,"ws"):await h(E2(j),"experimental.ws.handshake","ws",P,Q);Q();let T=s(k),p=k.attempt;if(!T||!p)throw G(k.scope);await $2(k,async()=>{if(!M?.refuseMisplaced)r2(j.headers,k.headers);let D=Z.rewriteHandshakeURL?.({...T,url:j.url,attempt:p});if(D!==void 0)j.url=D;if(M?.refuseMisplaced)r2(j.headers,k.headers);if(x(k.scope,Object.entries(j.headers)),M)L.add(k.key)})})},Q2));let t=Z.rewriteWebSocketFrame?.bind(Z);if(t)W2.push(await $.session.hook("experimental.ws.send",async(j)=>{let Q=E2(j);if(M&&!L.has(w2(Q.sessionID,Q.kind)))return;let P=o(Q.sessionID,Q.kind),k=await t({...Q,attempt:P?.attempt,frame:j.frame});if(k!==void 0)j.frame=k},Q2));W2.push(await $.session.hook("experimental.ws.receive",(j)=>{if(M&&!L.has(w2(j.sessionID,j.kind)))return;let Q=o(j.sessionID,j.kind);if(!Q)return;try{K2(Q,"ws",j.frame)}catch(P){u("opencode2 auth frame inspection threw",{error:J(P)})}},Q2)),W2.push(await $.session.hook("retry",async(j)=>{if(M&&R.get(j.sessionID)!==!0)return;let Q=j.decision,P=()=>d("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:Q,decision:Q});if(b(j.sessionID)&&!Z.retrySameAccount){await P();return}let k=Z2(j.sessionID);if(!k)return;if(k==="ambiguous"){await d("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:Q,decision:Q});return}let T=k;await H(T.scope,async(p)=>{let D=p,c=Z.retrySameAccount?.bind(Z),X2=T.attempt;if(c&&X2&&!T.outputStarted&&!T.sameAccountRetry){if(T.ended)await T.ended;if(T.limit)await T.limit.delivered;let U2=await U(T.scope.sessionID,async()=>{D();let H2=X2.accountId,B2=()=>X.has(T.id)&&T.accountId===H2&&Z2(j.sessionID)===T&&!T.outputStarted&&(!M||R.get(j.sessionID)===!0);if(!B2()||T.sameAccountRetry)return!1;T.sameAccountRetry=!0;let _2={...T.scope,accountId:H2,error:j.error,attempt:j.attempt,...T.limit?{limit:T.limit.signal}:{}},G2;try{G2=await c(_2)}catch(O2){u("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:j.sessionID,error:J(O2)})}if(!G2)return D(),!1;let T2={accountId:G2.accountId,input:_2};try{D()}catch(O2){throw await y(T2),O2}if(!B2()||G2.accountId!==H2)return await y(T2),!1;let C2=z.get(T.key);if(z.delete(T.key),C2)await I(C2);try{D()}catch(O2){throw await y(T2),O2}if(!B2())return await y(T2),!1;return z.set(T.key,{attemptId:T.id,sessionID:T.scope.sessionID,order:++F,accountId:H2,sameAccount:T2}),T.judged=!0,j.decision={retry:!0,delay:0},!0});if(D(),U2){await d("retry",{sessionID:j.sessionID,accountId:T.accountId,kind:T.scope.kind,attempt:j.attempt,reason:"same-account",hostDecision:Q,decision:j.decision,handle:T.attempt});return}}if(b(j.sessionID)){await P();return}T.judged=!0;let P2=T.attempt;if(P2&&!T.outputStarted){if(!T.limit){let U2=Z.limitFromError?.(j.error,P2);if(U2)V2(T,U2,"error")}if(T.ended)await T.ended;if(T.limit)await T.limit.delivered}D();let{decision:o2,reason:A2}=await U(T.scope.sessionID,async()=>{if(D(),b(j.sessionID))return{decision:Q,reason:"host-decides"};let U2=z.get(T.key);if(z.delete(T.key),U2)await I(U2);if(D(),b(j.sessionID))return{decision:Q,reason:"host-decides"};let H2=Q,B2,_2,G2;if(T.accountId===void 0||!P2)H2={retry:!1},B2="no-account";else if(T.outputStarted)H2={retry:!1},B2="output-started";else if(T.limit){let T2={accountId:T.accountId,limit:T.limit.signal},C2,O2={...T.scope,phase:"retry",previousAccountId:T.accountId,rerouteFrom:T2};try{C2=await Z.chooseAccount(O2)}catch(z0){u("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:T.scope.sessionID,error:J(z0)})}let S2=typeof C2==="object"?C2.hold:void 0,n2=typeof C2==="string"?C2:S2?T.accountId:void 0;if(n2!==void 0)G2={accountId:n2,input:O2};try{D()}catch(z0){if(G2)await A(G2);throw z0}if(b(j.sessionID)){if(G2)await A(G2);return{decision:Q,reason:"host-decides"}}if(S2&&Number.isFinite(S2.delayMs)&&S2.delayMs>=0)H2={retry:!0,delay:Math.min(S2.delayMs,w0)},B2="hold";else if(!S2&&n2!==void 0&&n2!==T.accountId)T.rerouted=!0,_2=T2,H2={retry:!0,delay:0},B2="reroute";else{if(S2&&G2)await A(G2),G2=void 0;B2="host-decides-last-account"}}else B2="host-decides";if(j.decision=H2,H2.retry&&T.accountId!==void 0&&X.has(T.id))z.set(T.key,{attemptId:T.id,sessionID:T.scope.sessionID,order:++F,accountId:T.accountId,..._2===void 0?{}:{rerouteFrom:_2},...G2===void 0?{}:{next:G2}});else if(G2)await A(G2);return{decision:H2,reason:B2}});D(),await d("retry",{sessionID:j.sessionID,...T.accountId===void 0?{}:{accountId:T.accountId},kind:T.scope.kind,attempt:j.attempt,reason:A2,hostDecision:Q,decision:o2,...P2===void 0?{}:{handle:P2}})})},Q2));let F2=(j)=>{if(K(j),R.delete(j),!E.get(j)?.foreignSeen)E.delete(j);for(let Q of L)if(JSON.parse(Q)[0]===j)L.delete(Q);for(let Q of[...X.values()]){if(Q.scope.sessionID!==j)continue;l(Q,"its session was forgotten"),X.delete(Q.id)}for(let[Q,P]of z)if(P.sessionID===j)n(Q)},N2=new AbortController,i2=$.event;if(i2)(async()=>{try{for await(let j of i2.subscribe({signal:N2.signal}))if(j.type==="session.deleted")F2(j.data.sessionID);else if(j.type==="session.status"&&j.data.status.type==="idle"){let Q=j.data.sessionID,P=++F;U(Q,async()=>{for(let[k,T]of z)if(T.sessionID===Q&&T.order<P)z.delete(k),await I(T)})}}catch(j){if(!N2.signal.aborted)u("opencode2 auth stopped listening for session deletion",{error:J(j)})}})();return{on(j,Q){let P=a.get(j);if(!P)P=new Set,a.set(j,P);let k=Q;return P.add(k),()=>{P.delete(k)}},accountFor(j,Q){return L2(w2(j,Q))?.accountId},forgetSession:F2,get size(){return X.size},async dispose(){if(j2)return;j2=!0;for(let j of e.keys())K(j);N2.abort();for(let j of X.values())l(j,"the installation was disposed");X.clear();for(let j of z.keys())n(j);L.clear(),R.clear(),E.clear(),a.clear(),await Promise.all(W.values()),await Promise.all(W2.map(async(j)=>{try{await j.dispose()}catch(Q){u("opencode2 auth hook did not dispose cleanly",{error:J(Q)})}}))}}}import{createHash as n1}from"node:crypto";import{AnthropicOAuthOriginError as r1,applyCustomHeaders as s1,assertNotCustodyTombstone as a1,classifyGzipRejection as t1,createProviderErrorRedactor as D0,createProviderErrorResponseScope as I0,decideRequestGzip as e1,dumpDirectRequest as y0,dumpRelayRequest as f0,dumpResponseArtifact as s2,encodeGzipRequestBody as $4,getAccountStoragePath as Z4,getRequestGzipLatch as j4,getRequestGzipLatchPath as J4,isDumpEnabled as X4,mergeAnthropicBetas as G4,remapModelId as v0,remapRequestBodyModel as Y4,setDumpEnabled as g0,stateRefusalCause as V4,stateRefusalPublicMessage as Q4,stripEmptyTrailingAssistantMessages as W4,TrailingAssistantHistoryError as U4}from"@cortexkit/anthropic-auth-core";var g2="anthropic",r0="x-common-auth-attempt",B4=["x-session-affinity","x-opencode-session","x-parent-session-id",m0,t2,I2,r0],a2=new Set(["authorization","x-api-key"]),z4="physical send before a response",M4="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",K4=512,H4=5000,N4=500,s0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),_0=($,Z="provider request failed")=>({type:s0.has($.type)?$.type:"provider_error",message:Z,...$.status!==void 0?{status:$.status}:{}});class a0 extends Error{sessionID;requestKind;kind="no-account";providerID=g2;constructor($,Z){super(M4);this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicNoAccountError"}}class P0 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=g2;constructor($,Z){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicRevokedError"}}class R2 extends Error{kind="unsupported-transport";providerID=g2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class t0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class e0 extends Error{kind="state-relocated";providerID=g2;constructor($){super(Q4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function e2($){let Z=V4($);return Z?new e0(Z):void 0}var D2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function d2($){try{return JSON.parse($)}catch{return}}function L0($){let Z={};for(let[V,Y]of Object.entries($??{}))Z[V.toLowerCase()]=Y;return Z}function h0($){let Z={};for(let V of B4){let Y=$.get(V);if(Y!==null&&V!==r0)Z[V]=Y;$.delete(V)}return Z}function _4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function L4($){return $ instanceof U4||$ instanceof l0||$ instanceof r1?new t0($):void 0}function F4($,Z){let V=[];if($.oauth)V.push($.oauth.accessToken);for(let[Y,M]of Object.entries($.apiHeaders??{})){if(M===null||!a2.has(Y))continue;V.push(M.replace(/^Bearer\s+/i,""))}for(let Y of a2){let M=Z.get(Y);if(M!==null)V.push(M.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")V.push($.dispatch.token);return[...new Set(V.filter(Boolean))]}var P4=new Set(["oauth-2025-04-20","claude-code-20250219",p0]);function T4($){let Z=$.split(",").map((V)=>V.trim()).filter((V)=>V&&!P4.has(V));return G4(null,Z)}function C4($){let Z=d2($);if(!D2(Z))return $;let V=W4(Z.messages),Y=Object.hasOwn(Z,"fallbacks"),{droppedMarkers:M}=c0(Z,!1),_=Y&&!Object.hasOwn(Z,"fallbacks"),O=Y4(Z);return V>0||M>0||_||O?JSON.stringify(Z):$}async function O4($,Z){if(!($ instanceof Promise))return"settled";let V;try{return await Promise.race([$.then(()=>"settled"),new Promise((Y)=>{V=setTimeout(()=>Y("timed-out"),Z)})])}finally{if(V!==void 0)clearTimeout(V)}}function h2($){let{source:Z,log:V}=$,Y=Math.max(1,$.maxPendingSends??K4),M=$.attemptEndTimeoutMs??H4,_=$.requestGzipLatch??j4(J4(Z4())),O=new WeakSet,C=new Map,N=new WeakMap,X=new WeakMap,B=(G)=>JSON.stringify([G.providerID,G.sessionID,G.kind,G.modelID,G.agent,G.accountId]),z=new Map,F=new WeakMap,L=new Map,R=new WeakMap,E=D0([]);E.dispose();let b=(G)=>(G&&L.get(G)?.redactor)??E,w=(G)=>{let K=L.get(G);if(!K)return;L.delete(G),K.redactor.dispose(),K.scope.dispose()},f=(G,K,H,x)=>{let S=F4(K,x),g=I0(S,H);v.set(G,H),L.set(G,{sessionID:K.sessionID,redactor:D0(S),scope:g}),g.settled.then(()=>w(G));while(L.size>Y){let h=L.keys().next().value;if(h===void 0)break;w(h)}},v=new WeakMap,i=(G,K)=>{let H=G?v.get(G):void 0;if(!H||!K.ok)return E.redactResponse(K);let x=I0([],H),S=x.redactResponse(K);return x.dispose(),S},a=(G,K)=>{let H=G?L.get(G)?.scope:void 0;if(!H)return i(G,K);try{return H.redactResponse(K)}catch{return i(G,K)}},Y2=!1,j2=new Map,e=new WeakMap,u=new WeakMap,J=new WeakMap,W=(G)=>G.agent==="cachekeep"||G.agent==="prime",U=async()=>{try{if(Z.isDumpEnabled)return await Z.isDumpEnabled()}catch{return!1}try{return X4()}catch{return!1}},q=(G)=>{j2.delete(G)},A=new WeakMap,y=(G,K)=>{if(G&&!K.ok)A.set(K.headers,G);return K},I=(G,K)=>{if(K.dispatch!=="http-relay")return!0;let H=/^req_[A-Za-z0-9_-]+$/.test(G.get("request-id")??"");return X.set(K,H),H},n=(G)=>new a0(G.sessionID,G.kind),d=new Map,m=async(G,K)=>{if(Y2)throw new P0(G.sessionID,G.kind);let H={revoked:!1},x=d.get(G.sessionID);if(!x)x=new Set,d.set(G.sessionID,x);x.add(H);let S=()=>{if(Y2||H.revoked)throw new P0(G.sessionID,G.kind)};try{let g=await K(S);return S(),g}finally{let g=d.get(G.sessionID);if(g?.delete(H)&&g.size===0)d.delete(G.sessionID)}},r=(G,K)=>{C.set(G,K);while(C.size>Y){let H=C.keys().next().value;if(H===void 0)break;C.delete(H),V?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:Y})}},l=(G,K)=>({providerID:G.providerID,modelID:G.modelID,sessionID:G.sessionID,agent:G.agent,kind:G.kind,accountId:G.accountId,attemptId:G.attemptId,transport:G.transport,route:K.route,provenance:K.provenance,dispatch:K.dispatch}),M2=(G)=>m(G,async(K)=>{let{accountId:H,...x}=G,S;try{S=await Z.authorizeAccount(x,H)}catch(g){let h=e2(g);if(h)throw V?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:h.cause instanceof Error?h.cause.name:""}),h;throw g}return K(),L2(x,S)}),L2=(G,K)=>{if(!K)throw n(G);if(K.dispatch?.kind==="websocket-relay")throw new R2;let H=K.dispatch?.kind==="http-relay"?"http-relay":"direct",x=K.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":K.dispatch.token}:void 0;if(K.route==="oauth"){if(!K.accessToken)throw n(G);a1(K.accessToken,g2);let h=Object.freeze({route:"oauth",provenance:K.provenance,dispatch:H});r(h,{sessionID:G.sessionID,oauth:{accessToken:K.accessToken,...K.identity?{identity:K.identity}:{}},dispatch:K.dispatch,oauthHeaders:K.headers});let $2=L0(K.headers);for(let o of a2)delete $2[o];return delete $2["anthropic-beta"],{headers:x??{...$2,"x-api-key":null,authorization:`Bearer ${K.accessToken}`},attempt:h}}let S={authorization:null,"x-api-key":null,...L0(K.headers)};if(!S.authorization&&!S["x-api-key"])throw n(G);let g=Object.freeze({route:"api",provenance:K.provenance,dispatch:H});return r(g,{sessionID:G.sessionID,...K.baseURL?{baseURL:K.baseURL}:{},dispatch:K.dispatch,apiHeaders:S}),{headers:x??S,attempt:g}},x2=(G)=>m(G,(K)=>y2(G,K)),y2=async(G,K)=>{let{request:H,attempt:x}=G,S=x.data;z.set(B(G),x);while(z.size>Y){let J2=z.keys().next();if(!J2.done)z.delete(J2.value)}let g=S?C.get(S):void 0;if(S)C.delete(S);if(!S||!g||S.route==="oauth"&&!g.oauth)throw n(G);let h=new Headers(H.headers);s1(h);let $2=h0(h),o=H.body===null?void 0:await H.text();K();let V2=o!==void 0&&_4(H.url),z2=o0(H.url,g.baseURL!==void 0?{baseURL:g.baseURL}:{}).url?.toString()??H.url;try{if(S.route==="oauth"&&g.oauth){d0(z2);let{accessToken:J2,identity:Z2}=g.oauth;for(let[W2,t]of Object.entries(L0(g.oauthHeaders))){if(a2.has(W2))continue;if(t===null)h.delete(W2);else h.set(W2,t)}let Q2=null;if(o!==void 0&&V2){let W2={...l(x,S),modelID:(()=>{let N2=d2(o);return v0(D2(N2)&&typeof N2.model==="string"?N2.model:G.modelID)})(),route:"oauth",correlation:$2},t=await Z.requestOptions?.(W2)??{};if(K(),x.agent!=="cachekeep")o=await n0(o,{...t,...Z2?{identity:Z2}:{},sessionId:G.sessionID,onToolNameMap:(N2)=>F.set(S,N2)});let F2=d2(o);Q2=D2(F2)?F2:null}i0(h,J2,{body:Q2,...Z2?{identity:Z2}:{},requestClass:u0(x.agent)?"auxiliary":"main"})}else{if(o!==void 0&&V2)o=C4(o);h.delete("authorization"),h.delete("x-api-key");for(let[Z2,Q2]of Object.entries(g.apiHeaders??{}))if(Q2===null)h.delete(Z2);else h.set(Z2,Q2);if(o!==void 0&&V2&&!h.has("content-type"))h.set("content-type","application/json");let J2=h.get("anthropic-beta");if(J2!==null){let Z2=T4(J2);if(Z2)h.set("anthropic-beta",Z2);else h.delete("anthropic-beta")}}}catch(J2){let Z2=L4(J2);if(!Z2)throw J2;throw N.set(S,Z2.check),V?.warn("refused an Anthropic request locally; nothing was sent",{check:Z2.check}),Z2}let K2=o!==void 0?d2(o):void 0;if(await Z.admitRequest?.({...l(x,S),modelID:v0(D2(K2)&&typeof K2.model==="string"?K2.model:G.modelID)}),h0(h),o!==void 0)h.delete("content-length");if(K(),f(S,g,D2(K2)&&K2.stream===!0?"event-stream":"http",h),S.route==="oauth"&&V2&&o!==void 0)await Z.onRequestPrepared?.({...l(x,S),url:z2,bodyText:o}),K();if(g.dispatch?.kind==="http-relay"){let J2=o??"";h.delete("x-relay-token");let Z2={protocol:1,type:"request",affinity:G.sessionID,upstream:{url:z2,method:H.method,headers:Object.fromEntries(h)},mode:"full_sync",revision:1,body:J2,next_hash:`sha256:${n1("sha256").update(J2).digest("hex")}`};if(V2&&o!==void 0&&!W(x)){let Q2=$2[I2]==="1"?"start":void 0,W2=JSON.stringify(Z2);j2.set(S,{affinity:G.sessionID,route:G.accountId,bodyText:J2,url:z2,method:H.method,headers:new Headers(h),dispatch:"http-relay",relayUrl:g.dispatch.url,envelope:Z2,relayBytes:W2.length,...Q2?{tag:Q2}:{}})}else q(S);return new Request(g.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":g.dispatch.token},redirect:"error",signal:H.signal,body:JSON.stringify(Z2)})}let q2=o;if(S.route==="oauth"&&V2&&o!==void 0){let J2=await e1({url:z2,body:o,latch:_});if(K(),J2.gzip)q2=await $4(o),h.set("content-encoding","gzip"),O.add(S),K()}if(V2&&o!==void 0&&!W(x)){let J2=$2[I2]==="1"?"start":void 0;j2.set(S,{affinity:G.sessionID,route:G.accountId,bodyText:o,url:z2,method:H.method,headers:new Headers(h),dispatch:"direct",...J2?{tag:J2}:{}})}else q(S);return new Request(z2,{method:H.method,headers:h,redirect:S.route==="oauth"?"error":H.redirect,signal:H.signal,...q2!==void 0?{body:q2}:{}})},s={providerID:g2,chooseAccount:(G)=>m(G,async()=>{let K=await Z.chooseAccount(G);if(typeof K==="object"&&G.phase==="retry")return K;if(typeof K!=="string"||!K)throw n(G);return K}),dropChoice:(G)=>Z.dropChoice?.(G),async retrySameAccount(G){if(!Z.retrySameAccount)return;let K=B(G),H=z.get(K);z.delete(K);let x=G.limit??(H?s.limitFromError?.(G.error,H):void 0);return Z.retrySameAccount({...G,error:_0(G.error),...x?{limit:x}:{}})},dropSameAccountRetry:(G)=>Z.dropSameAccountRetry?.({...G,error:_0(G.error)}),accountHeaders:M2,rewriteRequest:x2,rewriteHandshakeURL(){throw new R2},async rewriteResponse({response:G,attempt:K}){let H=K.data;if(H&&!I(G.headers,H)){if(H)q(H);if(G.status===401)return w(H),G.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return a(H,G)}if(H&&O.has(H))O.delete(H),t1(G).then((t)=>{if(!t)return;_.latchProcess(),V?.warn("gzipped request body rejected; later requests go uncompressed",{kind:t,status:G.status})},()=>{});let x=null,S=H?j2.get(H):void 0;if(H&&S){let t=!1;try{t=await U()}catch{t=!1}if(!t)q(H);else{try{g0(!0)}catch{}try{if(S.dispatch==="http-relay")x=await f0({affinity:S.affinity,transport:"http",protocol:1,mode:"full_sync",status:G.status,bodyText:S.bodyText,payload:S.envelope??{},relayBytes:S.relayBytes??0,...S.tag?{tag:S.tag}:{}});else x=await y0({affinity:S.affinity,route:S.route,status:G.status,bodyText:S.bodyText,url:S.url,method:S.method,headers:S.headers,...S.tag?{tag:S.tag}:{}})}catch{x=null}if(q(H),x){e.set(H,x);try{await s2(x,{status:G.status,message:null,complete:!1})}catch{}J.set(H,Promise.resolve())}}}let g=a(H,G);if(H?.route!=="oauth"||!g.body)return y(H,g);let h={...l(K,H),status:G.status},$2=Z.responseOptions?.(h)??{},o=(G.headers.get("content-type")??"").includes("application/json"),V2={...$2,toolNameMap:H?F.get(H):void 0,onToolNameRefusal:()=>{if(!H)return;N.set(H,"response_tool_names"),w(H)},laneStartOAuthServed:!0,...o?{responseMode:"json"}:{}};if(!H||!x)return y(H,F0(g,V2));let z2=x,K2=G.status,q2=(t)=>{let N2=(J.get(H)??Promise.resolve()).then(()=>t().then(()=>{return})).catch(()=>{return});J.set(H,N2)},J2=$2.onMessageStart,Z2=$2.onMessageDelta,Q2=$2.onMessageResponse,W2=$2.onStreamEnd;return y(H,F0(g,{...V2,onMessageStart:(t)=>{try{J2?.(t)}catch{}try{u.set(H,{...t}),q2(()=>s2(z2,{status:K2,message:t,complete:!1}))}catch{}},onMessageDelta:(t)=>{try{Z2?.(t)}catch{}try{let F2=u.get(H)??{},N2=F2.usage&&typeof F2.usage==="object"&&!Array.isArray(F2.usage)?F2.usage:{},i2={...F2,...t.usage?{usage:{...N2,...t.usage}}:{},...t.stopReason?{stop_reason:t.stopReason}:{}};q2(()=>s2(z2,{status:K2,message:i2,complete:!0}))}catch{}},onMessageResponse:(t)=>{try{Q2?.(t)}catch{}try{q2(()=>s2(z2,{status:K2,message:t,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await W2?.()}catch{}try{await(J.get(H)??Promise.resolve())}catch{}}}))},quotaFromHeaders(G,K,H){let x=H.data;if(!x||!I(G,x))return;return Z.quotaFromHeaders?.(G,{...l(H,x),status:K})},async limitFromResponse({status:G,headers:K,body:H,attempt:x}){let S=x.data;if(!S||N.get(S)==="response_tool_names")return;if(!I(K,S))return Z.limitFromRelayFailure?.({...l(x,S),status:G});if(R.set(S,`provider responded with HTTP ${G}`),!Z.limitFromResponse)return;let g=A.get(K)===S,h=b(S);return Z.limitFromResponse({...l(x,S),status:G,headers:K,body:async()=>g?await H():h.redactText(await H())})},inspectEvent({data:G,event:K,attempt:H}){if(H.data&&N.get(H.data)==="response_tool_names")return;let x=d2(G);if(!D2(x))return;let S=typeof x.type==="string"?x.type:K;if(S==="content_block_start"||S==="content_block_delta")return{outputStarted:!0};if(S==="message_stop")return{done:!0};if(S!=="error")return;let g=H.data,h=b(g),$2=D2(x.error)?x.error:{},o=typeof $2.type!=="string"?void 0:s0.has($2.type)?$2.type:h.redactText($2.type),V2=typeof $2.message==="string"?h.redactText($2.message):void 0;if(g?.dispatch==="http-relay"&&X.get(g)===!1)return;let z2=g?Z.limitFromStreamError?.({...l(H,g),errorType:o,message:V2}):void 0,K2={error:[o??"error",V2].filter(Boolean).join(": ").slice(0,N4),...z2?{limit:z2}:{}};if(g&&K2.error)R.set(g,K2.error);return K2},limitFromError(G,K){let H=K.data;if(!H||N.has(H))return;let x=_0(G,R.get(H));if(w(H),H.dispatch==="http-relay"&&X.get(H)===!1)return;return Z.limitFromHostError?.(x,l(K,H))},async onAttemptEnd(G,K){let H=G.data;if(!H)return;C.delete(H);let x=j2.get(H);if(x){q(H);try{if(await U()){try{g0(!0)}catch{}try{if(x.dispatch==="http-relay"){if(K.status!==void 0)await f0({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:K.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}})}else await y0({affinity:x.affinity,route:x.route,status:K.status,error:K.status===void 0?z4:void 0,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{}}}catch{}}let S=K.error?.reason;if(S==="cancelled"||S==="abandoned"||S===void 0&&(K.status===void 0||K.status<400))w(H);let g=N.get(H),{status:h,...$2}=K,o=Z.onAttemptEnd?.(l(G,H),{...$2,...h!==void 0&&(H.dispatch!=="http-relay"||X.get(H)===!0)?{status:h}:{},...g!==void 0?{localRefusal:{check:g}}:{}});if(await O4(o,M)==="timed-out")V?.warn("the account source did not finish recording a send",{timeoutMs:M})}};return{adapter:s,dispose(){Y2=!0;for(let[G,K]of d){for(let H of K)H.revoked=!0;Z.forgetSession?.(G)}d.clear(),C.clear(),z.clear(),j2.clear();for(let G of[...L.keys()])w(G)},forgetSession(G){for(let K of d.get(G)??[])K.revoked=!0;d.delete(G);for(let[K,H]of z)if(H.sessionID===G)z.delete(K);for(let[K,H]of C)if(H.sessionID===G)C.delete(K);for(let[K,H]of[...L])if(H.sessionID===G)w(K);for(let[K,H]of[...j2])if(H.affinity===G)j2.delete(K);Z.forgetSession?.(G)},get pendingSendCount(){return C.size},get heldCredentialCount(){let G=0;for(let K of C.values())if(K.oauth)G++;return G},get heldRedactorCount(){return L.size},get operationsInProgress(){let G=0;for(let K of d.values())G+=K.size;return G}}}import{setTimeout as u4}from"node:timers/promises";import{CacheKeepManager as p4,CacheKeepSessionRegistry as c4,getDefaultCacheKeepRegistryDirectory as i4,isCacheKeepActiveNow as W1,isCacheKeepHybridActive as p2,isCacheKeepSubagentsEnabled as j0,logger as J0,NativeAccountRefusal as b2,nativeAccountCanServe as B1,nativeAccountRefusal as o4}from"@cortexkit/anthropic-auth-core";import{createHash as q4,randomUUID as x4}from"node:crypto";import{constants as $1}from"node:fs";import{lstat as Z1,mkdir as S4,open as k4,readdir as j1,rm as $0,writeFile as R4}from"node:fs/promises";import{tmpdir as b4}from"node:os";import{join as u2}from"node:path";import{promisify as Y1}from"node:util";import{gunzip as A4,gzip as w4}from"node:zlib";import{CACHE_KEEP_MAX_BODY_BYTES as V1,createWindowsOwnerOnly as D4,ensureWindowsOwnerOnlyDirectory as I4,isOwnerOnly as J1,logger as y4,readWindowsOwnerOnly as f4,renameWithWindowsSharingRetry as v4}from"@cortexkit/anthropic-auth-core";var T0="2.4.5";var g4=Y1(w4),h4=Y1(A4),Z0=($)=>q4("sha256").update($).digest("hex"),X1=/^[a-f0-9]{64}\.json\.gz$/,C0=/^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/,G1=2*V1+65536;function m4($,Z=b4()){return u2(Z,`cortexkit-anthropic-auth-cachekeep-${Z0($).slice(0,16)}`)}function l4($){return{v:1,pluginVersion:T0,id:$.id,bodyText:$.bodyText,url:$.url,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt,oauthAccountIdentity:$.oauthAccountIdentity,isSubagent:$.isSubagent}}function Q1($){let Z=JSON.parse($);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid restart body");let V=!1;for(let Y of Object.keys(Z))if(/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(Y))delete Z[Y],V=!0;return V?JSON.stringify(Z):$}function d4($,Z,V){if(!$||typeof $!=="object"||Array.isArray($))return!1;if($.v!==1||$.pluginVersion!==T0||typeof $.id!=="string"||!$.id||`${Z0($.id)}.json.gz`!==Z||typeof $.bodyText!=="string"||Buffer.byteLength($.bodyText)>V1||typeof $.url!=="string"||typeof $.oauthAccountIdentity!=="string"||!$.oauthAccountIdentity||typeof $.isSubagent!=="boolean"||!Number.isFinite($.cacheExpiresAt)||$.cacheExpiresAt<=V||!Number.isFinite($.nextPrewarmAt))return!1;return Q1($.bodyText)===$.bodyText}class O0{options;directory;disabled=!1;chain=Promise.resolve();pending=new Map;timers=new Map;lastWrite=new Map;latest=new Map;constructor($){this.options=$;this.directory=m4($.storageId,$.root)}refuse(){if(this.disabled)return;this.disabled=!0;for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),y4.warn("cachekeep","restart storage unavailable; retaining sessions in memory only")}async directoryReady(){if(this.disabled)return!1;try{if(!await I4(this.directory,this.options.ownerOnly))try{await S4(this.directory,{mode:448})}catch(Z){if(Z.code!=="EEXIST")throw Z}let $=await Z1(this.directory);if(!$.isDirectory()||$.isSymbolicLink()||!await J1(this.directory,()=>$.uid===process.getuid?.()&&($.mode&511)===448,this.options.ownerOnly))throw Error("Unsafe restart directory");return!0}catch{return this.refuse(),!1}}enqueue($){this.chain=this.chain.then(async()=>{if(await this.directoryReady())await $()}).catch(()=>this.refuse())}async load($,Z){if(!await this.directoryReady())return;try{for(let V of(await j1(this.directory)).sort()){if(!X1.test(V)&&!C0.test(V))continue;let Y=u2(this.directory,V);try{if(C0.test(V))throw Error("Unfinished write");let M=await Z1(Y);if(!M.isFile()||M.isSymbolicLink()||M.size>G1||!await J1(Y,()=>M.uid===process.getuid?.()&&(M.mode&511)===384,this.options.ownerOnly))throw Error("Unsafe restart file");let _=await f4(Y,this.options.ownerOnly);if(!_){let N=await k4(Y,$1.O_RDONLY|$1.O_NOFOLLOW);try{_=await N.readFile()}finally{await N.close()}}let O=await h4(_,{maxOutputLength:G1}),C=JSON.parse(O.toString("utf8"));if(!d4(C,V,$)||!Z(C))throw Error("Stale restart file")}catch{await $0(Y,{force:!0})}}}catch{this.refuse()}}changed($){if(this.disabled)return;let Z=l4($),V=this.latest.get(Z.id);if(V&&V.bodyText===Z.bodyText&&V.url===Z.url&&V.oauthAccountIdentity===Z.oauthAccountIdentity&&V.cacheExpiresAt===Z.cacheExpiresAt&&V.nextPrewarmAt===Z.nextPrewarmAt&&V.isSubagent===Z.isSubagent)return;if(this.latest.set(Z.id,Z),this.pending.set(Z.id,Z),this.timers.has(Z.id))return;let Y=Math.max(250,(this.lastWrite.get(Z.id)??0)+5000-(this.options.now?.()??Date.now())),M=(this.options.setTimeoutImpl??setTimeout)(()=>this.flush(Z.id),Y);M.unref?.(),this.timers.set(Z.id,M)}flush($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($);let V=this.pending.get($);if(this.pending.delete($),!V)return this.chain;return this.lastWrite.set($,this.options.now?.()??Date.now()),this.enqueue(async()=>{let Y=u2(this.directory,`${Z0($)}.json.gz`),M=`${Y}.${x4()}.tmp`;try{let _={...V,bodyText:Q1(V.bodyText)},O=await g4(JSON.stringify(_));if(!await D4(M,O,this.options.ownerOnly))await R4(M,O,{flag:"wx",mode:384});await v4(M,Y,{platform:this.options.ownerOnly?.platform})}finally{await $0(M,{force:!0})}}),this.chain}removed($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($),this.pending.delete($),this.latest.delete($),this.lastWrite.delete($),this.enqueue(()=>$0(u2(this.directory,`${Z0($)}.json.gz`),{force:!0}))}clear(){for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),this.enqueue(async()=>{for(let $ of await j1(this.directory))if(X1.test($)||C0.test($))await $0(u2(this.directory,$),{force:!0})})}async drain(){for(let $ of this.pending.keys())this.flush($);await this.chain}}function m2($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}var U1=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function z1(){let $=globalThis;return $[U1]??=new Map,$[U1]}function n4($,Z){let V=new Map,Y=new Map,M=new O0({storageId:$,...Z.persistence}),_=new Set,O=0,C=new c4({directory:Z.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||i4("opencode"),now:Z.now}),N=()=>{let E;for(let b of Y.values())E=b;return E},X=Z.setIntervalImpl??globalThis.setInterval,B=new p4({loadStorage:async()=>{let E=N(),b=E?await E.loadStorage():null;if(E&&!p2(b)){for(let w of B.trackedSessions())B.untrack(w.id);M.clear()}return b},now:Z.now,setIntervalImpl:(E,b)=>X(()=>{let w=B.tick();return R.ticking=w.catch(()=>{J0.warn("cachekeep","tick failed")}),R.ticking},b),clearIntervalImpl:Z.clearIntervalImpl,onTargetChanged:(E)=>M.changed(E),onTargetRemoved:(E)=>{_.delete(E),M.removed(E)},onTrackedSessionsChanged:(E)=>C.publish(Y.size===0?[]:E),prepareHeaders(E,b,w){let f=N();if(!f)return;return V.set(w.id,{target:b,attempt:w,lease:f}),new Headers({"x-native-cachekeep-attempt":String(w.id)})},fetchImpl:async(E,b)=>{let w=new Request(E,b),f=Number(w.headers.get("x-native-cachekeep-attempt")),v=V.get(f);if(V.delete(f),!v||v.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(_.delete(v.target.id))await u4(Math.max(0,O+3000-Date.now()),void 0,{signal:v.attempt.signal}),O=Date.now();let i=v.lease.send(v.target,w,v.attempt.signal),a=i.then(()=>{},()=>{});return v.lease.inflight.add(a),a.then(()=>v.lease.inflight.delete(a)),i},onComplete:({attempt:E})=>{V.delete(E.id)}}),z,F=()=>{if(z!==void 0)clearTimeout(z);z=void 0},L=()=>{if(F(),Y.size>0)return;let E=B.dropExpiredTargets();if(E===void 0){let w=z1();if(w.get($)===R)w.delete($);return}let b=Z.now?.()??Date.now();if(z=setTimeout(L,Math.max(0,E-b)),typeof z==="object"&&"unref"in z)z.unref()},R={manager:B,registry:C,persistence:M,prepared:V,leases:Y,nextGeneration:0,retain(){B.stop(),V.clear(),L()},async adopt(){if(F(),R.loading??=(async()=>{let E=N();if(!E)return;let b=await E.read();if(!p2(b.policyStorage)){M.clear();return}let w=Z.now?.()??Date.now(),f=0;await M.load(w,(v)=>{if(!Y.size||B.trackedRequest(v.id))return!0;let i=b.accounts.find((j2)=>m2(j2)===v.oauthAccountIdentity);if(i?.type!=="oauth"||!B1(i)||v.isSubagent&&!j0(b.policyStorage))return!1;let a=v.nextPrewarmAt<=w?w+f++*3000:v.nextPrewarmAt,Y2=B.track({sessionId:v.id,url:v.url,headers:new Headers,bodyText:v.bodyText,storage:b.policyStorage,cacheMode:"hybrid",oauthAccountId:i.id,oauthAccountIdentity:v.oauthAccountIdentity,isSubagent:v.isSubagent,retained:{cacheExpiresAt:v.cacheExpiresAt,nextPrewarmAt:a}});if(Y2.tracked)_.add(v.id);return Y2.tracked})})().catch(()=>{J0.warn("cachekeep","failed to restore tracked sessions")}),await R.loading,!Y.size)return;if(B.dropExpiredTargets()===void 0)return;B.start(),C.publish(B.trackedSessions()).catch(()=>{J0.warn("cachekeep","failed to publish tracked sessions")})}};return R}function M1($){let{runtime:Z,source:V}=$,Y=new AbortController,M=z1(),_=M.get($.storageId)??n4($.storageId,$);M.set($.storageId,_);let{manager:O,registry:C}=_,N=async(L,R,E)=>{let b=E?AbortSignal.any([Y.signal,E]):Y.signal;b.throwIfAborted();let w=JSON.parse(await R.text()),f={providerID:"anthropic",modelID:w.model,sessionID:`oc2-cachekeep:${L.id}`,agent:"cachekeep",kind:"generate"},v=(u)=>{throw new b2(u)},i=h2({source:{...V,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(u){return{...await V.requestOptions?.(u,v),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(u,J){let W=await Z.read();b.throwIfAborted();let U=W.accounts.find((A)=>A.id===J);if(U?.type!=="oauth"||!B1(U))throw new b2("account-unavailable");if(m2(U)!==L.oauthAccountIdentity)throw new b2("credential-changed");if(L.isSubagent&&!j0(W.policyStorage)||!p2(W.policyStorage)||!W1(W.policyStorage,new Date($.now?.()??Date.now())))return;let q=await V.authorizeAccount(u,J,v);if(q?.provenance.kind==="local"&&m2({...U,binding:q.provenance.subject.binding,accountIdentity:q.provenance.subject.binding.identity})!==L.oauthAccountIdentity)throw new b2("credential-changed");if(q?.provenance.kind==="vault"&&q.provenance.credentialId!==U.credentialId)throw new b2("credential-changed");return q},async admitRequest(u){await V.admitRequest?.(u,v);let J=await Z.read(),W=J.accounts.find((U)=>U.id===u.accountId);if(b.throwIfAborted(),!W)throw new b2("account-unavailable");if(m2(W)!==L.oauthAccountIdentity)throw new b2("credential-changed");if(L.isSubagent&&!j0(J.policyStorage)||!p2(J.policyStorage)||!W1(J.policyStorage,new Date($.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),a,Y2,j2=!1,e=()=>i.forgetSession(f.sessionID);b.addEventListener("abort",e,{once:!0});try{let u=await Z.read(),J=u.accounts.find((I)=>m2(I)===L.oauthAccountIdentity)?.id;if(!J)throw new b2(u.accounts.some((I)=>I.id===L.oauthAccountId)?"credential-changed":"account-unavailable");let W=await i.adapter.accountHeaders({...f,accountId:J});if(!("headers"in W)||typeof W.headers!=="object"||W.headers===null||typeof W.attempt!=="object"||W.attempt===null||W.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");a={...f,accountId:J,attemptId:crypto.randomUUID(),transport:"http",data:W.attempt};let U=await i.adapter.rewriteRequest?.({...f,accountId:J,attempt:a,request:new Request(L.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w),signal:b})});if(!U)throw Error("CacheKeep rewrite refused");b.throwIfAborted();let q=await($.fetch??fetch)(U),A=await i.adapter.rewriteResponse?.({...f,accountId:J,attempt:a,request:U,response:q});if(!A)throw Error("CacheKeep response rewrite refused");if(Y2=A.status,i.adapter.quotaFromHeaders?.(A.headers,A.status,a),!A.ok)await i.adapter.limitFromResponse?.({status:Y2,headers:A.headers,body:()=>A.clone().text(),attempt:a});let y=await A.arrayBuffer();return j2=!0,new Response(y,{status:Y2,headers:A.headers})}catch(u){let J=o4(u);if(J)throw J;throw Error("Native CacheKeep was not completed")}finally{b.removeEventListener("abort",e);try{if(a)await i.adapter.onAttemptEnd?.(a,{status:Y2,outputStarted:!1,...j2?{}:{error:{reason:"cancelled"}}})}finally{i.dispose(),V.forgetSession?.(f.sessionID)}}},X={generation:_.nextGeneration++,stopped:!1,loadStorage:async()=>(await Z.read()).policyStorage,send:N,inflight:new Set,read:()=>Z.read()},B=_.leases.size===0;_.leases.set(X.generation,X);let z=B?_.adopt():_.loading??Promise.resolve(),F;return{ready:z,async track(L){let R=(v)=>{J0.debug("cachekeep","tracking skipped",{session:L.sessionID,reason:v})};if(X.stopped)return R("lease-stopped");if(L.route!=="oauth")return R("not-oauth");if(L.agent==="cachekeep"||L.agent==="prime")return R("background-agent");if(L.kind!=="primary")return R("not-primary");let E=await Z.read();if(X.stopped)return R("lease-stopped");if(!p2(E.policyStorage)){for(let v of O.trackedSessions())O.untrack(v.id);return _.persistence.clear(),R("hybrid-inactive")}let b=!1;try{b=await $.isSubagent?.(L.sessionID)??!1}catch{return R("session-lookup-failed")}if(X.stopped)return R("lease-stopped");if(b&&!j0(E.policyStorage))return R("subagents-disabled");let w=E.accounts.find((v)=>v.id===L.accountId);if(!w?.accountIdentity)return R("account-identity-missing");if(L.provenance.kind==="local"&&JSON.stringify(w.binding)!==JSON.stringify(L.provenance.subject.binding))return R("local-binding-changed");if(L.provenance.kind==="vault"&&w.credentialId!==L.provenance.credentialId)return R("vault-credential-changed");let f=O.track({sessionId:L.sessionID,url:L.url,headers:new Headers,bodyText:L.bodyText,storage:E.policyStorage,cacheMode:"hybrid",oauthAccountId:L.accountId,oauthAccountIdentity:m2(w),isSubagent:b});return await C.publish(O.trackedSessions()),f},registry:C,dispose(){if(F)return F;X.stopped=!0,Y.abort();for(let[R,E]of _.prepared)if(E.lease===X)_.prepared.delete(R);let L=_.leases.delete(X.generation)&&_.leases.size===0;if(L)_.retain();return F=(async()=>{try{if(L)await _.ticking;await z,await Promise.all(X.inflight),await _.persistence.drain()}finally{if(L&&_.leases.size===0)await C.dispose()}})(),F}}}async function K1($,Z,V){let Y=h2(Z),M=[],_=async(F,L,R)=>{let E=await $.session.hook(F,L,R);return M.push(E),E},O=new AbortController,C;try{C=await N0({session:{hook:_},event:$.event},Y.adapter,{logger:Z.log,gateOnPlaceholder:V})}catch(F){throw Y.dispose(),await Promise.allSettled(M.map((L)=>L.dispose())),F}let N=(F)=>{Y.forgetSession(F),C.forgetSession(F)},X=$.event,B=X?(async()=>{try{for await(let F of X.subscribe({signal:O.signal}))if(F.type==="session.deleted")N(F.data.sessionID)}catch(F){if(!O.signal.aborted)Z.log?.warn("stopped listening for session deletion",{error:F instanceof Error?F.name:"unknown"})}})():Promise.resolve(),z;return{installation:C,forgetSession:N,dispose(){if(z)return z;return Y.dispose(),O.abort(),z=(async()=>{await C.dispose(),await B})(),z}}}import{effectiveRelayTransport as H1,getQuotaCheckIntervalMs as r4,logger as s4,nativeAccountCanServe as a4,oauthProfileIsFresh as t4,quotaSnapshotCheckedAt as e4}from"@cortexkit/anthropic-auth-core";function N1($,Z){let V=new AbortController,Y,M=!1,_=async()=>{let N=await $.read();if(V.signal.throwIfAborted(),N.policyStorage.relay?.enabled===!0&&H1(N.policyStorage.relay.transport,N.policyStorage.relay.url)==="websocket")return;let X=N,B=r4(X.policyStorage);for(let z of X.accounts){if(V.signal.aborted)return;if(!a4(z)||z.type!=="oauth")continue;if(X.policyStorage.quota?.enabled!==!1&&Date.now()-e4(z.quota)>=B)await $.fetchQuota(z.id,Z,V.signal,void 0,"background").catch(()=>{});if(!t4(z.profile)&&!V.signal.aborted)await $.fetchProfile(z.id,Z,V.signal).catch(()=>{})}},O=()=>{if(M||Y)return Y;return Y=_().catch(()=>{if(!V.signal.aborted)s4.debug("opencode2","native background readings did not complete")}).finally(()=>{Y=void 0}),Y},C=$.vault.watch({intervalMs:60000,onRefresh:O,shouldRefresh:async()=>{let N=await $.read();return N.policyStorage.relay?.enabled!==!0||H1(N.policyStorage.relay.transport,N.policyStorage.relay.url)==="http"}});return C.ready.catch(()=>{}),{async dispose(){M=!0,C.close(),V.abort(),await Y}}}import{authorize as B$,buildCacheKeepStatusSummary as z$,buildClaudeQuotaSummary as M$,buildPrimeAccountStatuses as K$,buildPrimeStatusSummary as H$,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as N$,effectiveRelayTransport as _$,exchange as L$,formatNativeAccountState as F$,formatOAuthAccountTier as P$,getCacheKeepWindow as T$,getHostClaustrumEnrollmentPaths as C$,isCacheKeepAlways as O$,isCacheKeepHybridActive as E$,isCacheKeepPersistentlyEnabled as q$,nativeAccountCanServe as x$,parseLogLevel as S$,resetClaustrumEnrollmentState as k$,setDumpEnabled as R$}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as $$,effectiveRelayStatus as Z$,formatNativeAccountState as j$,formatOAuthAccountTier as _1,getCacheKeepWindow as J$,getRoutingMode as X$,isCacheKeepAlways as G$,isCacheKeepHybridActive as Y$,isPermanentRefreshError as V$,isPrimePersistentlyEnabled as Q$,nativeAccountCanServe as P1,refreshBackoffActive as L1}from"@cortexkit/anthropic-auth-core";var F1=($)=>P1($)&&$.state!=="unsupported-access"?void 0:j$($)||void 0,W$=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return P1($)?"on-vault-served":"on-cold"},U$=($,Z)=>typeof $==="number"&&$>Z;function T1($,Z){let{now:V}=Z,Y=$.policyStorage,M=$.accounts.filter((B)=>B.type==="oauth"),_=M.find((B)=>B.id==="main"),O=_?F1(_):void 0,C=_?.lastQuotaRefreshError?.nextRetryAt,N=_?.lastRefreshError,X=J$(Y);return X0({main:{quota:_?.quota??null,enabled:_?.enabled,tierLabel:_1(_?.profile),quotaBackedOff:U$(C,V),quotaBackoffUntil:C,refreshBackedOff:L1(N,_?.accountIdentity,V,void 0),refreshBackoffUntil:N?.nextRetryAt,stateLine:O,quotaDated:Boolean(O)},fallbacks:M.filter((B)=>B.id!=="main"&&(B.enabled||B.source==="vault")).map((B)=>{let z=F1(B),F=W$(B);return{id:B.id,label:B.label,quota:B.quota??null,enabled:B.enabled,tierLabel:_1(B.profile),needsReauth:V$(B.lastRefreshError)&&L1(B.lastRefreshError,B.accountIdentity,V,void 0),...F==="on-vault-reauth"?{vaultReauth:!0}:{},...F==="on-vault-served"?{vaultServed:!0}:{},...F!=="off"?{custodyState:F}:{},stateLine:z,quotaDated:Boolean(z)}}),...Z.activeId!==void 0&&{activeId:Z.activeId},route:X$(Y),relay:Z$(Y.relay),fastMode:Y.claudeFast?.enabled===!0,cacheKeep:{enabled:Y$(Y),...G$(Y)?{window:"always"}:X&&{window:`${X.startHour}-${X.endHour}`},trackedSessions:Z.trackedSessions},prime:Q$(Y)?{enabled:!0,accounts:$$(Y,{now:V})}:void 0,lastUpdated:V})}var E0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},C1=`For first-time model access, connect Anthropic with "${V0}".
|
|
4
|
-
Run: opencode auth login anthropic --method ${Y0}`,
|
|
5
|
-
Route: ${$.id}`;return`${Z==="main"?"Main account":`Fallback ${$.id}`}: ${
|
|
1
|
+
import{a as t2,b as f1,c as l1,d as m0,e as l0,f as G0,g as y2,h as d0,i as u0,j as v1,k as g1,l as h1,m as p0,n as d1,o as c0,p as i0,q as o0,r as n0,s as F0,t as o1}from"../index-zxyjjr82.js";import"../index-2ra790fx.js";import"../index-jc8zwxvw.js";import{y as c1}from"../index-eq1kbq5z.js";import{A as V0,C as p1,z as Y0}from"../index-qqs4ec18.js";import"../index-a0jxsmac.js";import{M as X0}from"../index-d4e8qj37.js";import"../index-crx0xd9j.js";import"../index-n8xr16kr.js";import{acquireNativeAccountRuntime as Y6,assertUnmanagedInjectedPaths as V6,authorize as Q6,createNativeUi as W6,decideOpenCodeStateLayoutOnce as U6,disconnectNativeVaultForHost as B6,exchange as z6,getPersistedLogLevel as K6,isDumpPersistentlyEnabled as M6,logger as S0,openCodeHolderKind as H6,readNativeEnrollmentMode as N6,registerNativePoolHolder as _6,resolveNativePoolPaths as L6,setDumpEnabled as F6,setLogLevel as P6,stateLayoutIoFailure as T6,unmovedRegistrationPolicy as C6}from"@cortexkit/anthropic-auth-core";class f2 extends Error{kind;providerID;sessionID;requestKind;constructor($){super($.message??`${$.providerID} ${$.requestKind} request refused (${$.kind})`);this.name="OpenCode2AuthError",this.kind=$.kind,this.providerID=$.providerID,this.sessionID=$.sessionID,this.requestKind=$.requestKind}}function R2($){return`common-auth-placeholder.${$}`}function R0($){let Z=R2($.integrationID);return{type:"oauth",methodID:$.methodID,access:Z,refresh:Z,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function K0($,Z){if($?.type!=="oauth")return!1;let Q=Z===void 0?void 0:R2(Z),Y=(M)=>Q===void 0?M.startsWith("common-auth-placeholder."):M===Q;return Y($.access)&&Y($.refresh)}var b0="No browser sign-in: this connects the plugin to the accounts in its vault.";async function M0($,Z){let Q=Z.now??Date.now,{integrationID:Y}=Z,M=(T)=>R0({integrationID:Y,methodID:T,now:Q()}),C=async(T,H)=>{return await Z.onLogin(T,{integrationID:Y,methodID:H}),M(H)},q=(T)=>async(H)=>{let G=T.method.id,B=await T.authorize(H),K={url:B.url,instructions:B.instructions,...B.expiresAt===void 0?{}:{expiresAt:B.expiresAt}};if(B.mode==="auto")return{...K,mode:"auto",callback:B.callback.then((L)=>C(L,G))};let _=B.callback;return{...K,mode:"code",callback:async(L)=>C(await _(L),G)}};return $.integration.transform((T)=>{let H=Z.label===void 0?{}:{label:()=>Z.label};for(let K of Z.methods)T.method.update({integrationID:Y,method:K.method,authorize:q(K),refresh:async(_)=>{if(!K0(_,Y))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return M(_.methodID)},...H});let G=Z.vault;if(G===void 0)return;let B=G.method.id;T.method.update({integrationID:Y,method:G.method,authorize:async()=>({url:"",instructions:G.instructions??b0,mode:"auto",callback:Promise.resolve().then(()=>G.activate({integrationID:Y,methodID:B})).then(()=>M(B))}),refresh:async(K)=>{if(!K0(K,Y)||K.methodID!==B)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return M(B)},...H})})}function n1($){let Z=[],Q;for(let Y of $.split(/\r?\n/))if(Y.startsWith("data:"))Z.push(Y.slice(5).replace(/^ /,""));else if(Y.startsWith("event:"))Q=Y.slice(6).trim();if(Z.length===0)return;return Q===void 0?{data:Z.join(`
|
|
2
|
+
`)}:{event:Q,data:Z.join(`
|
|
3
|
+
`)}}function H0($,Z){let Q=new TextDecoder,Y="",M=(q)=>{let T=n1(q);if(!T)return;try{$(T)}catch(H){Z(H)}},C=()=>{for(;;){let q=/\r?\n\r?\n/.exec(Y);if(!q)return;let T=Y.slice(0,q.index);Y=Y.slice(q.index+q[0].length),M(T)}};return new TransformStream({transform(q,T){T.enqueue(q),Y+=Q.decode(q,{stream:!0}),C()},flush(){if(Y+=Q.decode(),C(),Y.trim()!=="")M(Y);Y=""}})}var A0=512,w0=1200000,v2="x-common-auth-attempt",D2=($,Z)=>JSON.stringify([$,Z]),x2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function r1($){let Z=$.headers;return typeof Z==="object"&&Z!==null}function s1($,Z){let Q=$.getReader();return new ReadableStream({async pull(Y){let M;try{M=await Q.read()}catch(C){Z({reason:"failed",message:C instanceof Error?C.message:String(C)}),Y.error(C);return}if(M.done)Z(),Y.close();else Y.enqueue(M.value)},async cancel(Y){Z({reason:"cancelled",...Y===void 0?{}:{message:String(Y)}}),await Q.cancel(Y)}})}function r2($,Z){for(let[Q,Y]of Object.entries(Z)){let M=Q.toLowerCase();for(let C of Object.keys($))if(C.toLowerCase()===M)delete $[C];if(Y!==null)$[Q]=Y}}function a1($,Z){for(let[Q,Y]of Object.entries(Z))if(Y===null)$.delete(Q);else $.set(Q,Y)}async function N0($,Z,Q={}){let{providerID:Y}=Z,M=Q.gateOnPlaceholder,C=(j)=>M===void 0||M.credential(j)===R2(Y),q=Q.logger,T=Math.max(1,Q.maxRecords??A0),H=[...Q.hostCredentials??[R2(Y)],...M?[R2(Y)]:[]].filter((j)=>j!==""),G=new Map,B=new WeakMap,K=new Map,_=0,L=new Set,S=new Map,O=new Map,b=(j)=>{let W=O.get(j);return W?.ownedSeen===!0&&W.foreignSeen},w=(j,W)=>{S.set(j,W);let F=O.get(j)??{ownedSeen:!1,foreignSeen:!1};if(W)F.ownedSeen=!0;else F.foreignSeen=!0;O.set(j,F)},f=(j,W)=>{let F=M?.refuseMisplaced,k=F?[...W].filter(([,u])=>u.includes(R2(Y))):[],P=C(W)&&(!F||k.length>0);if(F){if(k.length>0&&(k.length!==1||!P))throw w(j.sessionID,!1),new f2({kind:"placement-refused",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,message:F(k[0]?.[0]??"")})}return w(j.sessionID,P),P},y=!1,o=!1,e=new Map,Q2=0,j2=!1,$2=new Map,p=(j,W)=>{try{q?.warn(j,W)}catch{}},l=(j)=>j instanceof Error?j.message:String(j),r=new Map,Z2=(j,W)=>{let F=(r.get(j)??Promise.resolve()).then(W),k=F.then(()=>{},()=>{});return r.set(j,k),k.then(()=>{if(r.get(j)===k)r.delete(j)}),F},J=(j,W)=>{let F=r.get(j);return F?F.then(()=>J(j,W)):W()},X=async(j)=>{try{await Z.dropChoice?.({...j.input,accountId:j.accountId})}catch(W){p("opencode2 auth dropChoice threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},z=async(j)=>{try{await Z.dropSameAccountRetry?.({...j.input,accountId:j.accountId})}catch(W){p("opencode2 auth dropSameAccountRetry threw; the request is unaffected",{sessionID:j.input.sessionID,error:l(W)})}},R=async(j)=>{if(j.next)await X(j.next);if(j.sameAccount)await z(j.sameAccount)},I=(j)=>{let W=K.get(j);if(K.delete(j),W)Z2(W.sessionID,()=>R(W))},A=async(j,W)=>{let F=e.get(j);if(!F||F.size===0)return;await Promise.all([...F].map(async(k)=>{try{await k(W)}catch(P){p("opencode2 auth listener threw; the request is unaffected",{event:j,error:l(P)})}}))},m=async(j,W)=>{try{await Z.onAttemptEnd?.(j,W)}catch(F){p("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:j.attemptId,error:l(F)})}},d=(j,W)=>{if(j.ended||!j.attempt)return;let F={...j.status===void 0?{}:{status:j.status},outputStarted:j.outputStarted,...j.limit?{limit:j.limit.signal}:{},...W?{error:W}:{}};if(W)j.endError=W;j.ended=m(j.attempt,F)},c=(j,W)=>d(j,{reason:"abandoned",message:W}),s=(j)=>[...G.values()].filter((W)=>W.key===j),h=(j)=>s(j).at(-1),X2=(j)=>{if(G.delete(j.id),K.get(j.key)?.attemptId===j.id||!s(j.key).length)I(j.key)},a=(j)=>{G.set(j.id,j);while(G.size>T){let W=G.values().next().value;if(W===void 0)break;c(W,"dropped to keep the record bound"),X2(W)}},J2=(j)=>j.accountId===void 0?void 0:{...j.scope,accountId:j.accountId},V=(j,W)=>new f2({kind:"no-account",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,...W===void 0?{}:{message:W}}),N=(j)=>{$2.get(j)?.clear(),$2.delete(j)},U=async(j,W)=>{let F=()=>V(j,`${Y} ${j.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(j2)throw F();let k=$2.get(j.sessionID);if(!k)k=new Set,$2.set(j.sessionID,k);let P={};k.add(P);let u=()=>{if(!k.has(P))throw F()};try{return await W(u)}finally{if(k.delete(P),k.size===0&&$2.get(j.sessionID)===k)$2.delete(j.sessionID)}},E=(j,W)=>{for(let[F,k]of W)if(H.some((P)=>k.includes(P)))throw new f2({kind:"host-credential-on-wire",providerID:Y,sessionID:j.sessionID,requestKind:j.kind,message:`${Y} ${j.kind} request still carries the host's placeholder credential in ${F}; the adapter's account headers must replace it`})},x=(j)=>{for(let W of s(j))if(W.ended||!W.attempt)X2(W);else if(W.transport==="ws"||W.judged)c(W,"a newer attempt of its session and kind began"),X2(W)},v=async(j,W,F,k)=>{let P=D2(j.sessionID,j.kind),{input:u,accountId:D,sameAccountRetry:i}=await J(j.sessionID,async()=>{F();let M2=K.get(P);K.delete(P);let L2=M2?.accountId??h(P)?.accountId;x(P);let H2=M2?.next,P2=M2?.sameAccount,U2=P2!==void 0&&P2.input.modelID===j.modelID&&P2.input.agent===j.agent,O2=H2!==void 0&&H2.input.modelID===j.modelID&&H2.input.agent===j.agent,E2={...j,phase:"request",...L2===void 0?{}:{previousAccountId:L2},...M2?.rerouteFrom?{rerouteFrom:M2.rerouteFrom}:{}};if(H2&&!O2)await Z2(j.sessionID,()=>X(H2)),F();if(P2&&!U2)await Z2(j.sessionID,()=>z(P2)),F();let q2=U2?P2.accountId:O2?H2.accountId:await Z.chooseAccount(E2);return{input:E2,accountId:typeof q2==="string"?q2:void 0,sameAccountRetry:U2}});F();let W2={},C2;if(D!==void 0){let M2=await Z.accountHeaders({...j,accountId:D});if(F(),r1(M2))W2=M2.headers,C2=M2.attempt;else W2=M2}let o2=`attempt-${++Q2}`,w2={id:o2,key:P,scope:j,accountId:D,headers:W2,attempt:D===void 0?void 0:{...j,accountId:D,attemptId:o2,transport:k,data:C2},...k===void 0?{}:{transport:k},outputStarted:!1,sameAccountRetry:i};if(a(w2),w2.attempt)A("select",{...j,accountId:w2.attempt.accountId,hook:W,...u.previousAccountId===void 0?{}:{previousAccountId:u.previousAccountId},...u.rerouteFrom===void 0?{}:{rerouteFrom:u.rerouteFrom},handle:w2.attempt});return w2},g=async(j,W,F,k,P)=>{let u=D2(j.sessionID,j.kind),D=k===void 0?void 0:G.get(k);if(D?.key!==u)D=void 0;if(!D){if(D=h(u),s(u).filter((W2)=>W2.transport===void 0&&!W2.ended).length>1&&!o)o=!0,p("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:j.sessionID,kind:j.kind})}if(!D||D.transport!==void 0||D.ended)D=await v(j,W,P,F);else if(D.transport=F,D.attempt)D.attempt.transport=F;if(F==="ws"){for(let i of s(u))if(i!==D&&i.transport==="ws")c(i,"a newer attempt of its session and kind went out over WebSocket")}return D},G2=async(j,W)=>{try{return await W()}catch(F){throw d(j,{reason:"failed",message:l(F)}),F}},n=(j,W)=>{let F=s(D2(j,W)).filter((k)=>k.transport==="ws").at(-1);return F?.attempt!==void 0&&!F.ended?F:void 0},B2=(j,W,F)=>{let k=J2(j);if(!k||!j.attempt||j.limit)return;j.limit={signal:W,delivered:A("limit",{...k,via:F,limit:W,outputStarted:j.outputStarted,handle:j.attempt})}},N2=(j,W,F,k)=>{let P=J2(j);if(!P||!j.attempt)return;A("quota",{...P,transport:W,...k===void 0?{}:{status:k},quota:F,handle:j.attempt})},_2=(j,W,F,k)=>{let P=j.attempt;if(!P)return;let u=Z.inspectEvent?.(k===void 0?{transport:W,data:F,attempt:P}:{transport:W,data:F,event:k,attempt:P});if(!u)return;if(u.quota!==void 0)N2(j,W,u.quota);if(u.outputStarted)j.outputStarted=!0;if(u.limit)B2(j,u.limit,W);if(u.error!==void 0)d(j,{reason:"failed",message:u.error});else if(u.done)d(j)},S2=(j,W)=>{let F=j.attempt;if(!F||W.accountId===j.accountId)return;if(F.reboundFrom??=F.accountId,F.accountId=W.accountId,"data"in W)F.data=W.data;j.accountId=W.accountId},V2=(j)=>!j.attempt||j.endError!==void 0||j.status!==void 0&&j.status>=400,Y2=(j)=>{let W=[...G.values()].filter((i)=>i.scope.sessionID===j),F=W.filter((i)=>i.limit&&!i.rerouted).at(-1);if(F)return F;let k=W.filter((i)=>i.scope.kind==="primary"),P=k.length>0?k:W;if(P.length<=1)return P[0];let u=P.filter((i)=>!i.judged&&V2(i)).at(-1);if(u)return u;let D=P.filter((i)=>i.attempt&&!i.ended);if(D.length>1)return"ambiguous";return D[0]??P.at(-1)},z2={providerID:Y},K2=[];K2.push(await $.session.hook("model.request",(j)=>{if(M)return;return U(x2(j),async(W)=>{let F=await v(x2(j),"model.request",W);if(W(),F.accountId===void 0)throw V(F.scope);r2(j.headers,{...F.headers,[v2]:F.id})})},z2)),K2.push(await $.session.hook("http.request",(j)=>{if(M){if(!f(x2(j),j.request.headers))return}return U(x2(j),async(W)=>{let F=j.request.headers.get(v2)??void 0,k=M?await v(x2(j),"http.request",W,"http"):await g(x2(j),"http.request","http",F,W);W();let P=J2(k),u=k.attempt;if(!P||!u)throw V(k.scope);await G2(k,async()=>{let D=j.request;if(Z.rewriteRequest){if(F!==void 0){let C2=new Headers(D.headers);C2.delete(v2),D=new Request(D,{headers:C2})}D=await Z.rewriteRequest({...P,request:D,attempt:u})??D,W()}let i=new Headers(D.headers);i.delete(v2),a1(i,k.headers),E(k.scope,i.entries());let W2=new Request(D,{headers:i});B.set(W2,k),j.request=W2})})},z2)),K2.push(await $.session.hook("http.response",async(j)=>{let W=B.get(j.request);if(!W){if(M)return;if(!y)y=!0,p("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:j.sessionID,kind:j.kind});return}let F=j.response;if(Z.answeredBy&&W.attempt){let i=W.attempt,W2=await G2(W,async()=>Z.answeredBy?.({request:j.request,response:F,attempt:i}));if(W2)S2(W,W2)}let k=J2(W),P=W.attempt;if(!k||!P)return;W.status=F.status;let u=Z.quotaFromHeaders?.(F.headers,F.status,P);if(u!==void 0)N2(W,"http",u,F.status);if(!F.ok&&Z.limitFromResponse){let i=await Z.limitFromResponse({status:F.status,headers:F.headers,body:()=>F.clone().text(),attempt:P});if(i)B2(W,i,"http")}if(!F.ok||!F.body)d(W);let D=F;if(F.body&&(Z.inspectEvent||Z.onAttemptEnd)){let i=F.body;if(Z.inspectEvent)i=i.pipeThrough(H0((W2)=>_2(W,"http",W2.data,W2.event),(W2)=>p("opencode2 auth event inspection threw",{error:l(W2)})));D=new Response(s1(i,(W2)=>d(W,W2)),{status:F.status,statusText:F.statusText,headers:F.headers})}if(Z.rewriteResponse)D=await Z.rewriteResponse({...k,request:j.request,response:D,attempt:P})??D;if(D!==F)j.response=D},z2)),K2.push(await $.session.hook("experimental.ws.handshake",(j)=>{if(M){let W=D2(j.sessionID,j.kind);if(L.delete(W),!f(x2(j),new Headers(j.headers)))return}return U(x2(j),async(W)=>{let F;for(let D of Object.keys(j.headers)){if(D.toLowerCase()!==v2)continue;F??=j.headers[D],delete j.headers[D]}let k=M?await v(x2(j),"experimental.ws.handshake",W,"ws"):await g(x2(j),"experimental.ws.handshake","ws",F,W);W();let P=J2(k),u=k.attempt;if(!P||!u)throw V(k.scope);await G2(k,async()=>{if(!M?.refuseMisplaced)r2(j.headers,k.headers);let D=Z.rewriteHandshakeURL?.({...P,url:j.url,attempt:u});if(D!==void 0)j.url=D;if(M?.refuseMisplaced)r2(j.headers,k.headers);if(E(k.scope,Object.entries(j.headers)),M)L.add(k.key)})})},z2));let t=Z.rewriteWebSocketFrame?.bind(Z);if(t)K2.push(await $.session.hook("experimental.ws.send",async(j)=>{let W=x2(j);if(M&&!L.has(D2(W.sessionID,W.kind)))return;let F=n(W.sessionID,W.kind),k=await t({...W,attempt:F?.attempt,frame:j.frame});if(k!==void 0)j.frame=k},z2));K2.push(await $.session.hook("experimental.ws.receive",(j)=>{if(M&&!L.has(D2(j.sessionID,j.kind)))return;let W=n(j.sessionID,j.kind);if(!W)return;try{_2(W,"ws",j.frame)}catch(F){p("opencode2 auth frame inspection threw",{error:l(F)})}},z2)),K2.push(await $.session.hook("retry",async(j)=>{if(M&&S.get(j.sessionID)!==!0)return;let W=j.decision,F=()=>A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});if(b(j.sessionID)&&!Z.retrySameAccount){await F();return}let k=Y2(j.sessionID);if(!k)return;if(k==="ambiguous"){await A("retry",{sessionID:j.sessionID,attempt:j.attempt,reason:"host-decides",hostDecision:W,decision:W});return}let P=k;await U(P.scope,async(u)=>{let D=u,i=Z.retrySameAccount?.bind(Z),W2=P.attempt;if(i&&W2&&!P.outputStarted&&!P.sameAccountRetry){if(P.ended)await P.ended;if(P.limit)await P.limit.delivered;let M2=await Z2(P.scope.sessionID,async()=>{D();let L2=W2.accountId,H2=()=>G.has(P.id)&&P.accountId===L2&&Y2(j.sessionID)===P&&!P.outputStarted&&(!M||S.get(j.sessionID)===!0);if(!H2()||P.sameAccountRetry)return!1;P.sameAccountRetry=!0;let P2={...P.scope,accountId:L2,error:j.error,attempt:j.attempt,...P.limit?{limit:P.limit.signal}:{}},U2;try{U2=await i(P2)}catch(q2){p("opencode2 auth retrySameAccount threw; recovery declined",{sessionID:j.sessionID,error:l(q2)})}if(!U2)return D(),!1;let O2={accountId:U2.accountId,input:P2};try{D()}catch(q2){throw await z(O2),q2}if(!H2()||U2.accountId!==L2)return await z(O2),!1;let E2=K.get(P.key);if(K.delete(P.key),E2)await R(E2);try{D()}catch(q2){throw await z(O2),q2}if(!H2())return await z(O2),!1;return K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:L2,sameAccount:O2}),P.judged=!0,j.decision={retry:!0,delay:0},!0});if(D(),M2){await A("retry",{sessionID:j.sessionID,accountId:P.accountId,kind:P.scope.kind,attempt:j.attempt,reason:"same-account",hostDecision:W,decision:j.decision,handle:P.attempt});return}}if(b(j.sessionID)){await F();return}P.judged=!0;let C2=P.attempt;if(C2&&!P.outputStarted){if(!P.limit){let M2=Z.limitFromError?.(j.error,C2);if(M2)B2(P,M2,"error")}if(P.ended)await P.ended;if(P.limit)await P.limit.delivered}D();let{decision:o2,reason:w2}=await Z2(P.scope.sessionID,async()=>{if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let M2=K.get(P.key);if(K.delete(P.key),M2)await R(M2);if(D(),b(j.sessionID))return{decision:W,reason:"host-decides"};let L2=W,H2,P2,U2;if(P.accountId===void 0||!C2)L2={retry:!1},H2="no-account";else if(P.outputStarted)L2={retry:!1},H2="output-started";else if(P.limit){let O2={accountId:P.accountId,limit:P.limit.signal},E2,q2={...P.scope,phase:"retry",previousAccountId:P.accountId,rerouteFrom:O2};try{E2=await Z.chooseAccount(q2)}catch(z0){p("opencode2 auth chooseAccount threw while the retry hook looked for another account; the host decides the retry",{sessionID:P.scope.sessionID,error:l(z0)})}let k2=typeof E2==="object"?E2.hold:void 0,n2=typeof E2==="string"?E2:k2?P.accountId:void 0;if(n2!==void 0)U2={accountId:n2,input:q2};try{D()}catch(z0){if(U2)await X(U2);throw z0}if(b(j.sessionID)){if(U2)await X(U2);return{decision:W,reason:"host-decides"}}if(k2&&Number.isFinite(k2.delayMs)&&k2.delayMs>=0)L2={retry:!0,delay:Math.min(k2.delayMs,w0)},H2="hold";else if(!k2&&n2!==void 0&&n2!==P.accountId)P.rerouted=!0,P2=O2,L2={retry:!0,delay:0},H2="reroute";else{if(k2&&U2)await X(U2),U2=void 0;H2="host-decides-last-account"}}else H2="host-decides";if(j.decision=L2,L2.retry&&P.accountId!==void 0&&G.has(P.id))K.set(P.key,{attemptId:P.id,sessionID:P.scope.sessionID,order:++_,accountId:P.accountId,...P2===void 0?{}:{rerouteFrom:P2},...U2===void 0?{}:{next:U2}});else if(U2)await X(U2);return{decision:L2,reason:H2}});D(),await A("retry",{sessionID:j.sessionID,...P.accountId===void 0?{}:{accountId:P.accountId},kind:P.scope.kind,attempt:j.attempt,reason:w2,hostDecision:W,decision:o2,...C2===void 0?{}:{handle:C2}})})},z2));let T2=(j)=>{if(N(j),S.delete(j),!O.get(j)?.foreignSeen)O.delete(j);for(let W of L)if(JSON.parse(W)[0]===j)L.delete(W);for(let W of[...G.values()]){if(W.scope.sessionID!==j)continue;c(W,"its session was forgotten"),G.delete(W.id)}for(let[W,F]of K)if(F.sessionID===j)I(W)},F2=new AbortController,i2=$.event;if(i2)(async()=>{try{for await(let j of i2.subscribe({signal:F2.signal}))if(j.type==="session.deleted")T2(j.data.sessionID);else if(j.type==="session.status"&&j.data.status.type==="idle"){let W=j.data.sessionID,F=++_;Z2(W,async()=>{for(let[k,P]of K)if(P.sessionID===W&&P.order<F)K.delete(k),await R(P)})}}catch(j){if(!F2.signal.aborted)p("opencode2 auth stopped listening for session deletion",{error:l(j)})}})();return{on(j,W){let F=e.get(j);if(!F)F=new Set,e.set(j,F);let k=W;return F.add(k),()=>{F.delete(k)}},accountFor(j,W){return h(D2(j,W))?.accountId},forgetSession:T2,get size(){return G.size},async dispose(){if(j2)return;j2=!0;for(let j of $2.keys())N(j);F2.abort();for(let j of G.values())c(j,"the installation was disposed");G.clear();for(let j of K.keys())I(j);L.clear(),S.clear(),O.clear(),e.clear(),await Promise.all(r.values()),await Promise.all(K2.map(async(j)=>{try{await j.dispose()}catch(W){p("opencode2 auth hook did not dispose cleanly",{error:l(W)})}}))}}}import{createHash as t1}from"node:crypto";import{AnthropicOAuthOriginError as e1,applyCustomHeaders as $4,assertNotCustodyTombstone as Z4,classifyGzipRejection as j4,createProviderErrorRedactor as D0,createProviderErrorResponseScope as I0,decideRequestGzip as J4,dumpDirectRequest as y0,dumpRelayRequest as f0,dumpResponseArtifact as s2,encodeGzipRequestBody as X4,getAccountStoragePath as G4,getRequestGzipLatch as Y4,getRequestGzipLatchPath as V4,isDumpEnabled as Q4,mergeAnthropicBetas as W4,remapModelId as v0,remapRequestBodyModel as U4,setDumpEnabled as g0,stateRefusalCause as B4,stateRefusalPublicMessage as z4,stripEmptyTrailingAssistantMessages as K4,TrailingAssistantHistoryError as M4}from"@cortexkit/anthropic-auth-core";var g2="anthropic",r0="x-common-auth-attempt",H4=["x-session-affinity","x-opencode-session","x-parent-session-id",m0,t2,y2,r0],a2=new Set(["authorization","x-api-key"]),N4="physical send before a response",_4="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",L4=512,F4=5000,P4=500,s0=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]),_0=($,Z="provider request failed")=>({type:s0.has($.type)?$.type:"provider_error",message:Z,...$.status!==void 0?{status:$.status}:{}});class a0 extends Error{sessionID;requestKind;kind="no-account";providerID=g2;constructor($,Z){super(_4);this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicNoAccountError"}}class P0 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=g2;constructor($,Z){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=Z;this.name="NativeAnthropicRevokedError"}}class b2 extends Error{kind="unsupported-transport";providerID=g2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class t0 extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}class e0 extends Error{kind="state-relocated";providerID=g2;constructor($){super(z4($)??$.message,{cause:$});this.name="NativeAnthropicStateRefusal"}}function e2($){let Z=B4($);return Z?new e0(Z):void 0}var I2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function d2($){try{return JSON.parse($)}catch{return}}function L0($){let Z={};for(let[Q,Y]of Object.entries($??{}))Z[Q.toLowerCase()]=Y;return Z}function h0($){let Z={};for(let Q of H4){let Y=$.get(Q);if(Y!==null&&Q!==r0)Z[Q]=Y;$.delete(Q)}return Z}function T4($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function C4($){return $ instanceof M4||$ instanceof l0||$ instanceof e1?new t0($):void 0}function O4($,Z){let Q=[];if($.oauth)Q.push($.oauth.accessToken);for(let[Y,M]of Object.entries($.apiHeaders??{})){if(M===null||!a2.has(Y))continue;Q.push(M.replace(/^Bearer\s+/i,""))}for(let Y of a2){let M=Z.get(Y);if(M!==null)Q.push(M.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")Q.push($.dispatch.token);return[...new Set(Q.filter(Boolean))]}var E4=new Set(["oauth-2025-04-20","claude-code-20250219",p0]);function q4($){let Z=$.split(",").map((Q)=>Q.trim()).filter((Q)=>Q&&!E4.has(Q));return W4(null,Z)}function x4($){let Z=d2($);if(!I2(Z))return $;let Q=K4(Z.messages),Y=Object.hasOwn(Z,"fallbacks"),{droppedMarkers:M}=c0(Z,!1),C=Y&&!Object.hasOwn(Z,"fallbacks"),q=U4(Z);return Q>0||M>0||C||q?JSON.stringify(Z):$}async function S4($,Z){if(!($ instanceof Promise))return"settled";let Q;try{return await Promise.race([$.then(()=>"settled"),new Promise((Y)=>{Q=setTimeout(()=>Y("timed-out"),Z)})])}finally{if(Q!==void 0)clearTimeout(Q)}}function h2($){let{source:Z,log:Q}=$,Y=Math.max(1,$.maxPendingSends??L4),M=$.attemptEndTimeoutMs??F4,C=$.requestGzipLatch??Y4(V4(G4())),q=new WeakSet,T=new Map,H=new WeakMap,G=new WeakMap,B=(V)=>JSON.stringify([V.providerID,V.sessionID,V.kind,V.modelID,V.agent,V.accountId]),K=new Map,_=new WeakMap,L=new Map,S=new WeakMap,O=D0([]);O.dispose();let b=(V)=>(V&&L.get(V)?.redactor)??O,w=(V)=>{let N=L.get(V);if(!N)return;L.delete(V),N.redactor.dispose(),N.scope.dispose()},f=(V,N,U,E)=>{let x=O4(N,E),v=I0(x,U);y.set(V,U),L.set(V,{sessionID:N.sessionID,redactor:D0(x),scope:v}),v.settled.then(()=>w(V));while(L.size>Y){let g=L.keys().next().value;if(g===void 0)break;w(g)}},y=new WeakMap,o=(V,N)=>{let U=V?y.get(V):void 0;if(!U||!N.ok)return O.redactResponse(N);let E=I0([],U),x=E.redactResponse(N);return E.dispose(),x},e=(V,N)=>{let U=V?L.get(V)?.scope:void 0;if(!U)return o(V,N);try{return U.redactResponse(N)}catch{return o(V,N)}},Q2=!1,j2=new Map,$2=new WeakMap,p=new WeakMap,l=new WeakMap,r=(V)=>V.agent==="cachekeep"||V.agent==="prime",Z2=async()=>{try{if(Z.isDumpEnabled)return await Z.isDumpEnabled()}catch{return!1}try{return Q4()}catch{return!1}},J=(V)=>{j2.delete(V)},X=new WeakMap,z=(V,N)=>{if(V&&!N.ok)X.set(N.headers,V);return N},R=(V,N)=>{if(N.dispatch!=="http-relay")return!0;let U=/^req_[A-Za-z0-9_-]+$/.test(V.get("request-id")??"");return G.set(N,U),U},I=(V)=>new a0(V.sessionID,V.kind),A=new Map,m=async(V,N)=>{if(Q2)throw new P0(V.sessionID,V.kind);let U={revoked:!1},E=A.get(V.sessionID);if(!E)E=new Set,A.set(V.sessionID,E);E.add(U);let x=()=>{if(Q2||U.revoked)throw new P0(V.sessionID,V.kind)};try{let v=await N(x);return x(),v}finally{let v=A.get(V.sessionID);if(v?.delete(U)&&v.size===0)A.delete(V.sessionID)}},d=(V,N)=>{T.set(V,N);while(T.size>Y){let U=T.keys().next().value;if(U===void 0)break;T.delete(U),Q?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:Y})}},c=(V,N)=>({providerID:V.providerID,modelID:V.modelID,sessionID:V.sessionID,agent:V.agent,kind:V.kind,accountId:V.accountId,attemptId:V.attemptId,transport:V.transport,route:N.route,provenance:N.provenance,dispatch:N.dispatch}),s=(V)=>m(V,async(N)=>{let{accountId:U,...E}=V,x;try{x=await Z.authorizeAccount(E,U)}catch(v){let g=e2(v);if(g)throw Q?.warn("refused an Anthropic request: its account state was moved or could not be recorded",{error:g.cause instanceof Error?g.cause.name:""}),g;throw v}return N(),h(E,x)}),h=(V,N)=>{if(!N)throw I(V);if(N.dispatch?.kind==="websocket-relay")throw new b2;let U=N.dispatch?.kind==="http-relay"?"http-relay":"direct",E=N.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":N.dispatch.token}:void 0;if(N.route==="oauth"){if(!N.accessToken)throw I(V);Z4(N.accessToken,g2);let g=Object.freeze({route:"oauth",provenance:N.provenance,dispatch:U});d(g,{sessionID:V.sessionID,oauth:{accessToken:N.accessToken,...N.identity?{identity:N.identity}:{}},dispatch:N.dispatch,oauthHeaders:N.headers});let G2=L0(N.headers);for(let n of a2)delete G2[n];return delete G2["anthropic-beta"],{headers:E??{...G2,"x-api-key":null,authorization:`Bearer ${N.accessToken}`},attempt:g}}let x={authorization:null,"x-api-key":null,...L0(N.headers)};if(!x.authorization&&!x["x-api-key"])throw I(V);let v=Object.freeze({route:"api",provenance:N.provenance,dispatch:U});return d(v,{sessionID:V.sessionID,...N.baseURL?{baseURL:N.baseURL}:{},dispatch:N.dispatch,apiHeaders:x}),{headers:E??x,attempt:v}},X2=(V)=>m(V,(N)=>a(V,N)),a=async(V,N)=>{let{request:U,attempt:E}=V,x=E.data;K.set(B(V),E);while(K.size>Y){let V2=K.keys().next();if(!V2.done)K.delete(V2.value)}let v=x?T.get(x):void 0;if(x)T.delete(x);if(!x||!v||x.route==="oauth"&&!v.oauth)throw I(V);let g=new Headers(U.headers);$4(g);let G2=h0(g),n=U.body===null?void 0:await U.text();N();let B2=n!==void 0&&T4(U.url),N2=o0(U.url,v.baseURL!==void 0?{baseURL:v.baseURL}:{}).url?.toString()??U.url;try{if(x.route==="oauth"&&v.oauth){d0(N2);let{accessToken:V2,identity:Y2}=v.oauth;for(let[K2,t]of Object.entries(L0(v.oauthHeaders))){if(a2.has(K2))continue;if(t===null)g.delete(K2);else g.set(K2,t)}let z2=null;if(n!==void 0&&B2){let K2={...c(E,x),modelID:(()=>{let F2=d2(n);return v0(I2(F2)&&typeof F2.model==="string"?F2.model:V.modelID)})(),route:"oauth",correlation:G2},t=await Z.requestOptions?.(K2)??{};if(N(),E.agent!=="cachekeep")n=await n0(n,{...t,...Y2?{identity:Y2}:{},sessionId:V.sessionID,onToolNameMap:(F2)=>_.set(x,F2)});let T2=d2(n);z2=I2(T2)?T2:null}i0(g,V2,{body:z2,...Y2?{identity:Y2}:{},requestClass:u0(E.agent)?"auxiliary":"main"})}else{if(n!==void 0&&B2)n=x4(n);g.delete("authorization"),g.delete("x-api-key");for(let[Y2,z2]of Object.entries(v.apiHeaders??{}))if(z2===null)g.delete(Y2);else g.set(Y2,z2);if(n!==void 0&&B2&&!g.has("content-type"))g.set("content-type","application/json");let V2=g.get("anthropic-beta");if(V2!==null){let Y2=q4(V2);if(Y2)g.set("anthropic-beta",Y2);else g.delete("anthropic-beta")}}}catch(V2){let Y2=C4(V2);if(!Y2)throw V2;throw H.set(x,Y2.check),Q?.warn("refused an Anthropic request locally; nothing was sent",{check:Y2.check}),Y2}let _2=n!==void 0?d2(n):void 0;if(await Z.admitRequest?.({...c(E,x),modelID:v0(I2(_2)&&typeof _2.model==="string"?_2.model:V.modelID)}),h0(g),n!==void 0)g.delete("content-length");if(N(),f(x,v,I2(_2)&&_2.stream===!0?"event-stream":"http",g),x.route==="oauth"&&B2&&n!==void 0)await Z.onRequestPrepared?.({...c(E,x),url:N2,bodyText:n}),N();if(v.dispatch?.kind==="http-relay"){let V2=n??"";g.delete("x-relay-token");let Y2={protocol:1,type:"request",affinity:V.sessionID,upstream:{url:N2,method:U.method,headers:Object.fromEntries(g)},mode:"full_sync",revision:1,body:V2,next_hash:`sha256:${t1("sha256").update(V2).digest("hex")}`};if(B2&&n!==void 0&&!r(E)){let z2=G2[y2]==="1"?"start":void 0,K2=JSON.stringify(Y2);j2.set(x,{affinity:V.sessionID,route:V.accountId,bodyText:V2,url:N2,method:U.method,headers:new Headers(g),dispatch:"http-relay",relayUrl:v.dispatch.url,envelope:Y2,relayBytes:K2.length,...z2?{tag:z2}:{}})}else J(x);return new Request(v.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":v.dispatch.token},redirect:"error",signal:U.signal,body:JSON.stringify(Y2)})}let S2=n;if(x.route==="oauth"&&B2&&n!==void 0){let V2=await J4({url:N2,body:n,latch:C});if(N(),V2.gzip)S2=await X4(n),g.set("content-encoding","gzip"),q.add(x),N()}if(B2&&n!==void 0&&!r(E)){let V2=G2[y2]==="1"?"start":void 0;j2.set(x,{affinity:V.sessionID,route:V.accountId,bodyText:n,url:N2,method:U.method,headers:new Headers(g),dispatch:"direct",...V2?{tag:V2}:{}})}else J(x);return new Request(N2,{method:U.method,headers:g,redirect:x.route==="oauth"?"error":U.redirect,signal:U.signal,...S2!==void 0?{body:S2}:{}})},J2={providerID:g2,chooseAccount:(V)=>m(V,async()=>{let N=await Z.chooseAccount(V);if(typeof N==="object"&&V.phase==="retry")return N;if(typeof N!=="string"||!N)throw I(V);return N}),dropChoice:(V)=>Z.dropChoice?.(V),async retrySameAccount(V){if(!Z.retrySameAccount)return;let N=B(V),U=K.get(N);K.delete(N);let E=V.limit??(U?J2.limitFromError?.(V.error,U):void 0);return Z.retrySameAccount({...V,error:_0(V.error),...E?{limit:E}:{}})},dropSameAccountRetry:(V)=>Z.dropSameAccountRetry?.({...V,error:_0(V.error)}),accountHeaders:s,rewriteRequest:X2,rewriteHandshakeURL(){throw new b2},async rewriteResponse({response:V,attempt:N}){let U=N.data;if(U&&!R(V.headers,U)){if(U)J(U);if(V.status===401)return w(U),V.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return e(U,V)}if(U&&q.has(U))q.delete(U),j4(V).then((t)=>{if(!t)return;C.latchProcess(),Q?.warn("gzipped request body rejected; later requests go uncompressed",{kind:t,status:V.status})},()=>{});let E=null,x=U?j2.get(U):void 0;if(U&&x){let t=!1;try{t=await Z2()}catch{t=!1}if(!t)J(U);else{try{g0(!0)}catch{}try{if(x.dispatch==="http-relay")E=await f0({affinity:x.affinity,transport:"http",protocol:1,mode:"full_sync",status:V.status,bodyText:x.bodyText,payload:x.envelope??{},relayBytes:x.relayBytes??0,...x.tag?{tag:x.tag}:{}});else E=await y0({affinity:x.affinity,route:x.route,status:V.status,bodyText:x.bodyText,url:x.url,method:x.method,headers:x.headers,...x.tag?{tag:x.tag}:{}})}catch{E=null}if(J(U),E){$2.set(U,E);try{await s2(E,{status:V.status,message:null,complete:!1})}catch{}l.set(U,Promise.resolve())}}}let v=e(U,V);if(U?.route!=="oauth"||!v.body)return z(U,v);let g={...c(N,U),status:V.status},G2=Z.responseOptions?.(g)??{},n=(V.headers.get("content-type")??"").includes("application/json"),B2={...G2,toolNameMap:U?_.get(U):void 0,onToolNameRefusal:()=>{if(!U)return;H.set(U,"response_tool_names"),w(U)},laneStartOAuthServed:!0,...n?{responseMode:"json"}:{}};if(!U||!E)return z(U,F0(v,B2));let N2=E,_2=V.status,S2=(t)=>{let F2=(l.get(U)??Promise.resolve()).then(()=>t().then(()=>{return})).catch(()=>{return});l.set(U,F2)},V2=G2.onMessageStart,Y2=G2.onMessageDelta,z2=G2.onMessageResponse,K2=G2.onStreamEnd;return z(U,F0(v,{...B2,onMessageStart:(t)=>{try{V2?.(t)}catch{}try{p.set(U,{...t}),S2(()=>s2(N2,{status:_2,message:t,complete:!1}))}catch{}},onMessageDelta:(t)=>{try{Y2?.(t)}catch{}try{let T2=p.get(U)??{},F2=T2.usage&&typeof T2.usage==="object"&&!Array.isArray(T2.usage)?T2.usage:{},i2={...T2,...t.usage?{usage:{...F2,...t.usage}}:{},...t.stopReason?{stop_reason:t.stopReason}:{}};S2(()=>s2(N2,{status:_2,message:i2,complete:!0}))}catch{}},onMessageResponse:(t)=>{try{z2?.(t)}catch{}try{S2(()=>s2(N2,{status:_2,message:t,complete:!0}))}catch{}},onStreamEnd:async()=>{try{await K2?.()}catch{}try{await(l.get(U)??Promise.resolve())}catch{}}}))},quotaFromHeaders(V,N,U){let E=U.data;if(!E||!R(V,E))return;return Z.quotaFromHeaders?.(V,{...c(U,E),status:N})},async limitFromResponse({status:V,headers:N,body:U,attempt:E}){let x=E.data;if(!x||H.get(x)==="response_tool_names")return;if(!R(N,x))return Z.limitFromRelayFailure?.({...c(E,x),status:V});if(S.set(x,`provider responded with HTTP ${V}`),!Z.limitFromResponse)return;let v=X.get(N)===x,g=b(x);return Z.limitFromResponse({...c(E,x),status:V,headers:N,body:async()=>v?await U():g.redactText(await U())})},inspectEvent({data:V,event:N,attempt:U}){if(U.data&&H.get(U.data)==="response_tool_names")return;let E=d2(V);if(!I2(E))return;let x=typeof E.type==="string"?E.type:N;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let v=U.data,g=b(v),G2=I2(E.error)?E.error:{},n=typeof G2.type!=="string"?void 0:s0.has(G2.type)?G2.type:g.redactText(G2.type),B2=typeof G2.message==="string"?g.redactText(G2.message):void 0;if(v?.dispatch==="http-relay"&&G.get(v)===!1)return;let N2=v?Z.limitFromStreamError?.({...c(U,v),errorType:n,message:B2}):void 0,_2={error:[n??"error",B2].filter(Boolean).join(": ").slice(0,P4),...N2?{limit:N2}:{}};if(v&&_2.error)S.set(v,_2.error);return _2},limitFromError(V,N){let U=N.data;if(!U||H.has(U))return;let E=_0(V,S.get(U));if(w(U),U.dispatch==="http-relay"&&G.get(U)===!1)return;return Z.limitFromHostError?.(E,c(N,U))},async onAttemptEnd(V,N){let U=V.data;if(!U)return;T.delete(U);let E=j2.get(U);if(E){J(U);try{if(await Z2()){try{g0(!0)}catch{}try{if(E.dispatch==="http-relay"){if(N.status!==void 0)await f0({affinity:E.affinity,transport:"http",protocol:1,mode:"full_sync",status:N.status,bodyText:E.bodyText,payload:E.envelope??{},relayBytes:E.relayBytes??0,...E.tag?{tag:E.tag}:{}})}else await y0({affinity:E.affinity,route:E.route,status:N.status,error:N.status===void 0?N4:void 0,bodyText:E.bodyText,url:E.url,method:E.method,headers:E.headers,...E.tag?{tag:E.tag}:{}})}catch{}}}catch{}}let x=N.error?.reason;if(x==="cancelled"||x==="abandoned"||x===void 0&&(N.status===void 0||N.status<400))w(U);let v=H.get(U),{status:g,...G2}=N,n=Z.onAttemptEnd?.(c(V,U),{...G2,...g!==void 0&&(U.dispatch!=="http-relay"||G.get(U)===!0)?{status:g}:{},...v!==void 0?{localRefusal:{check:v}}:{}});if(await S4(n,M)==="timed-out")Q?.warn("the account source did not finish recording a send",{timeoutMs:M})}};return{adapter:J2,dispose(){Q2=!0;for(let[V,N]of A){for(let U of N)U.revoked=!0;Z.forgetSession?.(V)}A.clear(),T.clear(),K.clear(),j2.clear();for(let V of[...L.keys()])w(V)},forgetSession(V){for(let N of A.get(V)??[])N.revoked=!0;A.delete(V);for(let[N,U]of K)if(U.sessionID===V)K.delete(N);for(let[N,U]of T)if(U.sessionID===V)T.delete(N);for(let[N,U]of[...L])if(U.sessionID===V)w(N);for(let[N,U]of[...j2])if(U.affinity===V)j2.delete(N);Z.forgetSession?.(V)},get pendingSendCount(){return T.size},get heldCredentialCount(){let V=0;for(let N of T.values())if(N.oauth)V++;return V},get heldRedactorCount(){return L.size},get operationsInProgress(){let V=0;for(let N of A.values())V+=N.size;return V}}}import{setTimeout as o4}from"node:timers/promises";import{CacheKeepManager as n4,CacheKeepSessionRegistry as r4,getDefaultCacheKeepRegistryDirectory as s4,isCacheKeepActiveNow as W1,isCacheKeepHybridActive as p2,isCacheKeepSubagentsEnabled as j0,logger as J0,NativeAccountRefusal as A2,nativeAccountCanServe as B1,nativeAccountRefusal as a4}from"@cortexkit/anthropic-auth-core";import{createHash as R4,randomUUID as b4}from"node:crypto";import{constants as $1}from"node:fs";import{lstat as Z1,mkdir as A4,open as w4,readdir as j1,rm as $0,writeFile as D4}from"node:fs/promises";import{tmpdir as I4}from"node:os";import{join as u2}from"node:path";import{promisify as Y1}from"node:util";import{gunzip as y4,gzip as f4}from"node:zlib";import{CACHE_KEEP_MAX_BODY_BYTES as V1,createWindowsOwnerOnly as v4,ensureWindowsOwnerOnlyDirectory as g4,isOwnerOnly as J1,logger as h4,readWindowsOwnerOnly as m4,renameWithWindowsSharingRetry as l4}from"@cortexkit/anthropic-auth-core";var T0="2.4.6";var d4=Y1(f4),u4=Y1(y4),Z0=($)=>R4("sha256").update($).digest("hex"),X1=/^[a-f0-9]{64}\.json\.gz$/,C0=/^[a-f0-9]{64}\.json\.gz\.[a-f0-9-]+\.tmp$/,G1=2*V1+65536;function p4($,Z=I4()){return u2(Z,`cortexkit-anthropic-auth-cachekeep-${Z0($).slice(0,16)}`)}function c4($){return{v:1,pluginVersion:T0,id:$.id,bodyText:$.bodyText,url:$.url,cacheExpiresAt:$.cacheExpiresAt,nextPrewarmAt:$.nextPrewarmAt,oauthAccountIdentity:$.oauthAccountIdentity,isSubagent:$.isSubagent}}function Q1($){let Z=JSON.parse($);if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("Invalid restart body");let Q=!1;for(let Y of Object.keys(Z))if(/^(authorization|x-api-key|cookie|set-cookie|headers|credentials|token|access[_-]?token|refresh[_-]?token)$/i.test(Y))delete Z[Y],Q=!0;return Q?JSON.stringify(Z):$}function i4($,Z,Q){if(!$||typeof $!=="object"||Array.isArray($))return!1;if($.v!==1||$.pluginVersion!==T0||typeof $.id!=="string"||!$.id||`${Z0($.id)}.json.gz`!==Z||typeof $.bodyText!=="string"||Buffer.byteLength($.bodyText)>V1||typeof $.url!=="string"||typeof $.oauthAccountIdentity!=="string"||!$.oauthAccountIdentity||typeof $.isSubagent!=="boolean"||!Number.isFinite($.cacheExpiresAt)||$.cacheExpiresAt<=Q||!Number.isFinite($.nextPrewarmAt))return!1;return Q1($.bodyText)===$.bodyText}class O0{options;directory;disabled=!1;chain=Promise.resolve();pending=new Map;timers=new Map;lastWrite=new Map;latest=new Map;constructor($){this.options=$;this.directory=p4($.storageId,$.root)}refuse(){if(this.disabled)return;this.disabled=!0;for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),h4.warn("cachekeep","restart storage unavailable; retaining sessions in memory only")}async directoryReady(){if(this.disabled)return!1;try{if(!await g4(this.directory,this.options.ownerOnly))try{await A4(this.directory,{mode:448})}catch(Z){if(Z.code!=="EEXIST")throw Z}let $=await Z1(this.directory);if(!$.isDirectory()||$.isSymbolicLink()||!await J1(this.directory,()=>$.uid===process.getuid?.()&&($.mode&511)===448,this.options.ownerOnly))throw Error("Unsafe restart directory");return!0}catch{return this.refuse(),!1}}enqueue($){this.chain=this.chain.then(async()=>{if(await this.directoryReady())await $()}).catch(()=>this.refuse())}async load($,Z){if(!await this.directoryReady())return;try{for(let Q of(await j1(this.directory)).sort()){if(!X1.test(Q)&&!C0.test(Q))continue;let Y=u2(this.directory,Q);try{if(C0.test(Q))throw Error("Unfinished write");let M=await Z1(Y);if(!M.isFile()||M.isSymbolicLink()||M.size>G1||!await J1(Y,()=>M.uid===process.getuid?.()&&(M.mode&511)===384,this.options.ownerOnly))throw Error("Unsafe restart file");let C=await m4(Y,this.options.ownerOnly);if(!C){let H=await w4(Y,$1.O_RDONLY|$1.O_NOFOLLOW);try{C=await H.readFile()}finally{await H.close()}}let q=await u4(C,{maxOutputLength:G1}),T=JSON.parse(q.toString("utf8"));if(!i4(T,Q,$)||!Z(T))throw Error("Stale restart file")}catch{await $0(Y,{force:!0})}}}catch{this.refuse()}}changed($){if(this.disabled)return;let Z=c4($),Q=this.latest.get(Z.id);if(Q&&Q.bodyText===Z.bodyText&&Q.url===Z.url&&Q.oauthAccountIdentity===Z.oauthAccountIdentity&&Q.cacheExpiresAt===Z.cacheExpiresAt&&Q.nextPrewarmAt===Z.nextPrewarmAt&&Q.isSubagent===Z.isSubagent)return;if(this.latest.set(Z.id,Z),this.pending.set(Z.id,Z),this.timers.has(Z.id))return;let Y=Math.max(250,(this.lastWrite.get(Z.id)??0)+5000-(this.options.now?.()??Date.now())),M=(this.options.setTimeoutImpl??setTimeout)(()=>this.flush(Z.id),Y);M.unref?.(),this.timers.set(Z.id,M)}flush($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($);let Q=this.pending.get($);if(this.pending.delete($),!Q)return this.chain;return this.lastWrite.set($,this.options.now?.()??Date.now()),this.enqueue(async()=>{let Y=u2(this.directory,`${Z0($)}.json.gz`),M=`${Y}.${b4()}.tmp`;try{let C={...Q,bodyText:Q1(Q.bodyText)},q=await d4(JSON.stringify(C));if(!await v4(M,q,this.options.ownerOnly))await D4(M,q,{flag:"wx",mode:384});await l4(M,Y,{platform:this.options.ownerOnly?.platform})}finally{await $0(M,{force:!0})}}),this.chain}removed($){let Z=this.timers.get($);if(Z)(this.options.clearTimeoutImpl??clearTimeout)(Z);this.timers.delete($),this.pending.delete($),this.latest.delete($),this.lastWrite.delete($),this.enqueue(()=>$0(u2(this.directory,`${Z0($)}.json.gz`),{force:!0}))}clear(){for(let $ of this.timers.values())(this.options.clearTimeoutImpl??clearTimeout)($);this.timers.clear(),this.pending.clear(),this.latest.clear(),this.lastWrite.clear(),this.enqueue(async()=>{for(let $ of await j1(this.directory))if(X1.test($)||C0.test($))await $0(u2(this.directory,$),{force:!0})})}async drain(){for(let $ of this.pending.keys())this.flush($);await this.chain}}function m2($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}var U1=Symbol.for("cortexkit.anthropic-auth.opencode2.cachekeep.v2");function z1(){let $=globalThis;return $[U1]??=new Map,$[U1]}function t4($,Z){let Q=new Map,Y=new Map,M=new O0({storageId:$,...Z.persistence}),C=new Set,q=0,T=new r4({directory:Z.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||s4("opencode"),now:Z.now}),H=()=>{let O;for(let b of Y.values())O=b;return O},G=Z.setIntervalImpl??globalThis.setInterval,B=new n4({loadStorage:async()=>{let O=H(),b=O?await O.loadStorage():null;if(O&&!p2(b)){for(let w of B.trackedSessions())B.untrack(w.id);M.clear()}return b},now:Z.now,setIntervalImpl:(O,b)=>G(()=>{let w=B.tick();return S.ticking=w.catch(()=>{J0.warn("cachekeep","tick failed")}),S.ticking},b),clearIntervalImpl:Z.clearIntervalImpl,onTargetChanged:(O)=>M.changed(O),onTargetRemoved:(O)=>{C.delete(O),M.removed(O)},onTrackedSessionsChanged:(O)=>T.publish(Y.size===0?[]:O),prepareHeaders(O,b,w){let f=H();if(!f)return;return Q.set(w.id,{target:b,attempt:w,lease:f}),new Headers({"x-native-cachekeep-attempt":String(w.id)})},fetchImpl:async(O,b)=>{let w=new Request(O,b),f=Number(w.headers.get("x-native-cachekeep-attempt")),y=Q.get(f);if(Q.delete(f),!y||y.lease.stopped)throw Error("CacheKeep attempt is unavailable");if(C.delete(y.target.id))await o4(Math.max(0,q+3000-Date.now()),void 0,{signal:y.attempt.signal}),q=Date.now();let o=y.lease.send(y.target,w,y.attempt.signal),e=o.then(()=>{},()=>{});return y.lease.inflight.add(e),e.then(()=>y.lease.inflight.delete(e)),o},onComplete:({attempt:O})=>{Q.delete(O.id)}}),K,_=()=>{if(K!==void 0)clearTimeout(K);K=void 0},L=()=>{if(_(),Y.size>0)return;let O=B.dropExpiredTargets();if(O===void 0){let w=z1();if(w.get($)===S)w.delete($);return}let b=Z.now?.()??Date.now();if(K=setTimeout(L,Math.max(0,O-b)),typeof K==="object"&&"unref"in K)K.unref()},S={manager:B,registry:T,persistence:M,prepared:Q,leases:Y,nextGeneration:0,retain(){B.stop(),Q.clear(),L()},async adopt(){if(_(),S.loading??=(async()=>{let O=H();if(!O)return;let b=await O.read();if(!p2(b.policyStorage)){M.clear();return}let w=Z.now?.()??Date.now(),f=0;await M.load(w,(y)=>{if(!Y.size||B.trackedRequest(y.id))return!0;let o=b.accounts.find((j2)=>m2(j2)===y.oauthAccountIdentity);if(o?.type!=="oauth"||!B1(o)||y.isSubagent&&!j0(b.policyStorage))return!1;let e=y.nextPrewarmAt<=w?w+f++*3000:y.nextPrewarmAt,Q2=B.track({sessionId:y.id,url:y.url,headers:new Headers,bodyText:y.bodyText,storage:b.policyStorage,cacheMode:"hybrid",oauthAccountId:o.id,oauthAccountIdentity:y.oauthAccountIdentity,isSubagent:y.isSubagent,retained:{cacheExpiresAt:y.cacheExpiresAt,nextPrewarmAt:e}});if(Q2.tracked)C.add(y.id);return Q2.tracked})})().catch(()=>{J0.warn("cachekeep","failed to restore tracked sessions")}),await S.loading,!Y.size)return;if(B.dropExpiredTargets()===void 0)return;B.start(),T.publish(B.trackedSessions()).catch(()=>{J0.warn("cachekeep","failed to publish tracked sessions")})}};return S}function K1($){let{runtime:Z,source:Q}=$,Y=new AbortController,M=z1(),C=M.get($.storageId)??t4($.storageId,$);M.set($.storageId,C);let{manager:q,registry:T}=C,H=async(L,S,O)=>{let b=O?AbortSignal.any([Y.signal,O]):Y.signal;b.throwIfAborted();let w=JSON.parse(await S.text()),f={providerID:"anthropic",modelID:w.model,sessionID:`oc2-cachekeep:${L.id}`,agent:"cachekeep",kind:"generate"},y=(p)=>{throw new A2(p)},o=h2({source:{...Q,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(p){return{...await Q.requestOptions?.(p,y),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(p,l){let r=await Z.read();b.throwIfAborted();let Z2=r.accounts.find((X)=>X.id===l);if(Z2?.type!=="oauth"||!B1(Z2))throw new A2("account-unavailable");if(m2(Z2)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!j0(r.policyStorage)||!p2(r.policyStorage)||!W1(r.policyStorage,new Date($.now?.()??Date.now())))return;let J=await Q.authorizeAccount(p,l,y);if(J?.provenance.kind==="local"&&m2({...Z2,binding:J.provenance.subject.binding,accountIdentity:J.provenance.subject.binding.identity})!==L.oauthAccountIdentity)throw new A2("credential-changed");if(J?.provenance.kind==="vault"&&J.provenance.credentialId!==Z2.credentialId)throw new A2("credential-changed");return J},async admitRequest(p){await Q.admitRequest?.(p,y);let l=await Z.read(),r=l.accounts.find((Z2)=>Z2.id===p.accountId);if(b.throwIfAborted(),!r)throw new A2("account-unavailable");if(m2(r)!==L.oauthAccountIdentity)throw new A2("credential-changed");if(L.isSubagent&&!j0(l.policyStorage)||!p2(l.policyStorage)||!W1(l.policyStorage,new Date($.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),e,Q2,j2=!1,$2=()=>o.forgetSession(f.sessionID);b.addEventListener("abort",$2,{once:!0});try{let p=await Z.read(),l=p.accounts.find((R)=>m2(R)===L.oauthAccountIdentity)?.id;if(!l)throw new A2(p.accounts.some((R)=>R.id===L.oauthAccountId)?"credential-changed":"account-unavailable");let r=await o.adapter.accountHeaders({...f,accountId:l});if(!("headers"in r)||typeof r.headers!=="object"||r.headers===null||typeof r.attempt!=="object"||r.attempt===null||r.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");e={...f,accountId:l,attemptId:crypto.randomUUID(),transport:"http",data:r.attempt};let Z2=await o.adapter.rewriteRequest?.({...f,accountId:l,attempt:e,request:new Request(L.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(w),signal:b})});if(!Z2)throw Error("CacheKeep rewrite refused");b.throwIfAborted();let J=await($.fetch??fetch)(Z2),X=await o.adapter.rewriteResponse?.({...f,accountId:l,attempt:e,request:Z2,response:J});if(!X)throw Error("CacheKeep response rewrite refused");if(Q2=X.status,o.adapter.quotaFromHeaders?.(X.headers,X.status,e),!X.ok)await o.adapter.limitFromResponse?.({status:Q2,headers:X.headers,body:()=>X.clone().text(),attempt:e});let z=await X.arrayBuffer();return j2=!0,new Response(z,{status:Q2,headers:X.headers})}catch(p){let l=a4(p);if(l)throw l;throw Error("Native CacheKeep was not completed")}finally{b.removeEventListener("abort",$2);try{if(e)await o.adapter.onAttemptEnd?.(e,{status:Q2,outputStarted:!1,...j2?{}:{error:{reason:"cancelled"}}})}finally{o.dispose(),Q.forgetSession?.(f.sessionID)}}},G={generation:C.nextGeneration++,stopped:!1,loadStorage:async()=>(await Z.read()).policyStorage,send:H,inflight:new Set,read:()=>Z.read()},B=C.leases.size===0;C.leases.set(G.generation,G);let K=B?C.adopt():C.loading??Promise.resolve(),_;return{ready:K,async track(L){let S=(y)=>{J0.debug("cachekeep","tracking skipped",{session:L.sessionID,reason:y})};if(G.stopped)return S("lease-stopped");if(L.route!=="oauth")return S("not-oauth");if(L.agent==="cachekeep"||L.agent==="prime")return S("background-agent");if(L.kind!=="primary")return S("not-primary");let O=await Z.read();if(G.stopped)return S("lease-stopped");if(!p2(O.policyStorage)){for(let y of q.trackedSessions())q.untrack(y.id);return C.persistence.clear(),S("hybrid-inactive")}let b=!1;try{b=await $.isSubagent?.(L.sessionID)??!1}catch{return S("session-lookup-failed")}if(G.stopped)return S("lease-stopped");if(b&&!j0(O.policyStorage))return S("subagents-disabled");let w=O.accounts.find((y)=>y.id===L.accountId);if(!w?.accountIdentity)return S("account-identity-missing");if(L.provenance.kind==="local"&&JSON.stringify(w.binding)!==JSON.stringify(L.provenance.subject.binding))return S("local-binding-changed");if(L.provenance.kind==="vault"&&w.credentialId!==L.provenance.credentialId)return S("vault-credential-changed");let f=q.track({sessionId:L.sessionID,url:L.url,headers:new Headers,bodyText:L.bodyText,storage:O.policyStorage,cacheMode:"hybrid",oauthAccountId:L.accountId,oauthAccountIdentity:m2(w),isSubagent:b});return await T.publish(q.trackedSessions()),f},registry:T,dispose(){if(_)return _;G.stopped=!0,Y.abort();for(let[S,O]of C.prepared)if(O.lease===G)C.prepared.delete(S);let L=C.leases.delete(G.generation)&&C.leases.size===0;if(L)C.retain();return _=(async()=>{try{if(L)await C.ticking;await K,await Promise.all(G.inflight),await C.persistence.drain()}finally{if(L&&C.leases.size===0)await T.dispose()}})(),_}}}async function M1($,Z,Q){let Y=h2(Z),M=[],C=async(_,L,S)=>{let O=await $.session.hook(_,L,S);return M.push(O),O},q=new AbortController,T;try{T=await N0({session:{hook:C},event:$.event},Y.adapter,{logger:Z.log,gateOnPlaceholder:Q})}catch(_){throw Y.dispose(),await Promise.allSettled(M.map((L)=>L.dispose())),_}let H=(_)=>{Y.forgetSession(_),T.forgetSession(_)},G=$.event,B=G?(async()=>{try{for await(let _ of G.subscribe({signal:q.signal}))if(_.type==="session.deleted")H(_.data.sessionID)}catch(_){if(!q.signal.aborted)Z.log?.warn("stopped listening for session deletion",{error:_ instanceof Error?_.name:"unknown"})}})():Promise.resolve(),K;return{installation:T,forgetSession:H,dispose(){if(K)return K;return Y.dispose(),q.abort(),K=(async()=>{await T.dispose(),await B})(),K}}}import{effectiveRelayTransport as H1,getQuotaCheckIntervalMs as e4,logger as $$,nativeAccountCanServe as Z$,oauthProfileIsFresh as j$,quotaSnapshotCheckedAt as J$}from"@cortexkit/anthropic-auth-core";function N1($,Z){let Q=new AbortController,Y,M=!1,C=async()=>{let H=await $.read();if(Q.signal.throwIfAborted(),H.policyStorage.relay?.enabled===!0&&H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="websocket")return;let G=H,B=e4(G.policyStorage);for(let K of G.accounts){if(Q.signal.aborted)return;if(!Z$(K)||K.type!=="oauth")continue;if(G.policyStorage.quota?.enabled!==!1&&Date.now()-J$(K.quota)>=B)await $.fetchQuota(K.id,Z,Q.signal,void 0,"background").catch(()=>{});if(!j$(K.profile)&&!Q.signal.aborted)await $.fetchProfile(K.id,Z,Q.signal).catch(()=>{})}},q=()=>{if(M||Y)return Y;return Y=C().catch(()=>{if(!Q.signal.aborted)$$.debug("opencode2","native background readings did not complete")}).finally(()=>{Y=void 0}),Y},T=$.vault.watch({intervalMs:60000,onRefresh:q,shouldRefresh:async()=>{let H=await $.read();return H.policyStorage.relay?.enabled!==!0||H1(H.policyStorage.relay.transport,H.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){M=!0,T.close(),Q.abort(),await Y}}}import{authorize as H$,buildCacheKeepStatusSummary as N$,buildClaudeQuotaSummary as _$,buildPrimeAccountStatuses as L$,buildPrimeStatusSummary as F$,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as P$,effectiveRelayTransport as T$,exchange as C$,formatNativeAccountState as O$,formatOAuthAccountTier as E$,getCacheKeepWindow as q$,getHostClaustrumEnrollmentPaths as x$,isCacheKeepAlways as S$,isCacheKeepHybridActive as k$,isCacheKeepPersistentlyEnabled as R$,nativeAccountCanServe as b$,parseLogLevel as A$,resetClaustrumEnrollmentState as w$,setDumpEnabled as D$}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as X$,effectiveRelayStatus as G$,formatNativeAccountState as Y$,formatOAuthAccountTier as _1,getCacheKeepWindow as V$,getRoutingMode as Q$,isCacheKeepAlways as W$,isCacheKeepHybridActive as U$,isPermanentRefreshError as B$,isPrimePersistentlyEnabled as z$,nativeAccountCanServe as P1,refreshBackoffActive as L1}from"@cortexkit/anthropic-auth-core";var F1=($)=>P1($)&&$.state!=="unsupported-access"?void 0:Y$($)||void 0,K$=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return P1($)?"on-vault-served":"on-cold"},M$=($,Z)=>typeof $==="number"&&$>Z;function T1($,Z){let{now:Q}=Z,Y=$.policyStorage,M=$.accounts.filter((B)=>B.type==="oauth"),C=M.find((B)=>B.id==="main"),q=C?F1(C):void 0,T=C?.lastQuotaRefreshError?.nextRetryAt,H=C?.lastRefreshError,G=V$(Y);return X0({main:{quota:C?.quota??null,enabled:C?.enabled,tierLabel:_1(C?.profile),quotaBackedOff:M$(T,Q),quotaBackoffUntil:T,refreshBackedOff:L1(H,C?.accountIdentity,Q,void 0),refreshBackoffUntil:H?.nextRetryAt,stateLine:q,quotaDated:Boolean(q)},fallbacks:M.filter((B)=>B.id!=="main"&&(B.enabled||B.source==="vault")).map((B)=>{let K=F1(B),_=K$(B);return{id:B.id,label:B.label,quota:B.quota??null,enabled:B.enabled,tierLabel:_1(B.profile),needsReauth:B$(B.lastRefreshError)&&L1(B.lastRefreshError,B.accountIdentity,Q,void 0),..._==="on-vault-reauth"?{vaultReauth:!0}:{},..._==="on-vault-served"?{vaultServed:!0}:{},..._!=="off"?{custodyState:_}:{},stateLine:K,quotaDated:Boolean(K)}}),...Z.activeId!==void 0&&{activeId:Z.activeId},route:Q$(Y),relay:G$(Y.relay),fastMode:Y.claudeFast?.enabled===!0,cacheKeep:{enabled:U$(Y),...W$(Y)?{window:"always"}:G&&{window:`${G.startHour}-${G.endHour}`},trackedSessions:Z.trackedSessions},prime:z$(Y)?{enabled:!0,accounts:X$(Y,{now:Q})}:void 0,lastUpdated:Q})}var E0=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{},C1=`For first-time model access, connect Anthropic with "${V0}".
|
|
4
|
+
Run: opencode auth login anthropic --method ${Y0}`,I$="No Claude accounts in the vault for this host yet. Add one with `ck auth login --provider anthropic`, then grant it to this host.",O1="The vault returned an account this plugin cannot use yet.";async function y$($){let Z=new AbortController,Q;try{return await Promise.race([$.vault.refresh(Z.signal).then(()=>"complete",()=>"failed"),new Promise((Y)=>{Q=setTimeout(()=>{Y("pending"),Z.abort()},2000)})])}finally{clearTimeout(Q)}}var E1=($)=>$.mode==="local"&&!$.accounts.some((Z)=>Z.id==="main"),f$=($)=>{let Z=$.id==="main"?"main":"fallback",Q=`${$.enabled?"enabled":"disabled"}, ${$.type}, ${$.source}${$.state?`, ${O$($)}`:""}`;if($.label)return`${$.label} [${Z}]: ${Q}
|
|
5
|
+
Route: ${$.id}`;return`${Z==="main"?"Main account":`Fallback ${$.id}`}: ${Q}`};function q1($){let{runtime:Z,source:Q}=$,Y=new Map,M=!1,C=async(G,B)=>{await Z.updateSettings((K)=>({...K,[G]:{...E0(K[G]),...B}}))},q=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(G,B)=>{if(M)throw Error("Native menu is closed");switch(B.signal?.throwIfAborted(),G.action){case"enable":case"disable":return await Z.setEnabled(G.values.id,G.action==="enable"),q();case"remove":return await Z.remove(G.values.id),q();case"move-up":case"move-down":{let _=(await Z.read()).accounts.map((w)=>w.id),L=_.indexOf(G.values.id),S=L+(G.action==="move-up"?-1:1);if(L<0||S<0||S>=_.length)return{ok:!1,text:"Account cannot move in that direction."};let O=_[L],b=_[S];if(O===void 0||b===void 0)return{ok:!1,text:"Account order changed."};return _[L]=b,_[S]=O,await Z.reorder(_),q()}case"add-apikey":return await Z.addApi(G.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let K=new AbortController;Y.get(G.sessionId)?.active.abort();let _={active:K,auth:void 0};Y.set(G.sessionId,_);let L=await H$("max");if(M||K.signal.aborted||B.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return _.auth=L,{ok:!0,text:`Open ${L.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let K=Y.get(G.sessionId);if(!K?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let _=await C$(G.values.code,K.auth.verifier,K.auth.redirectUri,K.auth.state);if(K.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),M||_.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await Z.loginOAuth({routeId:crypto.randomUUID(),credential:{access:_.access,refresh:_.refresh,expires:_.expires},label:G.values.label}),K.active.signal.throwIfAborted(),B.signal?.throwIfAborted(),M)return{ok:!1,text:"Sign-in cancelled."};Y.delete(G.sessionId);let L="OAuth account stored in the native account pool.";return{ok:!0,text:E1(await Z.read())?`${L}
|
|
6
6
|
|
|
7
7
|
${C1}
|
|
8
8
|
|
|
9
|
-
Adding an account here does not change OpenCode's Anthropic connection.`:L}}case"reset-backoff":{let
|
|
10
|
-
`)||
|
|
11
|
-
`);return E1(B)?`${
|
|
9
|
+
Adding an account here does not change OpenCode's Anthropic connection.`:L}}case"reset-backoff":{let K=await Z.read();for(let _ of K.accounts){if(B.signal?.throwIfAborted(),_.type!=="oauth")continue;let L=_.source==="vault"?await Z.authorizeVault(_.id,B.signal):await Z.captureLocalSubject(_.id);await Z.resetBackoff(_.id,L)}return q()}case"enrollment-reset":{let K=await w$(x$("opencode"),P$);return{ok:K==="reset",text:K==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":K==="refused-pending"?"An enrollment request may still be in progress. Quit OpenCode and run setup again; it picks up the same request.":"Only terminal enrollment state may be reset; active enrollment was left unchanged."}}case"quota-refresh":{let _=(await Z.read()).accounts.filter((O)=>O.type==="oauth"&&b$(O)),L=await Promise.allSettled(_.map((O)=>Z.fetchQuota(O.id,void 0,B.signal)));return{ok:L.every((O)=>O.status==="fulfilled"),text:`${L.filter((O)=>O.status==="fulfilled").length}/${_.length} native quota readings refreshed.`}}case"routing-reset":return await Q.resetRouting(G.sessionId),q();case"routing-mode":return await C("routing",{mode:G.values.mode}),q();case"killswitch-on":case"killswitch-off":return await C("killswitch",{enabled:G.action==="killswitch-on"}),q();case"killswitch-set":return await Z.updateSettings((K)=>{let _=E0(K.killswitch),L={...E0(_.accounts)},S=_.main;for(let O of G.values.entries){let b={five_hour:O.fh,seven_day:O.sd,...O.scoped!==void 0?{scoped:O.scoped}:{}};if(O.account==="main"||O.account==="all")S=b;if(O.account==="all")for(let w of Object.keys(L))L[w]=b;else if(O.account!=="main")L[O.account]=b}return{...K,killswitch:{..._,main:S,accounts:L}}}),q();case"cache-on":case"cache-off":return await C("claudeCache",{enabled:G.action==="cache-on"}),q();case"cache-mode":return await C("claudeCache",{mode:G.values.mode}),q();case"cachekeep-always":return await C("cacheKeep",{enabled:!0,always:!0}),q();case"cachekeep-off":return await C("cacheKeep",{enabled:!1}),q();case"cachekeep-window":return await C("cacheKeep",{enabled:!0,always:!1,startHour:G.values.startHour,endHour:G.values.endHour}),q();case"cachekeep-subagents":return await C("cacheKeep",{subagents:G.values.enabled==="on"}),q();case"dump-on":case"dump-off":{let K=G.action==="dump-on";await C("dump",{enabled:K});try{D$(K)}catch{}return q()}case"logging-level":{let K=A$(G.values.level);if(!K)throw Error("Invalid log level");return await Z.setLoggingLevel(K),q()}case"fast-on":case"fast-off":return await C("claudeFast",{enabled:G.action==="fast-on"}),q();case"prime-on":case"prime-off":return await C("prime",{enabled:G.action==="prime-on"}),q();case"start-fire":return await H(G.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},H=(G)=>$.start(G,G0);return{dispatch:T,async readStatus(G){let B=await Z.read();if(G==="account"){let _="No native Claude accounts.",L=[];if(B.mode==="claustrum"){let O=B.policyStorage.relay;if(O?.enabled===!0&&T$(O.transport,O.url)==="websocket")return new b2().message;let b=await y$(Z);if(B=await Z.read(),B.mode==="claustrum"){let w=await Z.vault.read();if(b==="complete"&&!w?.view)b="failed";if(_=b==="complete"?I$:"No saved Claude accounts for this host yet.",w?.rejected?.length){if(_=O1,B.accounts.length)L.push(O1)}if(b==="pending")L.push("Vault account lookup is still running.");else if(b==="failed")L.push("Vault account lookup did not complete; reopen /claude to retry.")}}let S=[B.accounts.map(f$).join(`
|
|
10
|
+
`)||_,...L].join(`
|
|
11
|
+
`);return E1(B)?`${S}
|
|
12
12
|
|
|
13
13
|
${C1}
|
|
14
|
-
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:R}if(X==="quota")return M$({accounts:B.accounts.filter((F)=>F.type==="oauth").map((F)=>({name:F.label??F.id,role:F.id==="main"?"main":"fallback",enabled:F.enabled,quota:F.quota,tierLabel:P$(F.profile),lastRefreshedAt:F.lastRefreshedAt,error:F.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(X==="prime")return H$({enabled:B.policyStorage.prime?.enabled===!0,accounts:K$(B.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(X==="cachekeep"){let F=await $.cacheKeepRegistry?.list()??[];return z$({enabled:q$(B.policyStorage),always:O$(B.policyStorage),hybridActive:E$(B.policyStorage),trackedSessionDetails:F,window:T$(B.policyStorage),trackedSessions:F.length,nextPrewarmAt:F.length?Math.min(...F.map((L)=>L.nextPrewarmAt)):void 0})}let z={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(B.settings[z[X]]??{})},async readSidebar(X){let[B,z]=await Promise.all([Z.read(),$.cacheKeepRegistry?.list()??[]]);return X0(T1(B,{activeId:V.servedAccount(X),trackedSessions:z.length,now:Date.now()}))},forgetSession(X){Y.get(X)?.active.abort(),Y.delete(X)},close(){M=!0;for(let X of Y.values())X.active.abort();Y.clear()}}}import{resolveClaudeModelCapabilities as D$}from"@cortexkit/anthropic-auth-core";function x1(){let $=new Map;return{install:(V)=>V.model.transform((Y)=>{$.clear();for(let M of Y.list("anthropic")){$.set(String(M.id),String(M.modelID));let _=D$(M.modelID)?.efforts.variants;if(!_)continue;Y.update("anthropic",String(M.id),(O)=>{let C=O.variants.filter((N)=>!_.some((X)=>X===String(N.id)));O.variants=[...C,..._.map((N)=>({id:N,settings:{effort:N,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(V)=>$.get(V)??V}}function S1($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as k1,effectiveRelayTransport as R1,nativeAccountCanServe as I$,PrimeManager as y$,tokenFingerprint as b1}from"@cortexkit/anthropic-auth-core";var A1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function w1($){let{runtime:Z,source:V}=$,Y=new AbortController,M=new Set,_=(N)=>({providerID:"anthropic",modelID:k1().model,sessionID:`oc2-prime:${N}`,agent:"prime",kind:"generate"}),O=async(N)=>{let X=_(N),B=h2({source:V}),z=performance.now();try{for(let F=0;F<3;F++){if(Y.signal.throwIfAborted(),(await Z.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let R=await B.adapter.accountHeaders({...X,accountId:N});if(!("headers"in R)||typeof R.headers!=="object"||R.headers===null||typeof R.attempt!=="object"||R.attempt===null)throw Error("Native Prime authorization refused");let E={...X,accountId:N,attemptId:crypto.randomUUID(),transport:"http",data:R.attempt},b,w=!1,f=!1,v=(i)=>{f=!0,i.body?.cancel().catch(()=>{})};try{let i=await B.adapter.rewriteRequest?.({...X,accountId:N,attempt:E,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(k1()),signal:Y.signal})});if(!i)throw Error("Native Prime rewrite refused");let a=new Headers(i.headers);for(let[q,A]of Object.entries(R.headers))if(A===null)a.delete(q);else a.set(q,A);let Y2=new Request(i,{headers:a}),j2=await($.fetch??fetch)(Y2),e=await B.adapter.rewriteResponse?.({...X,accountId:N,request:Y2,response:j2,attempt:E})??j2;b=e.status,B.adapter.quotaFromHeaders?.(e.headers,e.status,E);let u=e.ok?void 0:await B.adapter.limitFromResponse?.({status:e.status,headers:e.headers,body:()=>e.clone().text(),attempt:E});if(u&&/^(vault-newer|local-newer|relay-direct):/.test(u.reason)&&F<2){if(v(e),(await V.retrySameAccount?.({...X,accountId:N,attempt:F+1,limit:u,error:{type:"api_error",message:"Native Prime credential retry",status:e.status}}))?.accountId!==N)throw Error("Native Prime retry changed account");continue}if(!e.ok)return v(e),{ok:!1,status:b,ms:performance.now()-z,error:"Native Prime upstream refused the request"};let J=A1(await e.json()),W=A1(J.usage),U={inputTokens:typeof W.input_tokens==="number"?W.input_tokens:void 0,outputTokens:typeof W.output_tokens==="number"?W.output_tokens:void 0};if(E.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(e.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await V.recordPrime(R.attempt.provenance,U),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:b,ms:performance.now()-z,usage:U}}finally{await B.adapter.onAttemptEnd?.(E,{status:b,outputStarted:!1,...w?{}:{error:{reason:f?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-z}}finally{B.dispose()}},C=new y$({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await Z.read()).policyStorage,async getAccountFingerprint(N){let X=await Z.read(),B=X.accounts.find((L)=>L.id===N);if(!I$(B)||B?.type!=="oauth")return;if(X.policyStorage.relay?.enabled===!0&&R1(X.policyStorage.relay.transport,X.policyStorage.relay.url)==="websocket")return;if(B.source==="vault"){let L=await Z.authorizeVault(N,Y.signal),R=await Z.getOrCreateAuthLineage(N,L);return R?b1(R):void 0}let z=await Z.authorizeLocal(N,{signal:Y.signal});if(z.status!=="usable")return;let F=await Z.getOrCreateAuthLineage(N,z.subject);return F?b1(F):void 0},async refreshQuota(N){let X=await Z.read();if(X.policyStorage.relay?.enabled===!0&&R1(X.policyStorage.relay.transport,X.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await Z.fetchQuota(N,$.fetch,Y.signal),fresh:!0}},sendPrime(N){let X=O(N);return M.add(X),X.finally(()=>M.delete(X)),X},async recordSuccess(N){let X=(await Z.read()).accounts.find((B)=>B.id===N);if(!X?.prime)throw Error("Native Prime counters are unavailable");return X.prime}});return C.start(),{manager:C,async dispose(){C.stop(),Y.abort(),await Promise.allSettled(M)}}}import{createNativeUsagePublisher as f$,decideStickyQuotaFailure as v$,effectiveRelayTransport as g$,getClaudeCodeIdentityForVerifiedAccount as Q0,getQuotaCheckIntervalMs as h$,getRoutingMode as x0,isDumpPersistentlyEnabled as D1,isQuotaBearingHeaderFrame as m$,logger as l$,mergeHeaderQuotaForPersistence as d$,NativeVaultNoAccountError as u$,nativeAccountCanServe as l2,nativeAccountPolicy as W0,nativeLocalAccountRefusal as p$,nativeLocalQuotaLineage as c$,nativePollQuotaGenerallyExhausted as i$,normalizeQuotaHeaders as o$,quotaSnapshotCheckedAt as I1,quotaSnapshotHasStandardWindows as n$,readNativeAccountsForRequest as r$,remapModelId as U0,StickySessionRouter as s$,setDumpEnabled as a$,shouldFallbackStatus as t$,stickyQuotaSnapshotIsFresh as c2,stickyRetryAfterWithJitter as e$,stickyRouteFamilyForModel as $5}from"@cortexkit/anthropic-auth-core";var q0=($)=>["five_hour","seven_day"].some((Z)=>($?.[Z]?.remainingPercent??1)<=0);function Z5($,Z,V,Y){let M=$.rerouteFrom;if($.phase!=="retry"||M?.limit.status!==429||x0(Z.policyStorage)!=="sticky-balanced")return;let _=V.find((C)=>C.id===M.accountId);if(!_||!c2(_.quota,Z.policyStorage,Date.now(),Y))return;let O=v$({quota:_.quota,modelId:Y});if(O.action!=="hold")return;return{hold:{delayMs:e$($.sessionID,O.retryAfterSeconds)*1000}}}function f1($){let{runtime:Z}=$,V=f$("native-auth"),Y=new Map,M=(J)=>{let W=J.routingPath;if(!W)throw Error("Native routing storage is unavailable");let U=Y.get(W);if(!U)U=new s$({path:W,vaultSeed:J.routingSeed,onLockEvent:Z.onLockEvent,relocationGuard:Z.relocationGuard,localRecoveryPath:J.mode==="local"?J.routingRecoveryPath:void 0}),Y.set(W,U);return U.setVaultSeed(J.routingSeed),U},_=new WeakMap,O=new Map,C=new Map,N=new Map,X=new Map,B=new WeakSet,z=!1,F=()=>{while(O.size>512){let J=O.keys().next();if(!J.done)O.delete(J.value)}},L=(J)=>{try{a$(D1(J.policyStorage))}catch{}},R=async()=>{try{let J=await Z.read();return L(J),D1(J.policyStorage)}catch{return!1}},E=(J)=>({providerID:J.providerID,sessionID:J.sessionID,kind:J.kind,modelID:J.modelID,agent:J.agent}),b=(J,W)=>JSON.stringify([J.providerID,J.sessionID,J.kind,J.modelID,J.agent,W]),w=(J)=>{if(z)throw Error("Native Anthropic source is closed");let W=N.get(J.sessionID);if(!W){W=new AbortController,N.set(J.sessionID,W);while(N.size>512){let U=N.keys().next();if(!U.done)u.forgetSession?.(U.value)}}return W},f=(J,W,U)=>l2(J)&&(J.type==="api"||W0(J,W,U0(U)).status==="allowed"),v=(J,W)=>J.source===W.source&&J.accountIdentity===W.accountIdentity&&J.credentialId===W.credentialId,i=async(J,W,U,q,A)=>{let y=await Z.read();L(y),q.signal.throwIfAborted(),a(y);let I=y.accounts.find((n)=>n.id===J);if(!I||I.type!==U||!f(I,y,W))return A?.(!I||!l2(I)?"account-unavailable":"account-policy"),!1;if(U==="api"){let n=y.accounts.find((d)=>d.id==="main"&&d.type==="oauth");return!!n&&c2(n.quota,y.policyStorage)&&q0(n.quota)}return!0},a=(J)=>{let W=J.policyStorage.relay;if(W?.enabled===!0&&g$(W.transport,W.url)==="websocket")throw new R2},Y2=async(J,W)=>{if(a(J),W||J.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let U=await Z.getRelayConfig();if(!U)throw Error("request refused: native HTTP relay configuration is unavailable");if(U.transport!=="http")throw new R2;return{dispatch:{kind:"http-relay",url:U.url,token:U.token},relayFallback:U.fallbackToDirect}};async function j2(J,W,U){if(J.kind==="local"){let q=await Z.publishLocal(J.subject,U);if(!q&&U.quota)l$.warn("quota","Quota publication discarded");return q}if(J.kind==="vault"&&W.receipt)await Z.vault.publish(W.receipt,U);else if(J.kind==="api"&&U.lastUsed!==void 0)await Z.publishApi(J.subject,{lastUsed:U.lastUsed});return!0}function e(J,W,U){if(J.kind!=="local")return;let q=J.subject.binding,A=I1(U),y={lineage:c$(q),accountUuid:q.identity,entry:{quota:U,checkedAt:A,refreshAfter:A},generalExhausted:i$(U),routeBeforeSave:!0};return Z.quotaObservations.hold(W.account.id,y)?y:void 0}let u={async chooseAccount(J){let W=w(J);$.onOwnedRequest?.();let U=await Z.read();L(U),W.signal.throwIfAborted(),a(U);let q=U0(await $.resolveModelId?.(J)??J.modelID);if(W.signal.throwIfAborted(),U.mode==="claustrum")U=await r$(Z,W.signal),W.signal.throwIfAborted();if(U.policyStorage.quota?.enabled!==!1){let m=!1;for(let r of U.accounts){if(!l2(r)||r.type!=="oauth")continue;if(n$(r.quota)?c2(r.quota,U.policyStorage,Date.now(),q):Date.now()-I1(r.quota)<h$(U.policyStorage))continue;try{await Z.fetchQuota(r.id,$.fetch,W.signal,void 0,"admission"),m=!0}catch{W.signal.throwIfAborted()}}if(m)U=await Z.read();W.signal.throwIfAborted()}if(J.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(J.rerouteFrom.limit.reason))return;let A=[];for(let m of U.accounts){if(m.type!=="oauth"||!f(m,U,q))continue;if(m.source==="local"){let r=await Z.authorizeLocal(m.id,{signal:W.signal,policy:(l,M2)=>W0(l,M2,q)});if(W.signal.throwIfAborted(),r.status!=="usable")continue}A.push(m)}let y=Z5(J,U,A,q);if(y)return y;let I=A.filter((m)=>m.id!==J.rerouteFrom?.accountId);if(x0(U.policyStorage)==="sticky-balanced"){let m=I.map((l,M2)=>({accountId:l.id,order:M2,quota:l.quota??{kind:"unknown"}})),r=await M(U).resolve({sessionId:J.sessionID,family:$5(q),modelId:q,affinityModelId:J.modelID,candidates:m,retainAccountIds:new Set(I.map((l)=>l.id)),...U.mode==="claustrum"?{accountIdentities:new Map(U.accounts.flatMap((l)=>l.accountIdentity?[[l.id,l.accountIdentity]]:[]))}:{},storage:U.policyStorage,inputBytes:1,preferredAccountId:J.previousAccountId,preserveOnNoCandidate:!0});if(W.signal.throwIfAborted(),r)return r.accountId}else{let r=x0(U.policyStorage)==="fallback-first"?[...I.filter((l)=>l.id!=="main"),...I.filter((l)=>l.id==="main")]:[...I.filter((l)=>l.id==="main"),...I.filter((l)=>l.id!=="main")];if(r[0])return r[0].id}if(U.mode==="claustrum")throw new u$;let n=U.accounts.find((m)=>m.id==="main"&&m.type==="oauth");if(!n)return;let d=n.quota;if(J.rerouteFrom?.limit.status===429||!c2(d,U.policyStorage))try{d=await Z.fetchQuota("main",$.fetch,W.signal)}catch{return}if(W.signal.throwIfAborted(),!q0(d))return;return U.accounts.find((m)=>m.type==="api"&&l2(m)&&m.id!==J.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(J){let W=J.limit?.reason,U=W?O.get(W):void 0;if(!U||b(U.scope,U.accountId)!==b(J,J.accountId))return;O.delete(U.reason);let q=w(J),A=await Z.read();q.signal.throwIfAborted(),a(A);let y=U0(await $.resolveModelId?.(J)??J.modelID);q.signal.throwIfAborted();let I=A.accounts.find((m)=>m.id===J.accountId);if(!I||!v(I,U.account)||!f(I,A,y))return;let n=b(J,J.accountId),d=C.get(n)??[];return d.push(U),C.set(n,d),{accountId:J.accountId}},dropSameAccountRetry(J){let W=b(J,J.accountId),U=C.get(W),q=U?.findIndex((A)=>!J.limit||A.reason===J.limit.reason)??-1;if(q!==-1)U?.splice(q,1);if(U?.length===0)C.delete(W)},async authorizeAccount(J,W,U){let q=w(J),A=await Z.read();L(A),q.signal.throwIfAborted(),a(A);let y=U0(await $.resolveModelId?.(J)??J.modelID);q.signal.throwIfAborted();let I=A.accounts.find((s)=>s.id===W);if(!I||!f(I,A,y)){U?.(!I||!l2(I)?"account-unavailable":"account-policy");return}let n=b(J,W),d=C.get(n),m=d?.shift();if(d?.length===0)C.delete(n);if(m&&!v(I,m.account))return;let{dispatch:r,relayFallback:l}=await Y2(A,m?.direct===!0);if(q.signal.throwIfAborted(),m?.auth){if(!await i(W,y,m.auth.route,q,U))return;let s=_.get(m.auth.provenance);if(s?.receipt?.expiresAtMs!==void 0&&s.receipt.expiresAtMs!==null&&s.receipt.expiresAtMs<Date.now()+300000)return;if(s)_.set(m.auth.provenance,{...s,scope:{...J,modelID:y},account:I,active:q,relayFallback:l});return X.set(J.sessionID,W),{...m.auth,dispatch:r}}let M2={scope:{...J,modelID:y},active:q,account:I,retry:m?.retry??!1,relayFallback:l,quota:I.quota};if(I.type==="api"){let s=A.accounts.find((x)=>x.id==="main"&&x.type==="oauth");if(!s||!c2(s.quota,A.policyStorage)||!q0(s.quota))return;let G=await Z.authorizeApi(W,q.signal);if(q.signal.throwIfAborted(),!await i(W,y,"api",q))return;let K={kind:"api",subject:G.subject};return _.set(K,M2),X.set(J.sessionID,W),{route:"api",headers:G.authHeader==="authorization-bearer"?{authorization:`Bearer ${G.apiKey}`}:{"x-api-key":G.apiKey},baseURL:G.baseURL,provenance:K,dispatch:r}}if(I.source==="vault"){let s=await Z.authorizeVault(W,q.signal);if(q.signal.throwIfAborted(),m&&(s.credentialId!==m.account.credentialId||s.assertedAccountIdentity!==m.account.accountIdentity))return;if(!await i(W,y,"oauth",q,U))return;let G={kind:"vault",credentialId:s.credentialId,recordVersion:s.recordVersion};_.set(G,{...M2,receipt:s});let K=s.assertedAccountIdentity;if(!K){U?.("account-unavailable");return}return X.set(J.sessionID,W),{route:"oauth",accessToken:s.accessToken,provenance:G,dispatch:r,identity:Q0(K,K)}}let L2=await Z.authorizeLocal(W,{signal:q.signal,policy:(s,G)=>W0(s,G,y)});if(q.signal.throwIfAborted(),L2.status!=="usable"){let s=p$(L2);if(s)U?.(s.reason);return}if(!await i(W,y,"oauth",q,U))return;let x2={kind:"local",subject:L2.subject};_.set(x2,{...M2,access:L2.access}),X.set(J.sessionID,W);let y2=L2.subject.binding.identity;return{route:"oauth",accessToken:L2.access,provenance:x2,dispatch:r,identity:Q0(y2,y2)}},async requestOptions(J,W){let U=w(J),q=await Z.read();L(q),U.signal.throwIfAborted();let A=q.accounts.find((I)=>I.id===J.accountId);if(!A||!f(A,q,J.modelID))throw W?.(!A||!l2(A)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let y=_.get(J.provenance);if(y)_.set(J.provenance,{...y,scope:{...y.scope,modelID:J.modelID}});return $.requestOptions(J,q)},async admitRequest(J,W){let U=_.get(J.provenance);if(!U||!await i(J.accountId,J.modelID,J.route,U.active,W))throw Error("request refused: native account policy changed before dispatch");_.set(J.provenance,{...U,scope:{...U.scope,modelID:J.modelID}})},isDumpEnabled:()=>R(),onRequestPrepared:(J)=>$.onRequestPrepared?.(J),responseOptions(J){return $.responseOptions?.({...J,modelID:_.get(J.provenance)?.scope.modelID??J.modelID})},quotaFromHeaders(J,W){let U=_.get(W.provenance),q=y1(J);if(q)$.onRequestId?.(W,q);if(!U||W.route!=="oauth"||!m$(J))return;let A=W.provenance.kind==="local"?W.provenance.subject.binding.identity:U.receipt?.assertedAccountIdentity,y={...o$(J),...A?{accountIdentity:A}:{}},I=d$(U.quota,y);U.quota=I;let n=e(W.provenance,U,I),d=U.account.id,m=()=>{if(n)Z.quotaObservations.forget(d,n)};return V.observe(j2(W.provenance,U,{quota:I}).then((r)=>{if(!r)m()},(r)=>{throw m(),r})),y},async limitFromResponse(J){let W=_.get(J.provenance);if(!W)return;if(J.status===401&&W.receipt){if(!B.has(W.receipt))B.add(W.receipt),await Z.vault.reportFailure(W.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(W.retry||W.active.signal.aborted)return;let q=W.active,A=await Z.vault.prepareRetry(W.receipt,q.signal);if(q.signal.throwIfAborted(),!A.retry)return;let y=A.receipt,I=y.assertedAccountIdentity;if(!I)return;let n={kind:"vault",credentialId:y.credentialId,recordVersion:y.recordVersion};_.set(n,{...W,receipt:y,retry:!0});let d=`vault-newer:${J.attemptId}`;return O.set(d,{scope:E(J),reason:d,accountId:J.accountId,account:W.account,retry:!0,auth:{route:"oauth",accessToken:y.accessToken,provenance:n,identity:Q0(I,I)}}),F(),{reason:d,status:401}}if(J.status===401&&J.provenance.kind==="local"&&W.access&&!W.retry){if(W.active.signal.aborted)return;let q=W.active,A=await Z.authorizeLocal(J.accountId,{rejectedAccessToken:W.access,signal:q.signal,policy:(d,m)=>W0(d,m,W.scope.modelID)});if(q.signal.throwIfAborted(),A.status!=="usable"||A.access===W.access)return;let y={kind:"local",subject:A.subject};_.set(y,{...W,access:A.access,retry:!0});let I=A.subject.binding.identity,n=`local-newer:${J.attemptId}`;return O.set(n,{scope:E(J),reason:n,accountId:J.accountId,account:W.account,retry:!0,auth:{route:"oauth",accessToken:A.access,provenance:y,identity:Q0(I,I)}}),F(),{reason:n,status:401}}let U=await Z.read();if(t$(J.status,U.policyStorage))return{reason:`provider-${J.status}`,status:J.status};return},limitFromRelayFailure(J){let W=_.get(J.provenance);if(!W?.relayFallback||W.active.signal.aborted||!(J.status===401||J.status>=500))return;let U=`relay-direct:${J.attemptId}`;return O.set(U,{scope:E(J),reason:U,accountId:J.accountId,account:W.account,direct:!0,retry:!1}),F(),{reason:U}},limitFromStreamError(J){return J.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(J,W){let U=_.get(W.provenance);if(W.dispatch==="http-relay"&&U?.relayFallback&&!U.active.signal.aborted&&J.status===void 0){let q=`relay-direct:${W.attemptId}`;return O.set(q,{scope:E(W),reason:q,accountId:W.accountId,account:U.account,direct:!0,retry:!1}),F(),{reason:q}}return},async onAttemptEnd(J,W){let U=_.get(J.provenance);if(!U)return;try{if(W.status===401&&U.receipt&&!B.has(U.receipt))B.add(U.receipt),await Z.vault.reportFailure(U.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(!W.localRefusal&&W.status!==void 0)V.publish(()=>j2(J.provenance,U,{lastUsed:Date.now()}))}finally{_.delete(J.provenance)}},forgetSession(J){N.get(J)?.abort(),N.delete(J),X.delete(J);for(let[W,U]of O)if(U.scope.sessionID===J)O.delete(W);for(let[W,U]of C)if(U[0]?.scope.sessionID===J)C.delete(W);$.onForgetSession?.(J)},servedAccount:(J)=>X.get(J),resetRouting:async(J)=>M(await Z.read()).clear(J),async recordPrime(J,W){let U=_.get(J);if(!U||U.active.signal.aborted)return!1;if(J.kind==="local")return Z.incrementPrimeUsage(U.account.id,J.subject,W);if(J.kind==="vault"&&U.receipt)return Z.incrementPrimeUsage(U.account.id,U.receipt,W);return!1},drainRoutingPublications:()=>Promise.all([Z.drainRoutingPublications(),...[...Y.values()].map((J)=>J.drain())]).then(()=>{}),close(){z=!0;for(let J of N.values())J.abort();return N.clear(),C.clear(),O.clear(),Promise.all([V.drain(),u.drainRoutingPublications()]).then(()=>{})}};return u}import{remapModelId as j5}from"@cortexkit/anthropic-auth-core";function h1(){let $=new v1,Z=new Map,V=new Map,Y=new Map,M=new Set,_=new Set,O=new Map,C=(N)=>{while(N.size>512){let X=N.keys().next();if(!X.done)N.delete(X.value)}};return{async install(N){let X=[];try{X.push(await N.session.hook("context",(B)=>{let z=B.messages.map((L)=>{return{info:{id:L.id,sessionID:B.sessionID,role:L.role,agent:B.agent,model:{providerID:B.model.providerID,modelID:B.model.id}},parts:L.content.map((R)=>({type:R.type,...R.type==="text"?{text:R.text}:{}}))}});$.observeMessages(z);let F=B.messages.findLast((L)=>L.role==="user"&&L.id);if(F?.id)Z.set(B.sessionID,F.id);if(F?.content.some((L)=>L.type==="text"&&L.text===G0))M.add(B.sessionID);else M.delete(B.sessionID);C(Z)},{providerID:"anthropic"})),X.push(await N.session.hook("model.request",(B)=>{if(B.kind!=="primary")return;let z=Z.get(B.sessionID);if(!z)return;if($.markHeaders({sessionId:B.sessionID,messageId:z,agent:B.agent,headers:B.headers}),M.has(B.sessionID))B.headers[I2]="1"},{providerID:"anthropic"}))}catch(B){throw await Promise.allSettled(X.map((z)=>z.dispose())),B}return{dispose:async()=>{await Promise.all(X.map((B)=>B.dispose()))}}},requestOptions(N,X){let B=$.resolveHeader(N.correlation[t2]);if(B)V.set(N.attemptId,B),C(V);O.set(N.attemptId,N.sessionID),C(O);let z=N.correlation[I2]==="1";if(z)_.add(N.attemptId);return{cache1hEnabled:N.agent!=="compaction"&&N.agent!=="title"&&(X.policyStorage.claudeCache?.enabled??!0),cache1hMode:X.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:X.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:X.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:X.policyStorage.turnEndNote,serverSideFallbackEnabled:g1(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:z,billingLineage:B?{promptId:B.promptId,previousRequestId:B.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:Y.get(N.sessionID)}},responseOptions(N){return{serverSideFallbackModel:j5(N.modelID),laneStart:_.has(N.attemptId),onMessageStart(X){if(N.kind==="primary"&&typeof X.id==="string")Y.set(N.sessionID,X.id),C(Y)},onStreamEnd(){V.delete(N.attemptId),_.delete(N.attemptId),O.delete(N.attemptId)}}},onRequestId(N,X){$.commit(V.get(N.attemptId),X)},forgetSession(N){$.clearSession(N),Z.delete(N),Y.delete(N),M.delete(N);for(let[X,B]of O)if(B===N)V.delete(X),_.delete(X),O.delete(X)}}}var B0="cortexkit-anthropic-auth",P5='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',T5="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",C5="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function O5($){let Z=$.authorize??G5,V=$.exchange??W5,Y=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},M=async()=>{let C;try{C=await $.readMode()}catch{throw Error(C5)}return Y(),C},_=async()=>{if(await M()!=="local")throw Error(P5)};return{integrationID:"anthropic",methods:[{method:{id:Y0,type:"oauth",label:V0},async authorize(){Y(),await _();let C=await Z("max");return Y(),{mode:"code",url:C.url,instructions:"Paste the authorization code returned by Claude.",callback:async(N)=>{Y();let X=await V(N,C.verifier,C.redirectUri,C.state);if(!$.isActive()||X.type!=="success")throw Error("Claude sign-in did not complete");return{access:X.access,refresh:X.refresh,expires:X.expires}}}}}],vault:{method:{id:m1,type:"oauth",label:"Claude vault accounts"},async activate(){if(Y(),await M()!=="claustrum")throw Error(T5)}},async onLogin(C){Y(),await _(),await $.runtime.loginOAuth({routeId:"main",credential:C,replace:!0}),Y()},label:"Claude native account pool"}}function E5($){return{readMode:()=>M5("opencode",$),disconnectVault:()=>Q5({host:"opencode",env:$})}}function k0($={}){return{id:B0,setup:(Z)=>d1(Z,$)}}async function q5($){try{return await S5($)}catch(Z){throw x5(Z)}}function x5($){let Z=e2($);if(Z)return Z;let V=L5("decide where its account state is",[],$);return S0.error("state-layout",V.message,{code:V.code}),e2(V)??V}async function S5($){if($.paths){let V=$.paths;return await X5(V),{paths:V,holderRegistration:await K5({paths:V,role:"opencode2",kind:z5(),policy:F5(),onLockEvent:$.local?.onLockEvent})}}let Z=await V5({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await H5(void 0,void 0,Z.layout),holderRegistration:Z.kind==="state-home"?void 0:Z.registration}}async function d1($,Z={}){let{paths:V,holderRegistration:Y}=await q5(Z),M=J5({paths:V,host:"opencode",local:Z.local,vault:Z.vault}),_=E5(Z.vault?.env??process.env);try{let f=await M.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)_5(U5(f.policyStorage)??"info");N5(B5(f.policyStorage))}catch{}let O=!0,C=h1(),N=x1(),X,B,z,F=f1({runtime:M,paths:V,fetch:Z.fetch,requestOptions:C.requestOptions,responseOptions:C.responseOptions,onRequestId:C.onRequestId,onForgetSession:C.forgetSession,onRequestPrepared:async(f)=>{try{await z?.track(f)}catch{S0.warn("cachekeep","live request tracking failed")}},resolveModelId:async(f)=>N.modelId(f.modelID),onOwnedRequest:()=>{X??=N1(M,Z.fetch),B??=w1({runtime:M,paths:V,source:F,fetch:Z.fetch})}});z=M1({...Z.cacheKeep,runtime:M,source:F,storageId:V.storageId,fetch:Z.fetch,isSubagent:async(f)=>Boolean((await $.session.get({sessionID:f})).parentID)}),await z.ready;let L=q1({runtime:M,source:F,cacheKeepRegistry:z.registry,start:async(f,v)=>{await $.session.synthetic({sessionID:f,text:v,description:"Claude lane start",resume:!0})}}),R=[],E=await K1($,{source:F,log:{warn:(f,v)=>S0.warn("opencode2",f,v)}},{credential:S1}).catch(async(f)=>{throw Y?.close(),L.close(),await z?.dispose(),await F.close(),await M.drainQuotaPublications(),await M.close(),f}),b,w=()=>{if(b)return b;return O=!1,Y?.close(),L.close(),F.close(),b=(async()=>{await Promise.allSettled([E.dispose(),X?.dispose(),B?.dispose(),z?.dispose(),...R.map((f)=>f.dispose())]),await F.close(),await M.drainQuotaPublications(),await M.close()})(),b};try{R.push(await C.install($)),R.push(await N.install($)),R.push(await K0($,O5({isActive:()=>O,readMode:_.readMode,runtime:M})));let f={host:"opencode",dispatch:L.dispatch,readStatus:(i)=>L.readStatus(i),readAccounts:()=>M.read(),readMode:_.readMode,disconnectVault:_.disconnectVault,interactive:!0},v=Y5(f);return R.push(await l1($,v,L)),w}catch(f){throw await w(),f}}var Q8={id:B0,setup:k0().setup,server:u1};export{d1 as setupAnthropicAuth,Q8 as default,k0 as createAnthropicAuthPlugin,B0 as ANTHROPIC_AUTH_PLUGIN_ID};
|
|
14
|
+
Quota refresh checks the pool; it does not check OpenCode's Anthropic connection.`:S}if(G==="quota")return _$({accounts:B.accounts.filter((_)=>_.type==="oauth").map((_)=>({name:_.label??_.id,role:_.id==="main"?"main":"fallback",enabled:_.enabled,quota:_.quota,tierLabel:E$(_.profile),lastRefreshedAt:_.lastRefreshedAt,error:_.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(G==="prime")return F$({enabled:B.policyStorage.prime?.enabled===!0,accounts:L$(B.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(G==="cachekeep"){let _=await $.cacheKeepRegistry?.list()??[];return N$({enabled:R$(B.policyStorage),always:S$(B.policyStorage),hybridActive:k$(B.policyStorage),trackedSessionDetails:_,window:q$(B.policyStorage),trackedSessions:_.length,nextPrewarmAt:_.length?Math.min(..._.map((L)=>L.nextPrewarmAt)):void 0})}let K={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(B.settings[K[G]]??{})},async readSidebar(G){let[B,K]=await Promise.all([Z.read(),$.cacheKeepRegistry?.list()??[]]);return X0(T1(B,{activeId:Q.servedAccount(G),trackedSessions:K.length,now:Date.now()}))},forgetSession(G){Y.get(G)?.active.abort(),Y.delete(G)},close(){M=!0;for(let G of Y.values())G.active.abort();Y.clear()}}}import{resolveClaudeModelCapabilities as v$}from"@cortexkit/anthropic-auth-core";function x1(){let $=new Map;return{install:(Q)=>Q.model.transform((Y)=>{$.clear();for(let M of Y.list("anthropic")){$.set(String(M.id),String(M.modelID));let C=v$(M.modelID)?.efforts.variants;if(!C)continue;Y.update("anthropic",String(M.id),(q)=>{let T=q.variants.filter((H)=>!C.some((G)=>G===String(H.id)));q.variants=[...T,...C.map((H)=>({id:H,settings:{effort:H,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(Q)=>$.get(Q)??Q}}function S1($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as k1,effectiveRelayTransport as R1,nativeAccountCanServe as g$,PrimeManager as h$,tokenFingerprint as b1}from"@cortexkit/anthropic-auth-core";var A1=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function w1($){let{runtime:Z,source:Q}=$,Y=new AbortController,M=new Set,C=(H)=>({providerID:"anthropic",modelID:k1().model,sessionID:`oc2-prime:${H}`,agent:"prime",kind:"generate"}),q=async(H)=>{let G=C(H),B=h2({source:Q}),K=performance.now();try{for(let _=0;_<3;_++){if(Y.signal.throwIfAborted(),(await Z.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let S=await B.adapter.accountHeaders({...G,accountId:H});if(!("headers"in S)||typeof S.headers!=="object"||S.headers===null||typeof S.attempt!=="object"||S.attempt===null)throw Error("Native Prime authorization refused");let O={...G,accountId:H,attemptId:crypto.randomUUID(),transport:"http",data:S.attempt},b,w=!1,f=!1,y=(o)=>{f=!0,o.body?.cancel().catch(()=>{})};try{let o=await B.adapter.rewriteRequest?.({...G,accountId:H,attempt:O,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(k1()),signal:Y.signal})});if(!o)throw Error("Native Prime rewrite refused");let e=new Headers(o.headers);for(let[J,X]of Object.entries(S.headers))if(X===null)e.delete(J);else e.set(J,X);let Q2=new Request(o,{headers:e}),j2=await($.fetch??fetch)(Q2),$2=await B.adapter.rewriteResponse?.({...G,accountId:H,request:Q2,response:j2,attempt:O})??j2;b=$2.status,B.adapter.quotaFromHeaders?.($2.headers,$2.status,O);let p=$2.ok?void 0:await B.adapter.limitFromResponse?.({status:$2.status,headers:$2.headers,body:()=>$2.clone().text(),attempt:O});if(p&&/^(vault-newer|local-newer|relay-direct):/.test(p.reason)&&_<2){if(y($2),(await Q.retrySameAccount?.({...G,accountId:H,attempt:_+1,limit:p,error:{type:"api_error",message:"Native Prime credential retry",status:$2.status}}))?.accountId!==H)throw Error("Native Prime retry changed account");continue}if(!$2.ok)return y($2),{ok:!1,status:b,ms:performance.now()-K,error:"Native Prime upstream refused the request"};let l=A1(await $2.json()),r=A1(l.usage),Z2={inputTokens:typeof r.input_tokens==="number"?r.input_tokens:void 0,outputTokens:typeof r.output_tokens==="number"?r.output_tokens:void 0};if(O.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test($2.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(w=await Q.recordPrime(S.attempt.provenance,Z2),!w)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:b,ms:performance.now()-K,usage:Z2}}finally{await B.adapter.onAttemptEnd?.(O,{status:b,outputStarted:!1,...w?{}:{error:{reason:f?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-K}}finally{B.dispose()}},T=new h$({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await Z.read()).policyStorage,async getAccountFingerprint(H){let G=await Z.read(),B=G.accounts.find((L)=>L.id===H);if(!g$(B)||B?.type!=="oauth")return;if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")return;if(B.source==="vault"){let L=await Z.authorizeVault(H,Y.signal),S=await Z.getOrCreateAuthLineage(H,L);return S?b1(S):void 0}let K=await Z.authorizeLocal(H,{signal:Y.signal});if(K.status!=="usable")return;let _=await Z.getOrCreateAuthLineage(H,K.subject);return _?b1(_):void 0},async refreshQuota(H){let G=await Z.read();if(G.policyStorage.relay?.enabled===!0&&R1(G.policyStorage.relay.transport,G.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await Z.fetchQuota(H,$.fetch,Y.signal),fresh:!0}},sendPrime(H){let G=q(H);return M.add(G),G.finally(()=>M.delete(G)),G},async recordSuccess(H){let G=(await Z.read()).accounts.find((B)=>B.id===H);if(!G?.prime)throw Error("Native Prime counters are unavailable");return G.prime}});return T.start(),{manager:T,async dispose(){T.stop(),Y.abort(),await Promise.allSettled(M)}}}import{createNativeUsagePublisher as m$,decideStickyQuotaFailure as l$,effectiveRelayTransport as d$,getClaudeCodeIdentityForVerifiedAccount as Q0,getQuotaCheckIntervalMs as u$,getRoutingMode as x0,isDumpPersistentlyEnabled as D1,isQuotaBearingHeaderFrame as p$,logger as c$,mergeHeaderQuotaForPersistence as i$,NativeVaultNoAccountError as o$,nativeAccountCanServe as l2,nativeAccountPolicy as W0,nativeLocalAccountRefusal as n$,nativeLocalQuotaLineage as r$,nativePollQuotaGenerallyExhausted as s$,normalizeQuotaHeaders as a$,quotaSnapshotCheckedAt as I1,quotaSnapshotHasStandardWindows as t$,readNativeAccountsForRequest as e$,remapModelId as U0,StickySessionRouter as $6,setDumpEnabled as Z6,shouldFallbackStatus as j6,stickyQuotaSnapshotIsFresh as c2,stickyRetryAfterWithJitter as J6,stickyRouteFamilyForModel as y1}from"@cortexkit/anthropic-auth-core";var q0=($)=>["five_hour","seven_day"].some((Z)=>($?.[Z]?.remainingPercent??1)<=0);function X6($,Z,Q,Y){let M=$.rerouteFrom;if($.phase!=="retry"||M?.limit.status!==429||x0(Z.policyStorage)!=="sticky-balanced")return;let C=Q.find((T)=>T.id===M.accountId);if(!C||!c2(C.quota,Z.policyStorage,Date.now(),Y))return;let q=l$({quota:C.quota,modelId:Y});if(q.action!=="hold")return;return{hold:{delayMs:J6($.sessionID,q.retryAfterSeconds)*1000}}}function m1($){let{runtime:Z}=$,Q=m$("native-auth"),Y=h1(),M=new Set,C=new Map,q=(J)=>{let X=J.routingPath;if(!X)throw Error("Native routing storage is unavailable");let z=C.get(X);if(!z)z=new $6({path:X,vaultSeed:J.routingSeed,onLockEvent:Z.onLockEvent,relocationGuard:Z.relocationGuard,localRecoveryPath:J.mode==="local"?J.routingRecoveryPath:void 0}),C.set(X,z);return z.setVaultSeed(J.routingSeed),z},T=new WeakMap,H=new Map,G=new Map,B=new Map,K=new Map,_=new WeakSet,L=!1,S=()=>{while(H.size>512){let J=H.keys().next();if(!J.done)H.delete(J.value)}},O=(J)=>{try{Z6(D1(J.policyStorage))}catch{}},b=async()=>{try{let J=await Z.read();return O(J),D1(J.policyStorage)}catch{return!1}},w=(J)=>({providerID:J.providerID,sessionID:J.sessionID,kind:J.kind,modelID:J.modelID,agent:J.agent}),f=(J,X)=>JSON.stringify([J.providerID,J.sessionID,J.kind,J.modelID,J.agent,X]),y=(J)=>{if(L)throw Error("Native Anthropic source is closed");let X=B.get(J.sessionID);if(!X){X=new AbortController,B.set(J.sessionID,X);while(B.size>512){let z=B.keys().next();if(!z.done)Z2.forgetSession?.(z.value)}}return X},o=(J,X,z)=>l2(J)&&(J.type==="api"||W0(J,X,U0(z)).status==="allowed"),e=(J,X)=>J.source===X.source&&J.accountIdentity===X.accountIdentity&&J.credentialId===X.credentialId,Q2=async(J,X,z,R,I)=>{let A=await Z.read();O(A),R.signal.throwIfAborted(),j2(A);let m=A.accounts.find((d)=>d.id===J);if(!m||m.type!==z||!o(m,A,X))return I?.(!m||!l2(m)?"account-unavailable":"account-policy"),!1;if(z==="api"){let d=A.accounts.find((c)=>c.id==="main"&&c.type==="oauth");return!!d&&c2(d.quota,A.policyStorage)&&q0(d.quota)}return!0},j2=(J)=>{let X=J.policyStorage.relay;if(X?.enabled===!0&&d$(X.transport,X.url)==="websocket")throw new b2},$2=async(J,X)=>{if(j2(J),X||J.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let z=await Z.getRelayConfig();if(!z)throw Error("request refused: native HTTP relay configuration is unavailable");if(z.transport!=="http")throw new b2;return{dispatch:{kind:"http-relay",url:z.url,token:z.token},relayFallback:z.fallbackToDirect}};async function p(J,X,z){if(J.kind==="local"){let R=await Z.publishLocal(J.subject,z);if(!R&&z.quota)c$.warn("quota","Quota publication discarded");return R}if(J.kind==="vault"&&X.receipt)await Z.vault.publish(X.receipt,z);else if(J.kind==="api"&&z.lastUsed!==void 0)await Z.publishApi(J.subject,{lastUsed:z.lastUsed});return!0}function l(J,X,z){if(J.kind!=="local")return;let R=J.subject.binding,I=I1(z),A={lineage:r$(R),accountUuid:R.identity,entry:{quota:z,checkedAt:I,refreshAfter:I},generalExhausted:s$(z),routeBeforeSave:!0};return Z.quotaObservations.hold(X.account.id,A)?A:void 0}function r(J,X){if(X.exhaustionReported)return;X.exhaustionReported=!0,Y.report(J.sessionID,{accountIdentity:X.account.accountIdentity,credentialId:J.provenance.kind==="vault"?J.provenance.credentialId:X.account.credentialId},X.responseHeaders??new Headers,429,X.scope.modelID,!1)}let Z2={async chooseAccount(J){let X=y(J);$.onOwnedRequest?.();let z=await Z.read();O(z),X.signal.throwIfAborted(),j2(z);let R=U0(await $.resolveModelId?.(J)??J.modelID);if(X.signal.throwIfAborted(),z.mode==="claustrum")z=await e$(Z,X.signal),X.signal.throwIfAborted();if(z.policyStorage.quota?.enabled!==!1){let h=!1;for(let X2 of z.accounts){if(!l2(X2)||X2.type!=="oauth")continue;if(t$(X2.quota)?c2(X2.quota,z.policyStorage,Date.now(),R):Date.now()-I1(X2.quota)<u$(z.policyStorage))continue;try{await Z.fetchQuota(X2.id,$.fetch,X.signal,void 0,"admission"),h=!0}catch{X.signal.throwIfAborted()}}if(h)z=await Z.read();X.signal.throwIfAborted()}if(J.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(J.rerouteFrom.limit.reason))return;if(J.phase==="request")M.delete(J.sessionID);let I=await Y.accountFor(J.sessionID,R);if(X.signal.throwIfAborted(),I)z=await Z.read(),X.signal.throwIfAborted(),j2(z);let A=[];for(let h of z.accounts){if(h.type!=="oauth"||!o(h,z,R))continue;if(h.source==="local"){let X2=await Z.authorizeLocal(h.id,{signal:X.signal,policy:(a,J2)=>W0(a,J2,R)});if(X.signal.throwIfAborted(),X2.status!=="usable")continue}A.push(h)}if(I){let h=A.find((J2)=>v1(I,J2)),X2=A.map((J2,V)=>({accountId:J2.id,order:V,quota:J2.quota??{kind:"unknown"}})),a=!I.hold||J.phase==="retry"&&J.rerouteFrom?.accountId===h?.id;if(h&&a&&(I.hold||h.id!==J.rerouteFrom?.accountId)&&g1(h.id,X2,z.policyStorage,R)){let J2=await q(z).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:X2.filter((V)=>V.accountId===h.id),retainAccountIds:new Set([h.id]),...z.mode==="claustrum"?{accountIdentities:new Map([[h.id,I.account_id]])}:{},storage:z.policyStorage,inputBytes:1,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),J2)return I.hold?{hold:{delayMs:I.hold.retry_after_ms}}:J2.accountId}Y.override(J.sessionID,!a?"hold requires the same refused retry account":"unknown account, credential, account policy or Fable reserve")}let m=X6(J,z,A,R);if(m)return m;let d=A.filter((h)=>h.id!==J.rerouteFrom?.accountId);if(x0(z.policyStorage)==="sticky-balanced"){let h=d.map((a,J2)=>({accountId:a.id,order:J2,quota:a.quota??{kind:"unknown"}})),X2=await q(z).resolve({sessionId:J.sessionID,family:y1(R),modelId:R,affinityModelId:J.modelID,candidates:h,retainAccountIds:new Set(d.map((a)=>a.id)),...z.mode==="claustrum"?{accountIdentities:new Map(z.accounts.flatMap((a)=>a.accountIdentity?[[a.id,a.accountIdentity]]:[]))}:{},storage:z.policyStorage,inputBytes:1,preferredAccountId:J.previousAccountId,preserveOnNoCandidate:!0});if(X.signal.throwIfAborted(),X2)return X2.accountId}else{let X2=x0(z.policyStorage)==="fallback-first"?[...d.filter((a)=>a.id!=="main"),...d.filter((a)=>a.id==="main")]:[...d.filter((a)=>a.id==="main"),...d.filter((a)=>a.id!=="main")];if(X2[0])return X2[0].id}if(z.mode==="claustrum")throw new o$;let c=z.accounts.find((h)=>h.id==="main"&&h.type==="oauth");if(!c)return;let s=c.quota;if(J.rerouteFrom?.limit.status===429||!c2(s,z.policyStorage))try{s=await Z.fetchQuota("main",$.fetch,X.signal)}catch{return}if(X.signal.throwIfAborted(),!q0(s))return;return z.accounts.find((h)=>h.type==="api"&&l2(h)&&h.id!==J.rerouteFrom?.accountId)?.id},dropChoice(){},async retrySameAccount(J){let X=J.limit?.reason,z=X?H.get(X):void 0;if(!z||f(z.scope,z.accountId)!==f(J,J.accountId))return;H.delete(z.reason);let R=y(J),I=await Z.read();R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let m=I.accounts.find((s)=>s.id===J.accountId);if(!m||!e(m,z.account)||!o(m,I,A))return;let d=f(J,J.accountId),c=G.get(d)??[];return c.push(z),G.set(d,c),{accountId:J.accountId}},dropSameAccountRetry(J){let X=f(J,J.accountId),z=G.get(X),R=z?.findIndex((I)=>!J.limit||I.reason===J.limit.reason)??-1;if(R!==-1)z?.splice(R,1);if(z?.length===0)G.delete(X)},async authorizeAccount(J,X,z){let R=y(J),I=await Z.read();O(I),R.signal.throwIfAborted(),j2(I);let A=U0(await $.resolveModelId?.(J)??J.modelID);R.signal.throwIfAborted();let m=I.accounts.find((U)=>U.id===X);if(!m||!o(m,I,A)){z?.(!m||!l2(m)?"account-unavailable":"account-policy");return}let d=f(J,X),c=G.get(d),s=c?.shift();if(c?.length===0)G.delete(d);if(s&&!e(m,s.account))return;let{dispatch:h,relayFallback:X2}=await $2(I,s?.direct===!0);if(R.signal.throwIfAborted(),s?.auth){if(!await Q2(X,A,s.auth.route,R,z))return;let U=T.get(s.auth.provenance);if(U?.receipt?.expiresAtMs!==void 0&&U.receipt.expiresAtMs!==null&&U.receipt.expiresAtMs<Date.now()+300000)return;if(U)T.set(s.auth.provenance,{...U,scope:{...J,modelID:A},account:m,active:R,relayFallback:X2});return K.set(J.sessionID,X),{...s.auth,dispatch:h}}let a={scope:{...J,modelID:A},active:R,account:m,retry:s?.retry??!1,relayFallback:X2,quota:m.quota};if(m.type==="api"){let U=I.accounts.find((g)=>g.id==="main"&&g.type==="oauth");if(!U||!c2(U.quota,I.policyStorage)||!q0(U.quota))return;let E=await Z.authorizeApi(X,R.signal);if(R.signal.throwIfAborted(),!await Q2(X,A,"api",R))return;let x={kind:"api",subject:E.subject};return T.set(x,a),K.set(J.sessionID,X),{route:"api",headers:E.authHeader==="authorization-bearer"?{authorization:`Bearer ${E.apiKey}`}:{"x-api-key":E.apiKey},baseURL:E.baseURL,provenance:x,dispatch:h}}if(m.source==="vault"){let U=await Z.authorizeVault(X,R.signal);if(R.signal.throwIfAborted(),s&&(U.credentialId!==s.account.credentialId||U.assertedAccountIdentity!==s.account.accountIdentity))return;if(!await Q2(X,A,"oauth",R,z))return;let E={kind:"vault",credentialId:U.credentialId,recordVersion:U.recordVersion};T.set(E,{...a,receipt:U});let x=U.assertedAccountIdentity;if(!x){z?.("account-unavailable");return}return K.set(J.sessionID,X),{route:"oauth",accessToken:U.accessToken,provenance:E,dispatch:h,identity:Q0(x,x)}}let J2=await Z.authorizeLocal(X,{signal:R.signal,policy:(U,E)=>W0(U,E,A)});if(R.signal.throwIfAborted(),J2.status!=="usable"){let U=n$(J2);if(U)z?.(U.reason);return}if(!await Q2(X,A,"oauth",R,z))return;let V={kind:"local",subject:J2.subject};T.set(V,{...a,access:J2.access}),K.set(J.sessionID,X);let N=J2.subject.binding.identity;return{route:"oauth",accessToken:J2.access,provenance:V,dispatch:h,identity:Q0(N,N)}},async requestOptions(J,X){let z=y(J),R=await Z.read();O(R),z.signal.throwIfAborted();let I=R.accounts.find((m)=>m.id===J.accountId);if(!I||!o(I,R,J.modelID))throw X?.(!I||!l2(I)?"account-unavailable":"account-policy"),Error("request refused: native account is ineligible for this model");let A=T.get(J.provenance);if(A)T.set(J.provenance,{...A,scope:{...A.scope,modelID:J.modelID}});return $.requestOptions(J,R)},async admitRequest(J,X){let z=T.get(J.provenance);if(!z||!await Q2(J.accountId,J.modelID,J.route,z.active,X))throw Error("request refused: native account policy changed before dispatch");T.set(J.provenance,{...z,scope:{...z.scope,modelID:J.modelID}})},isDumpEnabled:()=>b(),onRequestPrepared:(J)=>$.onRequestPrepared?.(J),responseOptions(J){return $.responseOptions?.({...J,modelID:T.get(J.provenance)?.scope.modelID??J.modelID})},quotaFromHeaders(J,X){let z=T.get(X.provenance);if(z){z.responseHeaders=J;let h=X.status<400&&!M.has(X.sessionID);if(h)M.add(X.sessionID);if(X.status===429)r(X,z);else Y.report(X.sessionID,{accountIdentity:z.account.accountIdentity,credentialId:X.provenance.kind==="vault"?X.provenance.credentialId:z.account.credentialId},J,X.status,z.scope.modelID,h)}let R=f1(J);if(R)$.onRequestId?.(X,R);if(!z||X.route!=="oauth"||!p$(J))return;let I=X.provenance.kind==="local"?X.provenance.subject.binding.identity:z.receipt?.assertedAccountIdentity,A={...a$(J),...I?{accountIdentity:I}:{}},m=i$(z.quota,A);z.quota=m;let d=l(X.provenance,z,m),c=z.account.id,s=()=>{if(d)Z.quotaObservations.forget(c,d)};return Q.observe(p(X.provenance,z,{quota:m}).then((h)=>{if(!h)s()},(h)=>{throw s(),h})),A},async limitFromResponse(J){let X=T.get(J.provenance);if(!X)return;if(J.status===401&&X.receipt){if(!_.has(X.receipt))_.add(X.receipt),await Z.vault.reportFailure(X.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(X.retry||X.active.signal.aborted)return;let R=X.active,I=await Z.vault.prepareRetry(X.receipt,R.signal);if(R.signal.throwIfAborted(),!I.retry)return;let A=I.receipt,m=A.assertedAccountIdentity;if(!m)return;let d={kind:"vault",credentialId:A.credentialId,recordVersion:A.recordVersion};T.set(d,{...X,receipt:A,retry:!0});let c=`vault-newer:${J.attemptId}`;return H.set(c,{scope:w(J),reason:c,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:A.accessToken,provenance:d,identity:Q0(m,m)}}),S(),{reason:c,status:401}}if(J.status===401&&J.provenance.kind==="local"&&X.access&&!X.retry){if(X.active.signal.aborted)return;let R=X.active,I=await Z.authorizeLocal(J.accountId,{rejectedAccessToken:X.access,signal:R.signal,policy:(c,s)=>W0(c,s,X.scope.modelID)});if(R.signal.throwIfAborted(),I.status!=="usable"||I.access===X.access)return;let A={kind:"local",subject:I.subject};T.set(A,{...X,access:I.access,retry:!0});let m=I.subject.binding.identity,d=`local-newer:${J.attemptId}`;return H.set(d,{scope:w(J),reason:d,accountId:J.accountId,account:X.account,retry:!0,auth:{route:"oauth",accessToken:I.access,provenance:A,identity:Q0(m,m)}}),S(),{reason:d,status:401}}let z=await Z.read();if(j6(J.status,z.policyStorage))return{reason:`provider-${J.status}`,status:J.status};return},limitFromRelayFailure(J){let X=T.get(J.provenance);if(!X?.relayFallback||X.active.signal.aborted||!(J.status===401||J.status>=500))return;let z=`relay-direct:${J.attemptId}`;return H.set(z,{scope:w(J),reason:z,accountId:J.accountId,account:X.account,direct:!0,retry:!1}),S(),{reason:z}},limitFromStreamError(J){let X=T.get(J.provenance);if(X&&J.errorType==="rate_limit_error")r(J,X);return J.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(J,X){let z=T.get(X.provenance);if(X.dispatch==="http-relay"&&z?.relayFallback&&!z.active.signal.aborted&&J.status===void 0){let R=`relay-direct:${X.attemptId}`;return H.set(R,{scope:w(X),reason:R,accountId:X.accountId,account:z.account,direct:!0,retry:!1}),S(),{reason:R}}return},async onAttemptEnd(J,X){let z=T.get(J.provenance);if(!z)return;try{if(X.status===401&&z.receipt&&!_.has(z.receipt))_.add(z.receipt),await Z.vault.reportFailure(z.receipt,401,J.dispatch==="http-relay"?"relay_status_field":"direct");if(!X.localRefusal&&X.status!==void 0)Q.publish(()=>p(J.provenance,z,{lastUsed:Date.now()}))}finally{T.delete(J.provenance)}},forgetSession(J){M.delete(J),B.get(J)?.abort(),B.delete(J),K.delete(J);for(let[X,z]of H)if(z.scope.sessionID===J)H.delete(X);for(let[X,z]of G)if(z[0]?.scope.sessionID===J)G.delete(X);$.onForgetSession?.(J)},servedAccount:(J)=>K.get(J),resetRouting:async(J)=>q(await Z.read()).clear(J),async recordPrime(J,X){let z=T.get(J);if(!z||z.active.signal.aborted)return!1;if(J.kind==="local")return Z.incrementPrimeUsage(z.account.id,J.subject,X);if(J.kind==="vault"&&z.receipt)return Z.incrementPrimeUsage(z.account.id,z.receipt,X);return!1},drainRoutingPublications:()=>Promise.all([Z.drainRoutingPublications(),...[...C.values()].map((J)=>J.drain())]).then(()=>{}),close(){L=!0;for(let J of B.values())J.abort();return B.clear(),G.clear(),H.clear(),Promise.all([Q.drain(),Z2.drainRoutingPublications()]).then(()=>{})}};return Z2}import{remapModelId as G6}from"@cortexkit/anthropic-auth-core";function u1(){let $=new l1,Z=new Map,Q=new Map,Y=new Map,M=new Set,C=new Set,q=new Map,T=(H)=>{while(H.size>512){let G=H.keys().next();if(!G.done)H.delete(G.value)}};return{async install(H){let G=[];try{G.push(await H.session.hook("context",(B)=>{let K=B.messages.map((L)=>{return{info:{id:L.id,sessionID:B.sessionID,role:L.role,agent:B.agent,model:{providerID:B.model.providerID,modelID:B.model.id}},parts:L.content.map((S)=>({type:S.type,...S.type==="text"?{text:S.text}:{}}))}});$.observeMessages(K);let _=B.messages.findLast((L)=>L.role==="user"&&L.id);if(_?.id)Z.set(B.sessionID,_.id);if(_?.content.some((L)=>L.type==="text"&&L.text===G0))M.add(B.sessionID);else M.delete(B.sessionID);T(Z)},{providerID:"anthropic"})),G.push(await H.session.hook("model.request",(B)=>{if(B.kind!=="primary")return;let K=Z.get(B.sessionID);if(!K)return;if($.markHeaders({sessionId:B.sessionID,messageId:K,agent:B.agent,headers:B.headers}),M.has(B.sessionID))B.headers[y2]="1"},{providerID:"anthropic"}))}catch(B){throw await Promise.allSettled(G.map((K)=>K.dispose())),B}return{dispose:async()=>{await Promise.all(G.map((B)=>B.dispose()))}}},requestOptions(H,G){let B=$.resolveHeader(H.correlation[t2]);if(B)Q.set(H.attemptId,B),T(Q);q.set(H.attemptId,H.sessionID),T(q);let K=H.correlation[y2]==="1";if(K)C.add(H.attemptId);return{cache1hEnabled:H.agent!=="compaction"&&H.agent!=="title"&&(G.policyStorage.claudeCache?.enabled??!0),cache1hMode:G.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:G.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:G.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:G.policyStorage.turnEndNote,serverSideFallbackEnabled:d1(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:K,billingLineage:B?{promptId:B.promptId,previousRequestId:B.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:Y.get(H.sessionID)}},responseOptions(H){return{serverSideFallbackModel:G6(H.modelID),laneStart:C.has(H.attemptId),onMessageStart(G){if(H.kind==="primary"&&typeof G.id==="string")Y.set(H.sessionID,G.id),T(Y)},onStreamEnd(){Q.delete(H.attemptId),C.delete(H.attemptId),q.delete(H.attemptId)}}},onRequestId(H,G){$.commit(Q.get(H.attemptId),G)},forgetSession(H){$.clearSession(H),Z.delete(H),Y.delete(H),M.delete(H);for(let[G,B]of q)if(B===H)Q.delete(G),C.delete(G),q.delete(G)}}}var B0="cortexkit-anthropic-auth",O6='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',E6="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",q6="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function x6($){let Z=$.authorize??Q6,Q=$.exchange??z6,Y=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},M=async()=>{let T;try{T=await $.readMode()}catch{throw Error(q6)}return Y(),T},C=async()=>{if(await M()!=="local")throw Error(O6)};return{integrationID:"anthropic",methods:[{method:{id:Y0,type:"oauth",label:V0},async authorize(){Y(),await C();let T=await Z("max");return Y(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(H)=>{Y();let G=await Q(H,T.verifier,T.redirectUri,T.state);if(!$.isActive()||G.type!=="success")throw Error("Claude sign-in did not complete");return{access:G.access,refresh:G.refresh,expires:G.expires}}}}}],vault:{method:{id:p1,type:"oauth",label:"Claude vault accounts"},async activate(){if(Y(),await M()!=="claustrum")throw Error(E6)}},async onLogin(T){Y(),await C(),await $.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),Y()},label:"Claude native account pool"}}function S6($){return{readMode:()=>N6("opencode",$),disconnectVault:()=>B6({host:"opencode",env:$})}}function k0($={}){return{id:B0,setup:(Z)=>i1(Z,$)}}async function k6($){try{return await b6($)}catch(Z){throw R6(Z)}}function R6($){let Z=e2($);if(Z)return Z;let Q=T6("decide where its account state is",[],$);return S0.error("state-layout",Q.message,{code:Q.code}),e2(Q)??Q}async function b6($){if($.paths){let Q=$.paths;return await V6(Q),{paths:Q,holderRegistration:await _6({paths:Q,role:"opencode2",kind:H6(),policy:C6(),onLockEvent:$.local?.onLockEvent})}}let Z=await U6({role:"opencode2",onLockEvent:$.local?.onLockEvent});return{paths:await L6(void 0,void 0,Z.layout),holderRegistration:Z.kind==="state-home"?void 0:Z.registration}}async function i1($,Z={}){let{paths:Q,holderRegistration:Y}=await k6(Z),M=Y6({paths:Q,host:"opencode",local:Z.local,vault:Z.vault}),C=S6(Z.vault?.env??process.env);try{let f=await M.read();if(!process.env.OPENCODE_ANTHROPIC_AUTH_LOG_LEVEL)P6(K6(f.policyStorage)??"info");F6(M6(f.policyStorage))}catch{}let q=!0,T=u1(),H=x1(),G,B,K,_=m1({runtime:M,paths:Q,fetch:Z.fetch,requestOptions:T.requestOptions,responseOptions:T.responseOptions,onRequestId:T.onRequestId,onForgetSession:T.forgetSession,onRequestPrepared:async(f)=>{try{await K?.track(f)}catch{S0.warn("cachekeep","live request tracking failed")}},resolveModelId:async(f)=>H.modelId(f.modelID),onOwnedRequest:()=>{G??=N1(M,Z.fetch),B??=w1({runtime:M,paths:Q,source:_,fetch:Z.fetch})}});K=K1({...Z.cacheKeep,runtime:M,source:_,storageId:Q.storageId,fetch:Z.fetch,isSubagent:async(f)=>Boolean((await $.session.get({sessionID:f})).parentID)}),await K.ready;let L=q1({runtime:M,source:_,cacheKeepRegistry:K.registry,start:async(f,y)=>{await $.session.synthetic({sessionID:f,text:y,description:"Claude lane start",resume:!0})}}),S=[],O=await M1($,{source:_,log:{warn:(f,y)=>S0.warn("opencode2",f,y)}},{credential:S1}).catch(async(f)=>{throw Y?.close(),L.close(),await K?.dispose(),await _.close(),await M.drainQuotaPublications(),await M.close(),f}),b,w=()=>{if(b)return b;return q=!1,Y?.close(),L.close(),_.close(),b=(async()=>{await Promise.allSettled([O.dispose(),G?.dispose(),B?.dispose(),K?.dispose(),...S.map((f)=>f.dispose())]),await _.close(),await M.drainQuotaPublications(),await M.close()})(),b};try{S.push(await T.install($)),S.push(await H.install($)),S.push(await M0($,x6({isActive:()=>q,readMode:C.readMode,runtime:M})));let f={host:"opencode",dispatch:L.dispatch,readStatus:(o)=>L.readStatus(o),readAccounts:()=>M.read(),readMode:C.readMode,disconnectVault:C.disconnectVault,interactive:!0},y=W6(f);return S.push(await c1($,y,L)),w}catch(f){throw await w(),f}}var z8={id:B0,setup:k0().setup,server:o1};export{i1 as setupAnthropicAuth,z8 as default,k0 as createAnthropicAuthPlugin,B0 as ANTHROPIC_AUTH_PLUGIN_ID};
|
package/dist/v2/tui.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{x as q}from"../index-eq1kbq5z.js";import"../index-d4e8qj37.js";import"../index-n8xr16kr.js";var N="Open this link in your browser and sign in. Then choose Finish OAuth sign-in in the Accounts menu and paste the code Claude shows you.";async function g(D,M={}){let B=D.client.rpc(q),Z=!0,V=!1,Y=new AbortController,$=()=>{let j=D.ui.router.current();return j.type==="session"?j.sessionID:void 0};function C(j){return new Promise((Q)=>{let z="",J=!1,G=D.keymap.mode.push("cortexkit-protected-entry"),X=(H,W=!0)=>{if(J)return;J=!0,D.renderer.keyInput.off("keypress",O),D.renderer.keyInput.off("paste",P),Y.signal.removeEventListener("abort",K),G();let F=H?z:void 0;if(z="",W)D.ui.dialog.clear();Q(F)},K=()=>X(!1),O=(H)=>{if(H.preventDefault(),H.stopPropagation(),H.name==="escape"||H.ctrl&&H.name==="c")return X(!1);if(H.name==="return"||H.name==="enter")return X(!0);if(H.name==="backspace"){z=Array.from(z).slice(0,-1).join("");return}if(!H.ctrl&&!H.meta&&!H.option&&Array.from(H.sequence).every((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127))z=(z+H.sequence).slice(0,4096)},P=(H)=>{H.preventDefault(),H.stopPropagation(),z=(z+Array.from(new TextDecoder().decode(H.bytes)).filter((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127).join("")).slice(0,4096)};if(D.renderer.keyInput.prependListener("keypress",O),D.renderer.keyInput.prependListener("paste",P),Y.signal.addEventListener("abort",K,{once:!0}),D.ui.dialog.alert({title:j,message:"Type or paste the value. Input is hidden. Enter accepts; Escape cancels."}).then(()=>X(!1,!1),()=>X(!1,!1)),Y.signal.aborted)K()})}async function E(j){let Q={};for(let z of j.knobs){if(!Z)return;if(z.kind==="choice"){let J=await D.ui.dialog.select({title:z.label,options:z.choices.map((G)=>({title:G.label,value:G.value})),current:z.value});if(J===void 0)return;Q[z.id]=J}else if(z.kind==="toggle"){let J=await D.ui.dialog.select({title:z.label,options:[{title:"On",value:!0},{title:"Off",value:!1}],current:z.value});if(J===void 0)return;Q[z.id]=J}else{let J=z.kind==="text"&&z.masked?await C(z.label):await D.ui.dialog.prompt({title:z.label,value:z.value===void 0?void 0:String(z.value),placeholder:z.kind==="text"?z.placeholder:void 0});if(J===void 0)return;Q[z.id]=J===""&&!z.required?null:z.kind==="number"?Number(J):J}}return Q}async function A(j){if(M.showSignInLink)try{await M.showSignInLink(D,j,Y.signal);return}catch{}await D.ui.dialog.alert({title:"Claude sign-in",message:`${N}
|
|
2
2
|
|
|
3
3
|
${j}
|
|
4
4
|
`})}async function T(j,Q){let z=`${Q.title} status`;if(M.showStatus)try{await M.showStatus(D,{title:z,lines:Q.lines,...Q.slot==="quota"&&{readQuota:(J)=>B.sidebar({sessionId:j},{signal:J,location:D.location})}},Y.signal);return}catch{}await D.ui.dialog.alert({title:z,message:Q.lines.join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/opencode-anthropic-auth",
|
|
3
|
-
"version": "2.4.
|
|
3
|
+
"version": "2.4.6",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -77,7 +77,7 @@
|
|
|
77
77
|
},
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"@clack/prompts": "^1.6.0",
|
|
80
|
-
"@cortexkit/anthropic-auth-core": "2.4.
|
|
80
|
+
"@cortexkit/anthropic-auth-core": "2.4.6",
|
|
81
81
|
"@cortexkit/claustrum-client": "0.13.0",
|
|
82
82
|
"@cortexkit/private-files": "0.2.2",
|
|
83
83
|
"@cortexkit/subc-client": "^0.22.10",
|
package/dist/index-61bbefpq.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{J as M}from"./index-j2cv839v.js";import{logger as R}from"@cortexkit/anthropic-auth-core";var K=(f)=>f!==null&&typeof f==="object"&&!Array.isArray(f),X=(f)=>K(f)&&typeof f.sessionId==="string"&&f.sessionId.length>0,U=(f)=>{if(!X(f)||!K(f)||f.command!=="claude"||typeof f.sectionId!=="string"||typeof f.actionId!=="string")return!1;if(f.itemId!==void 0&&typeof f.itemId!=="string")return!1;if(f.confirmed!==void 0&&typeof f.confirmed!=="boolean")return!1;if(f.values!==void 0&&(!K(f.values)||!Object.values(f.values).every((j)=>j===null||typeof j==="string"||typeof j==="boolean"||typeof j==="number"&&Number.isFinite(j))))return!1;return!0};function H(f){return{"~standard":{version:1,vendor:"cortexkit-native",validate:(j)=>f(j)?{value:j}:{issues:[{message:"Invalid native menu payload"}]}}}}var A=(f)=>K(f)&&f.command==="claude"&&K(f.menu)&&f.menu.command==="claude"&&typeof f.menu.title==="string"&&Array.isArray(f.menu.sections),V=(f)=>K(f)&&f.command==="claude"&&typeof f.ok==="boolean"&&typeof f.text==="string"&&(f.authorizationUrl===void 0||typeof f.authorizationUrl==="string")&&K(f.menu)&&Array.isArray(f.menu.sections),L=!1,$=(f,j,B=new Set)=>{if(f===null||typeof f==="string"||typeof f==="boolean")return f;if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="object"&&f!==null&&!B.has(f)){if(B.add(f),Array.isArray(f)){let Q=Array.from(f,(D,G)=>$(D,`${j}[${G}]`,B)??null);return B.delete(f),Q}if(Object.getPrototypeOf(f)===Object.prototype||Object.getPrototypeOf(f)===null){let Q=Object.fromEntries(Object.entries(f).flatMap(([D,G])=>{let W=$(G,`${j}.${D}`,B);return W===void 0?[]:[[D,W]]}));return B.delete(f),Q}B.delete(f)}if(!L)L=!0,R.warn("sidebar","Dropped non-JSON sidebar field",{path:j});return},E={"~standard":{version:1,vendor:"cortexkit-native",validate:(f)=>{let j=M(f);return{value:$(j,"sidebar")}}}},F={id:"cortexkit-anthropic-native",methods:{open:{input:H(X),output:H(A)},apply:{input:H(U),output:H(V)},sidebar:{input:H(X),output:E}},events:{opened:{schema:H((f)=>X(f)&&A(f.payload))},notification:{schema:H((f)=>X(f)&&typeof f.message==="string"&&["info","warning","error"].includes(String(f.kind)))}}};async function T(f,j,B){let Q=new AbortController,D=(q)=>({sessionId:q,notify(Y,Z="info"){G.events.emit("notification",{sessionId:q,message:Y,kind:Z}).catch(()=>{})}}),G=await f.rpc.register(F,{open:(q)=>j.open(D(q.sessionId)),apply:(q)=>j.apply(q,D(q.sessionId)),sidebar:(q)=>B.readSidebar(q.sessionId)}),W;try{W=await f.command.transform((q)=>q.add({name:"claude",description:"Native Claude accounts and settings",async execute(Y){let Z=await j.open(D(Y.sessionID));await G.events.emit("opened",{sessionId:Y.sessionID,payload:Z})}}))}catch(q){throw await G.dispose(),q}let P=(async()=>{try{for await(let q of f.event.subscribe({signal:Q.signal}))if(q.type==="session.deleted")B.forgetSession(q.data.sessionID)}catch{}})(),z=!1;return{async dispose(){if(z)return;z=!0,Q.abort(),await Promise.all([G.dispose(),W.dispose(),P])}}}
|
|
2
|
-
export{F as u,T as v};
|