@cortexkit/opencode-anthropic-auth 2.1.2 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
1
  import{mkdir as l,readdir as u,readFile as c,rename as p,unlink as m,writeFile as d}from"node:fs/promises";import{join as a}from"node:path";function f(t){try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}async function b(t,r){await l(t,{recursive:!0});let s={...r,startedAt:Date.now()},e=a(t,`port-${r.pid}.json`),i=`${e}.${process.pid}.tmp`;return await d(i,JSON.stringify(s),{encoding:"utf8",mode:384}),await p(i,e),e}async function h(t,r){let s;try{s=await u(t)}catch{return null}let e=[];for(let n of s){if(!n.startsWith("port-")||!n.endsWith(".json"))continue;try{let o=JSON.parse(await c(a(t,n),"utf8"));if(Number.isFinite(o.port))if(f(o.pid))e.push(o);else m(a(t,n)).catch(()=>{})}catch{}}if(e.length===0)return null;let i=r&&r>=1?e.filter((n)=>n.pid===r):[];return(i.length>0?i:e).sort((n,o)=>o.startedAt-n.startedAt)[0]??null}
2
- export{b as aa,h as ba};
2
+ export{b as fa,h as ga};
@@ -0,0 +1,2 @@
1
+ import{randomUUID as P}from"node:crypto";import{mkdir as h,readFile as y,rename as S,rm as C,rmdir as w,stat as R,unlink as m,writeFile as b}from"node:fs/promises";import{tmpdir as d}from"node:os";import{dirname as v,join as M}from"node:path";import{formatQuota as c,isQuotaStale as s,logger as z,quotaDisplayProjection as I,quotaTextParts as u}from"@cortexkit/anthropic-auth-core";var n="OPENCODE_ANTHROPIC_AUTH_SIDEBAR_STATE_FILE",i=M(d(),"opencode-anthropic-auth"),l=M(i,"sidebar-state.json");function f(){return process.env[n]||l}var W={main:{quota:null},fallbacks:[],activeId:void 0,route:"main",relay:null,fastMode:!1,lastUpdated:0};function Q(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function N(J){return typeof J==="number"&&Number.isFinite(J)}function o(J){if(!Q(J))return;let Z=Number(J.count),V=Number(J.inputTokens),X=Number(J.outputTokens),G=Number(J.since);if(![Z,V,X,G].every(Number.isFinite)||Z<0||V<0||X<0||G<0)return;return{count:Math.floor(Z),inputTokens:Math.floor(V),outputTokens:Math.floor(X),since:Math.floor(G)}}function r(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(N(J.nextDueAt))Z.nextDueAt=J.nextDueAt;if(J.lastPrimedAt===null)Z.lastPrimedAt=null;else if(N(J.lastPrimedAt))Z.lastPrimedAt=J.lastPrimedAt;if(J.lastResult==="ok"||J.lastResult==="error"||J.lastResult==="skipped")Z.lastResult=J.lastResult;let V=o(J.usage);if(V)Z.usage=V;if(N(J.estimatedCostUsd))Z.estimatedCostUsd=J.estimatedCostUsd;return Z}function a(J){if(!Q(J))return;if(typeof J.enabled!=="boolean")return;let Z=Array.isArray(J.accounts)?J.accounts.map(r).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,resetsAt:typeof J.resetsAt==="string"?J.resetsAt:void 0,...N(J.checkedAt)&&{checkedAt:J.checkedAt}}}function D(J){if(!Q(J))return null;let Z={};if(N(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 G=J.scoped.map((Y)=>{if(!Q(Y))return;let $=q(Y);if(!$)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 j=typeof Y.modelId==="string"&&Y.modelId.trim()?Y.modelId.trim():void 0;return{...$,id:Y.id.trim(),title:Y.title.trim(),...j&&{modelId:j},modelName:Y.modelName.trim()}}).filter((Y)=>Y!=null);Z.scoped=G}if(Q(J.extraUsage)){let G=A(J.extraUsage.used),Y=A(J.extraUsage.limit);if(G&&Y&&typeof J.extraUsage.exhausted==="boolean")Z.extraUsage={used:G,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 p(J){if(!Q(J))return{...W};let Z={quota:null};if(Q(J.main)){let $=J.main;if(Z.quota=D($.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(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(Q).filter(($)=>typeof $.id==="string").map(($)=>({id:$.id,label:typeof $.label==="string"?$.label:void 0,quota:D($.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},tierLabel:typeof $.tierLabel==="string"&&$.tierLabel.trim()?$.tierLabel.trim():void 0})):[],X=null;if(Q(J.relay)){let $=J.relay;if(typeof $.enabled==="boolean"&&typeof $.transport==="string")X={enabled:$.enabled,transport:$.transport}}let G;if(Q(J.cacheKeep)){let $=J.cacheKeep;if(typeof $.enabled==="boolean")G={enabled:$.enabled,window:typeof $.window==="string"?$.window:void 0,trackedSessions:typeof $.trackedSessions==="number"?$.trackedSessions:void 0}}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,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:W.route,relay:X,fastMode:typeof J.fastMode==="boolean"?J.fastMode:W.fastMode,cacheKeep:G,prime:a(J.prime),fableRecoveries:Y.length>0?Y:void 0,lastUpdated:typeof J.lastUpdated==="number"?J.lastUpdated:0}}var H=Promise.resolve(),t=1000,e=2000,JJ=5,ZJ=15,E=new Map;function WJ(J,Z=f()){if(J)E.set(Z,J);else E.delete(Z)}function U(J){return E.get(J)}var k=null;function HJ(J){k=J}function UJ(){return k}function $J(J){return new Promise((Z)=>setTimeout(Z,J))}async function F(J){let Z=`${J}.lock`,V=U(J),X=V?.lockBudgetMs??t,G=V?.lockRetryMinMs??JJ,Y=V?.lockRetryMaxMs??ZJ,$=Date.now()+X;while(!0){try{await h(Z);let K=P(),x=M(Z,K);return await b(x,"",{encoding:"utf8",mode:384,flag:"wx"}),await V?.onLockAcquired?.(Z),{ownsLock:async()=>{try{return await R(x),!0}catch{return!1}},release:async()=>{try{await m(x)}catch{return}await V?.beforeReleaseDirectoryRemoval?.(Z),await w(Z).catch(()=>{})}}}catch(K){if(K.code!=="EEXIST")return z.trace("sidebar","state lock unavailable; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}try{let K=await R(Z);if(Date.now()-K.mtimeMs>e){await V?.afterStaleLockStat?.(Z);let x=`${Z}.evict-${process.pid}-${P()}`;try{await S(Z,x)}catch(O){if(O.code==="ENOENT")continue;throw O}await V?.onStaleLockClaimed?.(Z),await C(x,{recursive:!0,force:!0}).catch(()=>{});continue}}catch(K){if(K.code==="ENOENT")continue;return z.trace("sidebar","state lock inspection failed; write skipped",{stateFile:J,error:K instanceof Error?K.message:String(K)}),null}let j=$-Date.now();if(j<=0)return z.warn("sidebar","lock budget exhausted, write skipped",{stateFile:J,budgetMs:X}),null;let B=G+Math.floor(Math.random()*(Y-G+1));await $J(Math.min(B,j))}}async function qJ(J){return(await F(J))?.release??null}async function VJ(J,Z,V){let X=U(J),G=`${J}.${process.pid}.${P()}.tmp`;await b(G,JSON.stringify(Z),{encoding:"utf8",mode:384});try{if(!await V())return z.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await C(G,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await X?.beforeRename?.(J,G),!await V())return z.trace("sidebar","state lock lost before rename; write aborted",{stateFile:J}),await C(G,{force:!0}).catch(()=>{}),"lock-lost-before-rename";if(await S(G,J),await U(J)?.afterRename?.(J),!await V())return"lock-lost-after-rename";return"written"}catch(Y){throw await C(G,{force:!0}).catch(()=>{}),Y}}async function T(J=f()){try{let Z=await y(J,"utf8");return p(JSON.parse(Z))}catch{return W}}async function LJ(J,Z=f(),V={}){return H=H.then(async()=>{await h(v(Z),{recursive:!0});for(let X=0;X<2;X++){let G=X===1,Y=await F(Z);if(!Y){if(G)z.warn("sidebar","post-rename repair lock unavailable; write skipped",{stateFile:Z});return}let $=J,j;try{if(V.routingAuthoritative===!1){let B=await T(Z),K=await V.resolvePreservedRouting?.(B);if(K){let x=K.state??J;$={...x,activeId:K.activeId,route:K.route,lastUpdated:Math.max(x.lastUpdated,B.lastUpdated)}}await U(Z)?.afterMergeRead?.(Z)}else if(G){let B=await T(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 VJ(Z,$,Y.ownsLock)}finally{await Y.release()}if(j==="lock-lost-after-rename"){if(G){z.warn("sidebar","post-rename repair lost lock; write skipped",{stateFile:Z});return}z.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(()=>{}),H}async function PJ(){return H}function XJ(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){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 g(J){return new Date(J).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}function YJ(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 EJ(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:g(J.nextDueAt),hasError:!1};if(J.lastPrimedAt)return{text:`primed ${g(J.lastPrimedAt)} ✓`,hasError:!1};if(J.usage?.count)return{text:`✓ ${J.usage.count} ≈ $${YJ(J.estimatedCostUsd??0)}`,hasError:!1};return{text:"—",hasError:!1}}function MJ(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 fJ(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??[];return V.map((X,G)=>{let Y=I({scoped:V.map((B,K)=>({...B,usedPercent:K===G?100:0,remainingPercent:K===G?0:100,checkedAt:Z}))},Z),$=u(Y,{now:Z,form:"narrow"})[0],j=$?.replace(/ 0% left$/,"");return j&&j!==$?j:X.title})}function _J(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:G,reset:Y}=J,$={barCells:X,reset:Y||void 0};if(Z===void 0)return $;let j=(x)=>V+1+(x.barCells>0?x.barCells+1:0)+Bun.stringWidth(G)+(x.reset?1+Bun.stringWidth(x.reset):0),B=Math.min(KJ,X),K=[$];for(let x=X;x>=B;x--)K.push({barCells:x});return K.find((x)=>j(x)<=Z)??{barCells:B}}function DJ(J,Z,V){if(!J||J.state==="on-pace")return null;let X=`${J.state} ${Math.round(Math.abs(J.deltaPercent))}%`,G=V?`${X} · out in ${V}`:`${X} · lasts to reset`;if(Z===void 0||Bun.stringWidth(G)<=Z)return G;if(Z<=0)return"";let Y="";for(let $ of G){if(Bun.stringWidth(Y+$)>Z-1)break;Y+=$}return`${Y.trimEnd()}…`}function AJ(J,Z=Date.now()){let V=J?.five_hour?.usedPercent??null,X=J?.seven_day?.usedPercent??null,G=J?.scoped??[],Y=G.map((j)=>j.usedPercent);if(!J||V==null&&X==null&&G.length===0&&!J.extraUsage)return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:null,stale:!1};let $=I(J,Z);return{fiveHourUsedPercent:V,sevenDayUsedPercent:X,scopedUsedPercents:Y,text:c($,{now:Z,form:"narrow"}),stale:s($,{now:Z})}}function TJ(J,Z=!0){let V=J.activeId===void 0?void 0:XJ(J).id;return[{id:"main",name:"main",quota:J.main?.quota??null,quotaDated:J.main?.quotaDated,active:V==="main"},...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})):[]]}var gJ=18000000,hJ=604800000,xJ=300000,jJ=0.01,BJ=1;function SJ(J,Z,V){if(!J.resetsAt)return null;let X=new Date(J.resetsAt).getTime();if(!Number.isFinite(X))return null;let G=X-Z,Y=V-G;if(Y<xJ)return null;if(Y<Z*jJ)return null;if(Y>=Z)return null;let $=J.usedPercent,j=Math.min(Math.max(Y/Z*100,0),100),B=$-j,K=Math.abs(B)<BJ?"on-pace":B>0?"deficit":"reserve",x=null;if($>0){let O=Y*100/$,_=G+O;if(_<X)x=new Date(_).toISOString()}return{pacePercent:j,deltaPercent:B,state:K,runsOutAt:x}}
2
+ export{f as G,W as H,p as I,WJ as J,HJ as K,UJ as L,qJ as M,T as N,LJ as O,PJ as P,XJ as Q,L as R,g as S,YJ as T,EJ as U,MJ as V,fJ as W,GJ as X,_J as Y,KJ as Z,RJ as _,DJ as $,AJ as aa,TJ as ba,gJ as ca,hJ as da,SJ as ea};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{p as a}from"./index-x325vp4e.js";import"./index-6chd6jnr.js";import"./index-hazrk5c3.js";import"./index-b1dvkp15.js";import"./index-53nnxq39.js";import"./index-ah5s0bew.js";import"./index-f2ne65w4.js";export{a as AnthropicAuthPlugin};
1
+ import{p as a}from"./index-8ysjtqek.js";import"./index-6chd6jnr.js";import"./index-hazrk5c3.js";import"./index-b1dvkp15.js";import"./index-xbwa4x53.js";import"./index-ppdrzs41.js";import"./index-62x1p34p.js";export{a as AnthropicAuthPlugin};
@@ -1 +1 @@
1
- import{aa as a,ba as b}from"../index-ah5s0bew.js";import"../index-f2ne65w4.js";export{a as writePortFile,b as discoverPortFile};
1
+ import{fa as a,ga as b}from"../index-ppdrzs41.js";import"../index-62x1p34p.js";export{a as writePortFile,b as discoverPortFile};
@@ -1 +1 @@
1
- import{q as a}from"../index-6chd6jnr.js";import"../index-f2ne65w4.js";export{a as COMMAND_MODAL_NAMES};
1
+ import{q as a}from"../index-6chd6jnr.js";import"../index-62x1p34p.js";export{a as COMMAND_MODAL_NAMES};
@@ -1 +1 @@
1
- import{ba as s}from"../index-ah5s0bew.js";import"../index-f2ne65w4.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{ga as s}from"../index-ppdrzs41.js";import"../index-62x1p34p.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 +1 @@
1
- import{r as a,s as b}from"../index-hazrk5c3.js";import"../index-f2ne65w4.js";export{a as tmpdir,b as getRpcDir};
1
+ import{r as a,s as b}from"../index-hazrk5c3.js";import"../index-62x1p34p.js";export{a as tmpdir,b as getRpcDir};
@@ -158,13 +158,66 @@ export declare function resolveActiveAccount(state: SidebarState): {
158
158
  export declare function formatFallbackModelLabel(modelId: string | undefined): string;
159
159
  export declare function formatPrimeTime(epochMs: number): string;
160
160
  export declare function formatPrimeCost(value: number): string;
161
- export declare function formatPrimeAccountValue(account: PrimeSidebarAccountState): {
161
+ export declare function formatPrimeAccountValue(account: PrimeSidebarAccountState, now?: number): {
162
162
  text: string;
163
163
  hasError: boolean;
164
164
  };
165
165
  export declare function getFableRecoverySummary(state: SidebarState, sessionId: string): string | undefined;
166
166
  /** Keep full shared names when they fit; truncate only to preserve row columns. */
167
167
  export declare function formatQuotaRowLabel(name: string, width?: number): string;
168
+ /**
169
+ * The short names model-scoped rows read under, in the order of `quota.scoped`:
170
+ * the names common-auth's narrow one-line form gives them (`Fa` for Fable;
171
+ * models whose short names would collide are extended until they differ, as
172
+ * `Fabl` and `Fabr`), so the expanded rows and the collapsed line agree.
173
+ *
174
+ * common-auth exposes that short name only inside the narrow text, and the
175
+ * narrow line shows just one model window (the tightest). So each window's
176
+ * name is read from a narrow line of a copy of the reading in which that
177
+ * window alone is spent: every model window stays in, so collisions resolve
178
+ * exactly as they do in the real line, and the one piece the line shows is
179
+ * `<short name> 0% left`. The figures in the copy are never displayed.
180
+ */
181
+ export declare function scopedQuotaShortNames(quota: Pick<AccountQuota, 'scoped'> | null | undefined, now?: number): string[];
182
+ /**
183
+ * The width of the quota rows' label column: the longest label any of these
184
+ * accounts shows. `5h` and `7d` always show, so it is at least 2.
185
+ */
186
+ export declare function quotaLabelColumnWidth(quotas: readonly (AccountQuota | null | undefined)[], now?: number): number;
187
+ /** The narrowest a quota row's bar shrinks to. */
188
+ export declare const QUOTA_BAR_MIN_CELLS = 3;
189
+ export interface QuotaRowFit {
190
+ /** Bar cells to draw. */
191
+ barCells: number;
192
+ /** The reset text to draw at the right edge, or undefined for none. */
193
+ reset?: string;
194
+ }
195
+ /**
196
+ * Fits one quota row into `width` cells. The row reads `label bar figure` on
197
+ * the left and the reset at the right edge, with a one-cell gap before the
198
+ * reset that the caller always draws. When the full row is too wide, the
199
+ * reset is dropped first, so the figure (the percent left) is never cut to
200
+ * keep it; then the bar shrinks, down to `QUOTA_BAR_MIN_CELLS`. A row still
201
+ * too wide at that point keeps the minimum bar and is cut at the right edge
202
+ * by the caller's no-wrap text, which cuts the figure's end. Without a
203
+ * measured width the full row is used.
204
+ */
205
+ export declare function fitQuotaRow(input: {
206
+ width: number | undefined;
207
+ labelWidth: number;
208
+ barWidth: number;
209
+ /** The figure with any binding marker, such as `97% left •`. */
210
+ figure: string;
211
+ reset?: string;
212
+ }): QuotaRowFit;
213
+ /**
214
+ * The pacing subline for a window that is off pace: `deficit 12% · out in
215
+ * 1d23h` for a deficit that runs out before the reset, otherwise the delta
216
+ * and `lasts to reset` (`reserve 4% · lasts to reset`). When it is wider than
217
+ * `width` cells it is cut to fit and ends in `…` rather than wrapping. Null
218
+ * when there is no pacing or the window is on pace.
219
+ */
220
+ export declare function fitPaceLine(pacing: QuotaPacing | null, width: number | undefined, runsOutIn: string | undefined): string | null;
168
221
  export declare function getCollapsedQuotaSummary(quota: AccountQuota | null, now?: number): {
169
222
  fiveHourUsedPercent: number | null;
170
223
  sevenDayUsedPercent: number | null;
@@ -1 +1 @@
1
- import{$ as v,G as a,H as b,I as c,J as d,K as e,L as f,M as g,N as h,O as i,P as j,Q as k,R as l,S as m,T as n,U as o,V as p,W as q,X as r,Y as s,Z as t,_ as u}from"./index-53nnxq39.js";import"./index-f2ne65w4.js";export{i as setSidebarState,k as resolveActiveAccount,c as normalizeSidebarState,a as getSidebarStateFile,h as getSidebarState,f as getInitialSidebarRoutingTestHooks,p as getFableRecoverySummary,r as getCollapsedQuotaSummary,s as getCollapsedAccounts,q as formatQuotaRowLabel,m as formatPrimeTime,n as formatPrimeCost,o as formatPrimeAccountValue,l as formatFallbackModelLabel,j as drainSidebarWrites,v as computeQuotaPacing,d as __setSidebarStateWriteTestHooks,e as __setInitialSidebarRoutingTestHooks,g as __acquireSidebarStateLockForTest,u as SEVEN_DAY_MS,t as FIVE_HOUR_MS,b as DEFAULT_SIDEBAR_STATE};
1
+ import{$ as v,G as a,H as b,I as c,J as d,K as e,L as f,M as g,N as h,O as i,P as j,Q as k,R as l,S as m,T as n,U as o,V as p,W as q,X as r,Y as s,Z as t,_ as u,aa as w,ba as x,ca as y,da as z,ea as A}from"./index-xbwa4x53.js";import"./index-62x1p34p.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};
@@ -99,6 +99,10 @@ export declare function rewriteRequestBody(body: string, options?: {
99
99
  midConversationEffortEnabled?: boolean;
100
100
  midConversationEffortPlan?: string;
101
101
  midConversationEffortResolvedPlan?: OpenCodeEffortMarkerPlan;
102
+ turnEndNoteEnabled?: boolean;
103
+ turnEndNote?: {
104
+ tools: string[];
105
+ };
102
106
  perf?: RewritePerfCallback;
103
107
  hybridStandbyAnchor?: HybridMessageCacheAnchor;
104
108
  serverSideFallbackEnabled?: boolean;
@@ -0,0 +1,99 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { type RGBA } from '@opentui/core';
3
+ import { type JSX } from 'solid-js';
4
+ import { type AccountQuota, type SidebarState } from '../sidebar-state.js';
5
+ import { type AnthropicAuthTuiPrefs, type AppearancePrefs } from '../tui-preferences.js';
6
+ export type SidebarColor = RGBA | string;
7
+ /** The flat theme tokens the sidebar draws with; OpenCode 1's `theme.current` has them all. */
8
+ export interface SidebarTheme {
9
+ readonly text: SidebarColor;
10
+ readonly textMuted: SidebarColor;
11
+ readonly success: SidebarColor;
12
+ readonly warning: SidebarColor;
13
+ readonly error: SidebarColor;
14
+ readonly accent: SidebarColor;
15
+ readonly background: SidebarColor;
16
+ readonly borderActive: SidebarColor;
17
+ }
18
+ export declare function AccountBlock(props: {
19
+ theme: SidebarTheme;
20
+ appearance: AppearancePrefs;
21
+ name: string;
22
+ quota: AccountQuota | null;
23
+ active: boolean;
24
+ pacingEnabled: boolean;
25
+ needsReauth?: boolean;
26
+ vaultReauth?: boolean;
27
+ stateLine?: string;
28
+ quotaDated?: boolean;
29
+ tierLabel?: string;
30
+ /**
31
+ * The quota rows' label column width, shared across the sidebar's accounts
32
+ * so their bars line up; defaults to this account's own longest label.
33
+ */
34
+ labelWidth?: number;
35
+ marginTop?: number;
36
+ now: number;
37
+ }): any;
38
+ export interface SidebarController {
39
+ prefs: () => AnthropicAuthTuiPrefs;
40
+ collapsed: () => boolean;
41
+ toggleCollapsed: () => void;
42
+ /** Stops the preference watcher; OpenCode 1 keeps it for the process. */
43
+ dispose: () => void;
44
+ }
45
+ export declare function createSidebarController(initialPrefs: AnthropicAuthTuiPrefs): SidebarController;
46
+ /** The sidebar panel for one session; the host owns polling and the theme. */
47
+ export declare function ClaudeSidebar(props: {
48
+ state: () => SidebarState;
49
+ theme: () => SidebarTheme;
50
+ controller: SidebarController;
51
+ sessionId: string;
52
+ }): any;
53
+ /** The OpenCode 2 theme tokens the sidebar reads (`ResolvedTheme` subset). */
54
+ export interface HostTheme {
55
+ readonly text: {
56
+ readonly base: SidebarColor;
57
+ readonly muted: SidebarColor;
58
+ readonly action: {
59
+ readonly primary: {
60
+ readonly base: SidebarColor;
61
+ };
62
+ };
63
+ readonly feedback: {
64
+ readonly success: {
65
+ readonly base: SidebarColor;
66
+ };
67
+ readonly warning: {
68
+ readonly base: SidebarColor;
69
+ };
70
+ readonly error: {
71
+ readonly base: SidebarColor;
72
+ };
73
+ };
74
+ };
75
+ readonly background: {
76
+ readonly base: SidebarColor;
77
+ };
78
+ readonly border: {
79
+ readonly base: SidebarColor;
80
+ };
81
+ }
82
+ /** OpenCode 2's semantic theme as the flat tokens OpenCode 1 provides. */
83
+ export declare function sidebarThemeFromHost(theme: HostTheme): SidebarTheme;
84
+ /** The OpenCode 2 TUI context members the sidebar uses. */
85
+ export interface ClaudeSidebarHost {
86
+ readonly theme: HostTheme;
87
+ readonly ui: {
88
+ slot(claim: {
89
+ readonly append: 'sidebar.content';
90
+ readonly render: (input: {
91
+ readonly sessionID: string;
92
+ }) => JSX.Element;
93
+ }): () => void;
94
+ };
95
+ }
96
+ /** Reads one session's sidebar state from the location's server. */
97
+ export type ReadSidebarState = (sessionID: string, signal: AbortSignal) => Promise<SidebarState>;
98
+ /** Claims the OpenCode 2 session sidebar; the returned function releases it. */
99
+ export declare function mountClaudeSidebar(host: ClaudeSidebarHost, read: ReadSidebarState): Promise<() => void>;
@@ -1,4 +1,4 @@
1
- import"./index-f2ne65w4.js";import{readFileSync as k,watch as C}from"node:fs";import{mkdir as _,readFile as I,rename as E,writeFile as b}from"node:fs/promises";import{homedir as g}from"node:os";import{basename as F,dirname as P,join as N}from"node:path";import{clearTimeout as D,setTimeout as L}from"node:timers";import{applyEdits as T,modify as y,parse as f}from"jsonc-parser";var v="OPENCODE_TUI_PREFERENCES_FILE",h="tui-preferences.jsonc";function A(){let J=process.env[v];if(J)return J;let z=process.env.OPENCODE_CONFIG_DIR||N(process.env.XDG_CONFIG_HOME||N(g(),".config"),"opencode");return N(z,h)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}async function qq(){try{let J=await I(A(),"utf8"),z=[],q=f(J,z,{allowTrailingComma:!0});if(z.length>0)return{};return H(q)?q:{}}catch{return{}}}var m="anthropic-auth",p=160,R={forceToTop:!1,order:p,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 $(J,z){return typeof J==="boolean"?J:z}function Y(J,z,q,X){if(typeof J!=="number"||!Number.isFinite(J))return z;return Math.min(Math.max(Math.round(J),q),X)}function c(J,z,q){if(typeof J!=="string"||J.length===0)return z;return J.slice(0,q)}function w(J,z){if(typeof J!=="string")return z;return[...J][0]??z}function zq(J){let z=J[m];if(!H(z))return structuredClone(R);let q=R,X=H(z.header)?z.header:{},Q=H(z.sections)?z.sections:{},Z=H(z.appearance)?z.appearance:{},G=Y(Z.warnThreshold,q.appearance.warnThreshold,0,99),V=Math.max(Y(Z.errorThreshold,q.appearance.errorThreshold,0,100),Math.min(G+1,100));return{forceToTop:$(z.forceToTop,q.forceToTop),order:Y(z.order,q.order,-1e4,1e4),startCollapsed:$(z.startCollapsed,q.startCollapsed),rememberCollapsed:$(z.rememberCollapsed,q.rememberCollapsed),collapsed:typeof z.collapsed==="boolean"?z.collapsed:null,pollMs:Y(z.pollMs,q.pollMs,500,30000),refreshDebounceMs:Y(z.refreshDebounceMs,q.refreshDebounceMs,50,5000),header:{label:c(X.label,q.header.label,20),showVersion:$(X.showVersion,q.header.showVersion)},sections:{quota:$(Q.quota,q.sections.quota),fallbackAccounts:$(Q.fallbackAccounts,q.sections.fallbackAccounts),routing:$(Q.routing,q.sections.routing),cache:$(Q.cache,q.sections.cache),health:$(Q.health,q.sections.health),pacing:$(Q.pacing,q.sections.pacing)},appearance:{barWidth:Y(Z.barWidth,q.appearance.barWidth,4,40),barFilledChar:w(Z.barFilledChar,q.appearance.barFilledChar),barEmptyChar:w(Z.barEmptyChar,q.appearance.barEmptyChar),warnThreshold:G,errorThreshold:V}}}var u=-1e5;function Jq(J,z,q){let X=J[z];if(!H(X))return q;if(X.forceToTop===!0)return u+Object.keys(J).indexOf(z);return Y(X.order,q,-1e4,1e4)}var s=`// Shared preferences for opencode TUI plugins.
1
+ import"./index-62x1p34p.js";import{readFileSync as k,watch as C}from"node:fs";import{mkdir as _,readFile as I,rename as E,writeFile as b}from"node:fs/promises";import{homedir as g}from"node:os";import{basename as F,dirname as P,join as N}from"node:path";import{clearTimeout as D,setTimeout as L}from"node:timers";import{applyEdits as T,modify as y,parse as f}from"jsonc-parser";var v="OPENCODE_TUI_PREFERENCES_FILE",h="tui-preferences.jsonc";function A(){let J=process.env[v];if(J)return J;let z=process.env.OPENCODE_CONFIG_DIR||N(process.env.XDG_CONFIG_HOME||N(g(),".config"),"opencode");return N(z,h)}function H(J){return typeof J==="object"&&J!==null&&!Array.isArray(J)}async function qq(){try{let J=await I(A(),"utf8"),z=[],q=f(J,z,{allowTrailingComma:!0});if(z.length>0)return{};return H(q)?q:{}}catch{return{}}}var m="anthropic-auth",p=160,R={forceToTop:!1,order:p,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 $(J,z){return typeof J==="boolean"?J:z}function Y(J,z,q,X){if(typeof J!=="number"||!Number.isFinite(J))return z;return Math.min(Math.max(Math.round(J),q),X)}function c(J,z,q){if(typeof J!=="string"||J.length===0)return z;return J.slice(0,q)}function w(J,z){if(typeof J!=="string")return z;return[...J][0]??z}function zq(J){let z=J[m];if(!H(z))return structuredClone(R);let q=R,X=H(z.header)?z.header:{},Q=H(z.sections)?z.sections:{},Z=H(z.appearance)?z.appearance:{},G=Y(Z.warnThreshold,q.appearance.warnThreshold,0,99),V=Math.max(Y(Z.errorThreshold,q.appearance.errorThreshold,0,100),Math.min(G+1,100));return{forceToTop:$(z.forceToTop,q.forceToTop),order:Y(z.order,q.order,-1e4,1e4),startCollapsed:$(z.startCollapsed,q.startCollapsed),rememberCollapsed:$(z.rememberCollapsed,q.rememberCollapsed),collapsed:typeof z.collapsed==="boolean"?z.collapsed:null,pollMs:Y(z.pollMs,q.pollMs,500,30000),refreshDebounceMs:Y(z.refreshDebounceMs,q.refreshDebounceMs,50,5000),header:{label:c(X.label,q.header.label,20),showVersion:$(X.showVersion,q.header.showVersion)},sections:{quota:$(Q.quota,q.sections.quota),fallbackAccounts:$(Q.fallbackAccounts,q.sections.fallbackAccounts),routing:$(Q.routing,q.sections.routing),cache:$(Q.cache,q.sections.cache),health:$(Q.health,q.sections.health),pacing:$(Q.pacing,q.sections.pacing)},appearance:{barWidth:Y(Z.barWidth,q.appearance.barWidth,4,40),barFilledChar:w(Z.barFilledChar,q.appearance.barFilledChar),barEmptyChar:w(Z.barEmptyChar,q.appearance.barEmptyChar),warnThreshold:G,errorThreshold:V}}}var u=-1e5;function Jq(J,z,q){let X=J[z];if(!H(X))return q;if(X.forceToTop===!0)return u+Object.keys(J).indexOf(z);return Y(X.order,q,-1e4,1e4)}var s=`// 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,8 +1,11 @@
1
1
  import type { NativeMenuCommandId, NativeMenuDispatch } from '@cortexkit/anthropic-auth-core';
2
+ import type { SidebarState } from '../sidebar-state';
2
3
  /** Account, setting and session actions exposed through the server's menu RPC. */
3
4
  export interface NativeMenuCapabilities {
4
5
  readonly dispatch: NativeMenuDispatch;
5
6
  readonly readStatus: (command: Exclude<NativeMenuCommandId, 'start'>) => Promise<string>;
7
+ /** The quota sidebar's state for one session; carries no secrets. */
8
+ readonly readSidebar: (sessionID: string) => Promise<SidebarState>;
6
9
  readonly forgetSession: (sessionID: string) => void;
7
10
  readonly close: () => void;
8
11
  }
package/dist/v2/rpc.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { CommandApplyRequest, CommandApplyResult, CommandDialogPayload, Com
2
2
  import type { Plugin } from '@opencode/plugin';
3
3
  import type { Registration } from '@opencode/plugin/promise/registration';
4
4
  import type { StandardSchemaV1 } from '@standard-schema/spec';
5
+ import { type SidebarState } from '../sidebar-state';
5
6
  import type { NativeMenuCapabilities } from './menu-contract';
6
7
  export declare const NATIVE_MENU_RPC: {
7
8
  readonly id: 'cortexkit-anthropic-native';
@@ -22,6 +23,14 @@ export declare const NATIVE_MENU_RPC: {
22
23
  }>;
23
24
  readonly output: StandardSchemaV1<CommandApplyResult, CommandApplyResult>;
24
25
  };
26
+ readonly sidebar: {
27
+ readonly input: StandardSchemaV1<Record<string, unknown> & {
28
+ sessionId: string;
29
+ }, Record<string, unknown> & {
30
+ sessionId: string;
31
+ }>;
32
+ readonly output: StandardSchemaV1<unknown, SidebarState>;
33
+ };
25
34
  };
26
35
  readonly events: {
27
36
  readonly opened: {