@cortexkit/opencode-anthropic-auth 2.15.0 → 2.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  import{createRequire as q}from"node:module";var j=Object.create;var{getPrototypeOf:k,defineProperty:i,getOwnPropertyNames:l}=Object;var m=Object.prototype.hasOwnProperty;function n(a){return this[a]}var o,p,r=(a,b,d)=>{var f=a!=null&&typeof a==="object";if(f){var g=b?o??=new WeakMap:p??=new WeakMap,h=g.get(a);if(h)return h}d=a!=null?j(k(a)):{};let c=b||!a||!a.__esModule?i(d,"default",{value:a,enumerable:!0}):d;for(let e of l(a))if(!m.call(c,e))i(c,e,{get:n.bind(a,e),enumerable:!0});if(f)g.set(a,c);return c};var s=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var u=q(import.meta.url);
2
- export{r as ma,s as na,u as oa};
2
+ export{r as na,s as oa,u as pa};
@@ -1,2 +1,2 @@
1
1
  import{randomUUID as E}from"node:crypto";import{mkdir as g,readFile as y,rename as S,rm as O,rmdir as w,stat as D,unlink as m,writeFile as b}from"node:fs/promises";import{tmpdir as d}from"node:os";import{dirname as v,join as f}from"node:path";import{formatQuota as c,isQuotaStale as s,logger as C,quotaDisplayProjection as I,quotaWindowParts as u,resolveClaudeModelCapabilities as i}from"@cortexkit/anthropic-auth-core";var n="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",l=f(d(),"opencode-anthropic-auth"),o=f(l,"sidebar-state.json");function P(){return process.env[n]||o}var H={main:{quota:null},fallbacks:[],route:"main",relay:null,fastMode:!1,lastUpdated:0};function Q(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function z(J){return typeof J==="number"&&Number.isFinite(J)}function r(J){if(!Q(J))return;let Z=Number(J.count),V=Number(J.inputTokens),X=Number(J.outputTokens),x=Number(J.since);if(![Z,V,X,x].every(Number.isFinite)||Z<0||V<0||X<0||x<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(X),since:Math.floor(x)}}function a(J){if(!Q(J))return;if(typeof J.id!=="string"||!J.id.trim())return;if(typeof J.label!=="string"||!J.label.trim())return;let Z={id:J.id.trim(),label:J.label.trim()};if(J.nextDueAt===null)Z.nextDueAt=null;else if(z(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(z(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error"||J.lastResult==="skipped")Z.lastResult=J.lastResult;let V=r(J.usage);if(V)Z.usage=V;if(z(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function t(J){if(!Q(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(a).filter((V)=>V!=null):[];return{enabled:J.enabled,accounts:Z}}function q(J){if(!Q(J))return;let Z=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite(Z)||!Number.isFinite(V))return;return{usedPercent:Z,remainingPercent:V,...typeof J.resetsAt==="string"&&{resetsAt:J.resetsAt},...z(J.checkedAt)&&{checkedAt:J.checkedAt}}}function R(J){if(!Q(J))return null;let Z={};if(z(J.checkedAt))Z.checkedAt=J.checkedAt;let V=q(J.five_hour),X=q(J.seven_day);if(V)Z.five_hour=V;if(X)Z.seven_day=X;if(Array.isArray(J.scoped)){let x=J.scoped.map((Y)=>{if(!Q(Y))return;let G=q(Y);if(!G)return;if(typeof Y.id!=="string"||!Y.id.trim())return;if(typeof Y.title!=="string"||!Y.title.trim())return;if(typeof Y.modelName!=="string"||!Y.modelName.trim())return;let $=typeof Y.modelId==="string"&&Y.modelId.trim()?Y.modelId.trim():void 0;return{...G,id:Y.id.trim(),title:Y.title.trim(),...$&&{modelId:$},modelName:Y.modelName.trim()}}).filter((Y)=>Y!=null);Z.scoped=x}if(Q(J.extraUsage)){let x=A(J.extraUsage.used),Y=A(J.extraUsage.limit);if(x&&Y&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:x,limit:Y,...typeof J.extraUsage.utilizationPercent==="number"&&Number.isFinite(J.extraUsage.utilizationPercent)&&{utilizationPercent:J.extraUsage.utilizationPercent},...typeof J.extraUsage.severity==="string"&&{severity:J.extraUsage.severity},exhausted:J.extraUsage.exhausted}}if(typeof J.bindingWindow==="string"&&J.bindingWindow.trim())Z.bindingWindow=J.bindingWindow.trim();if(typeof J.fallbackAdvised==="boolean")Z.fallbackAdvised=J.fallbackAdvised;return Object.keys(Z).length?Z:null}function A(J){if(!Q(J))return;if(!Number.isInteger(J.amountMinor)||typeof J.currency!=="string"||!/^[A-Za-z]{3}$/.test(J.currency.trim())||!Number.isInteger(J.exponent)||J.exponent<0||J.exponent>20)return;return{amountMinor:J.amountMinor,currency:J.currency.trim(),exponent:J.exponent}}function k(J){if(!Q(J))return{...H};let Z={quota:null};if(Q(J.main)){let $=J.main;if(Z.quota=R($.quota),typeof $.enabled==="boolean")Z.enabled=$.enabled;if(typeof $.stateLine==="string")Z.stateLine=$.stateLine;if($.quotaDated===!0)Z.quotaDated=!0;if(typeof $.tierLabel==="string"&&$.tierLabel.trim())Z.tierLabel=$.tierLabel.trim();if(typeof $.quotaBackedOff==="boolean")Z.quotaBackedOff=$.quotaBackedOff;if(z($.quotaBackoffUntil))Z.quotaBackoffUntil=$.quotaBackoffUntil;if(typeof $.refreshBackedOff==="boolean")Z.refreshBackedOff=$.refreshBackedOff;if(z($.refreshBackoffUntil))Z.refreshBackoffUntil=$.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(Q).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,...typeof $.label==="string"&&{label:$.label},quota:R($.quota),enabled:typeof $.enabled==="boolean"?$.enabled:!1,...typeof $.stateLine==="string"&&{stateLine:$.stateLine},...$.quotaDated===!0&&{quotaDated:!0},needsReauth:typeof $.needsReauth==="boolean"?$.needsReauth:!1,...$.vaultReauth===!0&&{vaultReauth:!0},...$.vaultServed===!0&&{vaultServed:!0},...typeof $.custodyState==="string"&&{custodyState:$.custodyState},...typeof $.tierLabel==="string"&&$.tierLabel.trim()&&{tierLabel:$.tierLabel.trim()}})):[],X=null;if(Q(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")X={enabled:$.enabled,transport:$.transport}}let x;if(Q(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")x={enabled:$.enabled,...typeof $.window==="string"&&{window:$.window},...z($.trackedSessions)&&{trackedSessions:$.trackedSessions}}}let Y=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(Q).flatMap(($)=>{if(typeof $.sessionId!=="string"||$.mode!=="opus"&&$.mode!=="fable"&&$.mode!=="server"||typeof $.remaining!=="number"||!Number.isFinite($.remaining)||typeof $.changedAt!=="number"||!Number.isFinite($.changedAt))return[];return[{sessionId:$.sessionId,mode:$.mode,remaining:Math.max(0,Math.floor($.remaining)),changedAt:$.changedAt,...typeof $.requestedModelId==="string"&&{requestedModelId:$.requestedModelId},...typeof $.targetModelId==="string"&&{targetModelId:$.targetModelId}}]}):[],G=t(J.prime);return{main:Z,fallbacks:V,...typeof J.activeId==="string"&&{activeId:J.activeId},route:typeof J.route==="string"?J.route:H.route,relay:X,fastMode:typeof J.fastMode==="boolean"?J.fastMode:H.fastMode,...x&&{cacheKeep:x},...G&&{prime:G},...Y.length>0&&{fableRecoveries:Y},lastUpdated:z(J.lastUpdated)?J.lastUpdated:0}}var W=Promise.resolve(),e=1000,JJ=2000,ZJ=5,$J=15,M=new Map;function WJ(J,Z=P()){if(J)M.set(Z,J);else M.delete(Z)}function U(J){return M.get(J)}var p=null;function UJ(J){p=J}function qJ(){return p}function VJ(J){return new Promise((Z)=>setTimeout(Z,J))}async function F(J){let Z=`${J}.lock`,V=U(J),X=V?.lockBudgetMs??e,x=V?.lockRetryMinMs??ZJ,Y=V?.lockRetryMaxMs??$J,G=Date.now()+X;while(!0){try{await g(Z);let K=E(),j=f(Z,K);return await b(j,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await D(j),!0}catch{return!1}},release:async()=>{try{await m(j)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(K){if(K.code!=="EEXIST")return C.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}try{let K=await D(Z);if(Date.now()-K.mtimeMs>JJ){await V?.afterStaleLockStat?.(Z);let j=`${Z}.evict-${process.pid}-${E()}`;try{await S(Z,j)}catch(N){if(N.code==="ENOENT")continue;throw N}await V?.onStaleLockClaimed?.(Z),await O(j,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(K){if(K.code==="ENOENT")continue;return C.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}let $=G-Date.now();if($<=0)return C.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:X}),null;let B=x+Math.floor(Math.random()*(Y-x+1));await VJ(Math.min(B,$))}}async function LJ(J){return(await F(J))?.release??null}async function XJ(J,Z,V){let X=U(J),x=`${J}.${process.pid}.${E()}.tmp`;await b(x,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await X?.beforeRename?.(J,x),!await V())return C.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await O(x,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await S(x,J),await U(J)?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(Y){throw await O(x,{force:!0}).catch(()=>{}),Y}}async function T(J=P()){try{let Z=await y(J,"utf8");return k(JSON.parse(Z))}catch{return H}}async function EJ(J,Z=P(),V={}){return W=W.then(async()=>{await g(v(Z),{recursive:!0});for(let X=0;X<2;X++){let x=X===1,Y=await F(Z);if(!Y){if(x)C.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let G=J,$;try{if(V.routingAuthoritative===!1){let B=await T(Z),K=await V.resolvePreservedRouting?.(B);if(K){let j=K.state??J;G={...j,activeId:K.activeId,route:K.route,lastUpdated:Math.max(j.lastUpdated,B.lastUpdated)}}await U(Z)?.afterMergeRead?.(Z)}else if(x){let B=await T(Z);G={...B,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(B.lastUpdated,J.lastUpdated)}}G=k(G),$=await XJ(Z,G,Y.ownsLock)}finally{await Y.release()}if($==="lock-lost-after-rename"){if(x){C.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}C.warn("sidebar","state lock lost after rename; repairing write",{stateFile:Z});continue}if($==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:G.activeId,route:G.route});return}}).catch(()=>{}),W}async function MJ(){return W}function YJ(J){let Z=J.activeId;if(Z&&Z!=="main"){let V=J.fallbacks?.find((X)=>X.enabled&&X.id===Z);if(V)return{id:V.id,name:V.label??V.id,quota:V.quota,...V.stateLine&&{stateLine:V.stateLine,quotaDated:V.quotaDated}}}return{id:"main",name:"main",quota:J.main?.quota??null,...J.main?.stateLine&&{stateLine:J.main.stateLine,quotaDated:J.main.quotaDated}}}function L(J){let Z=i(J);if(Z?.id==="claude-fable-5-2"||Z?.id==="claude-mythos-5-2")return Z.name.replace(/^Claude /,"");if(J==="claude-mythos-5-1"||J?.startsWith("claude-mythos-5-1-"))return"Mythos 5.1";if(J==="claude-fable-5-1"||J?.startsWith("claude-fable-5-1-"))return"Fable 5.1";if(J==="claude-fable-5"||J?.startsWith("claude-fable-5-"))return"Fable 5";if(J==="claude-opus-5-5"||J?.startsWith("claude-opus-5-5-"))return"Opus 5.5";if(J==="claude-opus-5"||J?.startsWith("claude-opus-5-"))return"Opus 5";if(J==="claude-opus-4-8"||J?.startsWith("claude-opus-4-8-"))return"Opus 4.8";return J??"Fable 5"}function h(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function xJ(J){if(J===0)return"0";if(J<0.0001)return J.toExponential(2);return J.toFixed(Math.min(6,Math.max(0,4)))}function fJ(J,Z=Date.now()){if(J.lastResult==="error")return{text:"err",hasError:!0};if(J.lastResult==="skipped")return{text:"skip",hasError:!1};if(J.nextDueAt&&J.nextDueAt>Z)return{text:h(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${h(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${xJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function PJ(J,Z){let V=J.fableRecoveries?.find((X)=>X.sessionId===Z);if(!V)return;if(V.mode==="fable")return`${L(V.requestedModelId)} · restored`;if(V.mode==="server")return`${L(V.requestedModelId)}→${L(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function _J(J,Z=10){if(Z<=0)return"";let V=J;if(Bun.stringWidth(V)>Z){V="";for(let X of J){if(Bun.stringWidth(V+X)>Z-1)break;V+=X}V+="…"}return V+" ".repeat(Math.max(0,Z-Bun.stringWidth(V)))}function GJ(J,Z=Date.now()){let V=J?.scoped??[];if(!V.length)return[];let{windows:X}=u(I({scoped:V},Z),{now:Z});return V.map((x)=>X.find((Y)=>Y.kind==="window"&&Y.name===x.title)?.short||x.title)}function DJ(J,Z=Date.now()){return Math.max(2,...J.flatMap((V)=>GJ(V,Z).map((X)=>Bun.stringWidth(X))))}var KJ=3;function RJ(J){let{width:Z,labelWidth:V,barWidth:X,figure:x,reset:Y}=J,G={barCells:X,reset:Y||void 0};if(Z===void 0)return G;let $=(j)=>V+1+(j.barCells>0?j.barCells+1:0)+Bun.stringWidth(x)+(j.reset?1+Bun.stringWidth(j.reset):0),B=Math.min(KJ,X),K=[G];for(let j=X;j>=B;j--)K.push({barCells:j});return K.find((j)=>$(j)<=Z)??{barCells:B}}function AJ(J,Z,V,X,x){if(!J||J.state==="on-pace")return null;let Y=x!==void 0&&x<=0,G=V==="now"||V==="0m"?"<1m":V,$=`${J.state} ${Math.round(Math.abs(J.deltaPercent))}%`,B=Y?X?`used up · resets in ${X}`:"used up":G?`${$} · out in ${G}`:`${$} · lasts to reset`;if(Z===void 0||Bun.stringWidth(B)<=Z)return B;if(Z<=0)return"";let K="";for(let j of B){if(Bun.stringWidth(K+j)>Z-1)break;K+=j}return`${K.trimEnd()}…`}function TJ(J,Z=Date.now()){let V=J?.five_hour?.usedPercent??null,X=J?.seven_day?.usedPercent??null,x=J?.scoped??[],Y=x.map(($)=>$.usedPercent);if(!J||V==null&&X==null&&x.length===0&&!J.extraUsage)return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:null,stale:!1};let G=I(J,Z);return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:c(G,{now:Z,form:"narrow"}),stale:s(G,{now:Z})}}function hJ(J,Z=!0){let V=J.activeId===void 0?void 0:YJ(J).id;return[{id:"main",name:"main",quota:J.main?.quota??null,quotaDated:J.main?.quotaDated,active:V==="main",blocked:J.main?.enabled===!1||Boolean(J.main?.stateLine)},...Z?(J.fallbacks??[]).filter((X)=>X.enabled||X.custodyState&&X.custodyState!=="off").map((X)=>({id:X.id,name:X.label??X.id,quota:X.quota,quotaDated:X.quotaDated,active:V===X.id,blocked:!X.enabled||Boolean(X.stateLine)||X.needsReauth||X.vaultReauth===!0||X.custodyState!=null&&X.custodyState!=="off"&&X.custodyState!=="on-vault-served"})):[]]}var gJ=18000000,SJ=604800000,jJ=300000,BJ=0.01,QJ=1;function bJ(J,Z,V){if(!J.resetsAt)return null;let X=new Date(J.resetsAt).getTime();if(!Number.isFinite(X))return null;let x=X-Z,Y=V-x;if(Y<jJ)return null;if(Y<Z*BJ)return null;if(Y>=Z)return null;let G=J.usedPercent,$=Math.min(Math.max(Y/Z*100,0),100),B=G-$,K=Math.abs(B)<QJ?"on-pace":B>0?"deficit":"reserve",j=null;if(G>0){let N=Y*100/G,_=x+N;if(_<X)j=new Date(_).toISOString()}return{pacePercent:$,deltaPercent:B,state:K,runsOutAt:j}}
2
- export{P as L,H as M,k as N,WJ as O,UJ as P,qJ as Q,LJ as R,T as S,EJ as T,MJ as U,YJ as V,L as W,h as X,xJ as Y,fJ as Z,PJ as _,_J as $,GJ as aa,DJ as ba,KJ as ca,RJ as da,AJ as ea,TJ as fa,hJ as ga,gJ as ha,SJ as ia,bJ as ja};
2
+ export{P as M,H as N,k as O,WJ as P,UJ as Q,qJ as R,LJ as S,T,EJ as U,MJ as V,YJ as W,L as X,h as Y,xJ as Z,fJ as _,PJ as $,_J as aa,GJ as ba,DJ as ca,KJ as da,RJ as ea,AJ as fa,TJ as ga,hJ as ha,gJ as ia,SJ as ja,bJ as ka};
@@ -0,0 +1,2 @@
1
+ import{mkdir as L,readdir as M,readFile as N,rename as O,unlink as Q,writeFile as R}from"node:fs/promises";import{join as J}from"node:path";import{writerStamp as T}from"@cortexkit/anthropic-auth-core";function U(q){try{return process.kill(q,0),!0}catch(z){return z.code==="EPERM"}}var V={mkdir:async(q)=>{await L(q,{recursive:!0})},write:(q,z)=>R(q,z,{encoding:"utf8",mode:384}),rename:O,sleep:(q)=>new Promise((z)=>setTimeout(z,q))};async function Z(q,z,E={}){let C={...V,...E},G={...z,startedAt:Date.now(),writer:T()},H=J(q,`port-${z.pid}.json`),B=`${H}.${process.pid}.tmp`;for(let D=1;;D++){await C.mkdir(q);try{return await C.write(B,JSON.stringify(G)),await C.rename(B,H),H}catch(K){if(K.code!=="ENOENT"||D>=5)throw K;await C.sleep(25)}}}async function _(q,z){let E;try{E=await M(q)}catch{return null}let C=[];for(let B of E){if(!B.startsWith("port-")||!B.endsWith(".json"))continue;try{let D=JSON.parse(await N(J(q,B),"utf8"));if(Number.isFinite(D.port))if(U(D.pid))C.push(D);else Q(J(q,B)).catch(()=>{})}catch{}}if(C.length===0)return null;let G=z&&z>=1?C.filter((B)=>B.pid===z):[];return(G.length>0?G:C).sort((B,D)=>D.startedAt-B.startedAt)[0]??null}
2
+ export{Z as la,_ as ma};
@@ -1,2 +1,2 @@
1
1
  import{existsSync as Z,readFileSync as $}from"node:fs";import{dirname as W,join as B,resolve as X}from"node:path";import{fileURLToPath as Y}from"node:url";import{getHostDataHome as F,getHostHome as V}from"@cortexkit/anthropic-auth-core";var b="@cortexkit/opencode-anthropic-auth",x="@cortexkit/pi-anthropic-auth";function G(q=process.env,J=process.platform){let z=q.OPENCODE_CONFIG_DIR?.trim();if(z)return X(z);return B(q.XDG_CONFIG_HOME||B(V(q,J),".config"),"opencode")}function I(q=process.env){return B(F(q),"opencode")}function K(q=process.env){return B(I(q),"auth.json")}function M(q=process.env,J=process.platform){let z=q.PI_CODING_AGENT_DIR?.trim()||q.PI_AGENT_DIR?.trim();if(z)return X(z);return B(V(q,J),".pi","agent")}function R(q=process.env){let J=q.PI_CODING_AGENT_DIR,z=V(q),w=J||B(z,".pi","agent");if(w==="~")w=z;else if(w.startsWith("~/")||process.platform==="win32"&&w.startsWith("~\\"))w=B(z,w.slice(2));if(w.startsWith("file://"))w=Y(w);return B(w,"auth.json")}async function y(){let q=W(Y(import.meta.url));for(let J=0;J<5;J++){let z=B(q,"package.json");if(Z(z))try{let Q=JSON.parse($(z,"utf8"));if(typeof Q.version==="string"&&Q.version.trim())return Q.version.trim()}catch{}let w=W(q);if(w===q)break;q=w}return"1.22.0"}
2
- export{b as E,x as F,G,K as H,M as I,R as J,y as K};
2
+ export{b as F,x as G,G as H,K as I,M as J,R as K,y as L};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{u as a}from"./index-xh8wd32e.js";import"./index-6q2f3m0v.js";import"./index-77sph3hf.js";import"./index-427t44z7.js";import"./index-0btjtgy5.js";import"./index-27dah13x.js";import"./index-dpxaxyck.js";export{a as AnthropicAuthPlugin};
1
+ import{u as a}from"./index-d6y78qfh.js";import"./index-6q2f3m0v.js";import"./index-ct4m3d80.js";import"./index-yrce651f.js";import"./index-pvvgy8yx.js";import"./index-txrrjz4d.js";import"./index-k9d2hevp.js";export{a as AnthropicAuthPlugin};
@@ -10,9 +10,16 @@ export interface PortFileEntry {
10
10
  */
11
11
  writer?: WriterStamp;
12
12
  }
13
+ /** Filesystem operations and retry delay; tests supply controlled races. */
14
+ export interface PortFileWriterIo {
15
+ mkdir(dir: string): Promise<void>;
16
+ write(path: string, text: string): Promise<void>;
17
+ rename(from: string, to: string): Promise<void>;
18
+ sleep(ms: number): Promise<void>;
19
+ }
13
20
  export declare function writePortFile(dir: string, entry: {
14
21
  port: number;
15
22
  token: string;
16
23
  pid: number;
17
- }): Promise<string>;
24
+ }, overrides?: Partial<PortFileWriterIo>): Promise<string>;
18
25
  export declare function discoverPortFile(dir: string, expectedPid?: number): Promise<PortFileEntry | null>;
@@ -1 +1 @@
1
- import{ka as a,la as b}from"../index-27dah13x.js";import"../index-dpxaxyck.js";export{a as writePortFile,b as discoverPortFile};
1
+ import{la as a,ma as b}from"../index-txrrjz4d.js";import"../index-k9d2hevp.js";export{a as writePortFile,b as discoverPortFile};
@@ -1 +1 @@
1
- import{v as a}from"../index-6q2f3m0v.js";import"../index-dpxaxyck.js";export{a as COMMAND_MODAL_NAMES};
1
+ import{v as a}from"../index-6q2f3m0v.js";import"../index-k9d2hevp.js";export{a as COMMAND_MODAL_NAMES};
@@ -1 +1 @@
1
- import{la as s}from"../index-27dah13x.js";import"../index-dpxaxyck.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};
1
+ import{ma as s}from"../index-txrrjz4d.js";import"../index-k9d2hevp.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};
@@ -1,3 +1,4 @@
1
1
  import { tmpdir } from 'node:os';
2
2
  export declare function getRpcDir(projectDirectory: string): string;
3
+ export declare function getRpcRoot(): string;
3
4
  export { tmpdir };
@@ -1 +1 @@
1
- import{w as a,x as b}from"../index-77sph3hf.js";import"../index-dpxaxyck.js";export{a as tmpdir,b as getRpcDir};
1
+ import{w as a,x as b,y as c}from"../index-ct4m3d80.js";import"../index-k9d2hevp.js";export{a as tmpdir,c as getRpcRoot,b as getRpcDir};
@@ -1,6 +1,7 @@
1
1
  import { type CommandApplyRequest, type CommandApplyResult } from '@cortexkit/anthropic-auth-core';
2
2
  import type { drainNotifications } from './notifications';
3
3
  import type { ApplyRequest, ApplyResult } from './protocol';
4
+ import { type RpcSweepOptions } from './sweep';
4
5
  export interface RpcServerHandle {
5
6
  port: number;
6
7
  token: string;
@@ -13,5 +14,6 @@ export interface RpcServerOptions {
13
14
  apply?: (request: ApplyRequest) => Promise<ApplyResult>;
14
15
  /** Run menu actions through the host's credential service, not legacy account-file writes. */
15
16
  applyMenu?: (request: CommandApplyRequest) => Promise<CommandApplyResult>;
17
+ sweep?: RpcSweepOptions;
16
18
  }
17
19
  export declare function startRpcServer(options: RpcServerOptions): Promise<RpcServerHandle>;
@@ -0,0 +1,14 @@
1
+ export interface RpcSweepState {
2
+ lastFull?: number;
3
+ }
4
+ export interface RpcSweepOptions {
5
+ root?: string;
6
+ now?: () => number;
7
+ /** Signal-zero probe: only the OS "no such process" error proves a process dead. */
8
+ probe?: (pid: number) => void;
9
+ processStartedAtMs?: (pid: number) => Promise<number | null>;
10
+ state?: RpcSweepState;
11
+ log?: (name: string) => void;
12
+ }
13
+ /** Best-effort cleanup; callers may detach it without an unhandled rejection. */
14
+ export declare function sweepRpcState(activeDir: string, options?: RpcSweepOptions): Promise<void>;
@@ -1 +1 @@
1
- import{$ as q,L as a,M as b,N as c,O as d,P as e,Q as f,R as g,S as h,T as i,U as j,V as k,W as l,X as m,Y as n,Z as o,_ as p,aa as r,ba as s,ca as t,da as u,ea as v,fa as w,ga as x,ha as y,ia as z,ja as A}from"./index-0btjtgy5.js";import"./index-dpxaxyck.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};
1
+ import{$ as p,M as a,N as b,O as c,P as d,Q as e,R as f,S as g,T as h,U as i,V as j,W as k,X as l,Y as m,Z as n,_ as o,aa as q,ba as r,ca as s,da as t,ea as u,fa as v,ga as w,ha as x,ia as y,ja as z,ka as A}from"./index-pvvgy8yx.js";import"./index-k9d2hevp.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};
@@ -1,4 +1,4 @@
1
- import"./index-dpxaxyck.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.
1
+ import"./index-k9d2hevp.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.
@@ -1,5 +1,5 @@
1
1
  import { type AnthropicBillingRequest, AnthropicOAuthOriginError, type CacheKeepRealTurn, type ClaudeCodeIdentity, type ClaudeGateway, type RequestGzipLatch, stateRefusalCause, TrailingAssistantHistoryError } from '@cortexkit/anthropic-auth-core';
2
- import type { AccountRequest, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, HeaderEdits, HostError, LimitSignal, OpenCode2AuthAdapter, RequestScope, SameAccountRetryInput, SameAccountRetryResult, Transport } from '@cortexkit/common-auth/opencode2';
2
+ import type { AccountRequest, Attempt, AttemptOutcome, ChooseAccountInput, ChooseAccountResult, HeaderEdits, HostError, LimitSignal, OpenCode2AuthAdapter, RequestScope, SameAccountRetryInput, SameAccountRetryResult, Transport } from '@cortexkit/common-auth/opencode2';
3
3
  import { EffortMarkerCorrelationError } from '../effort-history';
4
4
  import { createStrippedStream, rewriteRequestBody } from '../transform';
5
5
  /** The provider OpenCode 2 serves Claude under. */
@@ -199,6 +199,10 @@ export interface NativeAnthropicSource<Q, P> {
199
199
  } | undefined) => void;
200
200
  /** Response observers for an OAuth response. */
201
201
  readonly responseOptions?: (input: NativeAnthropicResponseContext<P>) => NativeAnthropicResponseOptions | undefined;
202
+ /** Manual quota refusal only when the exhausted pool cannot hold another retry. */
203
+ readonly quotaStopMessage?: (input: NativeAnthropicResponseContext<P> & {
204
+ readonly hostAttempt: number;
205
+ }) => Promise<string | undefined> | string | undefined;
202
206
  /** Quota carried by the upstream response headers, read once per response. */
203
207
  readonly quotaFromHeaders?: (headers: Headers, input: NativeAnthropicResponseContext<P> & {
204
208
  /** Background cache requests harvest quota without reporting turn routing. */
@@ -265,6 +269,10 @@ export interface NativeAnthropicAdapterDeps<Q, P> {
265
269
  readonly now?: () => number;
266
270
  }
267
271
  export interface NativeAnthropicAdapter<Q, P> {
272
+ /** Bind the installer's host retry count to this physical send, never its session. */
273
+ bindHostAttempt(attempt: Attempt<NativeAnthropicAttemptData<P>>, hostAttempt: number): void;
274
+ /** Drop the pending quota-stop message if the send ends before its response body is rewritten. */
275
+ discardQuotaStopMessage(data: NativeAnthropicAttemptData<P>): void;
268
276
  /** Background drivers can refuse a rewritten request before their final dispatch. */
269
277
  discardUnsentBilling(data: NativeAnthropicAttemptData<P>): void;
270
278
  /** Receipt time of this adapter's final verified upstream OAuth 2xx response. */