@cortexkit/opencode-anthropic-auth 1.20.0 → 1.22.0

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.
Files changed (36) hide show
  1. package/README.md +42 -8
  2. package/dist/cli.js +1 -1
  3. package/dist/effort-history.d.ts +58 -0
  4. package/dist/fable-fallback.d.ts +6 -7
  5. package/dist/{index-hmebes3f.js → index-7f57ewkp.js} +1 -1
  6. package/dist/{index-vkecgsm3.js → index-8aga2zwv.js} +1 -1
  7. package/dist/{index-jjx6dbj3.js → index-926t2bzc.js} +1 -1
  8. package/dist/{index-j3323dyj.js → index-bx5hsgf8.js} +1 -1
  9. package/dist/{index-nqs7chg0.js → index-cgez4m0h.js} +1 -1
  10. package/dist/index-d3f8g6ve.js +428 -0
  11. package/dist/index-sh51yqxs.js +2 -0
  12. package/dist/index.d.ts +0 -38
  13. package/dist/index.js +23 -21
  14. package/dist/{logger-8b9bz0g8.js → logger-jrkranbz.js} +1 -1
  15. package/dist/request-policy.d.ts +25 -0
  16. package/dist/rpc/port-file.js +1 -1
  17. package/dist/rpc/protocol.d.ts +15 -0
  18. package/dist/rpc/protocol.js +1 -1
  19. package/dist/rpc/rpc-client.js +1 -1
  20. package/dist/rpc/rpc-dir.js +1 -1
  21. package/dist/sidebar-state.d.ts +2 -1
  22. package/dist/sidebar-state.js +1 -1
  23. package/dist/transform.d.ts +17 -1
  24. package/dist/tui/command-dialogs.d.ts +2 -8
  25. package/dist/tui-preferences.js +1 -1
  26. package/package.json +4 -4
  27. package/src/rpc/protocol.ts +17 -0
  28. package/src/sidebar-state.ts +16 -1
  29. package/src/tui/command-dialogs.tsx +40 -41
  30. package/src/tui-compiled/rpc/protocol.ts +17 -0
  31. package/src/tui-compiled/sidebar-state.ts +16 -1
  32. package/src/tui-compiled/tui/command-dialogs.tsx +49 -33
  33. package/src/tui-compiled/tui.tsx +7 -3
  34. package/src/tui.tsx +17 -3
  35. package/dist/index-afyr2g77.js +0 -2
  36. package/dist/index-ebq5g321.js +0 -427
