@cortexkit/opencode-anthropic-auth 2.9.1 → 2.10.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.
@@ -1,2 +1,2 @@
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")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}}
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
2
  export{P as K,H as L,k as M,WJ as N,UJ as O,qJ as P,LJ as Q,T as R,EJ as S,MJ as T,YJ as U,L as V,h as W,xJ as X,fJ as Y,PJ as Z,_J as _,GJ as $,DJ as aa,KJ as ba,RJ as ca,AJ as da,TJ as ea,hJ as fa,gJ as ga,SJ as ha,bJ as ia};
@@ -1,2 +1,2 @@
1
- import{M}from"./index-pxnn7mg1.js";import{logger as R}from"@cortexkit/anthropic-auth-core";var K=(f)=>f!==null&&typeof f==="object"&&!Array.isArray(f),X=(f)=>K(f)&&typeof f.sessionId==="string"&&f.sessionId.length>0,U=(f)=>{if(!X(f)||!K(f)||f.command!=="claude"||typeof f.sectionId!=="string"||typeof f.actionId!=="string")return!1;if(f.itemId!==void 0&&typeof f.itemId!=="string")return!1;if(f.confirmed!==void 0&&typeof f.confirmed!=="boolean")return!1;if(f.values!==void 0&&(!K(f.values)||!Object.values(f.values).every((j)=>j===null||typeof j==="string"||typeof j==="boolean"||typeof j==="number"&&Number.isFinite(j))))return!1;return!0};function H(f){return{"~standard":{version:1,vendor:"cortexkit-native",validate:(j)=>f(j)?{value:j}:{issues:[{message:"Invalid native menu payload"}]}}}}var A=(f)=>K(f)&&f.command==="claude"&&K(f.menu)&&f.menu.command==="claude"&&typeof f.menu.title==="string"&&Array.isArray(f.menu.sections),V=(f)=>K(f)&&f.command==="claude"&&typeof f.ok==="boolean"&&typeof f.text==="string"&&(f.authorizationUrl===void 0||typeof f.authorizationUrl==="string")&&K(f.menu)&&Array.isArray(f.menu.sections),L=!1,$=(f,j,B=new Set)=>{if(f===null||typeof f==="string"||typeof f==="boolean")return f;if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="object"&&f!==null&&!B.has(f)){if(B.add(f),Array.isArray(f)){let Q=Array.from(f,(D,G)=>$(D,`${j}[${G}]`,B)??null);return B.delete(f),Q}if(Object.getPrototypeOf(f)===Object.prototype||Object.getPrototypeOf(f)===null){let Q=Object.fromEntries(Object.entries(f).flatMap(([D,G])=>{let W=$(G,`${j}.${D}`,B);return W===void 0?[]:[[D,W]]}));return B.delete(f),Q}B.delete(f)}if(!L)L=!0,R.warn("sidebar","Dropped non-JSON sidebar field",{path:j});return},E={"~standard":{version:1,vendor:"cortexkit-native",validate:(f)=>{let j=M(f);return{value:$(j,"sidebar")}}}},F={id:"cortexkit-anthropic-native",methods:{open:{input:H(X),output:H(A)},apply:{input:H(U),output:H(V)},sidebar:{input:H(X),output:E}},events:{opened:{schema:H((f)=>X(f)&&A(f.payload))},notification:{schema:H((f)=>X(f)&&typeof f.message==="string"&&["info","warning","error"].includes(String(f.kind)))}}};async function T(f,j,B){let Q=new AbortController,D=(q)=>({sessionId:q,notify(Y,Z="info"){G.events.emit("notification",{sessionId:q,message:Y,kind:Z}).catch(()=>{})}}),G=await f.rpc.register(F,{open:(q)=>j.open(D(q.sessionId)),apply:(q)=>j.apply(q,D(q.sessionId)),sidebar:(q)=>B.readSidebar(q.sessionId)}),W;try{W=await f.command.transform((q)=>q.add({name:"claude",description:"Native Claude accounts and settings",async execute(Y){let Z=await j.open(D(Y.sessionID));await G.events.emit("opened",{sessionId:Y.sessionID,payload:Z})}}))}catch(q){throw await G.dispose(),q}let P=(async()=>{try{for await(let q of f.event.subscribe({signal:Q.signal}))if(q.type==="session.deleted")B.forgetSession(q.data.sessionID)}catch{}})(),z=!1;return{async dispose(){if(z)return;z=!0,Q.abort(),await Promise.all([G.dispose(),W.dispose(),P])}}}
1
+ import{M}from"./index-m7k9zxem.js";import{logger as R}from"@cortexkit/anthropic-auth-core";var K=(f)=>f!==null&&typeof f==="object"&&!Array.isArray(f),X=(f)=>K(f)&&typeof f.sessionId==="string"&&f.sessionId.length>0,U=(f)=>{if(!X(f)||!K(f)||f.command!=="claude"||typeof f.sectionId!=="string"||typeof f.actionId!=="string")return!1;if(f.itemId!==void 0&&typeof f.itemId!=="string")return!1;if(f.confirmed!==void 0&&typeof f.confirmed!=="boolean")return!1;if(f.values!==void 0&&(!K(f.values)||!Object.values(f.values).every((j)=>j===null||typeof j==="string"||typeof j==="boolean"||typeof j==="number"&&Number.isFinite(j))))return!1;return!0};function H(f){return{"~standard":{version:1,vendor:"cortexkit-native",validate:(j)=>f(j)?{value:j}:{issues:[{message:"Invalid native menu payload"}]}}}}var A=(f)=>K(f)&&f.command==="claude"&&K(f.menu)&&f.menu.command==="claude"&&typeof f.menu.title==="string"&&Array.isArray(f.menu.sections),V=(f)=>K(f)&&f.command==="claude"&&typeof f.ok==="boolean"&&typeof f.text==="string"&&(f.authorizationUrl===void 0||typeof f.authorizationUrl==="string")&&K(f.menu)&&Array.isArray(f.menu.sections),L=!1,$=(f,j,B=new Set)=>{if(f===null||typeof f==="string"||typeof f==="boolean")return f;if(typeof f==="number"&&Number.isFinite(f))return f;if(typeof f==="object"&&f!==null&&!B.has(f)){if(B.add(f),Array.isArray(f)){let Q=Array.from(f,(D,G)=>$(D,`${j}[${G}]`,B)??null);return B.delete(f),Q}if(Object.getPrototypeOf(f)===Object.prototype||Object.getPrototypeOf(f)===null){let Q=Object.fromEntries(Object.entries(f).flatMap(([D,G])=>{let W=$(G,`${j}.${D}`,B);return W===void 0?[]:[[D,W]]}));return B.delete(f),Q}B.delete(f)}if(!L)L=!0,R.warn("sidebar","Dropped non-JSON sidebar field",{path:j});return},E={"~standard":{version:1,vendor:"cortexkit-native",validate:(f)=>{let j=M(f);return{value:$(j,"sidebar")}}}},F={id:"cortexkit-anthropic-native",methods:{open:{input:H(X),output:H(A)},apply:{input:H(U),output:H(V)},sidebar:{input:H(X),output:E}},events:{opened:{schema:H((f)=>X(f)&&A(f.payload))},notification:{schema:H((f)=>X(f)&&typeof f.message==="string"&&["info","warning","error"].includes(String(f.kind)))}}};async function T(f,j,B){let Q=new AbortController,D=(q)=>({sessionId:q,notify(Y,Z="info"){G.events.emit("notification",{sessionId:q,message:Y,kind:Z}).catch(()=>{})}}),G=await f.rpc.register(F,{open:(q)=>j.open(D(q.sessionId)),apply:(q)=>j.apply(q,D(q.sessionId)),sidebar:(q)=>B.readSidebar(q.sessionId)}),W;try{W=await f.command.transform((q)=>q.add({name:"claude",description:"Native Claude accounts and settings",async execute(Y){let Z=await j.open(D(Y.sessionID));await G.events.emit("opened",{sessionId:Y.sessionID,payload:Z})}}))}catch(q){throw await G.dispose(),q}let P=(async()=>{try{for await(let q of f.event.subscribe({signal:Q.signal}))if(q.type==="session.deleted")B.forgetSession(q.data.sessionID)}catch{}})(),z=!1;return{async dispose(){if(z)return;z=!0,Q.abort(),await Promise.all([G.dispose(),W.dispose(),P])}}}
2
2
  export{F as x,T as y};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{t as a}from"./index-h492wy6c.js";import"./index-2ra790fx.js";import"./index-jc8zwxvw.js";import"./index-k6303ymz.js";import"./index-pxnn7mg1.js";import"./index-crx0xd9j.js";import"./index-n8xr16kr.js";export{a as AnthropicAuthPlugin};
