glintline 0.0.0-stage → 0.3.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.
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ var C=(t,e,n)=>()=>{if(t)try{e=t(t=0)}catch(r){n=[r]}if(n)throw n[0];return e};import{readFileSync as Ft}from"node:fs";import{homedir as Y}from"node:os";import{join as X}from"node:path";function L(t){return!!t&&$t.test(t)}function v(t){if(!t)return"claude";for(let[e,n]of Gt)if(e.test(t))return n;return t.toLowerCase().match(/[a-z]+/)?.[0]??t.toLowerCase()}function Pt(t){if(!t)return;let e=t.match(/(\d+)[.-](\d+)/);if(e)return`${e[1]}.${e[2]}`;return t.match(/(\d+)/)?.[1]}function Dt(t,e){let n=`${t??""} ${e??""}`;return L(n)?"1M":void 0}function Bt(){let t=[X(Y(),".claude","settings.local.json"),X(Y(),".claude","settings.json")];for(let e of t)try{let n=Ft(e,"utf8"),r=JSON.parse(n);if(typeof r.effortLevel==="string"&&r.effortLevel.length>0)return r.effortLevel}catch{}return null}function q(t){let{input:e,sessionEffort:n,fast:r}=t,o=e.model?.id,i=e.model?.display_name,a=i??o,l=v(a),c=Pt(a),f=Dt(o,i),d=jt(e,n,c);return{family:l,version:c,context:f,effort:d,effortSessionOnly:n?.sessionOnly,fast:typeof e.fast_mode==="boolean"?e.fast_mode:r}}function jt(t,e,n){let r=t.effort;if(r&&"level"in r)return typeof r.level==="string"?r.level.toLowerCase():void 0;let o=e?.level??Bt()??void 0;return zt(o,n)}function zt(t,e){if(t!=="xhigh")return t;return(e?parseFloat(e):0)>=4.7?t:"high"}var Gt,$t;var O=C(()=>{Gt=[[/opus/i,"opus"],[/sonnet/i,"sonnet"],[/haiku/i,"haiku"],[/fable/i,"fable"]],$t=/(?:\b|\[)1m\b|1[\s_-]?million/i});function p(t,e){if(!Ht)return;let n=e instanceof Error?e.message:String(e);process.stderr.write(`[glintline:${t}] ${n}
3
+ `)}var Ht;var y=C(()=>{Ht=process.env.GLINTLINE_DEBUG==="1"||process.env.GLINTLINE_DEBUG==="true"});import{mkdirSync as Jt,readFileSync as Kt,writeFileSync as Vt,statSync as Yt}from"node:fs";import{tmpdir as Xt}from"node:os";import{join as nt}from"node:path";import{createHash as qt}from"node:crypto";function Zt(){try{Jt(rt,{recursive:!0})}catch(t){p("cache.mkdir",t)}}function I(t){Zt();let e=qt("sha256").update(t).digest("hex").slice(0,16);return nt(rt,`${e}.json`)}function w(t,e){let n=I(t);try{let r=Yt(n);if((Date.now()-r.mtimeMs)/1000>e)return null;return JSON.parse(Kt(n,"utf8"))}catch{return null}}function x(t,e){let n=I(t);try{Vt(n,JSON.stringify(e))}catch(r){p("cache.write",r)}}var rt;var N=C(()=>{y();rt=nt(Xt(),"glintline-cache")});import{execFileSync as pe}from"node:child_process";import{readFileSync as me}from"node:fs";import{homedir as ge,platform as he}from"node:os";import{join as ye}from"node:path";function xe(){try{let t=pe("security",["find-generic-password","-s",be,"-w"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(!t)return null;return JSON.parse(t).claudeAiOauth?.accessToken??null}catch(t){return p("credentials.keychain",t),null}}function st(){try{let t=ye(ge(),".claude",".credentials.json"),e=me(t,"utf8");return JSON.parse(e).claudeAiOauth?.accessToken??null}catch(t){return p("credentials.file",t),null}}function W(){if(he()==="darwin")return xe()??st();return st()}var be="Claude Code-credentials";var at=C(()=>{y()});import{createHash as ut}from"node:crypto";import{spawn as _e}from"node:child_process";import{existsSync as Ce,unlinkSync as we}from"node:fs";import{resolve as Se}from"node:path";import{argv as Ee,execPath as Te}from"node:process";function Ne(t){let e={};if(!Array.isArray(t))return e;for(let n of t){if(!n||n.group!=="weekly")continue;let r=n.scope?.model?.display_name;if(typeof r!=="string")continue;let o=U({utilization:n.percent,resets_at:n.resets_at});if(o)e[v(r)]=o}return e}function lt(t){return"usage:"+ut("sha256").update(t).digest("hex").slice(0,16)}function M(t){return"usage-lock:"+ut("sha256").update(t).digest("hex").slice(0,16)}function Ae(t){if(!t)return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1000):0}function U(t){if(!t||t.utilization===void 0)return;return{utilization:t.utilization,resets_at:Ae(t.resets_at)}}function We(t){if(!t||t.utilization===void 0)return;return{is_enabled:t.is_enabled??!1,monthly_limit:t.monthly_limit??0,used_credits:t.used_credits??0,utilization:t.utilization}}function Ue(t){if(!t)return 1/0;return Math.floor(Date.now()/1000)-t.fetched_at}function ct(t){return w(M(t),ve)!==null}function Me(t){x(M(t),{at:Math.floor(Date.now()/1000)})}function Re(t){try{let e=I(M(t));if(Ce(e))we(e)}catch(e){p("usage-api.lock",e)}}function Fe(){let t=Ee[1];if(!t)return;let e=Se(t);try{_e(Te,[e,"--refresh-usage"],{detached:!0,stdio:"ignore"}).unref()}catch(n){p("usage-api.spawn",n)}}async function Ge(t){let e=new AbortController,n=setTimeout(()=>e.abort(),Le);try{let r=await fetch(Oe,{method:"GET",headers:{Accept:"application/json",Authorization:`Bearer ${t}`,"anthropic-beta":"oauth-2025-04-20","User-Agent":"glintline/0.1"},signal:e.signal});if(!r.ok)return p("usage-api.fetch",`HTTP ${r.status}`),null;let o=await r.json(),i={five_hour:U(o.five_hour),seven_day:U(o.seven_day),seven_day_scoped:Ne(o.limits),extra:We(o.extra_usage),fetched_at:Math.floor(Date.now()/1000),source:"api"};return x(lt(t),i),i}catch(r){return p("usage-api.fetch",r),null}finally{clearTimeout(n)}}async function ft(){let t=W();if(!t)return;if(ct(t))return;Me(t);try{await Ge(t)}finally{Re(t)}}function dt(){let t=W();if(!t)return null;let e=w(lt(t),ke);if(Ue(e)>=Ie&&!ct(t))Fe();return e?{...e,source:"cache"}:null}var Oe="https://api.anthropic.com/api/oauth/usage",Ie=60,ke=86400,Le=8000,ve=30;var R=C(()=>{at();O();N();y()});O();import{writeFileSync as vt}from"node:fs";function Z(t,e){let n=process.env[t];if(!n)return null;let r=parseFloat(n);if(!Number.isFinite(r)||r<=0)return null;return Math.min(r,e)}function Q(t,e){let n=Z("CLAUDE_CODE_AUTO_COMPACT_WINDOW",1e7)??t,r=Z("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE",100);if(r===null)return{total:n};let o=Math.round(n*(r/100));if(e)return{total:n,compactThreshold:o};return{total:o}}function tt(t,e){if(!t)return null;return{used:t.used,...Q(t.total,e)}}function et(t,e){let n=t.context_window;if(!n)return null;let r=Q(n.context_window_size??200000,e),o=n.current_usage;if(o){let i=(o.input_tokens??0)+(o.cache_creation_input_tokens??0)+(o.cache_read_input_tokens??0);if(i>0)return{used:i,...r}}if(n.total_input_tokens&&n.total_input_tokens>0)return{used:n.total_input_tokens,...r};if(n.used_percentage!==void 0)return{used:Math.round(n.used_percentage/100*r.total),...r};return null}N();O();y();import{openSync as Qt,readSync as te,closeSync as ee,statSync as ne}from"node:fs";var ot=4,re=604800;function k(){return{v:ot,scannedUpTo:0,ppid:0,effort:null,context:null,fast:!1,totals:{input:0,output:0,cacheRead:0,cacheCreation:0},last:null,lastId:null,lastOutput:0}}var oe=/Set effort level to ([a-z0-9-]+)(?:\s*\(([^)]*)\))?/i,ie=/\x1b\[[0-9;]*m/g,se=/Set model to .*?with ([a-z0-9-]+) effort/i,ae=/Fast mode (ON|OFF)/i,ue=200000;function le(t,e,n){if(n<=0)return"";let r=Qt(t,"r");try{let o=Buffer.alloc(n),i=te(r,o,0,n,e);return o.subarray(0,i).toString("utf8")}finally{ee(r)}}function ce(t){let e;if(typeof t==="string")e=t;else if(Array.isArray(t))e=t.map((r)=>typeof r==="object"&&r&&("text"in r)?String(r.text):"").join("");else return null;return e.match(/<local-command-stdout>([\s\S]*?)<\/local-command-stdout>/)?.[1]??null}function fe(t){return L(t)?1e6:ue}function de(t,e){if(!t||t[0]!=="{")return;let n;try{n=JSON.parse(t)}catch{return}if(n.type==="user"&&n.message?.role==="user"){let o=ce(n.message.content)?.replace(ie,"");if(o){let i=o.match(oe);if(i){let l=(i[1]??"").toLowerCase(),c=(i[2]??"").toLowerCase();e.effort={level:l,sessionOnly:c.includes("this session only")||c.includes("session only")}}else{let l=o.match(se);if(l)e.effort={level:(l[1]??"").toLowerCase(),sessionOnly:!1}}let a=o.match(ae);if(a)e.fast=a[1].toUpperCase()==="ON"}}if(n.type==="assistant"&&n.message?.usage&&!n.isSidechain){let r=n.message.usage,o=r.input_tokens??0,i=r.output_tokens??0,a=r.cache_creation_input_tokens??0,l=r.cache_read_input_tokens??0,c=n.message.id??null;if(c!==null&&c===e.lastId&&e.last)e.totals.input-=e.last.input,e.totals.output-=e.lastOutput,e.totals.cacheRead-=e.last.cacheRead,e.totals.cacheCreation-=e.last.cacheCreation;e.totals.input+=o,e.totals.output+=i,e.totals.cacheRead+=l,e.totals.cacheCreation+=a,e.last={input:o,cacheRead:l,cacheCreation:a},e.lastId=c,e.lastOutput=i;let f=o+a+l;if(f>0)e.context={used:f,total:fe(n.message.model)}}}function A(t){return"transcript:"+t}function it(t){if(!t)return k();let e;try{e=ne(t).size}catch(g){return p("transcript.stat",g),k()}let n=w(A(t),re),r=n&&n.v===ot?n:k();if(r.scannedUpTo>e)r=k();let o=process.ppid;if(r.ppid!==0&&r.ppid!==o&&r.effort?.sessionOnly)r.effort=null;if(r.ppid=o,r.scannedUpTo===e)return x(A(t),r),r;let i=r.scannedUpTo,a=e-i,l;try{l=le(t,i,a)}catch(g){return p("transcript.read",g),r}let c=l.split(`
4
+ `),d=i>0?1:0;for(let g=d;g<c.length-1;g++)de(c[g]??"",r);let b=c[c.length-1]??"";return r.scannedUpTo=e-Buffer.byteLength(b,"utf8"),x(A(t),r),r}R();function $e(t){if(t===void 0)return 0;if(typeof t==="number")return t;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1000):0}function pt(t){if(!t||t.used_percentage===void 0)return;return{utilization:t.used_percentage,resets_at:$e(t.resets_at)}}function Pe(t){let e=t.rate_limits;if(!e)return null;let n=pt(e.five_hour),r=pt(e.seven_day);if(!n&&!r)return null;return{five_hour:n,seven_day:r,fetched_at:Math.floor(Date.now()/1000),source:"stdin"}}function De(t,e){if(!e)return t;if(!t)return e;return{...e,five_hour:t.five_hour,seven_day:t.seven_day,source:t.source}}function mt(t,e){let n=Pe(t);if(!e)return n;return De(n,dt())}var Be=new Set(["extra"]);function gt(t){let e=(n)=>t.widgets.some((r)=>r.some(n));if(e((n)=>Be.has(n)))return!0;return e((n)=>n==="limit7d")&&t.limit7d.perModel}y();import{execFileSync as je}from"node:child_process";var ze=1500;function S(t,e){return je("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:ze}).trim()}function ht(t){let e="";try{e=S(["symbolic-ref","--short","HEAD"],t)}catch{try{e=S(["rev-parse","--short","HEAD"],t)}catch{return null}}let n=0,r=0,o=!1,i=(a)=>{if(!a)return;o=!0;for(let l of a.split(`
5
+ `)){let[c,f]=l.split("\t"),d=parseInt(c??"",10),b=parseInt(f??"",10);if(Number.isFinite(d))n+=d;if(Number.isFinite(b))r+=b}};try{i(S(["diff","--numstat"],t))}catch(a){p("git.diff",a)}try{i(S(["diff","--cached","--numstat"],t))}catch(a){p("git.diffCached",a)}try{if(S(["ls-files","--others","--exclude-standard"],t))o=!0}catch(a){p("git.untracked",a)}return{branch:e,added:n,removed:r,dirty:o}}var m=(t)=>`\x1B[38;5;${t}m`,s={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",gray:m(244),darkGray:m(240),darkestGray:m(236),lightGray:m(250),white:m(255),red:m(203),mutedRed:m(167),orange:m(214),yellow:m(220),mutedYellow:m(179),green:m(114),mutedGreen:m(108),cyan:m(73),mutedBlue:m(67),magenta:m(176),purple:m(141),lime:m(149),silver:m(251),pink:m(211),coral:m(209)},u=(t,e)=>`${t}${e}\x1B[0m`;function F(t){return t.replace(/\.0$/,"")}function h(t){if(t>=1e6){let e=t/1e6;return`${e>=10?e.toFixed(0):F(e.toFixed(1))}M`}if(t>=1000)return`${Math.round(t/1000)}K`;return String(t)}function G(t){if(t<=0)return"0m";let e=t/60;if(e<60)return`${Math.round(e)}m`;let n=e/60;if(n<24)return`${n>=10?Math.round(n):F(n.toFixed(1))}h`;let r=n/24;return`${r>=10?Math.round(r):F(r.toFixed(1))}d`}function yt(t){let e=new Date(t*1000);return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function _(t,e=!1){if(t>=90)return e?s.mutedRed:s.red;if(t>=75)return e?s.mutedYellow:s.yellow;return e?s.mutedGreen:s.green}function P(t){if(t>=80)return s.green;if(t>=50)return s.yellow;return s.gray}function bt(t,e,n){let r=t+e+n;return r>0?t/r*100:null}var D={square:{full:"■",empty:"□"},circle:{full:"●",empty:"○"},bar:{full:"█",empty:"░"},ascii:{full:"#",empty:"-"},dots:{full:"⬢",empty:"⬡"}};function xt(t,e,n,r){if(e<=0)return"";let{full:o,empty:i,threshold:a,fillEmpty:l=!1,calm:c=!1}=r,f=Math.min(1,Math.max(0,t/e)),d=Math.round(f*n),b=l?o:i,g=l?s.darkestGray:s.darkGray;if(a!==void 0&&a>0&&a<e){let Wt=t/a*100,Ut=_(Wt,c),Mt=Math.round(a/e*n),V=Math.max(0,Mt-d),Rt=Math.max(0,n-d-V);return u(Ut,o.repeat(d))+u(g,b.repeat(V))+u(s.gray,o.repeat(Rt))}let Nt=Math.max(0,n-d),At=_(f*100,c);return u(At,o.repeat(d))+u(g,b.repeat(Nt))}var He={opus:s.purple,sonnet:s.cyan,haiku:s.silver,fable:s.coral},Je=[["opus",5,s.lime]];function Ke(t,e){let n=e?parseFloat(e):0;for(let[r,o,i]of Je)if(t===r&&n>=o)return i;return He[t]??s.white}function Ve(t){let{model:e}=t,n=t.config.model,r=Ke(e.family,e.version),o=[];if(n.showFamily)o.push(u(s.bold+r,e.family));let i=[];if(n.showVersion&&e.version)i.push(e.version);if(n.showContext&&e.context)i.push(e.context);if(i.length>0)o.push(u(r,i.join(" ")));if(n.showEffortIcon&&e.effort){let l=t.config.effort.icons[e.effort];if(l)o.push(u(Ct(e.effort),l))}if(o.length===0)return null;let a=o.join(" ");return n.label?u(s.lightGray,n.label)+" "+a:a}function Ct(t){if(t==="max")return s.pink;if(t==="xhigh")return s.orange;return s.yellow}function Ye(t){let e=t.model.effort;if(!e)return null;let n=u(Ct(e),e);if(t.model.fast)n+=" "+u(s.orange,"fast");let r=t.config.effort.label;return r?u(s.lightGray,r)+" "+n:n}function Xe(t){if(!t.context)return null;let{context:e}=t,n=t.config.context,r=t.config.calmColors,o=e.compactThreshold??e.total,i=o>0?e.used/o*100:0,a=[];if(n.showBar){let c=D[n.barStyle]??D.square,f=n.barChars??c;a.push(xt(e.used,e.total,n.barWidth,{full:f.full,empty:f.empty,threshold:e.compactThreshold,fillEmpty:n.fillEmpty,calm:r}))}if(n.showNumbers){let c=_(i,r),f;if(e.compactThreshold!==void 0&&e.compactThreshold<e.total){let d=e.total-e.compactThreshold;if(f=u(c,h(e.used))+u(s.gray,"/")+u(s.lightGray,h(e.compactThreshold)),n.showBufferTokens)f+=u(s.gray,"/")+u(s.gray,h(d))}else f=u(c,`${h(e.used)}/${h(e.total)}`);if(n.showPercent)f+=" "+u(s.gray,"(")+u(c,`${Math.round(i)}%`)+u(s.gray,")");a.push(f)}if(a.length===0)return null;let l=a.join(n.gap);return n.label?u(s.lightGray,n.label)+" "+l:l}var wt={"5h":18000,"7d":604800};function _t(t,e,n,r){if(t.resets_at<=0)return null;let o=(e-(t.resets_at-n))/n;if(o>=1)return null;let i=r?s.lightGray:null;if(o<0.1)return{icon:"~",color:i??s.gray};let a=t.utilization,l=a/o;if(l<=100){if(l<50)return{icon:"↓↓",color:i??s.mutedGreen};if(l<80)return{icon:"↓",color:i??s.mutedGreen};return{icon:"~",color:i??s.gray}}let c=1-o,d=1-(100-a)/a*o/c;if(d>0.5)return{icon:"↑↑",color:i??s.mutedRed};if(d>0.15)return{icon:"↑",color:i??s.mutedYellow};return{icon:"~",color:i??s.gray}}function j(t,e,n,r,o,i){if(!t)return null;let a=Math.round(t.utilization),l=e.mono?s.lightGray:_(a,r),c=u(s.lightGray,e.label)+u(s.gray,e.separator)+u(l,`${a}%`);if(e.showBurnRate){let f=_t(t,n,o,e.mono);if(f)c+=" "+u(f.color,f.icon)}if(i){let f=u(s.darkGray,`${Math.round(i.utilization)}%`);if(e.showBurnRate){let d=_t(i,n,o,e.mono);if(d)f+=" "+u(d.color,d.icon)}c+=" "+u(s.darkGray,"(")+f+u(s.darkGray,")")}if(e.showCountdown&&t.resets_at>0){let f=t.resets_at-n;if(f>0)c+=u(s.gray,` ⟳ ${G(f)}`)}return c}function qe(t){return j(t.usage?.five_hour,t.config.limit5h,t.nowSec,t.config.calmColors,wt["5h"])}function Ze(t){let e=t.config.limit7d,n=t.usage?.seven_day,r=wt["7d"],o=e.perModel?t.usage?.seven_day_scoped?.[t.model.family]:void 0;if(o){let i=`${e.label}-${t.model.family}`;return j(o,{...e,label:i},t.nowSec,t.config.calmColors,r,n)}return j(n,e,t.nowSec,t.config.calmColors,r)}function Qe(t){let e=t.usage?.extra;if(!e||!e.is_enabled)return null;if(t.config.extra.onlyWhenActive){let a=t.model.fast,l=(t.usage?.five_hour?.utilization??0)>=100,c=(t.usage?.seven_day?.utilization??0)>=100;if(!a&&!l&&!c)return null}let n=Math.round(e.utilization),r=t.config.extra.mono?s.lightGray:_(n,t.config.calmColors),o=(e.used_credits/100).toFixed(2),i=(e.monthly_limit/100).toFixed(0);return u(s.lightGray,t.config.extra.label)+u(s.gray,": ")+u(r,`$${o}`)+u(s.gray,`/$${i}`)+" "+u(s.gray,"(")+u(r,`${n}%`)+u(s.gray,")")}function tn(t){let e=t.input.workspace?.git_worktree??t.input.worktree?.name;if(!e)return null;let n=t.config.git.worktreeLabel;return u(s.cyan,n?`${n} ${e}`:e)}function en(t){if(!t.git||!t.git.branch)return null;return u(s.magenta,"⎇ ")+u(s.bold+s.magenta,t.git.branch)}function nn(t){if(!t.git)return null;let e=t.git;if(e.added>0||e.removed>0)return u(s.gray,"(")+u(s.green,`+${e.added}`)+u(s.gray,",")+u(s.red,`-${e.removed}`)+u(s.gray,")");if(e.dirty)return u(s.yellow,"*");return null}function rn(t){return u(s.darkGray,t.config.separator)}function on(){return" "}function B(t){if(!t)return null;let e=bt(t.cacheRead,t.cacheCreation,t.input);return e===null?null:Math.round(e)}function sn(t){let e=t.config.cache,n=t.input.prompt_cache;if(!e.showExpiry||!n?.caching_observed)return null;let r=n.expires_at??0;if(n.warm&&r>t.nowSec){let a=yt(r);return u(s.gray,e.expiryLabel?`${e.expiryLabel} ${a}`:a)}let o=[];if(e.coldLabel)o.push(u(e.mono?s.lightGray:s.mutedBlue,e.coldLabel));let i=n.recache_tokens_if_cold;if(i)o.push(u(e.mono?s.lightGray:s.yellow,`↑${h(i)}`));return o.length>0?o.join(" "):null}function an(t){let e=t.config.cache,n=[];if(e.window==="both"){let i=B(t.cacheLast),a=B(t.totals);if(i!==null)n.push(u(e.mono?s.lightGray:P(i),`${i}%`));if(a!==null)n.push(u(s.darkGray,`Σ${a}%`))}else{let i=B(e.window==="last"?t.cacheLast:t.totals);if(i!==null)n.push(u(e.mono?s.lightGray:P(i),`${i}%`))}if(n.length===0)return null;if(!e.showPercent)n.length=0;let r=sn(t);if(r)n.push(r);if(n.length===0)return null;return(e.label?u(s.lightGray,e.label)+" ":"")+n.join(" ")}function un(t){let e=t.totals;if(e.cacheRead===0&&e.cacheCreation===0)return null;return u(s.green,`↓${h(e.cacheRead)}`)+" "+u(s.yellow,`↑${h(e.cacheCreation)}`)}function ln(t){if(t.config.cost.onlyWhenFast&&!t.model.fast)return null;let e=t.input.cost?.total_cost_usd;if(e===void 0)return null;return u(s.green,`$${e.toFixed(t.config.cost.precision)}`)}function cn(t){let e=t.input.cost?.total_lines_added,n=t.input.cost?.total_lines_removed;if(e===void 0&&n===void 0)return null;return u(s.green,`+${e??0}`)+u(s.gray,"/")+u(s.red,`-${n??0}`)}function fn(t){let e=t.input.cost?.total_duration_ms;if(!e)return null;let n=t.config.session,r=n.mono?s.lightGray:s.cyan;return(n.label?u(s.gray,n.label)+" ":"")+u(r,G(e/1000))}function dn(t){let e=t.input.version;return e?u(s.darkGray,`v${e}`):null}function pn(t){let e=t.input.workspace?.current_dir??t.input.cwd;if(!e)return null;let n=t.config.cwd,r=u(s.mutedBlue,mn(e,n.format,n.maxLength));return n.label?u(s.lightGray,n.label)+" "+r:r}function mn(t,e,n){let r=process.env.HOME??"",o=r&&t.startsWith(r)?"~"+t.slice(r.length):t;if(e==="full")return t;if(e==="home")return o;if(e==="short")return o.split("/").slice(-2).join("/");if(o.length<=n)return o;let i=o.split("/");if(i.length<=2)return o;let a=i[0],l=i.slice(-2).join("/"),c=`${a}/…/${l}`;if(c.length<=n)return c;let f=i[i.length-1];return`${a}/…/${f}`}function gn(t){let e=t.input.session_id;if(!e)return null;let n=t.config.session,r=n.idLength>0?n.idLength:e.length,o=e.slice(0,r),i=n.mono?s.lightGray:s.gray;return(n.idLabel?u(s.lightGray,n.idLabel)+" ":"")+u(i,o)}var hn={model:Ve,effort:Ye,context:Xe,limit5h:qe,limit7d:Ze,extra:Qe,"git.worktree":tn,"git.branch":en,"git.diff":nn,cache:an,"cache.tokens":un,cost:ln,lines:cn,session:fn,"session.id":gn,version:dn,cwd:pn,sep:rn,space:on},E=new Set(["sep","space"]);function St(t,e){let n=hn[t];return n?n(e):null}function z(t=process.env){let e=Number.parseInt(t.COLUMNS??"",10);return Number.isFinite(e)&&e>0?e:null}var yn=[[4352,4447],[11904,12350],[12353,13311],[13312,19903],[19968,40959],[40960,42191],[44032,55203],[63744,64255],[65072,65135],[65280,65376],[65504,65510],[127744,128591],[128640,128767],[129280,129535],[131072,262141]];function bn(t){return t>=768&&t<=879||t>=65024&&t<=65039||t>=8203&&t<=8205||t===65279}function xn(t){if(bn(t))return 0;for(let[e,n]of yn)if(t>=e&&t<=n)return 2;return 1}function H(t){let e=0;for(let n of t.replace(/\x1b\[[0-9;]*m/g,""))e+=xn(n.codePointAt(0));return e}function Et(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}function _n(t,e){let n=u(s.darkGray,e),r=[],o=null;for(let i=0;i<t.length;i++){let a=t[i];if(!a.out)continue;if(o!==null){let l=Et(o)===Et(a.name)&&o!==a.name;r.push(l?{name:"space",out:" "}:{name:"sep",out:n})}r.push(a),o=a.name}return r}function Cn(t){let e=[];for(let n=0;n<t.length;n++){let r=t[n];if(r.out===null||r.out==="")continue;if(E.has(r.name)){let i=e[e.length-1];if(!i)continue;if(!t.slice(n+1).some((l)=>l.out&&!E.has(l.name)))continue;if(E.has(i.name)){e[e.length-1]=r;continue}}e.push(r)}return e.map((n)=>n.out)}function Tt(t,e,n){let r=t.map((a)=>({name:a,out:St(a,e)})),i=t.some((a)=>E.has(a))?r:_n(r,n);return Cn(i).join("")}var wn={"cache:session":(t)=>t.cache.window==="both"?{...t,cache:{...t.cache,window:"last"}}:t,"cache:percent":(t)=>({...t,cache:{...t.cache,showPercent:!1}}),"context:buffer":(t)=>({...t,context:{...t.context,showBufferTokens:!1}}),"context:numbers":(t)=>({...t,context:{...t.context,showNumbers:!1}})};function Sn(t,e,n,r){let o=Tt(t,e,n);if(r===null)return o;let i=t,a=e;for(let l of e.config.dropWhenNarrow){if(H(o)<=r)break;let c=wn[l];if(c){if(!i.includes(l.slice(0,l.indexOf(":"))))continue;a={...a,config:c(a.config)}}else{if(!i.includes(l))continue;i=i.filter((f)=>f!==l)}o=Tt(i,a,n)}return o}function En(t,e){return t===null?null:t-2*(2+Math.max(0,e))}function Ot(t){let e={...t,nowSec:Math.floor(Date.now()/1000)},n=En(t.columns,t.config.statusLinePadding);return t.config.widgets.map((r)=>Sn(r,e,t.config.separator,n)).filter((r)=>r.length>0).join(`
6
+ `)}y();import{readFileSync as Tn}from"node:fs";import{homedir as J}from"node:os";import{join as K}from"node:path";var It={widgets:[["model","effort","cost","context","limit5h","limit7d","extra","git.worktree","git.branch","git.diff"],["session.id","cwd"]],separator:" │ ",calmColors:!1,dropWhenNarrow:[],statusLinePadding:0,model:{showFamily:!0,showVersion:!0,showContext:!0,showEffortIcon:!0,label:"✳"},effort:{label:"∼",icons:{low:"·",medium:"⁚",high:"⁖",xhigh:"⁘",max:"⁙"}},context:{showBar:!0,showNumbers:!0,showPercent:!1,showCompactBuffer:!1,showBufferTokens:!0,fillEmpty:!0,barWidth:10,barStyle:"square",gap:" ",label:"⊠"},limit5h:{showCountdown:!0,separator:" ",label:"5h",mono:!1,showBurnRate:!0},limit7d:{showCountdown:!0,separator:" ",label:"7d",mono:!1,showBurnRate:!0,perModel:!1},cost:{precision:2,onlyWhenFast:!0},extra:{onlyWhenActive:!1,label:"extra",mono:!1},cache:{label:"cache",mono:!1,window:"session",showPercent:!0,showExpiry:!1,expiryLabel:"⟳",coldLabel:"cold"},git:{worktreeLabel:"⎘"},session:{label:"⏱︎",mono:!1,idLength:8,idLabel:"#"},cwd:{format:"smart",maxLength:40,label:"⊕"}};function On(){let t=process.env.GLINTLINE_CONFIG;if(t)return[t];return[K(J(),".config","glintline","settings.json"),K(J(),".config","glintline.json"),K(J(),".claude","glintline.json")]}function In(t){try{return JSON.parse(Tn(t,"utf8"))}catch(e){if(e.code!=="ENOENT")p("config.read",e);return null}}function T(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}var kn=new Set(["__proto__","constructor","prototype"]);function kt(t,e){if(!e)return t;if(!T(t)||!T(e))return t;let n={...t};for(let r of Object.keys(e)){if(kn.has(r))continue;let o=e[r],i=n[r];if(o===void 0)continue;if(T(o)&&T(i))n[r]=kt(i,o);else n[r]=o}return n}function Ln(t){let e=t.widgets;if(Array.isArray(e)&&e.every((n)=>typeof n==="string"))return{...t,widgets:[e]};return t}function Lt(){for(let t of On()){let e=In(t);if(T(e))return Ln(kt(It,e))}return It}y();async function vn(){if(process.stdin.isTTY)return"";let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf8")}function Nn(t){if(!t.trim())return{};try{return JSON.parse(t)}catch{return{}}}async function An(){if(process.argv.includes("--refresh-usage")){await Promise.resolve().then(() => R());await ft();return}let t=await vn(),e=process.env.GLINTLINE_DUMP_STDIN;if(e)try{vt(e,t)}catch(d){p("stdin.dump",d)}let n=process.env.GLINTLINE_DUMP_ENV,r=Nn(t),o=r.workspace?.current_dir??r.cwd??process.cwd(),i=Lt(),a=it(r.transcript_path),l=mt(r,gt(i)),c=et(r,i.context.showCompactBuffer)??tt(a.context,i.context.showCompactBuffer),f=Ot({input:r,model:q({input:r,sessionEffort:a.effort,fast:a.fast}),context:c,usage:l,git:ht(o),totals:a.totals,cacheLast:a.last,config:i,columns:z()});if(n)try{vt(n,JSON.stringify({COLUMNS:process.env.COLUMNS??null,LINES:process.env.LINES??null,parsedColumns:z(),lines:f.split(`
7
+ `).map((d)=>({width:H(d),text:d.replace(/\x1b\[[0-9;]*m/g,"")}))},null,2))}catch(d){p("env.dump",d)}process.stdout.write(f)}An().catch((t)=>{p("main",t),process.exit(0)});
@@ -0,0 +1,38 @@
1
+ {
2
+ "widgets": [
3
+ ["model", "effort", "cost", "context", "limit5h", "limit7d", "extra", "git.worktree", "git.branch", "git.diff"],
4
+ ["session.id", "cwd"]
5
+ ],
6
+ "separator": " │ ",
7
+ "calmColors": false,
8
+ "dropWhenNarrow": [],
9
+ "statusLinePadding": 0,
10
+ "model": {
11
+ "showFamily": true,
12
+ "showVersion": true,
13
+ "showContext": true,
14
+ "showEffortIcon": true,
15
+ "label": "✳"
16
+ },
17
+ "effort": { "label": "∼", "icons": { "low": "·", "medium": "⁚", "high": "⁖", "xhigh": "⁘", "max": "⁙" } },
18
+ "context": {
19
+ "showBar": true,
20
+ "showNumbers": true,
21
+ "showPercent": false,
22
+ "showCompactBuffer": false,
23
+ "showBufferTokens": true,
24
+ "fillEmpty": true,
25
+ "barWidth": 10,
26
+ "barStyle": "square",
27
+ "gap": " ",
28
+ "label": "⊠"
29
+ },
30
+ "limit5h": { "showCountdown": true, "separator": " ", "label": "5h", "mono": false, "showBurnRate": true },
31
+ "limit7d": { "showCountdown": true, "separator": " ", "label": "7d", "mono": false, "showBurnRate": true, "perModel": false },
32
+ "cost": { "precision": 2, "onlyWhenFast": true },
33
+ "extra": { "onlyWhenActive": false, "label": "extra", "mono": false },
34
+ "cache": { "label": "cache", "mono": false, "window": "session", "showPercent": true, "showExpiry": false, "expiryLabel": "⟳", "coldLabel": "cold" },
35
+ "git": { "worktreeLabel": "⎘" },
36
+ "session": { "label": "⏱︎", "mono": false, "idLength": 8, "idLabel": "#" },
37
+ "cwd": { "format": "smart", "maxLength": 40, "label": "⊕" }
38
+ }
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "glintline",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.1",
4
+ "description": "A fast, configurable status line for Claude Code. Runs on Bun or Node, TypeScript, zero runtime dependencies, ~70ms per render on Bun.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Ivan Lagunovsky <ivan.lagunovsky@gmail.com>",
8
+ "homepage": "https://github.com/lagunovsky/glintline#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/lagunovsky/glintline.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/lagunovsky/glintline/issues"
15
+ },
16
+ "keywords": [
17
+ "claude",
18
+ "claude-code",
19
+ "statusline",
20
+ "bun",
21
+ "node",
22
+ "typescript",
23
+ "cli",
24
+ "anthropic"
25
+ ],
26
+ "engines": {
27
+ "bun": ">=1.1.0",
28
+ "node": ">=22"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "src",
33
+ "glintline.example.json",
34
+ "README.md",
35
+ "INSTALL.md",
36
+ "LICENSE",
37
+ "CHANGELOG.md"
38
+ ],
39
+ "main": "dist/glintline.js",
40
+ "bin": {
41
+ "glintline": "dist/glintline.js"
42
+ },
43
+ "scripts": {
44
+ "build": "bun build src/index.ts --target=node --outfile=dist/glintline.js --minify && chmod +x dist/glintline.js",
45
+ "dev": "bun src/index.ts",
46
+ "test": "bun test ./test",
47
+ "typecheck": "tsc --noEmit",
48
+ "check": "bun run typecheck && bun run test",
49
+ "prepack": "bun run build",
50
+ "prepublishOnly": "bun run check && bun run build"
51
+ },
52
+ "devDependencies": {
53
+ "@types/bun": "latest",
54
+ "typescript": "^5.6.0"
55
+ }
56
+ }
package/src/ansi.ts ADDED
@@ -0,0 +1,35 @@
1
+ const ESC = "\x1b[";
2
+
3
+ export const reset = `${ESC}0m`;
4
+ export const bold = `${ESC}1m`;
5
+ export const dim = `${ESC}2m`;
6
+
7
+ const fg = (n: number) => `${ESC}38;5;${n}m`;
8
+
9
+ export const c = {
10
+ reset,
11
+ bold,
12
+ dim,
13
+ gray: fg(244),
14
+ darkGray: fg(240),
15
+ darkestGray: fg(236),
16
+ lightGray: fg(250),
17
+ white: fg(255),
18
+ red: fg(203),
19
+ mutedRed: fg(167),
20
+ orange: fg(214),
21
+ yellow: fg(220),
22
+ mutedYellow: fg(179),
23
+ green: fg(114),
24
+ mutedGreen: fg(108),
25
+ cyan: fg(73),
26
+ mutedBlue: fg(67),
27
+ magenta: fg(176),
28
+ purple: fg(141),
29
+ lime: fg(149),
30
+ silver: fg(251),
31
+ pink: fg(211),
32
+ coral: fg(209),
33
+ };
34
+
35
+ export const wrap = (color: string, text: string) => `${color}${text}${reset}`;
package/src/cache.ts ADDED
@@ -0,0 +1,42 @@
1
+ import { mkdirSync, readFileSync, writeFileSync, statSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { debug } from "./debug";
6
+
7
+ const CACHE_DIR = join(tmpdir(), "glintline-cache");
8
+
9
+ function ensureDir(): void {
10
+ try {
11
+ mkdirSync(CACHE_DIR, { recursive: true });
12
+ } catch (e) {
13
+ debug("cache.mkdir", e);
14
+ }
15
+ }
16
+
17
+ export function cachePath(key: string): string {
18
+ ensureDir();
19
+ const safe = createHash("sha256").update(key).digest("hex").slice(0, 16);
20
+ return join(CACHE_DIR, `${safe}.json`);
21
+ }
22
+
23
+ export function readCache<T>(key: string, ttlSeconds: number): T | null {
24
+ const path = cachePath(key);
25
+ try {
26
+ const stat = statSync(path);
27
+ const ageSec = (Date.now() - stat.mtimeMs) / 1000;
28
+ if (ageSec > ttlSeconds) return null;
29
+ return JSON.parse(readFileSync(path, "utf8")) as T;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ export function writeCache<T>(key: string, value: T): void {
36
+ const path = cachePath(key);
37
+ try {
38
+ writeFileSync(path, JSON.stringify(value));
39
+ } catch (e) {
40
+ debug("cache.write", e);
41
+ }
42
+ }
package/src/config.ts ADDED
@@ -0,0 +1,209 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { debug } from "./debug";
5
+
6
+ export interface ModelOpts {
7
+ showFamily: boolean;
8
+ showVersion: boolean;
9
+ showContext: boolean;
10
+ showEffortIcon: boolean;
11
+ label: string;
12
+ }
13
+
14
+ export interface EffortOpts {
15
+ label: string;
16
+ icons: Record<string, string>;
17
+ }
18
+
19
+ export interface ContextOpts {
20
+ showBar: boolean;
21
+ showNumbers: boolean;
22
+ showPercent: boolean;
23
+ showCompactBuffer: boolean;
24
+ // In the buffer-aware view, the trailing `/buffer` of `used/threshold/buffer`.
25
+ showBufferTokens: boolean;
26
+ fillEmpty: boolean;
27
+ barWidth: number;
28
+ barStyle: string;
29
+ barChars?: { full: string; empty: string };
30
+ gap: string;
31
+ label: string;
32
+ }
33
+
34
+ export interface LimitOpts {
35
+ showCountdown: boolean;
36
+ separator: string;
37
+ label: string;
38
+ mono: boolean;
39
+ showBurnRate: boolean;
40
+ }
41
+
42
+ export interface Limit7dOpts extends LimitOpts {
43
+ // Swap the general weekly window for the active model's per-model weekly cap
44
+ // if one exists, labeling it `<label>-<family>` (e.g. "7d-fable") and showing
45
+ // the general cap dimmed in parens. Requires the OAuth API; no-op otherwise.
46
+ perModel: boolean;
47
+ }
48
+
49
+ export interface CostOpts {
50
+ precision: number;
51
+ onlyWhenFast: boolean;
52
+ }
53
+
54
+ export interface ExtraOpts {
55
+ onlyWhenActive: boolean;
56
+ label: string;
57
+ mono: boolean;
58
+ }
59
+
60
+ export interface CacheOpts {
61
+ label: string;
62
+ mono: boolean;
63
+ // "session" — cumulative hit-rate over the whole transcript (lifetime).
64
+ // "last" — hit-rate of the most recent assistant turn only, so it reflects
65
+ // whether the cache is warm right now (drops after a resume re-primes it).
66
+ // "both" — the last turn (primary, health-colored) followed by the session
67
+ // total marked with `Σ` in a dimmer color, e.g. `96% Σ91%`.
68
+ window: "session" | "last" | "both";
69
+ // The hit-rate percentages; off leaves only the expiry/cold state.
70
+ showPercent: boolean;
71
+ // Trail the prompt cache's state from stdin `prompt_cache` (Claude Code
72
+ // v2.1.251+): while warm, the local time it goes cold (`⟳ 14:49`); once cold,
73
+ // `coldLabel` and the tokens the next request writes back (`cold ↑28K`).
74
+ // Absent on a resumed session until its first response.
75
+ showExpiry: boolean;
76
+ expiryLabel: string;
77
+ coldLabel: string;
78
+ }
79
+
80
+ export interface GitOpts {
81
+ worktreeLabel: string;
82
+ }
83
+
84
+ export interface SessionOpts {
85
+ label: string;
86
+ mono: boolean;
87
+ idLength: number;
88
+ idLabel: string;
89
+ }
90
+
91
+ export type CwdFormat = "short" | "home" | "full" | "smart";
92
+
93
+ export interface CwdOpts {
94
+ format: CwdFormat;
95
+ maxLength: number;
96
+ label: string;
97
+ }
98
+
99
+ export interface Config {
100
+ widgets: string[][];
101
+ separator: string;
102
+ calmColors: boolean;
103
+ // Widgets to shed, least important first, while a rendered line is wider than
104
+ // the terminal — so the overflow eats these instead of truncating whatever
105
+ // happens to sit at the end of the line. Claude Code exports COLUMNS before
106
+ // running the status line (v2.1.153+); without it nothing is dropped.
107
+ dropWhenNarrow: string[];
108
+ // Mirror of `statusLine.padding` from Claude Code settings — it is not passed
109
+ // to the command, yet it narrows the room the line gets on both sides.
110
+ statusLinePadding: number;
111
+ model: ModelOpts;
112
+ effort: EffortOpts;
113
+ context: ContextOpts;
114
+ limit5h: LimitOpts;
115
+ limit7d: Limit7dOpts;
116
+ cost: CostOpts;
117
+ extra: ExtraOpts;
118
+ cache: CacheOpts;
119
+ git: GitOpts;
120
+ session: SessionOpts;
121
+ cwd: CwdOpts;
122
+ }
123
+
124
+ export const DEFAULT_CONFIG: Config = {
125
+ widgets: [
126
+ ["model", "effort", "cost", "context", "limit5h", "limit7d", "extra", "git.worktree", "git.branch", "git.diff"],
127
+ ["session.id", "cwd"],
128
+ ],
129
+ separator: " │ ",
130
+ calmColors: false,
131
+ dropWhenNarrow: [],
132
+ statusLinePadding: 0,
133
+ model: { showFamily: true, showVersion: true, showContext: true, showEffortIcon: true, label: "✳" },
134
+ effort: { label: "∼", icons: { low: "·", medium: "⁚", high: "⁖", xhigh: "⁘", max: "⁙" } },
135
+ context: { showBar: true, showNumbers: true, showPercent: false, showCompactBuffer: false, showBufferTokens: true, fillEmpty: true, barWidth: 10, barStyle: "square", gap: " ", label: "⊠" },
136
+ limit5h: { showCountdown: true, separator: " ", label: "5h", mono: false, showBurnRate: true },
137
+ limit7d: { showCountdown: true, separator: " ", label: "7d", mono: false, showBurnRate: true, perModel: false },
138
+ cost: { precision: 2, onlyWhenFast: true },
139
+ extra: { onlyWhenActive: false, label: "extra", mono: false },
140
+ cache: { label: "cache", mono: false, window: "session", showPercent: true, showExpiry: false, expiryLabel: "⟳", coldLabel: "cold" },
141
+ git: { worktreeLabel: "⎘" },
142
+ session: { label: "⏱︎", mono: false, idLength: 8, idLabel: "#" },
143
+ cwd: { format: "smart", maxLength: 40, label: "⊕" },
144
+ };
145
+
146
+ type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] };
147
+
148
+ function candidatePaths(): string[] {
149
+ const env = process.env.GLINTLINE_CONFIG;
150
+ if (env) return [env];
151
+ return [
152
+ join(homedir(), ".config", "glintline", "settings.json"),
153
+ join(homedir(), ".config", "glintline.json"),
154
+ join(homedir(), ".claude", "glintline.json"),
155
+ ];
156
+ }
157
+
158
+ function readJson(path: string): unknown {
159
+ try {
160
+ return JSON.parse(readFileSync(path, "utf8"));
161
+ } catch (e) {
162
+ if ((e as NodeJS.ErrnoException).code !== "ENOENT") debug("config.read", e);
163
+ return null;
164
+ }
165
+ }
166
+
167
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
168
+ return typeof v === "object" && v !== null && !Array.isArray(v);
169
+ }
170
+
171
+ const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);
172
+
173
+ function merge<T>(base: T, over: DeepPartial<T> | undefined): T {
174
+ if (!over) return base;
175
+ if (!isPlainObject(base) || !isPlainObject(over)) return base;
176
+ const out = { ...base } as Record<string, unknown>;
177
+ for (const key of Object.keys(over)) {
178
+ if (DANGEROUS_KEYS.has(key)) continue;
179
+ const val = (over as Record<string, unknown>)[key];
180
+ const baseVal = out[key];
181
+ if (val === undefined) continue;
182
+ if (isPlainObject(val) && isPlainObject(baseVal)) {
183
+ out[key] = merge(baseVal, val as DeepPartial<typeof baseVal>);
184
+ } else {
185
+ out[key] = val;
186
+ }
187
+ }
188
+ return out as T;
189
+ }
190
+
191
+ // A flat `["model", "effort"]` is one line, not a list of lines — without
192
+ // this, every line would be a string and the status line would render empty.
193
+ function normalizeWidgets(cfg: Config): Config {
194
+ const w: unknown = cfg.widgets;
195
+ if (Array.isArray(w) && w.every((name) => typeof name === "string")) {
196
+ return { ...cfg, widgets: [w as string[]] };
197
+ }
198
+ return cfg;
199
+ }
200
+
201
+ export function loadConfig(): Config {
202
+ for (const path of candidatePaths()) {
203
+ const parsed = readJson(path);
204
+ if (isPlainObject(parsed)) {
205
+ return normalizeWidgets(merge(DEFAULT_CONFIG, parsed as DeepPartial<Config>));
206
+ }
207
+ }
208
+ return DEFAULT_CONFIG;
209
+ }
package/src/context.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { StatusInput } from "./types";
2
+
3
+ export interface ContextUsage {
4
+ used: number;
5
+ total: number;
6
+ compactThreshold?: number;
7
+ }
8
+
9
+ const DEFAULT_CONTEXT_SIZE = 200_000;
10
+ const MAX_WINDOW_TOKENS = 10_000_000;
11
+
12
+ function readPositive(name: string, max: number): number | null {
13
+ const raw = process.env[name];
14
+ if (!raw) return null;
15
+ const n = parseFloat(raw);
16
+ if (!Number.isFinite(n) || n <= 0) return null;
17
+ return Math.min(n, max);
18
+ }
19
+
20
+ interface Totals {
21
+ total: number;
22
+ compactThreshold?: number;
23
+ }
24
+
25
+ function effectiveTotals(stdinTotal: number, showBuffer: boolean): Totals {
26
+ const window = readPositive("CLAUDE_CODE_AUTO_COMPACT_WINDOW", MAX_WINDOW_TOKENS) ?? stdinTotal;
27
+ const pct = readPositive("CLAUDE_AUTOCOMPACT_PCT_OVERRIDE", 100);
28
+ if (pct === null) return { total: window };
29
+ const threshold = Math.round(window * (pct / 100));
30
+ if (showBuffer) return { total: window, compactThreshold: threshold };
31
+ return { total: threshold };
32
+ }
33
+
34
+ // Apply the same auto-compact window/threshold logic to a context reading taken
35
+ // from the transcript fallback, so its percentage base matches the stdin path.
36
+ export function withAutoCompact(
37
+ ctx: { used: number; total: number } | null,
38
+ showBuffer: boolean,
39
+ ): ContextUsage | null {
40
+ if (!ctx) return null;
41
+ return { used: ctx.used, ...effectiveTotals(ctx.total, showBuffer) };
42
+ }
43
+
44
+ export function getContextFromInput(input: StatusInput, showBuffer: boolean): ContextUsage | null {
45
+ const cw = input.context_window;
46
+ if (!cw) return null;
47
+
48
+ const totals = effectiveTotals(cw.context_window_size ?? DEFAULT_CONTEXT_SIZE, showBuffer);
49
+ const cur = cw.current_usage;
50
+ if (cur) {
51
+ const used =
52
+ (cur.input_tokens ?? 0) +
53
+ (cur.cache_creation_input_tokens ?? 0) +
54
+ (cur.cache_read_input_tokens ?? 0);
55
+ if (used > 0) return { used, ...totals };
56
+ }
57
+ if (cw.total_input_tokens && cw.total_input_tokens > 0) {
58
+ return { used: cw.total_input_tokens, ...totals };
59
+ }
60
+ if (cw.used_percentage !== undefined) {
61
+ return { used: Math.round((cw.used_percentage / 100) * totals.total), ...totals };
62
+ }
63
+ return null;
64
+ }
@@ -0,0 +1,46 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir, platform } from "node:os";
4
+ import { join } from "node:path";
5
+ import { debug } from "./debug";
6
+
7
+ const KEYCHAIN_SERVICE = "Claude Code-credentials";
8
+
9
+ interface CredentialsFile {
10
+ claudeAiOauth?: { accessToken?: string };
11
+ }
12
+
13
+ function fromKeychain(): string | null {
14
+ try {
15
+ const out = execFileSync(
16
+ "security",
17
+ ["find-generic-password", "-s", KEYCHAIN_SERVICE, "-w"],
18
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] },
19
+ ).trim();
20
+ if (!out) return null;
21
+ const parsed = JSON.parse(out) as CredentialsFile;
22
+ return parsed.claudeAiOauth?.accessToken ?? null;
23
+ } catch (e) {
24
+ debug("credentials.keychain", e);
25
+ return null;
26
+ }
27
+ }
28
+
29
+ function fromFile(): string | null {
30
+ try {
31
+ const path = join(homedir(), ".claude", ".credentials.json");
32
+ const raw = readFileSync(path, "utf8");
33
+ const parsed = JSON.parse(raw) as CredentialsFile;
34
+ return parsed.claudeAiOauth?.accessToken ?? null;
35
+ } catch (e) {
36
+ debug("credentials.file", e);
37
+ return null;
38
+ }
39
+ }
40
+
41
+ export function getOAuthToken(): string | null {
42
+ if (platform() === "darwin") {
43
+ return fromKeychain() ?? fromFile();
44
+ }
45
+ return fromFile();
46
+ }
package/src/debug.ts ADDED
@@ -0,0 +1,9 @@
1
+ const ENABLED =
2
+ process.env.GLINTLINE_DEBUG === "1" ||
3
+ process.env.GLINTLINE_DEBUG === "true";
4
+
5
+ export function debug(scope: string, err: unknown): void {
6
+ if (!ENABLED) return;
7
+ const msg = err instanceof Error ? err.message : String(err);
8
+ process.stderr.write(`[glintline:${scope}] ${msg}\n`);
9
+ }