@@ -0,0 +1,2 @@
1
+ import{kd as O}from"./index-8aga2zwv.js";import{randomUUID as H}from"node:crypto";import{mkdir as g,readFile as F,rename as T,rm as z,rmdir as w,stat as P,unlink as y,writeFile as I}from"node:fs/promises";import{tmpdir as m}from"node:os";import{dirname as d,join as L}from"node:path";var v="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",c=L(m(),"opencode-anthropic-auth"),u=L(c,"sidebar-state.json");function E(){return process.env[v]||u}var C={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function K(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function W(J){return typeof J==="number"&&Number.isFinite(J)}function n(J){if(!K(J))return;let Z=Number(J.count),V=Number(J.inputTokens),x=Number(J.outputTokens),Y=Number(J.since);if(![Z,V,x,Y].every(Number.isFinite)||Z<0||V<0||x<0||Y<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(x),since:Math.floor(Y)}}function i(J){if(!K(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(W(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(W(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error")Z.lastResult=J.lastResult;let V=n(J.usage);if(V)Z.usage=V;if(W(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function s(J){if(!K(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(i).filter((V)=>V!=null):[];return{enabled:J.enabled,accounts:Z}}function h(J){if(!K(J))return;let Z=Number(J.usedPercent),V=Number(J.remainingPercent);if(!Number.isFinite(Z)||!Number.isFinite(V))return;return{usedPercent:Z,remainingPercent:V,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0}}function A(J){if(!K(J))return null;let Z={},V=h(J.five_hour),x=h(J.seven_day);if(V)Z.five_hour=V;if(x)Z.seven_day=x;if(Array.isArray(J.scoped)){let Y=J.scoped.map((X)=>{if(!K(X))return;let $=h(X);if(!$)return;if(typeof X.id!=="string"||!X.id.trim())return;if(typeof X.title!=="string"||!X.title.trim())return;if(typeof X.modelName!=="string"||!X.modelName.trim())return;let j=typeof X.modelId==="string"&&X.modelId.trim()?X.modelId.trim():void 0;return{...$,id:X.id.trim(),title:X.title.trim(),...j&&{modelId:j},modelName:X.modelName.trim()}}).filter((X)=>X!=null);Z.scoped=Y}if(K(J.extraUsage)){let Y=R(J.extraUsage.used),X=R(J.extraUsage.limit);if(Y&&X&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:Y,limit:X,...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 R(J){if(!K(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 p(J){if(!K(J))return{...C};let Z={quota:null};if(K(J.main)){let $=J.main;if(Z.quota=A($.quota),typeof $.tierLabel==="string"&&$.tierLabel.trim())Z.tierLabel=$.tierLabel.trim();if(typeof $.quotaBackedOff==="boolean")Z.quotaBackedOff=$.quotaBackedOff;if(typeof $.quotaBackoffUntil==="number")Z.quotaBackoffUntil=$.quotaBackoffUntil;if(typeof $.refreshBackedOff==="boolean")Z.refreshBackedOff=$.refreshBackedOff;if(typeof $.refreshBackoffUntil==="number")Z.refreshBackoffUntil=$.refreshBackoffUntil}let V=Array.isArray(J.fallbacks)?J.fallbacks.filter(K).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,label:typeof $.label==="string"?$.label:void 0,quota:A($.quota),enabled:typeof $.enabled==="boolean"?$.enabled:!1,needsReauth:typeof $.needsReauth==="boolean"?$.needsReauth:!1,...$.vaultReauth===!0&&{vaultReauth:!0},tierLabel:typeof $.tierLabel==="string"&&$.tierLabel.trim()?$.tierLabel.trim():void 0})):[],x=null;if(K(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")x={enabled:$.enabled,transport:$.transport}}let Y;if(K(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")Y={enabled:$.enabled,window:typeof $.window==="string"?$.window:void 0,trackedSessions:typeof $.trackedSessions==="number"?$.trackedSessions:void 0}}let X=Array.isArray(J.fableRecoveries)?J.fableRecoveries.filter(K).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,requestedModelId:typeof $.requestedModelId==="string"?$.requestedModelId:void 0,targetModelId:typeof $.targetModelId==="string"?$.targetModelId:void 0}]}):[];return{main:Z,fallbacks:V,activeId:typeof J.activeId==="string"?J.activeId:void 0,route:typeof J.route==="string"?J.route:C.route,relay:x,fastMode:typeof J.fastMode==="boolean"?J.fastMode:C.fastMode,cacheKeep:Y,prime:s(J.prime),fableRecoveries:X.length>0?X:void 0,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var q=Promise.resolve(),l=1000,o=2000,r=5,a=15,U=new Map;function QJ(J,Z=E()){if(J)U.set(Z,J);else U.delete(Z)}function M(J){return U.get(J)}var S=null;function BJ(J){S=J}function OJ(){return S}function t(J){return new Promise((Z)=>setTimeout(Z,J))}async function k(J){let Z=`${J}.lock`,V=M(J),x=V?.lockBudgetMs??l,Y=V?.lockRetryMinMs??r,X=V?.lockRetryMaxMs??a,$=Date.now()+x;while(!0){try{await g(Z);let G=H(),Q=L(Z,G);return await I(Q,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await P(Q),!0}catch{return!1}},release:async()=>{try{await y(Q)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(G){if(G.code!=="EEXIST")return O.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:G instanceof Error?G.message:String(G)}),null}try{let G=await P(Z);if(Date.now()-G.mtimeMs>o){await V?.afterStaleLockStat?.(Z);let Q=`${Z}.evict-${process.pid}-${H()}`;try{await T(Z,Q)}catch(N){if(N.code==="ENOENT")continue;throw N}await V?.onStaleLockClaimed?.(Z),await z(Q,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(G){if(G.code==="ENOENT")continue;return O.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:G instanceof Error?G.message:String(G)}),null}let j=$-Date.now();if(j<=0)return O.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:x}),null;let B=Y+Math.floor(Math.random()*(X-Y+1));await t(Math.min(B,j))}}async function NJ(J){return(await k(J))?.release??null}async function e(J,Z,V){let x=M(J),Y=`${J}.${process.pid}.${H()}.tmp`;await I(Y,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return O.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await z(Y,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await x?.beforeRename?.(J,Y),!await V())return O.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await z(Y,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await T(Y,J),await x?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(X){throw await z(Y,{force:!0}).catch(()=>{}),X}}async function b(J=E()){try{let Z=await F(J,"utf8");return p(JSON.parse(Z))}catch{return C}}async function zJ(J,Z=E(),V={}){return q=q.then(async()=>{await g(d(Z),{recursive:!0});for(let x=0;x<2;x++){let Y=x===1,X=await k(Z);if(!X){if(Y)O.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let $=J,j;try{if(V.routingAuthoritative===!1){let B=await b(Z),G=await V.resolvePreservedRouting?.(B);if(G){let Q=G.state??J;$={...Q,activeId:G.activeId,route:G.route,lastUpdated:Math.max(Q.lastUpdated,B.lastUpdated)}}await M(Z)?.afterMergeRead?.(Z)}else if(Y){let B=await b(Z);$={...B,activeId:J.activeId,route:J.route,relay:J.relay,fastMode:J.fastMode,cacheKeep:J.cacheKeep,lastUpdated:Math.max(B.lastUpdated,J.lastUpdated)}}$=p($),j=await e(Z,$,X.ownsLock)}finally{await X.release()}if(j==="lock-lost-after-rename"){if(Y){O.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}O.warn("sidebar","state lock lost after rename; repairing write",{stateFile:Z});continue}if(j==="lock-lost-before-rename")return;V.onRoutingResolved?.({activeId:$.activeId,route:$.route});return}}).catch(()=>{}),q}async function CJ(){return q}function qJ(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}}return{id:"main",name:"main",quota:J.main?.quota??null}}function JJ(J){let Z=J.replace(/\s+only$/i,"").trim();return/^fable$/i.test(Z)?"Fa":Z}function f(J){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"||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 D(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function ZJ(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 WJ(J){if(J.lastResult==="error")return{text:"err",hasError:!0};if(J.nextDueAt&&J.nextDueAt>Date.now())return{text:D(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${D(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${ZJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function hJ(J,Z){let V=J.fableRecoveries?.find((x)=>x.sessionId===Z);if(!V)return;if(V.mode==="fable")return`${f(V.requestedModelId)} · restored`;if(V.mode==="server")return`${f(V.requestedModelId)}→${f(V.targetModelId)} · safety`;return`Opus 4.8 · ${V.remaining} left`}function fJ(J){let Z=J?.five_hour?.usedPercent??null,V=J?.seven_day?.usedPercent??null,x=J?.scoped??[],Y=x.map((j)=>j.usedPercent);if(Z==null&&V==null&&x.length===0)return{fiveHourUsedPercent:Z,sevenDayUsedPercent:V,scopedUsedPercents:Y,text:null};let X=x.map((j)=>`${JJ(j.title)}: ${Math.round(j.usedPercent)}%`),$=Z==null&&V==null?[]:[`5h: ${Z==null?"—":`${Math.round(Z)}%`}`,`7d: ${V==null?"—":`${Math.round(V)}%`}`];return{fiveHourUsedPercent:Z,sevenDayUsedPercent:V,scopedUsedPercents:Y,text:[...$,...X].join(" ")}}var HJ=18000000,UJ=604800000,$J=300000,VJ=0.01,XJ=1;function LJ(J,Z,V){if(!J.resetsAt)return null;let x=new Date(J.resetsAt).getTime();if(!Number.isFinite(x))return null;let Y=x-Z,X=V-Y;if(X<$J)return null;if(X<Z*VJ)return null;if(X>=Z)return null;let $=J.usedPercent,j=Math.min(Math.max(X/Z*100,0),100),B=$-j,G=Math.abs(B)<XJ?"on-pace":B>0?"deficit":"reserve",Q=null;if($>0){let N=X*100/$,_=Y+N;if(_<x)Q=new Date(_).toISOString()}return{pacePercent:j,deltaPercent:B,state:G,runsOutAt:Q}}
2
+ export{E as a,C as b,p as c,QJ as d,BJ as e,OJ as f,NJ as g,b as h,zJ as i,CJ as j,qJ as k,JJ as l,f as m,D as n,ZJ as o,WJ as p,hJ as q,fJ as r,HJ as s,UJ as t,LJ as u};
package/dist/index.d.ts CHANGED
@@ -1,40 +1,2 @@
1
- import { type AccountStorage, type OAuthQuotaSnapshot } from '@cortexkit/anthropic-auth-core';
2
1
  import type { Plugin } from '@opencode-ai/plugin';
3
- /**
4
- * Format the user-facing 429 message for a killswitch block. When the block
5
- * is scoped-driven (the request's model matches a scoped window that is at
6
- * or below the killswitch threshold), the message names the model so the
7
- * operator can distinguish a per-model weekly block from a whole-account
8
- * kill. Otherwise the generic account-level message is used.
9
- */
10
- export declare function formatKillswitchBlockMessage(input: {
11
- retryAfterSeconds: number;
12
- modelName?: string;
13
- }): string;
14
- /**
15
- * Decide whether a killswitch block is scoped-driven (a per-model weekly
16
- * block) versus a whole-account 5h/7d-driven block. A block is scoped-driven
17
- * only when the request's model matches a scoped window AND that window is
18
- * actually at or below the per-account scoped threshold. A Fable request
19
- * with a healthy Fable window is therefore correctly classified as
20
- * account-level (the 5h/7d breach killed the account, not the Fable quota).
21
- *
22
- * Priority: account-level 5h/7d always wins. `killswitchPassesPolicy` called
23
- * WITHOUT a modelId evaluates only 5h/7d; if it returns false, 5h/7d drove
24
- * the block, so this is account-level regardless of the scoped window's
25
- * state. Only when 5h/7d pass AND the matched scoped window is at/below the
26
- * scoped threshold do we call it scoped-driven.
27
- */
28
- export declare function resolveScopedDrivenBlock(input: {
29
- mainQuota: OAuthQuotaSnapshot | undefined;
30
- requestModelId: string | undefined;
31
- storage: AccountStorage | null;
32
- }): {
33
- isScopedDriven: true;
34
- modelName: string;
35
- modelId: string;
36
- } | {
37
- isScopedDriven: false;
38
- };
39
- export declare function primeQuotaSnapshotIsFreshSince(quota: OAuthQuotaSnapshot | undefined, refreshStartedAt: number): boolean;
40
2
  export declare const AnthropicAuthPlugin: Plugin;