1
+ import{t as a}from"./index-hzf7nz91.js";import"./index-2ra790fx.js";import"./index-jc8zwxvw.js";import"./index-k6303ymz.js";import"./index-m7k9zxem.js";import"./index-crx0xd9j.js";import"./index-n8xr16kr.js";export{a as AnthropicAuthPlugin};
@@ -0,0 +1,80 @@
1
+ import { type OwnerOnlyOptions } from '@cortexkit/anthropic-auth-core';
2
+ /** Hash of a thinking block's signature or a redacted block's data. */
3
+ export declare function recoveryThinkingDigest(type: 'thinking' | 'redacted_thinking', value: string): string;
4
+ /**
5
+ * Drop recorded recovery-round thinking from every Anthropic turn in which
6
+ * unrecorded (source) thinking comes before it. Anthropic counts an assistant
7
+ * turn as its assistant messages plus the user messages that hold only tool
8
+ * results; any other user message starts a new turn. Other roles, such as
9
+ * mid-conversation system messages, do not end a turn. A block is kept when
10
+ * removing it would leave its message empty. Returns the number of blocks
11
+ * removed; the body is untouched when nothing matches.
12
+ */
13
+ export declare function stripRecoveryRoundThinking(body: Record<string, unknown>, recorded: ReadonlySet<string>): number;
14
+ /**
15
+ * Collect the digests of the thinking blocks in one streamed response, from
16
+ * parsed SSE event payloads. A block is reported once its
17
+ * `content_block_stop` arrives, so a block cut off mid-stream is never
18
+ * reported.
19
+ */
20
+ export declare function createRecoveryThinkingObserver(onDigest: (digest: string) => void): (event: Record<string, unknown>) => void;
21
+ export declare function recoveryThinkingStoreDirectory(root?: string): string;
22
+ /**
23
+ * Per-session digests of the thinking blocks written by the fallback model
24
+ * during refusal-recovery rounds, keyed by the source model's recovery family
25
+ * (the capability table's `refusalRecoveryFamily`, such as `fable-5-2`).
26
+ * Memory is the source of truth for requests; disk keeps the record across
27
+ * restarts. Each session's file is read once, at first use. Writes are
28
+ * coalesced and detached, so a request never waits for one. Files are
29
+ * owner-only and hold only digests.
30
+ */
31
+ export declare class RecoveryThinkingStore {
32
+ private readonly sessions;
33
+ /** Records evicted from memory whose last change is not on disk yet. */
34
+ private readonly unwritten;
35
+ private readonly directory;
36
+ private readonly now;
37
+ private readonly writeDelayMs;
38
+ private readonly ownerOnly;
39
+ private chain;
40
+ private timer;
41
+ private swept;
42
+ private warned;
43
+ constructor(options?: {
44
+ directory?: string;
45
+ now?: () => number;
46
+ writeDelayMs?: number;
47
+ ownerOnly?: OwnerOnlyOptions;
48
+ });
49
+ /** The recorded digests for one session and family; loads once per session. */
50
+ digests(sessionId: string, family: string): Promise<ReadonlySet<string>>;
51
+ /** Record one fallback-model thinking block; the write happens later. */
52
+ record(sessionId: string, family: string, digest: string): void;
53
+ /** Forget a deleted session, in memory and on disk. */
54
+ forgetSession(sessionId: string): void;
55
+ /** Write every pending change now. Tests use this; shutdown uses close. */
56
+ flush(): Promise<void>;
57
+ /**
58
+ * Write pending changes at shutdown, waiting at most SHUTDOWN_GRACE_MS. A
59
+ * round that ends just before a restart would otherwise lose its record.
60
+ */
61
+ close(): Promise<void>;
62
+ private session;
63
+ private load;
64
+ /**
65
+ * Queue the sweep once per process, behind any queued write or delete, so it
66
+ * never removes a temporary file this process is still writing. Requests
67
+ * never wait for it.
68
+ */
69
+ private startSweep;
70
+ /** Whether a record file belongs to a session this process is using. */
71
+ private inUse;
72
+ /** Delete idle records and stale temporaries. */
73
+ private sweep;
74
+ private schedule;
75
+ private enqueueWrites;
76
+ private enqueueWrite;
77
+ private directoryReady;
78
+ private write;
79
+ private warn;
80
+ }
@@ -47,5 +47,5 @@ export declare function enrollNativeVaultForHost(host: HarnessKind, options: Nat
47
47
  * message shows the same command so the user can run it by hand.
48
48
  */
49
49
  export declare function nativeVaultGrantArgs(host: HarnessKind, approvedName?: string): string[];
50
- /** Grant this OpenCode or Pi principal read access to the vault's anthropic-native category; enrollment alone grants no provider access. */
50
+ /** Grant this host read access only when enrollment could not propose permissions. */
51
51
  export declare function grantNativeVaultForHost(host: HarnessKind, options: Pick<NativeVaultEnrollmentOptions, 'env' | 'runner' | 'processFence' | 'ckBinary' | 'paths'>): Promise<string | undefined>;
@@ -154,7 +154,7 @@ export declare function resolveActiveAccount(state: SidebarState): {
154
154
  quotaDated?: boolean;
155
155
  };
156
156
  /**
157
- * Pretty label for a recoverable-refusal source model (Fable or Opus).
157
+ * Pretty label for a recoverable-refusal source model (Fable, Mythos or Opus).
158
158
  * Falls back to the raw id for unrecognized ids so the sidebar never goes
159
159
  * blank on a future model that has not yet been cataloged here.
160
160
  */
@@ -1 +1 @@
1
- import{$ as r,K as a,L as b,M as c,N as d,O as e,P as f,Q as g,R as h,S as i,T as j,U as k,V as l,W as m,X as n,Y as o,Z as p,_ as q,aa as s,ba as t,ca as u,da as v,ea as w,fa as x,ga as y,ha as z,ia as A}from"./index-pxnn7mg1.js";import"./index-n8xr16kr.js";export{i as setSidebarState,r as scopedQuotaShortNames,k as resolveActiveAccount,s as quotaLabelColumnWidth,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,w as getCollapsedQuotaSummary,x as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,u as fitQuotaRow,v as fitPaceLine,j as drainSidebarWrites,A as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,z as SEVEN_DAY_MS,t as QUOTA_BAR_MIN_CELLS,y as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
1
+ import{$ as r,K as a,L as b,M as c,N as d,O as e,P as f,Q as g,R as h,S as i,T as j,U as k,V as l,W as m,X as n,Y as o,Z as p,_ as q,aa as s,ba as t,ca as u,da as v,ea as w,fa as x,ga as y,ha as z,ia as A}from"./index-m7k9zxem.js";import"./index-n8xr16kr.js";export{i as setSidebarState,r as scopedQuotaShortNames,k as resolveActiveAccount,s as quotaLabelColumnWidth,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,w as getCollapsedQuotaSummary,x as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,u as fitQuotaRow,v as fitPaceLine,j as drainSidebarWrites,A as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,z as SEVEN_DAY_MS,t as QUOTA_BAR_MIN_CELLS,y as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
@@ -93,6 +93,8 @@ export declare function extractLatestHybridMessageCacheAnchor(bodyText: string):
93
93
  * on a longer history does not count as a prefix change.
94
94
  */
95
95
  export declare function hybridUserMessageCacheAnchorFingerprints(bodyText: string): string[];
96
+ /** Match a continuation's last cache marker to the full body kept for warming. */
97
+ export declare function sourceCacheAnchorMatchesWire(templateBody: string, wireBody: string): boolean;
96
98
  /**
97
99
  * Rewrite the full request body: sanitize system prompt and prefix tool names.
98
100
  */
@@ -123,6 +125,13 @@ export declare function rewriteRequestBody(body: string, options?: {
123
125
  };
124
126
  perf?: RewritePerfCallback;
125
127
  hybridStandbyAnchor?: HybridMessageCacheAnchor;
128
+ sourceRecoveryBody?: string;
129
+ /**
130
+ * Digests of thinking blocks written by the fallback model in this
131
+ * session's refusal-recovery rounds. Set only on requests to the source
132
+ * model; see recovery-thinking.ts.
133
+ */
134
+ recoveryRoundThinking?: ReadonlySet<string>;
126
135
  serverSideFallbackEnabled?: boolean;
127
136
  modelRemapEnabled?: boolean;
128
137
  laneStart?: boolean;
@@ -1,4 +1,4 @@
1
- import { AnthropicOAuthOriginError, type ClaudeCodeIdentity, type RequestGzipLatch, stateRefusalCause, TrailingAssistantHistoryError } from '@cortexkit/anthropic-auth-core';
1
+ import { type AnthropicBillingRequest, AnthropicOAuthOriginError, type ClaudeCodeIdentity, type RequestGzipLatch, stateRefusalCause, TrailingAssistantHistoryError } from '@cortexkit/anthropic-auth-core';
2
2
  import type { AccountRequest, 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';
@@ -149,6 +149,7 @@ export interface NativeAnthropicAttemptOutcome extends AttemptOutcome {
149
149
  * the adapter passes it is rejected at compile time.
150
150
  */
151
151
  export interface NativeAnthropicSource<Q, P> {
152
+ readonly billingRequest?: (input: NativeAnthropicAttemptContext<P>) => AnthropicBillingRequest | undefined;
152
153
  /**
153
154
  * Picks the account for one request; `undefined` refuses it. In phase
154
155
  * `retry` it may instead return a hold, which keeps the refused account and
@@ -253,6 +254,8 @@ export interface NativeAnthropicAdapterDeps<Q, P> {
253
254
  readonly now?: () => number;
254
255
  }
255
256
  export interface NativeAnthropicAdapter<Q, P> {
257
+ /** Background drivers can refuse a rewritten request before their final dispatch. */
258
+ discardUnsentBilling(data: NativeAnthropicAttemptData<P>): void;
256
259
  /** Receipt time of this adapter's final verified upstream OAuth 2xx response. */
257
260
  acceptedResponse(response: Response): {
258
261
  at: number;
@@ -1,4 +1,4 @@
1
- import { CacheKeepManager, CacheKeepSessionRegistry, type NativeAccountRuntime } from '@cortexkit/anthropic-auth-core';
1
+ import { type AnthropicBillingWarming, CacheKeepManager, CacheKeepSessionRegistry, type NativeAccountRuntime } from '@cortexkit/anthropic-auth-core';
2
2
  import { type CacheKeepStoreOptions } from './cachekeep-store';
3
3
  import type { NativeCacheRequestPrepared, NativeSource } from './source';
4
4
  export interface NativeCacheKeepOptions {
@@ -43,6 +43,15 @@ export declare function createNativeCacheKeep(options: NativeCacheKeepOptions &
43
43
  reason: string;
44
44
  } | undefined;
45
45
  discardAttempt(attemptId: string): void;
46
+ /**
47
+ * Keep-warm state for a model request's billing report, from memory only.
48
+ * API-key routes are never warmed; an older shared manager without the
49
+ * reader leaves the state undecided.
50
+ */
51
+ warming(input: {
52
+ sessionID: string;
53
+ route: string;
54
+ }): AnthropicBillingWarming | undefined;
46
55
  recordAcceptedUsage(sessionID: string, bodyText: string, usage: Parameters<CacheKeepManager['recordAcceptedUsage']>[2]): void;
47
56
  resolvedParent: (sessionID: string, isSubagent: boolean) => Promise<void>;
48
57
  forgetSession(sessionID: string): void;