@cortexkit/opencode-anthropic-auth 2.2.0 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v2/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import{a as O2,b as q$,c as D$,d as e2,e as $$,f as E2,g as L2,h as X$,i as J$,j as b$,k as Z$,l as Y$,m as W$,n as G$,o as j$,p as m$}from"../index-ccrq4mra.js";import"../index-6chd6jnr.js";import"../index-hazrk5c3.js";import{u as v$}from"../index-pden7a7y.js";import{v as I$,w as f$,y as g$}from"../index-0kxy8k2c.js";import"../index-b1dvkp15.js";import"../index-czyrqpxc.js";import"../index-ah5s0bew.js";import"../index-f2ne65w4.js";import{acquireNativeAccountRuntime as NX,authorize as LX,createNativeUi as PX,disconnectNativeVaultForHost as FX,exchange as TX,logger as y$,readNativeEnrollmentMode as OX,resolveNativePoolPaths as EX}from"@cortexkit/anthropic-auth-core";class _2 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 Q2($){return`common-auth-placeholder.${$}`}function i2($){let X=Q2($.integrationID);return{type:"oauth",methodID:$.methodID,access:X,refresh:X,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function q2($,X){if($?.type!=="oauth")return!1;let z=X===void 0?void 0:Q2(X),G=(N)=>z===void 0?N.startsWith("common-auth-placeholder."):N===z;return G($.access)&&G($.refresh)}var c2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function k2($,X){let z=X.now??Date.now,{integrationID:G}=X,N=(T)=>i2({integrationID:G,methodID:T,now:z()}),L=async(T,K)=>{return await X.onLogin(T,{integrationID:G,methodID:K}),N(K)},P=(T)=>async(K)=>{let Y=T.method.id,H=await T.authorize(K),V={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...V,mode:"auto",callback:H.callback.then((O)=>L(O,Y))};let B=H.callback;return{...V,mode:"code",callback:async(O)=>L(await B(O),Y)}};return $.integration.transform((T)=>{let K=X.label===void 0?{}:{label:()=>X.label};for(let V of X.methods)T.method.update({integrationID:G,method:V.method,authorize:P(V),refresh:async(B)=>{if(!q2(B,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return N(B.methodID)},...K});let Y=X.vault;if(Y===void 0)return;let H=Y.method.id;T.method.update({integrationID:G,method:Y.method,authorize:async()=>({url:"",instructions:Y.instructions??c2,mode:"auto",callback:Promise.resolve().then(()=>Y.activate({integrationID:G,methodID:H})).then(()=>N(H))}),refresh:async(V)=>{if(!q2(V,G)||V.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return N(H)},...K})})}function l$($){let X=[],z;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))X.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))z=G.slice(6).trim();if(X.length===0)return;return z===void 0?{data:X.join(`
1
+ import{a as O2,b as q$,c as D$,d as e2,e as $$,f as E2,g as L2,h as X$,i as J$,j as b$,k as Z$,l as Y$,m as W$,n as G$,o as j$,p as m$}from"../index-8ysjtqek.js";import"../index-6chd6jnr.js";import"../index-hazrk5c3.js";import{u as v$}from"../index-88zg9ztr.js";import{v as I$,w as f$,y as g$}from"../index-0kxy8k2c.js";import"../index-b1dvkp15.js";import"../index-xbwa4x53.js";import"../index-ppdrzs41.js";import"../index-62x1p34p.js";import{acquireNativeAccountRuntime as NX,authorize as LX,createNativeUi as PX,disconnectNativeVaultForHost as FX,exchange as TX,logger as y$,readNativeEnrollmentMode as OX,resolveNativePoolPaths as EX}from"@cortexkit/anthropic-auth-core";class _2 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 Q2($){return`common-auth-placeholder.${$}`}function i2($){let X=Q2($.integrationID);return{type:"oauth",methodID:$.methodID,access:X,refresh:X,expires:$.now+31536000000,metadata:{["commonAuthPlaceholder"]:!0}}}function q2($,X){if($?.type!=="oauth")return!1;let z=X===void 0?void 0:Q2(X),G=(N)=>z===void 0?N.startsWith("common-auth-placeholder."):N===z;return G($.access)&&G($.refresh)}var c2="No browser sign-in: this connects the plugin to the accounts in its vault.";async function k2($,X){let z=X.now??Date.now,{integrationID:G}=X,N=(T)=>i2({integrationID:G,methodID:T,now:z()}),L=async(T,K)=>{return await X.onLogin(T,{integrationID:G,methodID:K}),N(K)},P=(T)=>async(K)=>{let Y=T.method.id,H=await T.authorize(K),V={url:H.url,instructions:H.instructions,...H.expiresAt===void 0?{}:{expiresAt:H.expiresAt}};if(H.mode==="auto")return{...V,mode:"auto",callback:H.callback.then((O)=>L(O,Y))};let B=H.callback;return{...V,mode:"code",callback:async(O)=>L(await B(O),Y)}};return $.integration.transform((T)=>{let K=X.label===void 0?{}:{label:()=>X.label};for(let V of X.methods)T.method.update({integrationID:G,method:V.method,authorize:P(V),refresh:async(B)=>{if(!q2(B,G))throw Error("This login method refreshes only its pool placeholder; sign in again with the plugin's login method.");return N(B.methodID)},...K});let Y=X.vault;if(Y===void 0)return;let H=Y.method.id;T.method.update({integrationID:G,method:Y.method,authorize:async()=>({url:"",instructions:Y.instructions??c2,mode:"auto",callback:Promise.resolve().then(()=>Y.activate({integrationID:G,methodID:H})).then(()=>N(H))}),refresh:async(V)=>{if(!q2(V,G)||V.methodID!==H)throw Error("This login method refreshes only its vault placeholder; choose the plugin's vault login method again.");return N(H)},...K})})}function l$($){let X=[],z;for(let G of $.split(/\r?\n/))if(G.startsWith("data:"))X.push(G.slice(5).replace(/^ /,""));else if(G.startsWith("event:"))z=G.slice(6).trim();if(X.length===0)return;return z===void 0?{data:X.join(`
2
2
  `)}:{event:z,data:X.join(`
3
3
  `)}}function D2($,X){let z=new TextDecoder,G="",N=(P)=>{let T=l$(P);if(!T)return;try{$(T)}catch(K){X(K)}},L=()=>{for(;;){let P=/\r?\n\r?\n/.exec(G);if(!P)return;let T=G.slice(0,P.index);G=G.slice(P.index+P[0].length),N(T)}};return new TransformStream({transform(P,T){T.enqueue(P),G+=z.decode(P,{stream:!0}),L()},flush(){if(G+=z.decode(),L(),G.trim()!=="")N(G);G=""}})}var o2=512,H2="x-common-auth-attempt",U2=($,X)=>JSON.stringify([$,X]),G2=($)=>({providerID:$.model.providerID,modelID:$.model.id,sessionID:$.sessionID,agent:$.agent,kind:$.kind});function d$($){let X=$.headers;return typeof X==="object"&&X!==null}function p$($,X){let z=$.getReader();return new ReadableStream({async pull(G){let N;try{N=await z.read()}catch(L){X({reason:"failed",message:L instanceof Error?L.message:String(L)}),G.error(L);return}if(N.done)X(),G.close();else G.enqueue(N.value)},async cancel(G){X({reason:"cancelled",...G===void 0?{}:{message:String(G)}}),await z.cancel(G)}})}function b2($,X){for(let[z,G]of Object.entries(X)){let N=z.toLowerCase();for(let L of Object.keys($))if(L.toLowerCase()===N)delete $[L];if(G!==null)$[z]=G}}function u$($,X){for(let[z,G]of Object.entries(X))if(G===null)$.delete(z);else $.set(z,G)}async function w2($,X,z={}){let{providerID:G}=X,N=z.gateOnPlaceholder,L=(J)=>N===void 0||N.credential(J)===Q2(G),P=z.logger,T=Math.max(1,z.maxRecords??o2),K=[...z.hostCredentials??[Q2(G)],...N?[Q2(G)]:[]].filter((J)=>J!==""),Y=new Map,H=new WeakMap,V=new Map,B=new Set,O=new Map,q=!1,R=!1,m=new Map,b=0,i=!1,n=new Map,c=(J,Q)=>{try{P?.warn(J,Q)}catch{}},a=(J)=>J instanceof Error?J.message:String(J),Z=async(J,Q)=>{let C=m.get(J);if(!C||C.size===0)return;await Promise.all([...C].map(async(F)=>{try{await F(Q)}catch(I){c("opencode2 auth listener threw; the request is unaffected",{event:J,error:a(I)})}}))},j=async(J,Q)=>{try{await X.onAttemptEnd?.(J,Q)}catch(C){c("opencode2 auth onAttemptEnd threw; the request is unaffected",{attemptId:J.attemptId,error:a(C)})}},W=(J,Q)=>{if(J.ended||!J.attempt)return;let C={...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=j(J.attempt,C)},A=(J,Q)=>W(J,{reason:"abandoned",message:Q}),E=(J)=>[...Y.values()].filter((Q)=>Q.key===J),w=(J)=>E(J).at(-1),y=(J)=>{if(Y.delete(J.id),!E(J.key).length)V.delete(J.key)},s=(J)=>{Y.set(J.id,J);while(Y.size>T){let Q=Y.values().next().value;if(Q===void 0)break;A(Q,"dropped to keep the record bound"),y(Q)}},p=(J)=>J.accountId===void 0?void 0:{...J.scope,accountId:J.accountId},h=(J,Q)=>new _2({kind:"no-account",providerID:G,sessionID:J.sessionID,requestKind:J.kind,...Q===void 0?{}:{message:Q}}),o=(J)=>{n.get(J)?.clear(),n.delete(J)},l=async(J,Q)=>{let C=()=>h(J,`${G} ${J.kind} request has no account: its auth selection was revoked by session forgetting or installation disposal`);if(i)throw C();let F=n.get(J.sessionID);if(!F)F=new Set,n.set(J.sessionID,F);let I={};F.add(I);let v=()=>{if(!F.has(I))throw C()};try{return await Q(v)}finally{if(F.delete(I),F.size===0&&n.get(J.sessionID)===F)n.delete(J.sessionID)}},U=(J,Q)=>{for(let[C,F]of Q)if(K.some((I)=>F.includes(I)))throw new _2({kind:"host-credential-on-wire",providerID:G,sessionID:J.sessionID,requestKind:J.kind,message:`${G} ${J.kind} request still carries the host's placeholder credential in ${C}; the adapter's account headers must replace it`})},M=(J)=>{for(let Q of E(J))if(Q.ended||!Q.attempt)y(Q);else if(Q.transport==="ws"||Q.judged)A(Q,"a newer attempt of its session and kind began"),y(Q)},_=async(J,Q,C,F)=>{let I=U2(J.sessionID,J.kind),v=V.get(I);V.delete(I);let D=v?.accountId??w(I)?.accountId;M(I);let g={...J,...D===void 0?{}:{previousAccountId:D},...v?.rerouteFrom===void 0?{}:{rerouteFrom:v.rerouteFrom}},u=await X.chooseAccount(g);C();let W2={},p2;if(u!==void 0){let F2=await X.accountHeaders({...J,accountId:u});if(C(),d$(F2))W2=F2.headers,p2=F2.attempt;else W2=F2}let u2=`attempt-${++b}`,M2={id:u2,key:I,scope:J,accountId:u,headers:W2,attempt:u===void 0?void 0:{...J,accountId:u,attemptId:u2,transport:F,data:p2},...F===void 0?{}:{transport:F},outputStarted:!1};if(s(M2),M2.attempt)Z("select",{...J,accountId:M2.attempt.accountId,hook:Q,...g.previousAccountId===void 0?{}:{previousAccountId:g.previousAccountId},...g.rerouteFrom===void 0?{}:{rerouteFrom:g.rerouteFrom},handle:M2.attempt});return M2},S=async(J,Q,C,F,I)=>{let v=U2(J.sessionID,J.kind),D=F===void 0?void 0:Y.get(F);if(D?.key!==v)D=void 0;if(!D){if(D=w(v),E(v).filter((u)=>u.transport===void 0&&!u.ended).length>1&&!R)R=!0,c("opencode2 auth tied a send without its attempt mark to the newest of several waiting attempts",{sessionID:J.sessionID,kind:J.kind})}if(!D||D.transport!==void 0||D.ended)D=await _(J,Q,I,C);else if(D.transport=C,D.attempt)D.attempt.transport=C;if(C==="ws"){for(let g of E(v))if(g!==D&&g.transport==="ws")A(g,"a newer attempt of its session and kind went out over WebSocket")}return D},x=async(J,Q)=>{try{return await Q()}catch(C){throw W(J,{reason:"failed",message:a(C)}),C}},k=(J,Q)=>{let C=E(U2(J,Q)).filter((F)=>F.transport==="ws").at(-1);return C?.attempt!==void 0&&!C.ended?C:void 0},f=(J,Q,C)=>{let F=p(J);if(!F||!J.attempt||J.limit)return;J.limit={signal:Q,delivered:Z("limit",{...F,via:C,limit:Q,outputStarted:J.outputStarted,handle:J.attempt})}},r=(J,Q,C,F)=>{let I=p(J);if(!I||!J.attempt)return;Z("quota",{...I,transport:Q,...F===void 0?{}:{status:F},quota:C,handle:J.attempt})},d=(J,Q,C,F)=>{let I=J.attempt;if(!I)return;let v=X.inspectEvent?.(F===void 0?{transport:Q,data:C,attempt:I}:{transport:Q,data:C,event:F,attempt:I});if(!v)return;if(v.quota!==void 0)r(J,Q,v.quota);if(v.outputStarted)J.outputStarted=!0;if(v.limit)f(J,v.limit,Q);if(v.error!==void 0)W(J,{reason:"failed",message:v.error});else if(v.done)W(J)},X2=(J,Q)=>{let C=J.attempt;if(!C||Q.accountId===J.accountId)return;if(C.reboundFrom??=C.accountId,C.accountId=Q.accountId,"data"in Q)C.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=[...Y.values()].filter((g)=>g.scope.sessionID===J),C=Q.filter((g)=>g.limit&&!g.rerouted).at(-1);if(C)return C;let F=Q.filter((g)=>g.scope.kind==="primary"),I=F.length>0?F:Q;if(I.length<=1)return I[0];let v=I.filter((g)=>!g.judged&&J2(g)).at(-1);if(v)return v;let D=I.filter((g)=>g.attempt&&!g.ended);if(D.length>1)return"ambiguous";return D[0]??I.at(-1)},$2={providerID:G},t=[];t.push(await $.session.hook("model.request",(J)=>{if(N)return;return l(G2(J),async(Q)=>{let C=await _(G2(J),"model.request",Q);if(Q(),C.accountId===void 0)throw h(C.scope);b2(J.headers,{...C.headers,[H2]:C.id})})},$2)),t.push(await $.session.hook("http.request",(J)=>{if(N){let Q=L(J.request.headers);if(O.set(J.sessionID,Q),!Q)return}return l(G2(J),async(Q)=>{let C=J.request.headers.get(H2)??void 0,F=N?await _(G2(J),"http.request",Q,"http"):await S(G2(J),"http.request","http",C,Q);Q();let I=p(F),v=F.attempt;if(!I||!v)throw h(F.scope);await x(F,async()=>{let D=J.request;if(X.rewriteRequest){if(C!==void 0){let W2=new Headers(D.headers);W2.delete(H2),D=new Request(D,{headers:W2})}D=await X.rewriteRequest({...I,request:D,attempt:v})??D,Q()}let g=new Headers(D.headers);g.delete(H2),u$(g,F.headers),U(F.scope,g.entries());let u=new Request(D,{headers:g});H.set(u,F),J.request=u})})},$2)),t.push(await $.session.hook("http.response",async(J)=>{let Q=H.get(J.request);if(!Q){if(N)return;if(!q)q=!0,c("opencode2 auth dropped an http.response whose request it did not produce",{sessionID:J.sessionID,kind:J.kind});return}let C=J.response;if(X.answeredBy&&Q.attempt){let g=Q.attempt,u=await x(Q,async()=>X.answeredBy?.({request:J.request,response:C,attempt:g}));if(u)X2(Q,u)}let F=p(Q),I=Q.attempt;if(!F||!I)return;Q.status=C.status;let v=X.quotaFromHeaders?.(C.headers,C.status,I);if(v!==void 0)r(Q,"http",v,C.status);if(!C.ok&&X.limitFromResponse){let g=await X.limitFromResponse({status:C.status,headers:C.headers,body:()=>C.clone().text(),attempt:I});if(g)f(Q,g,"http")}if(!C.ok||!C.body)W(Q);let D=C;if(C.body&&(X.inspectEvent||X.onAttemptEnd)){let g=C.body;if(X.inspectEvent)g=g.pipeThrough(D2((u)=>d(Q,"http",u.data,u.event),(u)=>c("opencode2 auth event inspection threw",{error:a(u)})));D=new Response(p$(g,(u)=>W(Q,u)),{status:C.status,statusText:C.statusText,headers:C.headers})}if(X.rewriteResponse)D=await X.rewriteResponse({...F,request:J.request,response:D,attempt:I})??D;if(D!==C)J.response=D},$2)),t.push(await $.session.hook("experimental.ws.handshake",(J)=>{if(N){let Q=L(new Headers(J.headers)),C=U2(J.sessionID,J.kind);if(O.set(J.sessionID,Q),B.delete(C),!Q)return}return l(G2(J),async(Q)=>{let C;for(let D of Object.keys(J.headers)){if(D.toLowerCase()!==H2)continue;C??=J.headers[D],delete J.headers[D]}let F=N?await _(G2(J),"experimental.ws.handshake",Q,"ws"):await S(G2(J),"experimental.ws.handshake","ws",C,Q);Q();let I=p(F),v=F.attempt;if(!I||!v)throw h(F.scope);await x(F,async()=>{b2(J.headers,F.headers);let D=X.rewriteHandshakeURL?.({...I,url:J.url,attempt:v});if(D!==void 0)J.url=D;if(U(F.scope,Object.entries(J.headers)),N)B.add(F.key)})})},$2));let e=X.rewriteWebSocketFrame?.bind(X);if(e)t.push(await $.session.hook("experimental.ws.send",async(J)=>{let Q=G2(J);if(N&&!B.has(U2(Q.sessionID,Q.kind)))return;let C=k(Q.sessionID,Q.kind),F=await e({...Q,attempt:C?.attempt,frame:J.frame});if(F!==void 0)J.frame=F},$2));t.push(await $.session.hook("experimental.ws.receive",(J)=>{if(N&&!B.has(U2(J.sessionID,J.kind)))return;let Q=k(J.sessionID,J.kind);if(!Q)return;try{d(Q,"ws",J.frame)}catch(C){c("opencode2 auth frame inspection threw",{error:a(C)})}},$2)),t.push(await $.session.hook("retry",async(J)=>{if(N&&O.get(J.sessionID)!==!0)return;let Q=Z2(J.sessionID);if(!Q)return;let C=J.decision;if(Q==="ambiguous"){await Z("retry",{sessionID:J.sessionID,attempt:J.attempt,reason:"host-decides",hostDecision:C,decision:C});return}let F=Q;await l(F.scope,async(I)=>{F.judged=!0;let v=C,D,g,u=F.attempt;if(F.accountId===void 0||!u)v={retry:!1},D="no-account";else if(F.outputStarted)v={retry:!1},D="output-started";else{if(!F.limit){let W2=X.limitFromError?.(J.error,u);if(W2)f(F,W2,"error")}if(F.ended)await F.ended,I();if(F.limit)await F.limit.delivered,I(),F.rerouted=!0,g={accountId:F.accountId,limit:F.limit.signal},v={retry:!0,delay:0},D="reroute";else D="host-decides"}if(J.decision=v,v.retry&&F.accountId!==void 0)V.set(F.key,{sessionID:F.scope.sessionID,accountId:F.accountId,...g===void 0?{}:{rerouteFrom:g}});await Z("retry",{sessionID:J.sessionID,...F.accountId===void 0?{}:{accountId:F.accountId},kind:F.scope.kind,attempt:J.attempt,reason:D,hostDecision:C,decision:v,...u===void 0?{}:{handle:u}})})},$2));let j2=(J)=>{o(J),O.delete(J);for(let Q of B)if(JSON.parse(Q)[0]===J)B.delete(Q);for(let Q of[...Y.values()]){if(Q.scope.sessionID!==J)continue;A(Q,"its session was forgotten"),Y.delete(Q.id)}for(let[Q,C]of V)if(C.sessionID===J)V.delete(Q)},Y2=new AbortController,V2=$.event;if(V2)(async()=>{try{for await(let J of V2.subscribe({signal:Y2.signal}))if(J.type==="session.deleted")j2(J.data.sessionID)}catch(J){if(!Y2.signal.aborted)c("opencode2 auth stopped listening for session deletion",{error:a(J)})}})();return{on(J,Q){let C=m.get(J);if(!C)C=new Set,m.set(J,C);let F=Q;return C.add(F),()=>{C.delete(F)}},accountFor(J,Q){return w(U2(J,Q))?.accountId},forgetSession:j2,get size(){return Y.size},async dispose(){if(i)return;i=!0;for(let J of n.keys())o(J);Y2.abort();for(let J of Y.values())A(J,"the installation was disposed");Y.clear(),V.clear(),B.clear(),O.clear(),m.clear(),await Promise.all(t.map(async(J)=>{try{await J.dispose()}catch(Q){c("opencode2 auth hook did not dispose cleanly",{error:a(Q)})}}))}}}import{CacheKeepManager as _1,CacheKeepSessionRegistry as C1,getDefaultCacheKeepRegistryDirectory as N1,isCacheKeepActiveNow as B$,isCacheKeepHybridActive as f2,isCacheKeepSubagentsEnabled as g2,logger as L1}from"@cortexkit/anthropic-auth-core";import{createHash as i$}from"node:crypto";import{applyCustomHeaders as c$,assertNotCustodyTombstone as o$,classifyGzipRejection as n$,createProviderErrorRedactor as n2,createProviderErrorResponseScope as r2,decideRequestGzip as r$,encodeGzipRequestBody as s$,getAccountStoragePath as a$,getRequestGzipLatch as t$,getRequestGzipLatchPath as e$,mergeAnthropicBetas as $1,remapModelId as s2,remapRequestBodyModel as X1,stripEmptyTrailingAssistantMessages as J1,TrailingAssistantHistoryError as Z1}from"@cortexkit/anthropic-auth-core";var N2="anthropic",V$="x-common-auth-attempt",Y1=["x-session-affinity","x-opencode-session","x-parent-session-id",e2,O2,L2,V$],T2=new Set(["authorization","x-api-key"]),W1="Claude pool login is selected but no native account is usable. Complete offline migration or repair the pool and its quota policy before retrying.",G1=512,j1=5000,V1=500,a2=new Set(["invalid_request_error","authentication_error","billing_error","permission_error","not_found_error","request_too_large","rate_limit_error","timeout_error","api_error","overloaded_error"]);class Q$ extends Error{sessionID;requestKind;kind="no-account";providerID=N2;constructor($,X){super(W1);this.sessionID=$;this.requestKind=X;this.name="NativeAnthropicNoAccountError"}}class I2 extends Error{sessionID;requestKind;kind="session-forgotten";providerID=N2;constructor($,X){super("request refused: its session was closed while it was being prepared");this.sessionID=$;this.requestKind=X;this.name="NativeAnthropicRevokedError"}}class K2 extends Error{kind="unsupported-transport";providerID=N2;constructor(){super("request refused: WebSocket relay is not supported on OpenCode 2; select HTTP relay or direct transport");this.name="NativeAnthropicTransportRefusal"}}class U$ extends Error{kind="local-invalid-request";status=400;check;constructor($){super($.message,{cause:$});this.name="NativeAnthropicLocalRefusal",this.check=$.check}}var B2=($)=>typeof $==="object"&&$!==null&&!Array.isArray($);function C2($){try{return JSON.parse($)}catch{return}}function y2($){let X={};for(let[z,G]of Object.entries($??{}))X[z.toLowerCase()]=G;return X}function t2($){let X={};for(let z of Y1){let G=$.get(z);if(G!==null&&z!==V$)X[z]=G;$.delete(z)}return X}function Q1($){try{return new URL($).pathname.endsWith("/messages")}catch{return!1}}function U1($){return $ instanceof Z1||$ instanceof $$?new U$($):void 0}function B1($,X){let z=[];if($.oauth)z.push($.oauth.accessToken);for(let[G,N]of Object.entries($.apiHeaders??{})){if(N===null||!T2.has(G))continue;z.push(N.replace(/^Bearer\s+/i,""))}for(let G of T2){let N=X.get(G);if(N!==null)z.push(N.replace(/^Bearer\s+/i,""))}if($.dispatch?.kind==="http-relay")z.push($.dispatch.token);return[...new Set(z.filter(Boolean))]}var H1=new Set(["oauth-2025-04-20","claude-code-20250219",J$]);function K1($){let X=$.split(",").map((z)=>z.trim()).filter((z)=>z&&!H1.has(z));return $1(null,X)}function z1($){let X=C2($);if(!B2(X))return $;let z=J1(X.messages),G=Object.hasOwn(X,"fallbacks"),{droppedMarkers:N}=Z$(X,!1),L=G&&!Object.hasOwn(X,"fallbacks"),P=X1(X);return z>0||N>0||L||P?JSON.stringify(X):$}async function M1($,X){if(!($ instanceof Promise))return"settled";let z;try{return await Promise.race([$.then(()=>"settled"),new Promise((G)=>{z=setTimeout(()=>G("timed-out"),X)})])}finally{if(z!==void 0)clearTimeout(z)}}function z2($){let{source:X,log:z}=$,G=Math.max(1,$.maxPendingSends??G1),N=$.attemptEndTimeoutMs??j1,L=$.requestGzipLatch??t$(e$(a$())),P=new WeakSet,T=new Map,K=new WeakMap,Y=new WeakMap,H=new WeakMap,V=new Map,B=new WeakMap,O=n2([]);O.dispose();let q=(U)=>(U&&V.get(U)?.redactor)??O,R=(U)=>{let M=V.get(U);if(!M)return;V.delete(U),M.redactor.dispose(),M.scope.dispose()},m=(U,M,_,S)=>{let x=B1(M,S),k=r2(x,_);b.set(U,_),V.set(U,{sessionID:M.sessionID,redactor:n2(x),scope:k}),k.settled.then(()=>R(U));while(V.size>G){let f=V.keys().next().value;if(f===void 0)break;R(f)}},b=new WeakMap,i=(U,M)=>{let _=U?b.get(U):void 0;if(!_||!M.ok)return O.redactResponse(M);let S=r2([],_),x=S.redactResponse(M);return S.dispose(),x},n=(U,M)=>{let _=U?V.get(U)?.scope:void 0;if(!_)return i(U,M);try{return _.redactResponse(M)}catch{return i(U,M)}},c=!1,a=new WeakMap,Z=(U,M)=>{if(U&&!M.ok)a.set(M.headers,U);return M},j=(U,M)=>{if(M.dispatch!=="http-relay")return!0;let _=/^req_[A-Za-z0-9_-]+$/.test(U.get("request-id")??"");return Y.set(M,_),_},W=(U)=>new Q$(U.sessionID,U.kind),A=new Map,E=async(U,M)=>{if(c)throw new I2(U.sessionID,U.kind);let _={revoked:!1},S=A.get(U.sessionID);if(!S)S=new Set,A.set(U.sessionID,S);S.add(_);let x=()=>{if(c||_.revoked)throw new I2(U.sessionID,U.kind)};try{let k=await M(x);return x(),k}finally{let k=A.get(U.sessionID);if(k?.delete(_)&&k.size===0)A.delete(U.sessionID)}},w=(U,M)=>{T.set(U,M);while(T.size>G){let _=T.keys().next().value;if(_===void 0)break;T.delete(_),z?.warn("dropped the oldest pending Anthropic send to stay bounded",{bound:G})}},y=(U,M)=>({providerID:U.providerID,modelID:U.modelID,sessionID:U.sessionID,agent:U.agent,kind:U.kind,accountId:U.accountId,attemptId:U.attemptId,transport:U.transport,route:M.route,provenance:M.provenance,dispatch:M.dispatch}),s=(U)=>E(U,async(M)=>{let{accountId:_,...S}=U,x=await X.authorizeAccount(S,_);return M(),p(S,x)}),p=(U,M)=>{if(!M)throw W(U);if(M.dispatch?.kind==="websocket-relay")throw new K2;let _=M.dispatch?.kind==="http-relay"?"http-relay":"direct",S=M.dispatch?.kind==="http-relay"?{authorization:null,"x-api-key":null,"x-relay-token":M.dispatch.token}:void 0;if(M.route==="oauth"){if(!M.accessToken)throw W(U);o$(M.accessToken,N2);let f=Object.freeze({route:"oauth",provenance:M.provenance,dispatch:_});w(f,{sessionID:U.sessionID,oauth:{accessToken:M.accessToken,...M.identity?{identity:M.identity}:{}},dispatch:M.dispatch,oauthHeaders:M.headers});let r=y2(M.headers);for(let d of T2)delete r[d];return delete r["anthropic-beta"],{headers:S??{...r,"x-api-key":null,authorization:`Bearer ${M.accessToken}`},attempt:f}}let x={authorization:null,"x-api-key":null,...y2(M.headers)};if(!x.authorization&&!x["x-api-key"])throw W(U);let k=Object.freeze({route:"api",provenance:M.provenance,dispatch:_});return w(k,{sessionID:U.sessionID,...M.baseURL?{baseURL:M.baseURL}:{},dispatch:M.dispatch,apiHeaders:x}),{headers:S??x,attempt:k}},h=(U)=>E(U,(M)=>o(U,M)),o=async(U,M)=>{let{request:_,attempt:S}=U,x=S.data,k=x?T.get(x):void 0;if(x)T.delete(x);if(!x||!k||x.route==="oauth"&&!k.oauth)throw W(U);let f=new Headers(_.headers);c$(f);let r=t2(f),d=_.body===null?void 0:await _.text();M();let X2=d!==void 0&&Q1(_.url);try{if(x.route==="oauth"&&k.oauth){let{accessToken:t,identity:e}=k.oauth;for(let[Y2,V2]of Object.entries(y2(k.oauthHeaders))){if(T2.has(Y2))continue;if(V2===null)f.delete(Y2);else f.set(Y2,V2)}let j2=null;if(d!==void 0&&X2){let Y2={...y(S,x),modelID:(()=>{let Q=C2(d);return s2(B2(Q)&&typeof Q.model==="string"?Q.model:U.modelID)})(),route:"oauth",correlation:r},V2=await X.requestOptions?.(Y2)??{};M(),d=await G$(d,{...V2,...e?{identity:e}:{},sessionId:U.sessionID,onToolNameMap:(Q)=>H.set(x,Q)});let J=C2(d);j2=B2(J)?J:null}Y$(f,t,{body:j2,...e?{identity:e}:{},requestClass:X$(S.agent)?"auxiliary":"main"})}else{if(d!==void 0&&X2)d=z1(d);f.delete("authorization"),f.delete("x-api-key");for(let[e,j2]of Object.entries(k.apiHeaders??{}))if(j2===null)f.delete(e);else f.set(e,j2);if(d!==void 0&&X2&&!f.has("content-type"))f.set("content-type","application/json");let t=f.get("anthropic-beta");if(t!==null){let e=K1(t);if(e)f.set("anthropic-beta",e);else f.delete("anthropic-beta")}}}catch(t){let e=U1(t);if(!e)throw t;throw K.set(x,e.check),z?.warn("refused an Anthropic request locally; nothing was sent",{check:e.check}),e}let J2=d!==void 0?C2(d):void 0;if(await X.admitRequest?.({...y(S,x),modelID:s2(B2(J2)&&typeof J2.model==="string"?J2.model:U.modelID)}),t2(f),d!==void 0)f.delete("content-length");M(),m(x,k,B2(J2)&&J2.stream===!0?"event-stream":"http",f);let Z2=W$(_.url,k.baseURL!==void 0?{baseURL:k.baseURL}:{}).url?.toString()??_.url;if(x.route==="oauth"&&X2&&d!==void 0)await X.onRequestPrepared?.({...y(S,x),url:Z2,bodyText:d}),M();if(k.dispatch?.kind==="http-relay"){let t=d??"";f.delete("x-relay-token");let e={protocol:1,type:"request",affinity:U.sessionID,upstream:{url:Z2,method:_.method,headers:Object.fromEntries(f)},mode:"full_sync",revision:1,body:t,next_hash:`sha256:${i$("sha256").update(t).digest("hex")}`};return new Request(k.dispatch.url,{method:"POST",headers:{"content-type":"application/json","x-relay-token":k.dispatch.token},redirect:"error",signal:_.signal,body:JSON.stringify(e)})}let $2=d;if(x.route==="oauth"&&X2&&d!==void 0){let t=await r$({url:Z2,body:d,latch:L});if(M(),t.gzip)$2=await s$(d),f.set("content-encoding","gzip"),P.add(x),M()}return new Request(Z2,{method:_.method,headers:f,redirect:_.redirect,signal:_.signal,...$2!==void 0?{body:$2}:{}})};return{adapter:{providerID:N2,chooseAccount:(U)=>E(U,async()=>{let M=await X.chooseAccount(U);if(!M)throw W(U);return M}),accountHeaders:s,rewriteRequest:h,rewriteHandshakeURL(){throw new K2},rewriteResponse({response:U,attempt:M}){let _=M.data;if(_&&!j(U.headers,_)){if(U.status===401)return R(_),U.body?.cancel().catch(()=>{}),Response.json({type:"error",error:{type:"api_error",message:"Relay authentication failed before Anthropic received the request"}},{status:502});return n(_,U)}if(_&&P.has(_))P.delete(_),n$(U).then((r)=>{if(!r)return;L.latchProcess(),z?.warn("gzipped request body rejected; later requests go uncompressed",{kind:r,status:U.status})},()=>{});let S=n(_,U);if(_?.route!=="oauth"||!S.body)return Z(_,S);let x={...y(M,_),status:U.status},k=X.responseOptions?.(x)??{},f=(U.headers.get("content-type")??"").includes("application/json");return Z(_,j$(S,{...k,toolNameMap:H.get(_),onToolNameRefusal:()=>{K.set(_,"response_tool_names"),R(_)},laneStartOAuthServed:!0,...f?{responseMode:"json"}:{}}))},quotaFromHeaders(U,M,_){let S=_.data;if(!S||!j(U,S))return;return X.quotaFromHeaders?.(U,{...y(_,S),status:M})},async limitFromResponse({status:U,headers:M,body:_,attempt:S}){let x=S.data;if(!x||K.get(x)==="response_tool_names")return;if(!j(M,x))return X.limitFromRelayFailure?.({...y(S,x),status:U});if(B.set(x,`provider responded with HTTP ${U}`),!X.limitFromResponse)return;let k=a.get(M)===x,f=q(x);return X.limitFromResponse({...y(S,x),status:U,headers:M,body:async()=>k?await _():f.redactText(await _())})},inspectEvent({data:U,event:M,attempt:_}){if(_.data&&K.get(_.data)==="response_tool_names")return;let S=C2(U);if(!B2(S))return;let x=typeof S.type==="string"?S.type:M;if(x==="content_block_start"||x==="content_block_delta")return{outputStarted:!0};if(x==="message_stop")return{done:!0};if(x!=="error")return;let k=_.data,f=q(k),r=B2(S.error)?S.error:{},d=typeof r.type!=="string"?void 0:a2.has(r.type)?r.type:f.redactText(r.type),X2=typeof r.message==="string"?f.redactText(r.message):void 0;if(k?.dispatch==="http-relay"&&Y.get(k)===!1)return;let J2=k?X.limitFromStreamError?.({...y(_,k),errorType:d,message:X2}):void 0,Z2={error:[d??"error",X2].filter(Boolean).join(": ").slice(0,V1),...J2?{limit:J2}:{}};if(k&&Z2.error)B.set(k,Z2.error);return Z2},limitFromError(U,M){let _=M.data;if(!_||K.has(_))return;let S={type:a2.has(U.type)?U.type:"provider_error",message:B.get(_)??"provider request failed",...U.status!==void 0?{status:U.status}:{}};if(R(_),_.dispatch==="http-relay"&&Y.get(_)===!1)return;return X.limitFromHostError?.(S,y(M,_))},async onAttemptEnd(U,M){let _=U.data;if(!_)return;T.delete(_);let S=M.error?.reason;if(S==="cancelled"||S==="abandoned"||S===void 0&&(M.status===void 0||M.status<400))R(_);let x=K.get(_),{status:k,...f}=M,r=X.onAttemptEnd?.(y(U,_),{...f,...k!==void 0&&(_.dispatch!=="http-relay"||Y.get(_)===!0)?{status:k}:{},...x!==void 0?{localRefusal:{check:x}}:{}});if(await M1(r,N)==="timed-out")z?.warn("the account source did not finish recording a send",{timeoutMs:N})}},dispose(){c=!0;for(let[U,M]of A){for(let _ of M)_.revoked=!0;X.forgetSession?.(U)}A.clear(),T.clear();for(let U of[...V.keys()])R(U)},forgetSession(U){for(let M of A.get(U)??[])M.revoked=!0;A.delete(U);for(let[M,_]of T)if(_.sessionID===U)T.delete(M);for(let[M,_]of[...V])if(_.sessionID===U)R(M);X.forgetSession?.(U)},get pendingSendCount(){return T.size},get heldCredentialCount(){let U=0;for(let M of T.values())if(M.oauth)U++;return U},get heldRedactorCount(){return V.size},get operationsInProgress(){let U=0;for(let M of A.values())U+=M.size;return U}}}function P2($){return JSON.stringify([$.source,$.accountIdentity,$.credentialId,$.binding?.storageId,$.binding?.rowId,$.binding?.credentialEpoch])}function H$($){let{runtime:X,source:z}=$,G=new AbortController,N=!1,L=new C1({directory:$.registryDirectory||process.env.OPENCODE_ANTHROPIC_AUTH_CACHEKEEP_REGISTRY_DIR||N1("opencode"),now:$.now}),P=new Map,T=async(V,B,O)=>{let q=O?AbortSignal.any([G.signal,O]):G.signal;q.throwIfAborted();let R=JSON.parse(await B.text()),m={providerID:"anthropic",modelID:R.model,sessionID:`oc2-cachekeep:${V.id}`,agent:"cachekeep",kind:"generate"},b=z2({source:{...z,onRequestPrepared:void 0,responseOptions:void 0,async requestOptions(Z){return{...await z.requestOptions?.(Z),laneStart:!1,billingLineage:void 0,cacheDiagnosticsPreviousMessageId:void 0}},async authorizeAccount(Z,j){let W=await X.read();q.throwIfAborted();let A=W.accounts.find((w)=>w.id===j);if(A?.type!=="oauth"||P2(A)!==V.oauthAccountIdentity||V.isSubagent&&!g2(W.policyStorage)||!f2(W.policyStorage)||!B$(W.policyStorage,new Date($.now?.()??Date.now())))return;let E=await z.authorizeAccount(Z,j);if(E?.provenance.kind==="local"&&P2({...A,binding:E.provenance.subject.binding,accountIdentity:E.provenance.subject.binding.identity})!==V.oauthAccountIdentity)return;if(E?.provenance.kind==="vault"&&E.provenance.credentialId!==A.credentialId)return;return E},async admitRequest(Z){await z.admitRequest?.(Z);let j=await X.read(),W=j.accounts.find((A)=>A.id===Z.accountId);if(q.throwIfAborted(),!W||P2(W)!==V.oauthAccountIdentity||V.isSubagent&&!g2(j.policyStorage)||!f2(j.policyStorage)||!B$(j.policyStorage,new Date($.now?.()??Date.now())))throw Error("CacheKeep policy changed before dispatch")}}}),i,n,c=!1,a=()=>b.forgetSession(m.sessionID);q.addEventListener("abort",a,{once:!0});try{let Z=(await X.read()).accounts.find((y)=>P2(y)===V.oauthAccountIdentity)?.id;if(!Z)throw Error("CacheKeep account is unavailable");let j=await b.adapter.accountHeaders({...m,accountId:Z});if(!("headers"in j)||typeof j.headers!=="object"||j.headers===null||typeof j.attempt!=="object"||j.attempt===null||j.attempt.route!=="oauth")throw Error("CacheKeep authorization refused");i={...m,accountId:Z,attemptId:crypto.randomUUID(),transport:"http",data:j.attempt};let W=await b.adapter.rewriteRequest?.({...m,accountId:Z,attempt:i,request:new Request(V.url,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(R),signal:q})});if(!W)throw Error("CacheKeep rewrite refused");q.throwIfAborted();let A=await($.fetch??fetch)(W),E=await b.adapter.rewriteResponse?.({...m,accountId:Z,attempt:i,request:W,response:A});if(!E)throw Error("CacheKeep response rewrite refused");if(n=E.status,b.adapter.quotaFromHeaders?.(E.headers,E.status,i),!E.ok)await b.adapter.limitFromResponse?.({status:n,headers:E.headers,body:()=>E.clone().text(),attempt:i});let w=await E.arrayBuffer();return c=!0,new Response(w,{status:n,headers:E.headers})}catch{throw Error("Native CacheKeep was not completed")}finally{q.removeEventListener("abort",a);try{if(i)await b.adapter.onAttemptEnd?.(i,{status:n,outputStarted:!1,...c?{}:{error:{reason:"cancelled"}}})}finally{b.dispose(),z.forgetSession?.(m.sessionID)}}},K=$.setIntervalImpl??globalThis.setInterval,Y=new _1({loadStorage:async()=>N?null:(await X.read()).policyStorage,now:$.now,setIntervalImpl:(V,B)=>K(()=>Y.tick().catch(()=>{L1.warn("cachekeep","tick failed")}),B),clearIntervalImpl:$.clearIntervalImpl,onTrackedSessionsChanged:(V)=>L.publish(N?[]:V),prepareHeaders(V,B,O){if(N)return;return P.set(O.id,{target:B,attempt:O}),new Headers({"x-native-cachekeep-attempt":String(O.id)})},fetchImpl:async(V,B)=>{let O=new Request(V,B),q=Number(O.headers.get("x-native-cachekeep-attempt")),R=P.get(q);if(P.delete(q),!R)throw Error("CacheKeep attempt is unavailable");return T(R.target,O,R.attempt.signal)},onComplete:({attempt:V})=>{P.delete(V.id)}}),H;return{async track(V){if(N||V.route!=="oauth"||V.agent==="cachekeep"||V.agent==="prime"||V.kind!=="primary")return;let B=await X.read();if(N||!f2(B.policyStorage))return;let O=!1;try{O=await $.isSubagent?.(V.sessionID)??!1}catch{return}if(N||O&&!g2(B.policyStorage))return;let q=B.accounts.find((R)=>R.id===V.accountId);if(!q?.accountIdentity)return;if(V.provenance.kind==="local"&&JSON.stringify(q.binding)!==JSON.stringify(V.provenance.subject.binding))return;if(V.provenance.kind==="vault"&&q.credentialId!==V.provenance.credentialId)return;Y.track({sessionId:V.sessionID,url:V.url,headers:new Headers,bodyText:V.bodyText,storage:B.policyStorage,cacheMode:"hybrid",oauthAccountId:V.accountId,oauthAccountIdentity:P2(q),isSubagent:O}),await L.publish(Y.trackedSessions())},registry:L,dispose(){if(H)return H;return N=!0,Y.stop(),G.abort(),H=(async()=>{try{await Y.tick()}finally{P.clear(),await L.dispose()}})(),H}}}async function K$($,X,z){let G=z2(X),N=[],L=async(B,O,q)=>{let R=await $.session.hook(B,O,q);return N.push(R),R},P=new AbortController,T;try{T=await w2({session:{hook:L},event:$.event},G.adapter,{logger:X.log,gateOnPlaceholder:z})}catch(B){throw G.dispose(),await Promise.allSettled(N.map((O)=>O.dispose())),B}let K=(B)=>{G.forgetSession(B),T.forgetSession(B)},Y=$.event,H=Y?(async()=>{try{for await(let B of Y.subscribe({signal:P.signal}))if(B.type==="session.deleted")K(B.data.sessionID)}catch(B){if(!P.signal.aborted)X.log?.warn("stopped listening for session deletion",{error:B instanceof Error?B.name:"unknown"})}})():Promise.resolve(),V;return{installation:T,forgetSession:K,dispose(){if(V)return V;return G.dispose(),P.abort(),V=(async()=>{await T.dispose(),await H})(),V}}}import{effectiveRelayTransport as z$,getQuotaCheckIntervalMs as P1,logger as F1,nativeAccountCanServe as T1,oauthProfileIsFresh as O1,quotaSnapshotCheckedAt as E1}from"@cortexkit/anthropic-auth-core";function M$($,X){let z=new AbortController,G,N=!1,L=async()=>{let K=await $.read();if(z.signal.throwIfAborted(),K.policyStorage.relay?.enabled===!0&&z$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="websocket")return;let Y=K,H=P1(Y.policyStorage);for(let V of Y.accounts){if(z.signal.aborted)return;if(!T1(V)||V.type!=="oauth")continue;if(Y.policyStorage.quota?.enabled!==!1&&Date.now()-E1(V.quota)>=H)await $.fetchQuota(V.id,X,z.signal,void 0,"background").catch(()=>{});if(!O1(V.profile)&&!z.signal.aborted)await $.fetchProfile(V.id,X,z.signal).catch(()=>{})}},P=()=>{if(N||G)return G;return G=L().catch(()=>{if(!z.signal.aborted)F1.debug("opencode2","native background readings did not complete")}).finally(()=>{G=void 0}),G},T=$.vault.watch({intervalMs:60000,onRefresh:P,shouldRefresh:async()=>{let K=await $.read();return K.policyStorage.relay?.enabled!==!0||z$(K.policyStorage.relay.transport,K.policyStorage.relay.url)==="http"}});return T.ready.catch(()=>{}),{async dispose(){N=!0,T.close(),z.abort(),await G}}}import{authorize as f1,buildCacheKeepStatusSummary as g1,buildClaudeQuotaSummary as v1,buildPrimeAccountStatuses as h1,buildPrimeStatusSummary as m1,CLAUSTRUM_OPENCODE_ENROLLMENT_NAME as l1,exchange as d1,formatNativeAccountState as p1,formatOAuthAccountTier as u1,getCacheKeepWindow as i1,getHostClaustrumEnrollmentPaths as c1,isCacheKeepAlways as o1,isCacheKeepHybridActive as n1,isCacheKeepPersistentlyEnabled as r1,nativeAccountCanServe as s1,resetClaustrumEnrollmentState as a1}from"@cortexkit/anthropic-auth-core";import{buildPrimeAccountStatuses as S1,effectiveRelayStatus as x1,formatNativeAccountState as R1,formatOAuthAccountTier as _$,getCacheKeepWindow as A1,getRoutingMode as q1,isCacheKeepAlways as k1,isCacheKeepHybridActive as D1,isPermanentRefreshError as b1,isPrimePersistentlyEnabled as w1,nativeAccountCanServe as L$,refreshBackoffActive as C$}from"@cortexkit/anthropic-auth-core";var N$=($)=>L$($)&&$.state!=="unsupported-access"?void 0:R1($)||void 0,y1=($)=>{if($.source!=="vault")return"off";if($.state==="needs_reauth")return"on-vault-reauth";return L$($)?"on-vault-served":"on-cold"},I1=($,X)=>typeof $==="number"&&$>X;function P$($,X){let{now:z}=X,G=$.policyStorage,N=$.accounts.filter((H)=>H.type==="oauth"),L=N.find((H)=>H.id==="main"),P=L?N$(L):void 0,T=L?.lastQuotaRefreshError?.nextRetryAt,K=L?.lastRefreshError,Y=A1(G);return{main:{quota:L?.quota??null,enabled:L?.enabled,tierLabel:_$(L?.profile),quotaBackedOff:I1(T,z),quotaBackoffUntil:T,refreshBackedOff:C$(K,L?.accountIdentity,z,void 0),refreshBackoffUntil:K?.nextRetryAt,stateLine:P,quotaDated:Boolean(P)},fallbacks:N.filter((H)=>H.id!=="main"&&(H.enabled||H.source==="vault")).map((H)=>{let V=N$(H),B=y1(H);return{id:H.id,label:H.label,quota:H.quota??null,enabled:H.enabled,tierLabel:_$(H.profile),needsReauth:b1(H.lastRefreshError)&&C$(H.lastRefreshError,H.accountIdentity,z,void 0),...B==="on-vault-reauth"?{vaultReauth:!0}:{},...B==="on-vault-served"?{vaultServed:!0}:{},...B!=="off"?{custodyState:B}:{},stateLine:V,quotaDated:Boolean(V)}}),activeId:X.activeId,route:q1(G),relay:x1(G.relay),fastMode:G.claudeFast?.enabled===!0,cacheKeep:{enabled:D1(G),window:k1(G)?"always":Y?`${Y.startHour}-${Y.endHour}`:void 0,trackedSessions:X.trackedSessions},prime:w1(G)?{enabled:!0,accounts:S1(G,{now:z})}:void 0,lastUpdated:z}}var v2=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function F$($){let{runtime:X,source:z}=$,G=new Map,N=!1,L=async(Y,H)=>{await X.updateSettings((V)=>({...V,[Y]:{...v2(V[Y]),...H}}))},P=()=>({ok:!0,text:"Native Claude settings updated."}),T=async(Y,H)=>{if(N)throw Error("Native menu is closed");switch(H.signal?.throwIfAborted(),Y.action){case"enable":case"disable":return await X.setEnabled(Y.values.id,Y.action==="enable"),P();case"remove":return await X.remove(Y.values.id),P();case"move-up":case"move-down":{let B=(await X.read()).accounts.map((b)=>b.id),O=B.indexOf(Y.values.id),q=O+(Y.action==="move-up"?-1:1);if(O<0||q<0||q>=B.length)return{ok:!1,text:"Account cannot move in that direction."};let R=B[O],m=B[q];if(R===void 0||m===void 0)return{ok:!1,text:"Account order changed."};return B[O]=m,B[q]=R,await X.reorder(B),P()}case"add-apikey":return await X.addApi(Y.values),{ok:!0,text:"API route stored in the native account pool."};case"add-oauth-start":{let V=new AbortController;G.get(Y.sessionId)?.active.abort();let B={active:V,auth:void 0};G.set(Y.sessionId,B);let O=await f1("max");if(N||V.signal.aborted||H.signal?.aborted)return{ok:!1,text:"Sign-in cancelled."};return B.auth=O,{ok:!0,text:`Open ${O.url} and paste the returned code using Finish OAuth sign-in.`}}case"add-oauth-finish":{let V=G.get(Y.sessionId);if(!V?.auth)return{ok:!1,text:"Start OAuth sign-in in this session first."};let B=await d1(Y.values.code,V.auth.verifier,V.auth.redirectUri,V.auth.state);if(V.active.signal.throwIfAborted(),H.signal?.throwIfAborted(),N||B.type!=="success")return{ok:!1,text:"OAuth sign-in did not complete."};if(await X.loginOAuth({routeId:crypto.randomUUID(),credential:B,label:Y.values.label}),V.active.signal.throwIfAborted(),H.signal?.throwIfAborted(),N)return{ok:!1,text:"Sign-in cancelled."};return G.delete(Y.sessionId),{ok:!0,text:"OAuth account stored in the native account pool."}}case"reset-backoff":{let V=await X.read();for(let B of V.accounts){if(H.signal?.throwIfAborted(),B.type!=="oauth")continue;let O=B.source==="vault"?await X.authorizeVault(B.id,H.signal):await X.captureLocalSubject(B.id);await X.resetBackoff(B.id,O)}return P()}case"enrollment-reset":{let V=await a1(c1("opencode"),l1);return{ok:V==="reset",text:V==="reset"?"Terminal enrollment state reset. Run offline setup to reconnect.":"Only terminal enrollment state may be reset; active enrollment was left unchanged."}}case"quota-refresh":{let B=(await X.read()).accounts.filter((R)=>R.type==="oauth"&&s1(R)),O=await Promise.allSettled(B.map((R)=>X.fetchQuota(R.id,void 0,H.signal)));return{ok:O.every((R)=>R.status==="fulfilled"),text:`${O.filter((R)=>R.status==="fulfilled").length}/${B.length} native quota readings refreshed.`}}case"routing-reset":return await z.resetRouting(Y.sessionId),P();case"routing-mode":return await L("routing",{mode:Y.values.mode}),P();case"killswitch-on":case"killswitch-off":return await L("killswitch",{enabled:Y.action==="killswitch-on"}),P();case"killswitch-set":return await X.updateSettings((V)=>{let B=v2(V.killswitch),O={...v2(B.accounts)},q=B.main;for(let R of Y.values.entries){let m={five_hour:R.fh,seven_day:R.sd,...R.scoped!==void 0?{scoped:R.scoped}:{}};if(R.account==="main"||R.account==="all")q=m;if(R.account==="all")for(let b of Object.keys(O))O[b]=m;else if(R.account!=="main")O[R.account]=m}return{...V,killswitch:{...B,main:q,accounts:O}}}),P();case"cache-on":case"cache-off":return await L("claudeCache",{enabled:Y.action==="cache-on"}),P();case"cache-mode":return await L("claudeCache",{mode:Y.values.mode}),P();case"cachekeep-always":return await L("cacheKeep",{enabled:!0,always:!0}),P();case"cachekeep-off":return await L("cacheKeep",{enabled:!1}),P();case"cachekeep-window":return await L("cacheKeep",{enabled:!0,always:!1,startHour:Y.values.startHour,endHour:Y.values.endHour}),P();case"cachekeep-subagents":return await L("cacheKeep",{subagents:Y.values.enabled==="on"}),P();case"dump-on":case"dump-off":return await L("dump",{enabled:Y.action==="dump-on"}),P();case"logging-level":return await L("logging",{level:Y.values.level}),P();case"fast-on":case"fast-off":return await L("claudeFast",{enabled:Y.action==="fast-on"}),P();case"prime-on":case"prime-off":return await L("prime",{enabled:Y.action==="prime-on"}),P();case"start-fire":return await K(Y.sessionId),{ok:!0,text:"Claude lane start queued in this session."}}},K=(Y)=>$.start(Y,E2);return{dispatch:T,async readStatus(Y){let H=await X.read();if(Y==="account")return H.accounts.map((B)=>`${B.id}${B.label?` (${B.label})`:""}: ${B.type}, ${B.source}, ${B.enabled?"enabled":"disabled"}${B.state?`, ${p1(B)}`:""}${B.accountIdentity?`, ${B.accountIdentity}`:""}`).join(`
4
4
  `)||"No native Claude accounts.";if(Y==="quota")return v1({accounts:H.accounts.filter((B)=>B.type==="oauth").map((B)=>({name:B.label??B.id,role:B.id==="main"?"main":"fallback",enabled:B.enabled,quota:B.quota,tierLabel:u1(B.profile),lastRefreshedAt:B.lastRefreshedAt,error:B.lastQuotaRefreshError?.message}))}).replace(/Usage:[^\n]*/,"Use /claude to refresh native quota readings.");if(Y==="prime")return m1({enabled:H.policyStorage.prime?.enabled===!0,accounts:h1(H.policyStorage)}).replace(/Usage:[^\n]*/,"Use /claude to change Prime settings.");if(Y==="cachekeep"){let B=await $.cacheKeepRegistry?.list()??[];return g1({enabled:r1(H.policyStorage),always:o1(H.policyStorage),hybridActive:n1(H.policyStorage),trackedSessionDetails:B,window:i1(H.policyStorage),trackedSessions:B.length,nextPrewarmAt:B.length?Math.min(...B.map((O)=>O.nextPrewarmAt)):void 0})}let V={routing:"routing",killswitch:"killswitch",cache:"claudeCache",cachekeep:"cacheKeep",dump:"dump",logging:"logging",fast:"claudeFast",prime:"prime"};return JSON.stringify(H.settings[V[Y]]??{})},async readSidebar(Y){let[H,V]=await Promise.all([X.read(),$.cacheKeepRegistry?.list()??[]]);return P$(H,{activeId:z.servedAccount(Y),trackedSessions:V.length,now:Date.now()})},forgetSession(Y){G.get(Y)?.active.abort(),G.delete(Y)},close(){N=!0;for(let Y of G.values())Y.active.abort();G.clear()}}}import{isClaudeFable51Model as t1,isClaudeHaiku55Model as e1,isClaudeOpus5FamilyModel as $X,isClaudeSonnet55Model as XX}from"@cortexkit/anthropic-auth-core";function T$(){let $=new Map;return{install:(z)=>z.model.transform((G)=>{$.clear();for(let N of G.list("anthropic")){if($.set(String(N.id),String(N.modelID)),!(t1(N.modelID)||$X(N.modelID)||XX(N.modelID)||e1(N.modelID)))continue;G.update("anthropic",String(N.id),(L)=>{let P=["low","medium","high","xhigh","max"],T=L.variants.filter((K)=>!P.some((Y)=>Y===String(K.id)));L.variants=[...T,...P.map((K)=>({id:K,settings:{effort:K,thinking:{type:"adaptive",display:"summarized"}}}))]})}}),modelId:(z)=>$.get(z)??z}}function O$($){return $.get("authorization")?.match(/^Bearer ([^\s]+)$/i)?.[1]??$.get("x-api-key")??void 0}import{buildPrimeRequestBody as E$,effectiveRelayTransport as S$,nativeAccountCanServe as JX,PrimeManager as ZX}from"@cortexkit/anthropic-auth-core";var x$=($)=>$!==null&&typeof $==="object"&&!Array.isArray($)?$:{};function R$($){let{runtime:X,source:z}=$,G=new AbortController,N=new Set,L=(K)=>({providerID:"anthropic",modelID:E$().model,sessionID:`oc2-prime:${K}`,agent:"prime",kind:"generate"}),P=async(K)=>{let Y=L(K),H=z2({source:z}),V=performance.now();try{for(let B=0;B<3;B++){if(G.signal.throwIfAborted(),(await X.read()).policyStorage.prime?.enabled!==!0)throw Error("Native Prime is disabled");let q=await H.adapter.accountHeaders({...Y,accountId:K});if(!("headers"in q)||typeof q.headers!=="object"||q.headers===null||typeof q.attempt!=="object"||q.attempt===null)throw Error("Native Prime authorization refused");let R={...Y,accountId:K,attemptId:crypto.randomUUID(),transport:"http",data:q.attempt},m,b=!1,i=!1,n=(c)=>{i=!0,c.body?.cancel().catch(()=>{})};try{let c=await H.adapter.rewriteRequest?.({...Y,accountId:K,attempt:R,request:new Request("https://api.anthropic.com/v1/messages",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(E$()),signal:G.signal})});if(!c)throw Error("Native Prime rewrite refused");let a=new Headers(c.headers);for(let[s,p]of Object.entries(q.headers))if(p===null)a.delete(s);else a.set(s,p);let Z=new Request(c,{headers:a}),j=await($.fetch??fetch)(Z),W=await H.adapter.rewriteResponse?.({...Y,accountId:K,request:Z,response:j,attempt:R})??j;m=W.status,H.adapter.quotaFromHeaders?.(W.headers,W.status,R);let A=W.ok?void 0:await H.adapter.limitFromResponse?.({status:W.status,headers:W.headers,body:()=>W.clone().text(),attempt:R});if(A&&/^(vault-newer|local-newer|relay-direct):/.test(A.reason)&&B<2){if(n(W),await z.chooseAccount({...Y,rerouteFrom:{accountId:K,limit:A}})!==K)throw Error("Native Prime retry changed account");continue}if(!W.ok)return n(W),{ok:!1,status:m,ms:performance.now()-V,error:"Native Prime upstream refused the request"};let E=x$(await W.json()),w=x$(E.usage),y={inputTokens:typeof w.input_tokens==="number"?w.input_tokens:void 0,outputTokens:typeof w.output_tokens==="number"?w.output_tokens:void 0};if(R.data?.dispatch==="http-relay"&&!/^req_[A-Za-z0-9_-]+$/.test(W.headers.get("request-id")??""))throw Error("Native Prime relay response has no upstream provenance");if(b=await z.recordPrime(q.attempt.provenance,y),!b)throw Error("Native Prime counter attribution was superseded");return{ok:!0,status:m,ms:performance.now()-V,usage:y}}finally{await H.adapter.onAttemptEnd?.(R,{status:m,outputStarted:!1,...b?{}:{error:{reason:i?"cancelled":"failed"}}})}}return{ok:!1,error:"Native Prime retry budget exhausted"}}catch{return{ok:!1,error:"Native Prime was not completed",ms:performance.now()-V}}finally{H.dispose()}},T=new ZX({storagePath:$.paths.legacyConfig,loadStorage:async()=>(await X.read()).policyStorage,async getAccountFingerprint(K){let Y=await X.read(),H=Y.accounts.find((B)=>B.id===K);if(!JX(H)||H?.type!=="oauth")return;if(Y.policyStorage.relay?.enabled===!0&&S$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")return;if(H.source==="vault"){let B=await X.authorizeVault(K,G.signal);return X.getOrCreateAuthLineage(K,B)}let V=await X.authorizeLocal(K,{signal:G.signal});return V.status==="usable"?X.getOrCreateAuthLineage(K,V.subject):void 0},async refreshQuota(K){let Y=await X.read();if(Y.policyStorage.relay?.enabled===!0&&S$(Y.policyStorage.relay.transport,Y.policyStorage.relay.url)==="websocket")throw Error("WebSocket relay is unsupported on OpenCode 2");return{quota:await X.fetchQuota(K,$.fetch,G.signal),fresh:!0}},sendPrime(K){let Y=P(K);return N.add(Y),Y.finally(()=>N.delete(Y)),Y},async recordSuccess(K){let Y=(await X.read()).accounts.find((H)=>H.id===K);if(!Y?.prime)throw Error("Native Prime counters are unavailable");return Y.prime}});return T.start(),{manager:T,async dispose(){T.stop(),G.abort(),await Promise.allSettled(N)}}}import{createNativeUsagePublisher as YX,effectiveRelayTransport as WX,getClaudeCodeIdentityForVerifiedAccount as S2,getQuotaCheckIntervalMs as GX,getRoutingMode as A$,isQuotaBearingHeaderFrame as jX,mergeHeaderQuotaForPersistence as VX,NativeVaultNoAccountError as QX,nativeAccountCanServe as h2,nativeAccountPolicy as x2,normalizeQuotaHeaders as UX,quotaSnapshotCheckedAt as BX,quotaSnapshotHasStandardWindows as HX,readNativeAccountsForRequest as KX,remapModelId as m2,StickySessionRouter as zX,shouldFallbackStatus as MX,stickyQuotaSnapshotIsFresh as R2,stickyRouteFamilyForModel as _X}from"@cortexkit/anthropic-auth-core";var l2=($)=>["five_hour","seven_day"].some((X)=>($?.[X]?.remainingPercent??1)<=0);function k$($){let{runtime:X}=$,z=YX("native-auth"),G=new Map,N=(Z)=>{let j=Z.routingPath;if(!j)throw Error("Native routing storage is unavailable");let W=G.get(j);if(!W)W=new zX({path:j,vaultSeed:Z.routingSeed,onLockEvent:X.onLockEvent,localRecoveryPath:Z.mode==="local"?Z.routingRecoveryPath:void 0}),G.set(j,W);return W.setVaultSeed(Z.routingSeed),W},L=new WeakMap,P=new Map,T=new Map,K=new Map,Y=new Map,H=new WeakSet,V=!1,B=()=>{while(P.size>512){let Z=P.keys().next();if(!Z.done)P.delete(Z.value)}},O=(Z,j)=>JSON.stringify([Z.sessionID,Z.kind,Z.modelID,j]),q=(Z)=>{if(V)throw Error("Native Anthropic source is closed");let j=K.get(Z.sessionID);if(!j){j=new AbortController,K.set(Z.sessionID,j);while(K.size>512){let W=K.keys().next();if(!W.done)c.forgetSession?.(W.value)}}return j},R=(Z,j,W)=>h2(Z)&&(Z.type==="api"||x2(Z,j,m2(W)).status==="allowed"),m=async(Z,j,W,A)=>{let E=await X.read();A.signal.throwIfAborted(),b(E);let w=E.accounts.find((y)=>y.id===Z);if(!w||w.type!==W||!R(w,E,j))return!1;if(W==="api"){let y=E.accounts.find((s)=>s.id==="main"&&s.type==="oauth");return!!y&&R2(y.quota,E.policyStorage)&&l2(y.quota)}return!0},b=(Z)=>{let j=Z.policyStorage.relay;if(j?.enabled===!0&&WX(j.transport,j.url)==="websocket")throw new K2},i=async(Z,j)=>{if(b(Z),j||Z.policyStorage.relay?.enabled!==!0)return{dispatch:{kind:"direct"},relayFallback:!1};let W=await X.getRelayConfig();if(!W)throw Error("request refused: native HTTP relay configuration is unavailable");if(W.transport!=="http")throw new K2;return{dispatch:{kind:"http-relay",url:W.url,token:W.token},relayFallback:W.fallbackToDirect}};async function n(Z,j,W){if(Z.kind==="local")await X.publishLocal(Z.subject,W);else if(Z.kind==="vault"&&j.receipt)await X.vault.publish(j.receipt,W);else if(Z.kind==="api"&&W.lastUsed!==void 0)await X.publishApi(Z.subject,{lastUsed:W.lastUsed})}let c={async chooseAccount(Z){let j=q(Z);$.onOwnedRequest?.();let W=await X.read();j.signal.throwIfAborted(),b(W);let A=m2(await $.resolveModelId?.(Z)??Z.modelID);if(j.signal.throwIfAborted(),W.mode==="claustrum")W=await KX(X,j.signal),j.signal.throwIfAborted();if(W.policyStorage.quota?.enabled!==!1){let h=!1;for(let o of W.accounts){if(!h2(o)||o.type!=="oauth")continue;if(HX(o.quota)?R2(o.quota,W.policyStorage,Date.now(),A):Date.now()-BX(o.quota)<GX(W.policyStorage))continue;try{await X.fetchQuota(o.id,$.fetch,j.signal,void 0,"admission"),h=!0}catch{j.signal.throwIfAborted()}}if(h)W=await X.read();j.signal.throwIfAborted()}let E=Z.rerouteFrom?P.get(Z.rerouteFrom.limit.reason):void 0;if(Z.rerouteFrom&&/^(vault-newer|local-newer|relay-direct):/.test(Z.rerouteFrom.limit.reason)&&!E)return;if(E&&Z.rerouteFrom){P.delete(Z.rerouteFrom.limit.reason);let h=W.accounts.find((U)=>U.id===E.accountId);if(!h||!R(h,W,A))return;let o=O(Z,E.accountId),l=T.get(o)??[];return l.push(E),T.set(o,l),E.accountId}let w=[];for(let h of W.accounts){if(h.type!=="oauth"||!R(h,W,A))continue;if(h.source==="local"){let o=await X.authorizeLocal(h.id,{signal:j.signal,policy:(l,U)=>x2(l,U,A)});if(j.signal.throwIfAborted(),o.status!=="usable")continue}w.push(h)}let y=w.filter((h)=>h.id!==Z.rerouteFrom?.accountId);if(A$(W.policyStorage)==="sticky-balanced"){let h=y.map((l,U)=>({accountId:l.id,order:U,quota:l.quota??{kind:"unknown"}})),o=await N(W).resolve({sessionId:Z.sessionID,family:_X(A),modelId:A,affinityModelId:Z.modelID,candidates:h,retainAccountIds:new Set(y.map((l)=>l.id)),...W.mode==="claustrum"?{accountIdentities:new Map(W.accounts.flatMap((l)=>l.accountIdentity?[[l.id,l.accountIdentity]]:[]))}:{},storage:W.policyStorage,inputBytes:1,preferredAccountId:Z.previousAccountId});if(j.signal.throwIfAborted(),o)return o.accountId}else{let o=A$(W.policyStorage)==="fallback-first"?[...y.filter((l)=>l.id!=="main"),...y.filter((l)=>l.id==="main")]:[...y.filter((l)=>l.id==="main"),...y.filter((l)=>l.id!=="main")];if(o[0])return o[0].id}if(W.mode==="claustrum")throw new QX;let s=W.accounts.find((h)=>h.id==="main"&&h.type==="oauth");if(!s)return;let p=s.quota;if(Z.rerouteFrom?.limit.status===429||!R2(p,W.policyStorage))try{p=await X.fetchQuota("main",$.fetch,j.signal)}catch{return}if(j.signal.throwIfAborted(),!l2(p))return;return W.accounts.find((h)=>h.type==="api"&&h2(h)&&h.id!==Z.rerouteFrom?.accountId)?.id},async authorizeAccount(Z,j){let W=q(Z),A=await X.read();W.signal.throwIfAborted(),b(A);let E=m2(await $.resolveModelId?.(Z)??Z.modelID);W.signal.throwIfAborted();let w=A.accounts.find((S)=>S.id===j);if(!w||!R(w,A,E))return;let y=O(Z,j),s=T.get(y),p=s?.shift();if(s?.length===0)T.delete(y);let{dispatch:h,relayFallback:o}=await i(A,p?.direct===!0);if(W.signal.throwIfAborted(),p?.auth){if(!await m(j,E,p.auth.route,W))return;let S=L.get(p.auth.provenance);if(S?.receipt?.expiresAtMs!==void 0&&S.receipt.expiresAtMs!==null&&S.receipt.expiresAtMs<Date.now()+300000)return;if(S)L.set(p.auth.provenance,{...S,scope:{...Z,modelID:E},account:w,active:W,relayFallback:o});return Y.set(Z.sessionID,j),{...p.auth,dispatch:h}}let l={scope:{...Z,modelID:E},active:W,account:w,retry:p?.retry??!1,relayFallback:o,quota:w.quota};if(w.type==="api"){let S=A.accounts.find((r)=>r.id==="main"&&r.type==="oauth");if(!S||!R2(S.quota,A.policyStorage)||!l2(S.quota))return;let x=await X.authorizeApi(j,W.signal);if(W.signal.throwIfAborted(),!await m(j,E,"api",W))return;let k={kind:"api",subject:x.subject};return L.set(k,l),Y.set(Z.sessionID,j),{route:"api",headers:x.authHeader==="authorization-bearer"?{authorization:`Bearer ${x.apiKey}`}:{"x-api-key":x.apiKey},baseURL:x.baseURL,provenance:k,dispatch:h}}if(w.source==="vault"){let S=await X.authorizeVault(j,W.signal);if(W.signal.throwIfAborted(),!await m(j,E,"oauth",W))return;let x={kind:"vault",credentialId:S.credentialId,recordVersion:S.recordVersion};L.set(x,{...l,receipt:S});let k=S.assertedAccountIdentity;if(!k)return;return Y.set(Z.sessionID,j),{route:"oauth",accessToken:S.accessToken,provenance:x,dispatch:h,identity:S2(k,k)}}let U=await X.authorizeLocal(j,{signal:W.signal,policy:(S,x)=>x2(S,x,E)});if(W.signal.throwIfAborted(),U.status!=="usable")return;if(!await m(j,E,"oauth",W))return;let M={kind:"local",subject:U.subject};L.set(M,{...l,access:U.access}),Y.set(Z.sessionID,j);let _=U.subject.binding.identity;return{route:"oauth",accessToken:U.access,provenance:M,dispatch:h,identity:S2(_,_)}},async requestOptions(Z){let j=q(Z),W=await X.read();j.signal.throwIfAborted();let A=W.accounts.find((w)=>w.id===Z.accountId);if(!A||!R(A,W,Z.modelID))throw Error("request refused: native account is ineligible for this model");let E=L.get(Z.provenance);if(E)L.set(Z.provenance,{...E,scope:{...E.scope,modelID:Z.modelID}});return $.requestOptions(Z,W)},async admitRequest(Z){let j=L.get(Z.provenance);if(!j||!await m(Z.accountId,Z.modelID,Z.route,j.active))throw Error("request refused: native account policy changed before dispatch");L.set(Z.provenance,{...j,scope:{...j.scope,modelID:Z.modelID}})},onRequestPrepared:(Z)=>$.onRequestPrepared?.(Z),responseOptions(Z){return $.responseOptions?.({...Z,modelID:L.get(Z.provenance)?.scope.modelID??Z.modelID})},quotaFromHeaders(Z,j){let W=L.get(j.provenance),A=q$(Z);if(A)$.onRequestId?.(j,A);if(!W||j.route!=="oauth"||!jX(Z))return;let E=j.provenance.kind==="local"?j.provenance.subject.binding.identity:W.receipt?.assertedAccountIdentity,w={...UX(Z),...E?{accountIdentity:E}:{}};W.quota=VX(W.quota,w);let y=z.observe(n(j.provenance,W,{quota:W.quota}));return a.set(j.provenance,y),w},async limitFromResponse(Z){let j=L.get(Z.provenance);if(!j)return;if(Z.status===401&&j.receipt){if(!H.has(j.receipt))H.add(j.receipt),await X.vault.reportFailure(j.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(j.retry||j.active.signal.aborted)return;let A=j.active,E=await X.vault.prepareRetry(j.receipt,A.signal);if(A.signal.throwIfAborted(),!E.retry)return;let w=E.receipt,y=w.assertedAccountIdentity;if(!y)return;let s={kind:"vault",credentialId:w.credentialId,recordVersion:w.recordVersion};L.set(s,{...j,receipt:w,retry:!0});let p=`vault-newer:${Z.attemptId}`;return P.set(p,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:w.accessToken,provenance:s,identity:S2(y,y)}}),B(),{reason:p,status:401}}if(Z.status===401&&Z.provenance.kind==="local"&&j.access&&!j.retry){if(j.active.signal.aborted)return;let A=j.active,E=await X.authorizeLocal(Z.accountId,{rejectedAccessToken:j.access,signal:A.signal,policy:(p,h)=>x2(p,h,j.scope.modelID)});if(A.signal.throwIfAborted(),E.status!=="usable"||E.access===j.access)return;let w={kind:"local",subject:E.subject};L.set(w,{...j,access:E.access,retry:!0});let y=E.subject.binding.identity,s=`local-newer:${Z.attemptId}`;return P.set(s,{sessionID:Z.sessionID,accountId:Z.accountId,retry:!0,auth:{route:"oauth",accessToken:E.access,provenance:w,identity:S2(y,y)}}),B(),{reason:s,status:401}}let W=await X.read();if(MX(Z.status,W.policyStorage))return{reason:`provider-${Z.status}`,status:Z.status};return},limitFromRelayFailure(Z){let j=L.get(Z.provenance);if(!j?.relayFallback||j.active.signal.aborted||!(Z.status===401||Z.status>=500))return;let W=`relay-direct:${Z.attemptId}`;return P.set(W,{sessionID:Z.sessionID,accountId:Z.accountId,direct:!0,retry:!1}),B(),{reason:W}},limitFromStreamError(Z){return Z.errorType==="rate_limit_error"?{reason:"provider-rate-limit",status:429}:void 0},limitFromHostError(Z,j){let W=L.get(j.provenance);if(j.dispatch==="http-relay"&&W?.relayFallback&&!W.active.signal.aborted&&Z.status===void 0){let A=`relay-direct:${j.attemptId}`;return P.set(A,{sessionID:j.sessionID,accountId:j.accountId,direct:!0,retry:!1}),B(),{reason:A}}return},async onAttemptEnd(Z,j){let W=L.get(Z.provenance);if(!W)return;try{if(await a.get(Z.provenance),j.status===401&&W.receipt&&!H.has(W.receipt))H.add(W.receipt),await X.vault.reportFailure(W.receipt,401,Z.dispatch==="http-relay"?"relay_status_field":"direct");if(!j.localRefusal&&j.status!==void 0)z.publish(()=>n(Z.provenance,W,{lastUsed:Date.now()}))}finally{L.delete(Z.provenance),a.delete(Z.provenance)}},forgetSession(Z){K.get(Z)?.abort(),K.delete(Z),Y.delete(Z);for(let[j,W]of P)if(W.sessionID===Z)P.delete(j);for(let[j,W]of T)if(W[0]?.sessionID===Z)T.delete(j);$.onForgetSession?.(Z)},servedAccount:(Z)=>Y.get(Z),resetRouting:async(Z)=>N(await X.read()).clear(Z),async recordPrime(Z,j){let W=L.get(Z);if(!W||W.active.signal.aborted)return!1;if(Z.kind==="local")return X.incrementPrimeUsage(W.account.id,Z.subject,j);if(Z.kind==="vault"&&W.receipt)return X.incrementPrimeUsage(W.account.id,W.receipt,j);return!1},drainRoutingPublications:()=>Promise.all([X.drainRoutingPublications(),...[...G.values()].map((Z)=>Z.drain())]).then(()=>{}),close(){V=!0;for(let Z of K.values())Z.abort();return K.clear(),T.clear(),P.clear(),Promise.all([z.drain(),c.drainRoutingPublications()]).then(()=>{})}},a=new WeakMap;return c}import{remapModelId as CX}from"@cortexkit/anthropic-auth-core";function w$(){let $=new D$,X=new Map,z=new Map,G=new Map,N=new Set,L=new Set,P=new Map,T=(K)=>{while(K.size>512){let Y=K.keys().next();if(!Y.done)K.delete(Y.value)}};return{async install(K){let Y=[];try{Y.push(await K.session.hook("context",(H)=>{let V=H.messages.map((O)=>{return{info:{id:O.id,sessionID:H.sessionID,role:O.role,agent:H.agent,model:{providerID:H.model.providerID,modelID:H.model.id}},parts:O.content.map((q)=>({type:q.type,...q.type==="text"?{text:q.text}:{}}))}});$.observeMessages(V);let B=H.messages.findLast((O)=>O.role==="user"&&O.id);if(B?.id)X.set(H.sessionID,B.id);if(B?.content.some((O)=>O.type==="text"&&O.text===E2))N.add(H.sessionID);else N.delete(H.sessionID);T(X)},{providerID:"anthropic"})),Y.push(await K.session.hook("model.request",(H)=>{if(H.kind!=="primary")return;let V=X.get(H.sessionID);if(!V)return;if($.markHeaders({sessionId:H.sessionID,messageId:V,agent:H.agent,headers:H.headers}),N.has(H.sessionID))H.headers[L2]="1"},{providerID:"anthropic"}))}catch(H){throw await Promise.allSettled(Y.map((V)=>V.dispose())),H}return{dispose:async()=>{await Promise.all(Y.map((H)=>H.dispose()))}}},requestOptions(K,Y){let H=$.resolveHeader(K.correlation[O2]);if(H)z.set(K.attemptId,H),T(z);P.set(K.attemptId,K.sessionID),T(P);let V=K.correlation[L2]==="1";if(V)L.add(K.attemptId);return{cache1hEnabled:K.agent!=="compaction"&&K.agent!=="title"&&(Y.policyStorage.claudeCache?.enabled??!0),cache1hMode:Y.policyStorage.claudeCache?.mode??"explicit",fastModeEnabled:Y.policyStorage.claudeFast?.enabled===!0,thinkingPrefixMismatchBehavior:Y.policyStorage.thinkingBinding?.prefixMismatchBehavior,midConversationEffortEnabled:!1,turnEndNoteEnabled:!0,turnEndNote:Y.policyStorage.turnEndNote,serverSideFallbackEnabled:b$(process.env.OPENCODE_ANTHROPIC_AUTH_CONTENT_FILTER_FALLBACK)==="server",laneStart:V,billingLineage:H?{promptId:H.promptId,previousRequestId:H.previousRequestId}:void 0,cacheDiagnosticsPreviousMessageId:G.get(K.sessionID)}},responseOptions(K){return{serverSideFallbackModel:CX(K.modelID),laneStart:L.has(K.attemptId),onMessageStart(Y){if(K.kind==="primary"&&typeof Y.id==="string")G.set(K.sessionID,Y.id),T(G)},onStreamEnd(){z.delete(K.attemptId),L.delete(K.attemptId),P.delete(K.attemptId)}}},onRequestId(K,Y){$.commit(z.get(K.attemptId),Y)},forgetSession(K){$.clearSession(K),X.delete(K),G.delete(K),N.delete(K);for(let[Y,H]of P)if(H===K)z.delete(Y),L.delete(Y),P.delete(Y)}}}var A2="cortexkit-anthropic-auth",SX='This OpenCode is enrolled in the Claude vault and uses only vault accounts. Choose "Claude vault accounts" instead; no local account was changed.',xX="This OpenCode is not enrolled in the Claude vault. Enroll it first, or sign in with Claude Pro / Max.",RX="The Claude vault enrollment could not be read; repair it and retry. Nothing was changed.";function AX($){let X=$.authorize??LX,z=$.exchange??TX,G=()=>{if(!$.isActive())throw Error("Claude authentication setup is closed")},N=async()=>{let T;try{T=await $.readMode()}catch{throw Error(RX)}return G(),T},L=async()=>{if(await N()!=="local")throw Error(SX)};return{integrationID:"anthropic",methods:[{method:{id:I$,type:"oauth",label:f$},async authorize(){G(),await L();let T=await X("max");return G(),{mode:"code",url:T.url,instructions:"Paste the authorization code returned by Claude.",callback:async(K)=>{G();let Y=await z(K,T.verifier,T.redirectUri,T.state);if(!$.isActive()||Y.type!=="success")throw Error("Claude sign-in did not complete");return{access:Y.access,refresh:Y.refresh,expires:Y.expires}}}}}],vault:{method:{id:g$,type:"oauth",label:"Claude vault accounts"},async activate(){if(G(),await N()!=="claustrum")throw Error(xX)}},async onLogin(T){G(),await L(),await $.runtime.loginOAuth({routeId:"main",credential:T,replace:!0}),G()},label:"Claude native account pool"}}function qX($){return{readMode:()=>OX("opencode",$),disconnectVault:()=>FX({host:"opencode",env:$})}}function d2($={}){return{id:A2,setup:(X)=>h$(X,$)}}async function h$($,X={}){let z=X.paths??await EX(),G=NX({paths:z,host:"opencode",local:X.local,vault:X.vault}),N=qX(X.vault?.env??process.env),L=!0,P=w$(),T=T$(),K,Y,H,V=k$({runtime:G,paths:z,fetch:X.fetch,requestOptions:P.requestOptions,responseOptions:P.responseOptions,onRequestId:P.onRequestId,onForgetSession:P.forgetSession,onRequestPrepared:async(b)=>{try{await H?.track(b)}catch{y$.warn("cachekeep","live request tracking failed")}},resolveModelId:async(b)=>T.modelId(b.modelID),onOwnedRequest:()=>{K??=M$(G,X.fetch),Y??=R$({runtime:G,paths:z,source:V,fetch:X.fetch})}});H=H$({...X.cacheKeep,runtime:G,source:V,fetch:X.fetch,isSubagent:async(b)=>Boolean((await $.session.get({sessionID:b})).parentID)});let B=F$({runtime:G,source:V,cacheKeepRegistry:H.registry,start:async(b,i)=>{await $.session.synthetic({sessionID:b,text:i,description:"Claude lane start",resume:!0})}}),O=[],q=await K$($,{source:V,log:{warn:(b,i)=>y$.warn("opencode2",b,i)}},{credential:O$}).catch(async(b)=>{throw B.close(),await H?.dispose(),await V.close(),G.close(),b}),R,m=()=>{if(R)return R;return L=!1,B.close(),V.close(),R=(async()=>{await Promise.allSettled([q.dispose(),K?.dispose(),Y?.dispose(),H?.dispose(),...O.map((b)=>b.dispose())]),await V.close(),G.close()})(),R};try{O.push(await P.install($)),O.push(await T.install($)),O.push(await k2($,AX({isActive:()=>L,readMode:N.readMode,runtime:G})));let b={host:"opencode",dispatch:B.dispatch,readStatus:(n)=>B.readStatus(n),readAccounts:()=>G.read(),readMode:N.readMode,disconnectVault:N.disconnectVault,interactive:!0},i=PX(b);return O.push(await v$($,i,B)),m}catch(b){throw await m(),b}}var iJ={id:A2,setup:d2().setup,server:m$};export{h$ as setupAnthropicAuth,iJ as default,d2 as createAnthropicAuthPlugin,A2 as ANTHROPIC_AUTH_PLUGIN_ID};
package/dist/v2/tui.js CHANGED
@@ -1,2 +1,2 @@
1
- import{t as P}from"../index-pden7a7y.js";import"../index-czyrqpxc.js";import"../index-f2ne65w4.js";async function T(D,R={}){let Y=D.client.rpc(P),L=!0,q=!1,O=new AbortController,Q=()=>{let z=D.ui.router.current();return z.type==="session"?z.sessionID:void 0};function U(z){return new Promise((K)=>{let j="",H=!1,W=D.keymap.mode.push("cortexkit-protected-entry"),J=(B,G=!0)=>{if(H)return;H=!0,D.renderer.keyInput.off("keypress",Z),D.renderer.keyInput.off("paste",$),O.signal.removeEventListener("abort",X),W();let C=B?j:void 0;if(j="",G)D.ui.dialog.clear();K(C)},X=()=>J(!1),Z=(B)=>{if(B.preventDefault(),B.stopPropagation(),B.name==="escape"||B.ctrl&&B.name==="c")return J(!1);if(B.name==="return"||B.name==="enter")return J(!0);if(B.name==="backspace"){j=Array.from(j).slice(0,-1).join("");return}if(!B.ctrl&&!B.meta&&!B.option&&Array.from(B.sequence).every((G)=>G.charCodeAt(0)>=32&&G.charCodeAt(0)!==127))j=(j+B.sequence).slice(0,4096)},$=(B)=>{B.preventDefault(),B.stopPropagation(),j=(j+Array.from(new TextDecoder().decode(B.bytes)).filter((G)=>G.charCodeAt(0)>=32&&G.charCodeAt(0)!==127).join("")).slice(0,4096)};if(D.renderer.keyInput.prependListener("keypress",Z),D.renderer.keyInput.prependListener("paste",$),O.signal.addEventListener("abort",X,{once:!0}),D.ui.dialog.alert({title:z,message:"Type or paste the value. Input is hidden. Enter accepts; Escape cancels."}).then(()=>J(!1,!1),()=>J(!1,!1)),O.signal.aborted)X()})}async function V(z){let K={};for(let j of z.knobs){if(!L)return;if(j.kind==="choice"){let H=await D.ui.dialog.select({title:j.label,options:j.choices.map((W)=>({title:W.label,value:W.value})),current:j.value});if(H===void 0)return;K[j.id]=H}else if(j.kind==="toggle"){let H=await D.ui.dialog.select({title:j.label,options:[{title:"On",value:!0},{title:"Off",value:!1}],current:j.value});if(H===void 0)return;K[j.id]=H}else{let H=j.kind==="text"&&j.masked?await U(j.label):await D.ui.dialog.prompt({title:j.label,value:j.value===void 0?void 0:String(j.value),placeholder:j.kind==="text"?j.placeholder:void 0});if(H===void 0)return;K[j.id]=H===""&&!j.required?null:j.kind==="number"?Number(H):H}}return K}async function F(z,K){if(!L||q||Q()!==z)return;q=!0;let j=K;try{while(L&&Q()===z){let H=await D.ui.dialog.select({title:j.menu.title,options:j.menu.sections.map((G)=>({title:G.title,description:G.lines.join(`
1
+ import{t as P}from"../index-88zg9ztr.js";import"../index-xbwa4x53.js";import"../index-62x1p34p.js";async function T(D,R={}){let Y=D.client.rpc(P),L=!0,q=!1,O=new AbortController,Q=()=>{let z=D.ui.router.current();return z.type==="session"?z.sessionID:void 0};function U(z){return new Promise((K)=>{let j="",H=!1,W=D.keymap.mode.push("cortexkit-protected-entry"),J=(B,G=!0)=>{if(H)return;H=!0,D.renderer.keyInput.off("keypress",Z),D.renderer.keyInput.off("paste",$),O.signal.removeEventListener("abort",X),W();let C=B?j:void 0;if(j="",G)D.ui.dialog.clear();K(C)},X=()=>J(!1),Z=(B)=>{if(B.preventDefault(),B.stopPropagation(),B.name==="escape"||B.ctrl&&B.name==="c")return J(!1);if(B.name==="return"||B.name==="enter")return J(!0);if(B.name==="backspace"){j=Array.from(j).slice(0,-1).join("");return}if(!B.ctrl&&!B.meta&&!B.option&&Array.from(B.sequence).every((G)=>G.charCodeAt(0)>=32&&G.charCodeAt(0)!==127))j=(j+B.sequence).slice(0,4096)},$=(B)=>{B.preventDefault(),B.stopPropagation(),j=(j+Array.from(new TextDecoder().decode(B.bytes)).filter((G)=>G.charCodeAt(0)>=32&&G.charCodeAt(0)!==127).join("")).slice(0,4096)};if(D.renderer.keyInput.prependListener("keypress",Z),D.renderer.keyInput.prependListener("paste",$),O.signal.addEventListener("abort",X,{once:!0}),D.ui.dialog.alert({title:z,message:"Type or paste the value. Input is hidden. Enter accepts; Escape cancels."}).then(()=>J(!1,!1),()=>J(!1,!1)),O.signal.aborted)X()})}async function V(z){let K={};for(let j of z.knobs){if(!L)return;if(j.kind==="choice"){let H=await D.ui.dialog.select({title:j.label,options:j.choices.map((W)=>({title:W.label,value:W.value})),current:j.value});if(H===void 0)return;K[j.id]=H}else if(j.kind==="toggle"){let H=await D.ui.dialog.select({title:j.label,options:[{title:"On",value:!0},{title:"Off",value:!1}],current:j.value});if(H===void 0)return;K[j.id]=H}else{let H=j.kind==="text"&&j.masked?await U(j.label):await D.ui.dialog.prompt({title:j.label,value:j.value===void 0?void 0:String(j.value),placeholder:j.kind==="text"?j.placeholder:void 0});if(H===void 0)return;K[j.id]=H===""&&!j.required?null:j.kind==="number"?Number(H):H}}return K}async function F(z,K){if(!L||q||Q()!==z)return;q=!0;let j=K;try{while(L&&Q()===z){let H=await D.ui.dialog.select({title:j.menu.title,options:j.menu.sections.map((G)=>({title:G.title,description:G.lines.join(`
2
2
  `),value:G}))});if(!H||!L||Q()!==z)return;let W=[...H.actions.map((G)=>({action:G,itemId:void 0})),...H.items.flatMap((G)=>G.actions.map((C)=>({action:C,itemId:G.id})))],J=await D.ui.dialog.select({title:H.title,options:W.map((G)=>({title:G.action.label,description:G.action.description,value:G}))});if(!J)continue;let X=await V(J.action);if(!X||!L||Q()!==z)return;let Z=J.action.confirm?await D.ui.dialog.confirm({title:J.action.label,message:J.action.confirm.message}):void 0;if(J.action.confirm&&Z!==!0)continue;if(!L||Q()!==z)return;let $={command:"claude",sectionId:H.id,itemId:J.itemId,actionId:J.action.id,sessionId:z,values:X,confirmed:Z},B=await Y.apply($,{signal:O.signal,location:D.location});if(!L||Q()!==z)return;await D.ui.dialog.alert({title:B.ok?"Claude":"Claude action refused",message:B.text}),j={command:B.command,menu:B.menu}}}finally{q=!1}}let w=Y.events.on("opened",(z)=>F(z.data.sessionId,z.data.payload),{signal:O.signal}),A=Y.events.on("notification",(z)=>{if(L&&Q()===z.data.sessionId)D.ui.toast.show({title:"Claude",sessionID:z.data.sessionId,message:z.data.message,variant:z.data.kind})},{signal:O.signal});D.keymap.layer(()=>({commands:[{id:"cortexkit.claude",title:"Claude",group:"Claude",palette:!0,slash:{name:"claude"},async run(){let z=Q();if(!z){await D.ui.dialog.alert({title:"Claude",message:"Open a session before using the Claude menu."});return}let K=await Y.open({sessionId:z},{signal:O.signal,location:D.location});await F(z,K)}}]}));let M;try{M=await R.mountSidebar?.(D,(z,K)=>Y.sidebar({sessionId:z},{signal:K,location:D.location}))}catch{}return()=>{L=!1,O.abort(),w(),A(),M?.()}}var E={id:"cortexkit-anthropic-auth",setup:T};export{T as setupAnthropicTui,E as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "2.2.0",
3
+ "version": "2.2.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -77,7 +77,7 @@
77
77
  },
78
78
  "dependencies": {
79
79
  "@clack/prompts": "^1.6.0",
80
- "@cortexkit/anthropic-auth-core": "2.2.0",
80
+ "@cortexkit/anthropic-auth-core": "2.2.1",
81
81
  "@cortexkit/claustrum-client": "0.12.0",
82
82
  "@cortexkit/private-files": "0.2.1",
83
83
  "@cortexkit/subc-client": "^0.22.0",
@@ -132,6 +132,7 @@ import {
132
132
  isQuotaStale,
133
133
  logger,
134
134
  quotaDisplayProjection,
135
+ quotaTextParts,
135
136
  } from '@cortexkit/anthropic-auth-core'
136
137
 
137
138
  const STATE_FILE_ENV = 'OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE'
@@ -951,6 +952,130 @@ export function formatQuotaRowLabel(name: string, width = 10): string {
951
952
  return label + ' '.repeat(Math.max(0, width - Bun.stringWidth(label)))
952
953
  }
953
954
 
955
+ /**
956
+ * The short names model-scoped rows read under, in the order of `quota.scoped`:
957
+ * the names common-auth's narrow one-line form gives them (`Fa` for Fable;
958
+ * models whose short names would collide are extended until they differ, as
959
+ * `Fabl` and `Fabr`), so the expanded rows and the collapsed line agree.
960
+ *
961
+ * common-auth exposes that short name only inside the narrow text, and the
962
+ * narrow line shows just one model window (the tightest). So each window's
963
+ * name is read from a narrow line of a copy of the reading in which that
964
+ * window alone is spent: every model window stays in, so collisions resolve
965
+ * exactly as they do in the real line, and the one piece the line shows is
966
+ * `<short name> 0% left`. The figures in the copy are never displayed.
967
+ */
968
+ export function scopedQuotaShortNames(
969
+ quota: Pick<AccountQuota, 'scoped'> | null | undefined,
970
+ now = Date.now(),
971
+ ): string[] {
972
+ const scoped = quota?.scoped ?? []
973
+ return scoped.map((window, index) => {
974
+ const probe = quotaDisplayProjection(
975
+ {
976
+ scoped: scoped.map((other, at) => ({
977
+ ...other,
978
+ usedPercent: at === index ? 100 : 0,
979
+ remainingPercent: at === index ? 0 : 100,
980
+ checkedAt: now,
981
+ })),
982
+ },
983
+ now,
984
+ )
985
+ const piece = quotaTextParts(probe, { now, form: 'narrow' })[0]
986
+ const name = piece?.replace(/ 0% left$/, '')
987
+ return name && name !== piece ? name : window.title
988
+ })
989
+ }
990
+
991
+ /**
992
+ * The width of the quota rows' label column: the longest label any of these
993
+ * accounts shows. `5h` and `7d` always show, so it is at least 2.
994
+ */
995
+ export function quotaLabelColumnWidth(
996
+ quotas: readonly (AccountQuota | null | undefined)[],
997
+ now = Date.now(),
998
+ ): number {
999
+ return Math.max(
1000
+ 2,
1001
+ ...quotas.flatMap((quota) =>
1002
+ scopedQuotaShortNames(quota, now).map((name) => Bun.stringWidth(name)),
1003
+ ),
1004
+ )
1005
+ }
1006
+
1007
+ /** The narrowest a quota row's bar shrinks to. */
1008
+ export const QUOTA_BAR_MIN_CELLS = 3
1009
+
1010
+ export interface QuotaRowFit {
1011
+ /** Bar cells to draw. */
1012
+ barCells: number
1013
+ /** The reset text to draw at the right edge, or undefined for none. */
1014
+ reset?: string
1015
+ }
1016
+
1017
+ /**
1018
+ * Fits one quota row into `width` cells. The row reads `label bar figure` on
1019
+ * the left and the reset at the right edge, with a one-cell gap before the
1020
+ * reset that the caller always draws. When the full row is too wide, the
1021
+ * reset is dropped first, so the figure (the percent left) is never cut to
1022
+ * keep it; then the bar shrinks, down to `QUOTA_BAR_MIN_CELLS`. A row still
1023
+ * too wide at that point keeps the minimum bar and is cut at the right edge
1024
+ * by the caller's no-wrap text, which cuts the figure's end. Without a
1025
+ * measured width the full row is used.
1026
+ */
1027
+ export function fitQuotaRow(input: {
1028
+ width: number | undefined
1029
+ labelWidth: number
1030
+ barWidth: number
1031
+ /** The figure with any binding marker, such as `97% left •`. */
1032
+ figure: string
1033
+ reset?: string
1034
+ }): QuotaRowFit {
1035
+ const { width, labelWidth, barWidth, figure, reset } = input
1036
+ const full: QuotaRowFit = { barCells: barWidth, reset: reset || undefined }
1037
+ if (width === undefined) return full
1038
+ const cells = (fit: QuotaRowFit) =>
1039
+ labelWidth +
1040
+ 1 +
1041
+ (fit.barCells > 0 ? fit.barCells + 1 : 0) +
1042
+ Bun.stringWidth(figure) +
1043
+ (fit.reset ? 1 + Bun.stringWidth(fit.reset) : 0)
1044
+ const minimum = Math.min(QUOTA_BAR_MIN_CELLS, barWidth)
1045
+ const candidates: QuotaRowFit[] = [full]
1046
+ for (let barCells = barWidth; barCells >= minimum; barCells--) {
1047
+ candidates.push({ barCells })
1048
+ }
1049
+ return candidates.find((fit) => cells(fit) <= width) ?? { barCells: minimum }
1050
+ }
1051
+
1052
+ /**
1053
+ * The pacing subline for a window that is off pace: `deficit 12% · out in
1054
+ * 1d23h` for a deficit that runs out before the reset, otherwise the delta
1055
+ * and `lasts to reset` (`reserve 4% · lasts to reset`). When it is wider than
1056
+ * `width` cells it is cut to fit and ends in `…` rather than wrapping. Null
1057
+ * when there is no pacing or the window is on pace.
1058
+ */
1059
+ export function fitPaceLine(
1060
+ pacing: QuotaPacing | null,
1061
+ width: number | undefined,
1062
+ runsOutIn: string | undefined,
1063
+ ): string | null {
1064
+ if (!pacing || pacing.state === 'on-pace') return null
1065
+ const head = `${pacing.state} ${Math.round(Math.abs(pacing.deltaPercent))}%`
1066
+ const line = runsOutIn
1067
+ ? `${head} \u00b7 out in ${runsOutIn}`
1068
+ : `${head} \u00b7 lasts to reset`
1069
+ if (width === undefined || Bun.stringWidth(line) <= width) return line
1070
+ if (width <= 0) return ''
1071
+ let cut = ''
1072
+ for (const character of line) {
1073
+ if (Bun.stringWidth(cut + character) > width - 1) break
1074
+ cut += character
1075
+ }
1076
+ return `${cut.trimEnd()}\u2026`
1077
+ }
1078
+
954
1079
  export function getCollapsedQuotaSummary(
955
1080
  quota: AccountQuota | null,
956
1081
  now = Date.now(),