@promptctl/cc-candybar 1.180.8 → 1.180.10

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 (2) hide show
  1. package/dist/index.mjs +4 -4
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o from"node:os";import{spawn as s,spawnSync as c}from"node:child_process";import l,{closeSync as u,constants as d,existsSync as f,fstatSync as p,linkSync as m,mkdtempSync as h,openSync as g,readFileSync as _,readSync as v,rmSync as y,statSync as b,writeFileSync as x}from"node:fs";import{StringDecoder as S}from"node:string_decoder";import{inspect as C,parseArgs as w,types as ee}from"node:util";import{clearImmediate as T,setImmediate as te}from"node:timers";import E,{basename as ne,dirname as D,isAbsolute as O,join as re,sep as k}from"node:path";import ie,{createHash as ae,createHmac as oe,randomBytes as se,randomUUID as ce,timingSafeEqual as le}from"node:crypto";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{get as ge}from"node:https";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));let Oe=!1;const ke=()=>Oe;function Ae(e){Oe=e}function je(e){return ke()?`[DEBUG] ${e()}\n`:``}function A(e,...t){ke()&&console.error(`[DEBUG] ${e}`,...t)}function Me(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Ne=(e,t)=>A(t);function Pe(e,t){return ee.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!f(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Fe={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function Ie(e,t,n){let r=Fe[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function Le(e,t){return{...e.inherited,...t.envOverlay}}const Re=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function ze(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}function Be(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function Ve(e,t,n){let r=He(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.now()),null):(e.scope.stats?.onRefused(t),r)}function He(e,t,n){if(e.scope.signal.aborted)return Re(e.scope.signal);if(n?.aborted)return Re(n);let r=Ie(e.lastStartAt,t,e.scope.clock.now());return r.allowed?null:ze(t,r.minIntervalMs,r.sinceLastMs)}const Ue=`\$1 == "+" { live[\$2] = 1; next } \$1 == "-" { delete live[\$2]; next } END { for (g in live) groups = groups " -" g; if (groups != "") system("kill -TERM" groups " 2>/dev/null; sleep ${250/1e3}; kill -KILL" groups " 2>/dev/null") }`;function We(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function Ge(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),We(e,n))}function Ke(e){return e.fault===null?[]:[{kind:`lifeline`,message:`programs launched now would outlive their launcher if it died: its launch lifeline ${e.fault}, and the next launch starts another`}]}function qe(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.now(),i;try{i=s(`awk`,[Ue],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,n.now()-r),We(e,`did not start: ${Pe(i,void 0)}`),null}t?.onEnd(`lifeline`,n.now()-r);let a=i.stdin;if(a==null)return i.once(`error`,t=>We(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&We(e,null)}),i.once(`error`,t=>Ge(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>Ge(e,i,`exited ${n??t}`)),a.on(`error`,t=>Ge(e,i,`pipe failed: ${t.message}`)),Be(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function Je(e,t){e.liveGroups.add(t),e.lifeline??=qe(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function Ye(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Xe(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Ze=16*1024*1024,Qe=`output exceeded ${Ze} bytes`;function $e(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!et(e)))throw t}}function et(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function tt(e,t){let n=new S(`utf8`),r=``,i=0,a=e=>{let a=e.subarray(0,Ze-i);i+=a.length,r+=n.write(a),a.length<e.length&&t()};return e?.on(`data`,a),()=>{e?.off(`data`,a);let t=r+n.end();return r=``,t}}async function nt(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category,t.signal);if(i!==null)return i;let a=r.now();return n?.onStart(t.category),new Promise(i=>{let o;try{o=s(t.bin,t.args??[],{cwd:t.cwd,env:Le(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,r.now()-a),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)});return}let c=o.pid;c!==void 0&&Je(e,c);let l=new Promise(e=>o.once(`exit`,e)),u=()=>ee(`output-limit`),d=tt(o.stdout,u),f=tt(o.stderr,u),p=()=>({stdout:d(),stderr:f()}),m=!1,h=null,g=null,_=null,v=null,y=()=>ee(`aborted`),b=()=>{t.signal?.removeEventListener(`abort`,y),e.inFlight.delete(y)},x=i=>{if(!m){m=!0,h?.(),g?.(),_?.(),b(),c!==void 0&&Ye(e,c),n?.onEnd(t.category,r.now()-a);for(let e of[o.stdout,o.stderr])e?.unref();i()}},S=e=>x(()=>i(e)),C=(n,r)=>{try{$e(n,r)}catch(n){e.unreaped.set(o,t.category),l.then(()=>e.unreaped.delete(o)),S({ok:!1,reason:`signal-refused`,...p(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},w=()=>T(o.exitCode,o.signalCode);if(c!==void 0){let e=t=>{if(!m){if(dt(c)){r.defer(w);return}_=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ee=e=>{if(v!==null)return;if((o.exitCode!==null||o.signalCode!==null)&&c!==void 0&&dt(c)){v=e===`timeout`?null:e,r.defer(w);return}v=e,h?.(),b();let t=o.pid;t!==void 0&&(g=r.after(250,()=>{C(t,`SIGKILL`),l.then(()=>r.defer(w))}),C(t,`SIGTERM`))};o.on(`error`,e=>{S({ok:!1,reason:`spawn-error`,...p(),exitCode:null,signal:null,error:Pe(e,t.cwd)})});let T=(e,t)=>{if(v!==null){S({ok:!1,reason:v,...p(),exitCode:e,signal:t,...v===`output-limit`?{error:Qe}:{}});return}if(e===0){S({ok:!0,...p(),exitCode:e});return}S({ok:!1,reason:t?`signal`:`non-zero`,...p(),exitCode:e,signal:t})};o.on(`close`,T),t.timeoutMs&&t.timeoutMs>0&&(h=r.after(t.timeoutMs,()=>ee(`timeout`))),t.signal?.addEventListener(`abort`,y,{once:!0}),e.inFlight.add(y),o.stdin?.on(`error`,()=>{}),o.stdin?.end(t.stdinInput)})}function rt(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=[`pipe`,`pipe`,`pipe`];try{let i=c(t.bin,t.args??[],{cwd:t.cwd,env:Le(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:o,encoding:`utf8`});n?.onEnd(t.category,r.now()-a);let s=typeof i.stdout==`string`?i.stdout:``,l=typeof i.stderr==`string`?i.stderr:``,u=i.error?.code;return i.error&&u!==`EPIPE`&&u!==`ECONNRESET`?{ok:!1,reason:u===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:s,stderr:l,exitCode:null,signal:i.signal??null,error:Pe(i.error,t.cwd)}:i.status===0?{ok:!0,stdout:s,stderr:l,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:s,stderr:l,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,r.now()-a),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)}}}function it(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=at(e.scope,t);return n?.onEnd(t.category,r.now()-a),o}function at(e,t){let n;try{n=s(t.bin,t.args??[],{cwd:t.cwd,env:Le(e,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const ot=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function st(e,t,n){let{stats:r,clock:i}=e.scope,a=Ve(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.now();r?.onStart(t.category);let c;try{c=s(`/bin/sh`,[`-c`,`out=$1 err=$2 status=$3; shift 3; read go || exit 0; "$@" >"$out" 2>"$err" </dev/null; echo "exit $?" >"$status.$$" && ln "$status.$$" "$status"; rm -f "$status.$$"`,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:Le(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,i.now()-o),{ok:!1,reason:`spawn-error`,error:Pe(e,t.cwd)}}r?.onEnd(t.category,i.now()-o),c.once(`error`,()=>{});let l=c.pid,u=c.stdin;return u.on(`error`,()=>{}),l===void 0?(u.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(c.unref(),u.unref(),{ok:!0,pid:l,release:()=>u.end(`go
3
- `),withdraw:()=>u.end()})}function ct(e){let t;try{t=_(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function lt(e,t){try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}function ut(e){return lt(e,0)}function dt(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function ft(e,t,n,r){let i=`${t}.${process.pid}`;try{x(i,`${ot(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let a=!0;try{m(i,t)}catch(e){if(e.code!==`EEXIST`)throw e;a=!1}finally{y(i,{force:!0})}let o=lt(e,`SIGTERM`);return o&&r.after(250,()=>lt(e,`SIGKILL`),{unref:!0}),{stands:a,signalled:o}}function pt(e,t){return ht(e,t).launcher}function mt(e,t){let{launcher:n,state:r}=ht(e,t);return{...n,launchSync:e=>rt(r,e)}}function ht(e,t){let n={clock:t,launch:e=>Be(r,nt(r,e)),launchDetachedSync:e=>it(r,e),launchJobSync:(e,t)=>st(r,e,t),lifelineWarnings:()=>Ke(r),settled:async()=>(await Promise.all(r.ending),{unreaped:[...r.unreaped.values()]}),__lifelineForTest:()=>{let e=r.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&Ge(r,e.process,`cut by a test`)}}}},r={scope:{stats:null,observeLifeline:()=>n.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map};return r.scope.signal.addEventListener(`abort`,()=>{r.inFlight.forEach(e=>e()),Xe(r)},{once:!0}),{launcher:n,state:r}}const gt={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=te(e);return()=>T(t)}};function _t(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function vt(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function yt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=gt;return{host:e,launcher:mt({inherited:process.env},t),clock:t}}const bt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function xt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function St(e){return bt.test(e)?e:xt(e)}function Ct(e){return`${e.dir===void 0?``:`cd ${St(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${St(t)} `).join(``)}${[e.program,...e.args].map(St).join(` `)}`}const wt=`cc-extra`;function Tt(e){return E.join(E.dirname(e),wt,`src`,`bun-attach.js`)}function Et(e){return E.join(E.dirname(e),`bun-graph.js`)}const Dt=`attach-preload.cjs`;function Ot(e){return E.join(E.dirname(e),Dt)}function kt(e,t){return Ct({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const At=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function jt(e,t){return t.isSymbolicLink()?Buffer.from(l.readlinkSync(e)):l.readFileSync(e)}function Mt(e,t,n=At){return l.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=l.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Mt(e,r):[[E.relative(e,r).split(E.sep).join(`/`),jt(r,i)]]})}function Nt(e){let t=ie.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Pt(e){return Nt(Mt(e,e))}const Ft=[`Cargo.toml`,`Cargo.lock`,`src`];function It(e){return Nt(Mt(e,e,e=>Ft.includes(e)))}const Lt=e=>e.slice(0,7),Rt=`1.180.8`;function zt(e){let t=E.dirname(E.dirname(e));return l.existsSync(E.join(t,`src`))?t:null}function Bt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Rt,digest:e}}function Vt(){return`6ffd31ce3fdf2c1dca92bb2fc509ede64eaaabd8851e3864996fbeebc11bf503`}function Ht(e){let t=JSON.parse(l.readFileSync(E.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${E.join(e,`package.json`)} has no version string`);return n}function Ut(e,t){try{let n=zt(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Pt(E.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ht(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function j(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Wt(e){let t=j(e.env,`XDG_STATE_HOME`)??E.join(e.home,`.local`,`state`);return E.join(t,`cc-candybar`)}function Gt(e){let t=j(e.env,`XDG_CACHE_HOME`)??E.join(e.home,`.cache`);return E.join(t,`cc-candybar`)}function Kt(e){return Wt(e)}function qt(e){return e.env.CC_CANDYBAR_SOCKET||Jt()}function Jt(){let e=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Yt(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function M(e){Yt(E.dirname(e));for(let t of[e,Xt(e)])try{if(l.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Xt(e){return`${e}.lease`}function Zt(e){return Xt(qt(e))}function Qt(e){return E.join(Wt(e),`session-state.json`)}function $t(e){return E.join(Wt(e),`settings-history.json`)}function en(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function tn(e){return E.join(Wt(e),`spawn.lock`)}function nn(e){return E.join(Wt(e),`spawn.cooldown`)}function rn(e){return E.join(Wt(e),`spawn.backoff`)}function an(e){return E.join(Wt(e),`watch-probe`)}function on(e){return E.join(Wt(e),`daemon.log`)}function sn(e){return{socket:qt(e),lease:Zt(e),state:Wt(e),registry:en(e),log:on(e),sessionState:Qt(e),settingsHistory:$t(e),watchProbe:an(e),spawnBackoff:rn(e)}}function cn(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${E.join(j(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:j(t,`XDG_CONFIG_HOME`)??E.join(e.home,`.config`),dataHome:j(t,`XDG_DATA_HOME`)??E.join(e.home,`.local`,`share`),dataDirs:(j(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function ln(e,t,n){let r=un(e);l.mkdirSync(E.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??l.statSync(r,{throwIfNoEntry:!1})?.mode;try{l.writeFileSync(i,t,a===void 0?{}:{mode:a}),l.renameSync(i,r)}catch(e){throw l.rmSync(i,{force:!0}),e}}function un(e){return dn(e).at(-1)}function dn(e){let{hops:t,stopped:n}=fn(e);if(n!==null)throw n;return t}function fn(e){let t=[e];try{for(let e=0;e<mn;e++){let e=pn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${mn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function pn(e){try{return l.lstatSync(e).isSymbolicLink()?E.resolve(l.realpathSync(E.dirname(e)),l.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const mn=40,hn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function gn(e){return Object.fromEntries(hn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const _n=[`native`,`node`,`frames`];function vn(e,t){return{kind:e,bundle:t,source:null}}const yn=[`ansi`,`frame`],bn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function xn(e){let t=kn(e.termCols),n=kn(e.termRows),r=An(e.ssh),i=Dn(e.tmux),a=En(e.configEnv),o=En(e.claudeConfigDir),s=N(e.terminalEnv),c=Rn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Sn(e,t){return bn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Cn(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const wn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Tn(e){let t=Object.keys(wn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[wn[t](n.join(`, `))]});return t.length===0?null:t.join(`
2
+ import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i}from"node:url";import{json as a}from"node:stream/consumers";import o from"node:os";import{spawn as s,spawnSync as c}from"node:child_process";import l,{closeSync as u,constants as d,existsSync as f,fstatSync as p,linkSync as m,mkdtempSync as h,openSync as g,readFileSync as _,readSync as v,rmSync as y,statSync as b,writeFileSync as x}from"node:fs";import{StringDecoder as S}from"node:string_decoder";import{inspect as C,parseArgs as w,types as ee}from"node:util";import{clearImmediate as T,setImmediate as te}from"node:timers";import E,{basename as ne,dirname as D,isAbsolute as O,join as re,sep as k}from"node:path";import ie,{createHash as ae,createHmac as oe,randomBytes as se,randomUUID as ce,timingSafeEqual as le}from"node:crypto";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{get as ge}from"node:https";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));let Oe=!1;const ke=()=>Oe;function Ae(e){Oe=e}function je(e){return ke()?`[DEBUG] ${e()}\n`:``}function A(e,...t){ke()&&console.error(`[DEBUG] ${e}`,...t)}function Me(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Ne=(e,t)=>A(t);function Pe(e,t){return ee.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!f(t)?`working directory does not exist: ${t}`:e.message:String(e)}const Fe={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function Ie(e,t,n){let r=Fe[t];if(r===void 0)return{allowed:!0};let i=e.get(t);if(i===void 0)return{allowed:!0};let a=n-i;return a>=r?{allowed:!0}:{allowed:!1,minIntervalMs:r,sinceLastMs:a}}function Le(e,t){return{...e.inherited,...t.envOverlay}}const Re=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function ze(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}function Be(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function Ve(e,t,n){let r=He(e,t,n);return r===null?(e.lastStartAt.set(t,e.scope.clock.now()),null):(e.scope.stats?.onRefused(t),r)}function He(e,t,n){if(e.scope.signal.aborted)return Re(e.scope.signal);if(n?.aborted)return Re(n);let r=Ie(e.lastStartAt,t,e.scope.clock.now());return r.allowed?null:ze(t,r.minIntervalMs,r.sinceLastMs)}const Ue=`\$1 == "+" { live[\$2] = 1; next } \$1 == "-" { delete live[\$2]; next } END { for (g in live) groups = groups " -" g; if (groups != "") system("kill -TERM" groups " 2>/dev/null; sleep ${250/1e3}; kill -KILL" groups " 2>/dev/null") }`;function We(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function Ge(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),We(e,n))}function Ke(e){return e.fault===null?[]:[{kind:`lifeline`,message:`programs launched now would outlive their launcher if it died: its launch lifeline ${e.fault}, and the next launch starts another`}]}function qe(e){let{stats:t,clock:n}=e.scope;t?.onStart(`lifeline`);let r=n.now(),i;try{i=s(`awk`,[Ue],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(i){return t?.onEnd(`lifeline`,n.now()-r),We(e,`did not start: ${Pe(i,void 0)}`),null}t?.onEnd(`lifeline`,n.now()-r);let a=i.stdin;if(a==null)return i.once(`error`,t=>We(e,`did not start: ${t.message}`)),null;i.once(`spawn`,()=>{e.lifeline?.process===i&&We(e,null)}),i.once(`error`,t=>Ge(e,i,`failed: ${t.message}`)),i.once(`exit`,(t,n)=>Ge(e,i,`exited ${n??t}`)),a.on(`error`,t=>Ge(e,i,`pipe failed: ${t.message}`)),Be(e,new Promise(e=>i.once(`close`,e))),i.unref(),a.unref();for(let t of e.liveGroups)a.write(`+ ${t}\n`);return{process:i,pipe:a}}function Je(e,t){e.liveGroups.add(t),e.lifeline??=qe(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function Ye(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Xe(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}const Ze=16*1024*1024,Qe=`output exceeded ${Ze} bytes`;function $e(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!et(e)))throw t}}function et(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function tt(e,t,n,r){let{stats:i}=e.scope,a=new S(`utf8`),o=``,s=0,c=0,l=r,u=`closed`;return n?.on(`error`,()=>i?.onPipeError(t)),n?.on(`data`,e=>{if(l===null){if(c+=e.length,i?.onDrainRead(t,e.length),c<=16777216)return;u=`cut`,n.destroy();return}let r=Math.max(0,Ze-s);o+=a.write(e.subarray(0,r)),s+=e.length,s>16777216&&l()}),{take:()=>{if(l===null)return``;l=null;let e=o+a.end();return o=``,e},drain:()=>{if(!(n===null||n.destroyed||n.readableEnded)){if(e.scope.signal.aborted){n.destroy();return}n.once(`close`,()=>{e.drains.delete(n),i?.onDrainClose(t,u)}),n.unref(),e.drains.add(n),i?.onDrainOpen(t)}}}}async function nt(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category,t.signal);if(i!==null)return i;let a=r.now();return n?.onStart(t.category),new Promise(i=>{let o;try{o=s(t.bin,t.args??[],{cwd:t.cwd,env:Le(e.scope,t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,r.now()-a),i({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)});return}let c=o.pid;c!==void 0&&Je(e,c);let l=new Promise(e=>o.once(`exit`,e)),u=()=>ee(`output-limit`),d=tt(e,t.category,o.stdout,u),f=tt(e,t.category,o.stderr,u),p=()=>({stdout:d.take(),stderr:f.take()}),m=!1,h=null,g=null,_=null,v=null,y=()=>ee(`aborted`),b=()=>{t.signal?.removeEventListener(`abort`,y),e.inFlight.delete(y)},x=i=>{m||(m=!0,h?.(),g?.(),_?.(),b(),c!==void 0&&Ye(e,c),n?.onEnd(t.category,r.now()-a),o.off(`close`,te),o.off(`error`,T),d.drain(),f.drain(),i())},S=e=>x(()=>i(e)),C=(n,r)=>{try{$e(n,r)}catch(n){e.unreaped.set(o,t.category),l.then(()=>e.unreaped.delete(o)),S({ok:!1,reason:`signal-refused`,...p(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},w=()=>te(o.exitCode,o.signalCode);if(c!==void 0){let e=t=>{if(!m){if(dt(c)){r.defer(w);return}_=r.after(t,()=>e(Math.min(t*2,1e3)))}};l.then(()=>r.defer(()=>e(25)))}let ee=e=>{if(v!==null)return;if((o.exitCode!==null||o.signalCode!==null)&&c!==void 0&&dt(c)){v=e===`timeout`?null:e,r.defer(w);return}v=e,h?.(),b();let t=o.pid;t!==void 0&&(g=r.after(250,()=>{C(t,`SIGKILL`),l.then(()=>r.defer(w))}),C(t,`SIGTERM`))},T=e=>{S({ok:!1,reason:`spawn-error`,...p(),exitCode:null,signal:null,error:Pe(e,t.cwd)})};o.on(`error`,T);let te=(e,t)=>{if(v!==null){S({ok:!1,reason:v,...p(),exitCode:e,signal:t,...v===`output-limit`?{error:Qe}:{}});return}if(e===0){S({ok:!0,...p(),exitCode:e});return}S({ok:!1,reason:t?`signal`:`non-zero`,...p(),exitCode:e,signal:t})};o.on(`close`,te),t.timeoutMs&&t.timeoutMs>0&&(h=r.after(t.timeoutMs,()=>ee(`timeout`))),t.signal?.addEventListener(`abort`,y,{once:!0}),e.inFlight.add(y),o.stdin?.on(`error`,()=>{}),o.stdin?.end(t.stdinInput)})}function rt(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=[`pipe`,`pipe`,`pipe`];try{let i=c(t.bin,t.args??[],{cwd:t.cwd,env:Le(e.scope,t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:o,encoding:`utf8`});n?.onEnd(t.category,r.now()-a);let s=typeof i.stdout==`string`?i.stdout:``,l=typeof i.stderr==`string`?i.stderr:``,u=i.error?.code;return i.error&&u!==`EPIPE`&&u!==`ECONNRESET`?{ok:!1,reason:u===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:s,stderr:l,exitCode:null,signal:i.signal??null,error:Pe(i.error,t.cwd)}:i.status===0?{ok:!0,stdout:s,stderr:l,exitCode:i.status}:{ok:!1,reason:i.signal?`signal`:`non-zero`,stdout:s,stderr:l,exitCode:i.status,signal:i.signal??null}}catch(e){return n?.onEnd(t.category,r.now()-a),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)}}}function it(e,t){let{stats:n,clock:r}=e.scope,i=Ve(e,t.category);if(i!==null)return i;let a=r.now();n?.onStart(t.category);let o=at(e.scope,t);return n?.onEnd(t.category,r.now()-a),o}function at(e,t){let n;try{n=s(t.bin,t.args??[],{cwd:t.cwd,env:Le(e,t),detached:!0,stdio:`ignore`})}catch(e){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:Pe(e,t.cwd)}}return n.once(`error`,()=>{}),n.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${t.bin}): no pid (binary not found or unexecutable)`}:(n.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}const ot=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function st(e,t,n){let{stats:r,clock:i}=e.scope,a=Ve(e,t.category);if(a!==null)return{ok:!1,reason:a.reason,error:a.error};let o=i.now();r?.onStart(t.category);let c;try{c=s(`/bin/sh`,[`-c`,`out=$1 err=$2 status=$3; shift 3; read go || exit 0; "$@" >"$out" 2>"$err" </dev/null; echo "exit $?" >"$status.$$" && ln "$status.$$" "$status"; rm -f "$status.$$"`,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:Le(e.scope,t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,i.now()-o),{ok:!1,reason:`spawn-error`,error:Pe(e,t.cwd)}}r?.onEnd(t.category,i.now()-o),c.once(`error`,()=>{});let l=c.pid,u=c.stdin;return u.on(`error`,()=>{}),l===void 0?(u.destroy(),{ok:!1,reason:`spawn-error`,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(c.unref(),u.unref(),{ok:!0,pid:l,release:()=>u.end(`go
3
+ `),withdraw:()=>u.end()})}function ct(e){let t;try{t=_(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function lt(e,t){try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}function ut(e){return lt(e,0)}function dt(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function ft(e,t,n,r){let i=`${t}.${process.pid}`;try{x(i,`${ot(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let a=!0;try{m(i,t)}catch(e){if(e.code!==`EEXIST`)throw e;a=!1}finally{y(i,{force:!0})}let o=lt(e,`SIGTERM`);return o&&r.after(250,()=>lt(e,`SIGKILL`),{unref:!0}),{stands:a,signalled:o}}function pt(e,t){return ht(e,t).launcher}function mt(e,t){let{launcher:n,state:r}=ht(e,t);return{...n,launchSync:e=>rt(r,e)}}function ht(e,t){let n={clock:t,launch:e=>Be(r,nt(r,e)),launchDetachedSync:e=>it(r,e),launchJobSync:(e,t)=>st(r,e,t),lifelineWarnings:()=>Ke(r),settled:async()=>(await Promise.all(r.ending),{unreaped:[...r.unreaped.values()]}),__lifelineForTest:()=>{let e=r.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&Ge(r,e.process,`cut by a test`)}}}},r={scope:{stats:null,observeLifeline:()=>n.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e,clock:t},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map,drains:new Set};return r.scope.signal.addEventListener(`abort`,()=>{r.inFlight.forEach(e=>e()),r.drains.forEach(e=>e.destroy()),Xe(r)},{once:!0}),{launcher:n,state:r}}const gt={now:()=>Date.now(),monotonic:()=>performance.now(),after:(e,t,n)=>{let r=setTimeout(t,e);return n?.unref&&r.unref(),()=>clearTimeout(r)},every:(e,t,n)=>{let r=setInterval(t,e);return n?.unref&&r.unref(),()=>clearInterval(r)},defer:e=>{let t=te(e);return()=>T(t)}};function _t(e,t,n){return new Promise((r,i)=>{let a=()=>Object.assign(Error(`The operation was aborted`),{name:`AbortError`,code:`ABORT_ERR`,cause:n?.reason});if(n?.aborted){i(a());return}let o=()=>{s(),i(a())},s=e.after(t,()=>{n?.removeEventListener(`abort`,o),r()});n?.addEventListener(`abort`,o,{once:!0})})}function vt(e,t){let n=new AbortController;return e.after(t,()=>n.abort(new DOMException(`The operation was aborted due to timeout`,`TimeoutError`)),{unref:!0}),n.signal}function yt(){let e={env:process.env,home:o.homedir(),tmp:o.tmpdir()},t=gt;return{host:e,launcher:mt({inherited:process.env},t),clock:t}}const bt=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function xt(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function St(e){return bt.test(e)?e:xt(e)}function Ct(e){return`${e.dir===void 0?``:`cd ${St(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${St(t)} `).join(``)}${[e.program,...e.args].map(St).join(` `)}`}const wt=`cc-extra`;function Tt(e){return E.join(E.dirname(e),wt,`src`,`bun-attach.js`)}function Et(e){return E.join(E.dirname(e),`bun-graph.js`)}const Dt=`attach-preload.cjs`;function Ot(e){return E.join(E.dirname(e),Dt)}function kt(e,t){return Ct({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const At=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function jt(e,t){return t.isSymbolicLink()?Buffer.from(l.readlinkSync(e)):l.readFileSync(e)}function Mt(e,t,n=At){return l.readdirSync(t).filter(n).sort().flatMap(n=>{let r=E.join(t,n),i=l.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Mt(e,r):[[E.relative(e,r).split(E.sep).join(`/`),jt(r,i)]]})}function Nt(e){let t=ie.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Pt(e){return Nt(Mt(e,e))}const Ft=[`Cargo.toml`,`Cargo.lock`,`src`];function It(e){return Nt(Mt(e,e,e=>Ft.includes(e)))}const Lt=e=>e.slice(0,7),Rt=`1.180.10`;function zt(e){let t=E.dirname(E.dirname(e));return l.existsSync(E.join(t,`src`))?t:null}function Bt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Rt,digest:e}}function Vt(){return`738ccdcec4b4ce6ef2946625b3ab03f8ad3dfe9e785577c066fe6c72e10430bc`}function Ht(e){let t=JSON.parse(l.readFileSync(E.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${E.join(e,`package.json`)} has no version string`);return n}function Ut(e,t){try{let n=zt(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Pt(E.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ht(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function j(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Wt(e){let t=j(e.env,`XDG_STATE_HOME`)??E.join(e.home,`.local`,`state`);return E.join(t,`cc-candybar`)}function Gt(e){let t=j(e.env,`XDG_CACHE_HOME`)??E.join(e.home,`.cache`);return E.join(t,`cc-candybar`)}function Kt(e){return Wt(e)}function qt(e){return e.env.CC_CANDYBAR_SOCKET||Jt()}function Jt(){let e=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Yt(e){l.mkdirSync(e,{recursive:!0,mode:448});let t=l.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=o.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function M(e){Yt(E.dirname(e));for(let t of[e,Xt(e)])try{if(l.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Xt(e){return`${e}.lease`}function Zt(e){return Xt(qt(e))}function Qt(e){return E.join(Wt(e),`session-state.json`)}function $t(e){return E.join(Wt(e),`settings-history.json`)}function en(e){let t=e.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(t)return t;let n=o.userInfo().uid;return E.join(`/tmp`,`cc-candybar-${n}`,`daemons`)}function tn(e){return E.join(Wt(e),`spawn.lock`)}function nn(e){return E.join(Wt(e),`spawn.cooldown`)}function rn(e){return E.join(Wt(e),`spawn.backoff`)}function an(e){return E.join(Wt(e),`watch-probe`)}function on(e){return E.join(Wt(e),`daemon.log`)}function sn(e){return{socket:qt(e),lease:Zt(e),state:Wt(e),registry:en(e),log:on(e),sessionState:Qt(e),settingsHistory:$t(e),watchProbe:an(e),spawnBackoff:rn(e)}}function cn(e){let{env:t}=e,n=`/usr/local/share:/usr/share`,r=process.platform===`darwin`?`${E.join(j(t,`HOMEBREW_PREFIX`)??`/opt/homebrew`,`share`)}:${n}`:n;return{home:e.home,configHome:j(t,`XDG_CONFIG_HOME`)??E.join(e.home,`.config`),dataHome:j(t,`XDG_DATA_HOME`)??E.join(e.home,`.local`,`share`),dataDirs:(j(t,`XDG_DATA_DIRS`)??r).split(`:`).filter(e=>e!==``)}}function ln(e,t,n){let r=un(e);l.mkdirSync(E.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??l.statSync(r,{throwIfNoEntry:!1})?.mode;try{l.writeFileSync(i,t,a===void 0?{}:{mode:a}),l.renameSync(i,r)}catch(e){throw l.rmSync(i,{force:!0}),e}}function un(e){return dn(e).at(-1)}function dn(e){let{hops:t,stopped:n}=fn(e);if(n!==null)throw n;return t}function fn(e){let t=[e];try{for(let e=0;e<mn;e++){let e=pn(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${mn} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function pn(e){try{return l.lstatSync(e).isSymbolicLink()?E.resolve(l.realpathSync(E.dirname(e)),l.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const mn=40,hn=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function gn(e){return Object.fromEntries(hn.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const _n=[`native`,`node`,`frames`];function vn(e,t){return{kind:e,bundle:t,source:null}}const yn=[`ansi`,`frame`],bn=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function xn(e){let t=kn(e.termCols),n=kn(e.termRows),r=An(e.ssh),i=Dn(e.tmux),a=En(e.configEnv),o=En(e.claudeConfigDir),s=N(e.terminalEnv),c=Rn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Sn(e,t){return bn.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Cn(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const wn={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Tn(e){let t=Object.keys(wn).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[wn[t](n.join(`, `))]});return t.length===0?null:t.join(`
4
4
  `)}function N(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=hn.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function En(e){return typeof e==`string`&&E.isAbsolute(e)?e:void 0}function Dn(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const On=1e4;function kn(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>On?On:t}function An(e){return typeof e==`boolean`?e:void 0}function jn(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var Mn=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}},Nn=class extends Error{constructor(e){super(e===`connect`?`CONNECT_TIMEOUT`:`TIMEOUT`),this.phase=e,this.name=`ClientTimeoutError`}};function Pn(e){return Fn(JSON.stringify(e))}function Fn(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function In(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new Mn(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new Mn(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Ln(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=t=>{if(!o){o=!0,c(),e.off(`data`,l),e.off(`error`,u),e.off(`close`,d);try{t()}catch{}}},c=r.after(n-r.now(),()=>{s(()=>{e.destroy(),a(new Nn(`deadline`))})}),l=In(e=>s(()=>i(e)),e=>s(()=>a(e))),u=e=>s(()=>a(e)),d=()=>s(()=>a(Error(`socket closed before response`)));e.on(`data`,l),e.on(`error`,u),e.on(`close`,d),e.write(Pn(t))})}function Rn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=En(n);return _n.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function zn(e,t,n,r){let i;try{i=await Gn(qt(e.host),n.connectMs,e.clock)}catch(e){return Wn(e)}return Bn(i,e.clock,t,n,r)}async function Bn(e,t,n,r,i){try{let a=t.now()+r.budgetMs,o=n(a),s=await Ln(e,{v:3,...o},a,t);return Un(o.kind,s,i)}catch(e){return Wn(e)}finally{e.destroy()}}function Vn(e,t){return typeof e==`string`?e:t}function Hn(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function Un(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=Vn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:Hn(r.daemonV)};case`TIMEOUT`:return{kind:`busy`,phase:`deadline`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function Wn(e){if(e instanceof Mn||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return e instanceof Nn?{kind:`busy`,phase:e.phase,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function Gn(e,t,n){return new Promise((r,i)=>{let a=ue.createConnection({path:e}),o=n.after(t,()=>{a.destroy(),i(new Nn(`connect`))});a.once(`connect`,()=>{o(),r(a)}),a.once(`error`,e=>{o(),i(e)})})}function Kn(e){if(e.kind===`busy`)return`daemon busy (${e.message})`;if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}function qn(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function Jn(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-60-n.monoMs)}const Yn={connectMs:50,budgetMs:150},Xn={connectMs:50,budgetMs:350};function Zn(e){let t=e.output;return typeof t==`string`?t:void 0}function Qn(e){return Un(`render`,e,Zn)}function $n(e,t,n,r,i,a=Yn){return zn(e,e=>({kind:`render`,hookData:t,args:n,cwd:r,deadline:e,...i}),a,Zn)}function er(e,t,n){return zn(e,()=>({kind:`pane-session`,socket:t,pane:n}),Xn,e=>`paneSession`in e?e.paneSession:void 0)}function tr(e,t,n){return zn(e,()=>({kind:`click`,verb:t,value:n,clientVersion:Rt}),Xn,Zn)}const nr=5e3;async function rr(e){let t=[];for(let n of e){let e=await n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
5
5
  `)}const ir=`/usr/bin/footprint`;function ar(e,t,n){return t===`darwin`?[lr(e,ir,[`-p`,String(n)]),lr(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[ur(`/proc/self/smaps_rollup`),ur(`/proc/self/status`)]:[]}function or(e,t,n){return t===`darwin`?sr(n,t=>e.launch({bin:ir,args:t,timeoutMs:nr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function sr(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${dr(r.stderr)}`};let i=cr(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function cr(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function lr(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:nr,category:`limits.memory-report`});return r.ok?r.stdout.trim().length>0?{kind:`text`,text:r.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${r.reason}${r.error===void 0?``:`: ${r.error}`}${dr(r.stderr)}`}}}}function ur(e){return{name:e,read:async()=>{try{let t=l.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function dr(e){let t=e.split(`
6
6
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const fr=`CC_CANDYBAR_RSS_LIMIT_MB`;function pr(e){let t=e[fr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${fr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function mr(e){return pr(e)*2}const hr=1024*1024,gr=e=>Math.round(e/hr);function _r(e){return pr(e)*hr}const vr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function yr(e,t){return e>t}function br(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const xr=.75;function Sr(e,t){return e>t*xr}function Cr(e,t,n){let{prefix:r,suffix:i}=vr[t];return E.join(e,`${r}${n}${i}`)}function wr(e){for(let t of Object.keys(vr)){let{prefix:n,suffix:r}=vr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Tr(e){let t=e.limitBytes??1024*hr,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null,o=!1,s;function c(){return a??=l().finally(()=>{a=null}),a}async function l(){if(r)return!0;let{rss:a,heapTotal:s}=e.memoryBytes(),c=br(await e.memoryCharge(a),i),l={kind:`measured`,charge:c,rss:a,heapTotal:s};if(i=l,e.log(`info`,`memory ${Or(l,t)}`),o||c.bytes<=t)return!1;r=!0,e.log(`warn`,`${Er(c)} > limit ${gr(t)} MB (rss ${gr(a)} MB, v8 heap ${gr(s)} MB); recording memory then shutting down`);let u=`${new Date(e.clock.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return await kr(e.log,`memory report`,async()=>{let t=Cr(e.snapshotDir,`memoryReport`,u),n=await e.captureMemoryReport();o||(e.writeMemoryReport(t,n),e.log(`info`,`memory report written: ${t}`))}),o?(e.log(`info`,`daemon closed during the breach: no snapshot, no exit`),!1):(await kr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=Cr(e.snapshotDir,`heapSnapshot`,u);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),await kr(e.log,`artifact rotation`,async()=>{for(let{artifacts:t}of Ar(e.listArtifacts()).slice(n))for(let n of Object.values(t))await kr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0)}function u(){return i.kind===`measured`&&Sr(i.charge.bytes,t)?`${Er(i.charge)} approaching limit ${gr(t)} MB (v8 heap ${gr(i.heapTotal)} MB)`:null}function d(){let n;try{n={kind:`ok`,value:Ar(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function f(t=6e4){let n=async()=>{try{if(await c())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}o||(s=e.clock.after(t,()=>void n(),{unref:!0}))};n()}function p(){o=!0,s?.()}return{check:c,describeNextRestart:u,serving:d,arm:f,disarm:p}}function Er(e){return e.kind===`charged`?`${e.measure} ${gr(e.bytes)} MB`:`rss ${gr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${gr(e.gap)} MB gap`} (standing in: ${e.unread})`}function Dr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Or({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${gr(e.gap)}MB`:``;return`measure=${Dr(e)} charge=${gr(e.bytes)}MB rss=${gr(t)}MB heap=${gr(n)}MB limit=${gr(r)}MB${i}`}async function kr(e,t,n){try{await n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Ar(e){let t=new Map;for(let n of e){let e=E.basename(n),r=wr(e);if(r===null)continue;let{prefix:i,suffix:a}=vr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(vr);return[...t].sort(([e],[t])=>yr(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function jr(e,t,n,r={}){let i=n.snapshotDir;return{clock:n.clock,pid:process.pid,snapshotDir:i,log:n.log,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:or(n.launcher,process.platform,process.pid),captureMemoryReport:()=>rr(ar(n.launcher,process.platform,process.pid)),writeMemoryReport:(e,t)=>l.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>de.writeHeapSnapshot(e),writeLogNow:n.writeLogNow,listArtifacts:()=>{let e;try{e=l.readdirSync(i)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>wr(e)!==null).map(e=>E.join(i,e))},removeFile:e=>l.unlinkSync(e),shutdown:t,startedAtMs:e,...r}}function Mr(e,n={}){let{host:r,clock:i}=e;if(Jr(r)!==null)return;let a=n.spawn??(()=>Xr(e)),o=Gr(r,i);if(o.kind===`contended`){let e=Pr(r,i);e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Nr(r,i,a));return}if(o.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${o.reason}) — spawning unlocked\n`),Nr(r,i,a);return}try{Nr(r,i,a)}finally{qr()}}function Nr(e,t,n){Vr(e,t)&&Fr(n)}function Pr(e,t){try{let n=l.statSync(tn(e));return t.now()-n.mtimeMs}catch{return null}}function Fr(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -470,8 +470,8 @@ function run(argv) {
470
470
  `)+1,i=n.lastIndexOf(`
471
471
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
472
472
  `)){let t=WX(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function aQ(e){let t=Do(e,sF+1);return t.kind===`ok`?F(iQ(t.value.buf,t.value.fromStart)):t}function oQ(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const sQ={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};async function cQ(e,t){if(hc(t)===void 0)return{kind:`ok`,value:null};let n=dY(await e.launch({bin:`git`,args:[...uY],cwd:t,envOverlay:{GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(n.kind===`failed`)return n;let r=gY(n.value);if(r===null)return{kind:`ok`,value:null};let i=lY(r);if(i===null)return{kind:`ok`,value:null};let a=iY[i],o=sQ[i],s=o.loginHost(cY(r)),c=await e.launch({bin:a,args:[...o.args(s)],cwd:t,timeoutMs:2e3,category:`doctor.forge`});return lQ(a,s,o.nonZero,c)}function lQ(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):aY(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:tY(r.stderr)}):{kind:`failed`,reason:eY(e,r)}}function uQ(e,t){let n={layers:e.layers,target:t,warnings:e.warning===null?[]:e.warning.split(`
473
- `)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const dQ=e=>HZ(()=>zo(e));function fQ(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:jo(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:dQ(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function pQ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function mQ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:ute(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:lte(t),tmuxClient:t}}}}async function hQ(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(ite(s))return{kind:`bundling`,name:s,version:c};if(!ate(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function gQ(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Rt};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function _Q(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function vQ(e,t,n,r){return{pullRequests:await _Q(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await _Q(t.rateLimits,()=>r)}}function yQ(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function bQ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=uK(d.config,r,()=>!1),p=await pQ(e,t.tmux),m=mQ(p,t.terminalEnv),h=[...new Set([...Yee(f),...UP(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:hQ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),vQ(e,AX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:uQ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:oQ(e,o),claudeSettings:fQ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:jo(Ao(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function xQ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;ln(e,qa(Po(e),t.path,JSON.stringify(t.value),Ma));let r=e=>({...e,sources:dQ(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||yr(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const SQ=16384;var CQ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)}};recordRollingNow(){let e=this.clock.now();if(this.rollingTimestamps.length<SQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%SQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=this.clock.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,refused:Object.fromEntries(this.subprocessRefused),p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Rt,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const wQ={connectMs:200,budgetMs:500};async function TQ(e,t){return EQ(await DQ(e),t.includes(`--json`))}function EQ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${Kn(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
474
- `:null,r=OQ(e.value);return r===null?{stdout:n??IQ(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function DQ(e){return zn(e,()=>({kind:`stats`}),wQ,e=>`stats`in e?e.stats:void 0)}function OQ(e,t=kQ){let n=CQ.referenceSnapshot(),r=AQ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=MQ(e.version,e.sourceDigest??null),a=MQ(Rt,Vt());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const kQ=Object.keys(CQ.referenceSnapshot());function AQ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!jQ(e))return[];if(!jQ(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...AQ(e[i],t[i],a)):r.push(a)}return r}function jQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MQ(e,t){return`${e} [${t===null?`no digest`:Lt(t)}]`}function NQ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function PQ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function FQ(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function IQ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${MQ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${FQ(e.uptimeSec)}`),t.push(` rss ${NQ(e.rssBytes)}`),t.push(` heapUsed ${NQ(e.heapUsedBytes)}`),t.push(` heapTotal ${NQ(e.heapTotalBytes)}`),t.push(` external ${NQ(e.externalBytes)}`),t.push(` arrayBuffers ${NQ(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${PQ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${PQ(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Uc(e.fileEvents)}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${NQ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${NQ(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${NQ(e.renderCache.accountedBytes)} / ${NQ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
473
+ `)};return e.error===null?{...n,kind:`loaded`,unused:e.unused}:{...n,kind:`failed`,error:e.error}}const dQ=e=>HZ(()=>zo(e));function fQ(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:jo(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:dQ(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}async function pQ(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:await e.probeTmux(t)}}function mQ(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:ute(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:lte(t),tmuxClient:t}}}}async function hQ(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(ite(s))return{kind:`bundling`,name:s,version:c};if(!ate(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:await e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:await e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function gQ(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Rt};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}async function _Q(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:await t()}}async function vQ(e,t,n,r){return{pullRequests:await _Q(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:await _Q(t.rateLimits,()=>r)}}function yQ(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}async function bQ(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=uK(d.config,r,()=>!1),p=await pQ(e,t.tmux),m=mQ(p,t.terminalEnv),h=[...new Set([...Yee(f),...UP(JSON.stringify(d.config))])].join(``),[g,_,v]=await Promise.all([h===``?{kind:`none`}:hQ(e,m,t,h).then(e=>({kind:`glyphs`,glyphs:h,terminal:e})),e.daemons(),vQ(e,AX(d.config,f.preset),n,a)]);return{tmux:p,width:l,terminal:m,nerdFont:g,marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:_,read:u.postMortemsRead},config:uQ(d,n.target),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:v,transcripts:oQ(e,o),claudeSettings:fQ({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:jo(Ao(t.claudeConfigDir,e.home))},c.kind===`ok`?c.value:[])}}function xQ(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;ln(e,qa(Po(e),t.path,JSON.stringify(t.value),Ma));let r=e=>({...e,sources:dQ(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||yr(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const SQ=16384;var CQ=class e{startedAt;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;constructor(e){this.clock=e,this.startedAt=new Date(e.now())}firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;dirWatchesOpened=0;dirWatchesClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessDraining=0;subprocessDrainedBytes=0;subprocessDrainsCut=0;subprocessPipeErrors=0;subprocessRefusals=new Map;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;get subprocessRefused(){return this.subprocessRefusals}launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)},onRefused:e=>{this.subprocessRefusals.set(e,(this.subprocessRefusals.get(e)??0)+1)},onDrainOpen:()=>{this.subprocessDraining++},onDrainRead:(e,t)=>{this.subprocessDrainedBytes+=t},onDrainClose:(e,t)=>{this.subprocessDraining--,t===`cut`&&this.subprocessDrainsCut++},onPipeError:()=>{this.subprocessPipeErrors++}};recordRollingNow(){let e=this.clock.now();if(this.rollingTimestamps.length<SQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%SQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=this.clock.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,refused:Object.fromEntries(this.subprocessRefused),draining:this.subprocessDraining,drainedBytes:this.subprocessDrainedBytes,drainsCut:this.subprocessDrainsCut,pipeErrors:this.subprocessPipeErrors,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e({now:()=>0}).snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},fileEvents:{delivery:{kind:`delivering`,unreported:[],missedSince:null},stalls:0,catchUps:0,probes:0,probeFailures:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0,pending:0},journalTurns:{holder:null,heldMs:0,queued:0,gathers:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,dirWatchesActive:0,handlerProbes:[],clients:[],bundle:`/`,sourceDigest:null,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Rt,sourceDigest:e.sourceDigest,protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((this.clock.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,fileEvents:e.fileEvents,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,journalTurns:e.journalTurns,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors,dirs:{active:e.dirWatchesActive,opened:this.dirWatchesOpened,closed:this.dirWatchesClosed}},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};const wQ={connectMs:200,budgetMs:500};async function TQ(e,t){return EQ(await DQ(e),t.includes(`--json`))}function EQ(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${Kn(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
474
+ `:null,r=OQ(e.value);return r===null?{stdout:n??IQ(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function DQ(e){return zn(e,()=>({kind:`stats`}),wQ,e=>`stats`in e?e.stats:void 0)}function OQ(e,t=kQ){let n=CQ.referenceSnapshot(),r=AQ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=MQ(e.version,e.sourceDigest??null),a=MQ(Rt,Vt());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const kQ=Object.keys(CQ.referenceSnapshot());function AQ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!jQ(e))return[];if(!jQ(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...AQ(e[i],t[i],a)):r.push(a)}return r}function jQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function MQ(e,t){return`${e} [${t===null?`no digest`:Lt(t)}]`}function NQ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function PQ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function FQ(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function IQ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${MQ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${FQ(e.uptimeSec)}`),t.push(` rss ${NQ(e.rssBytes)}`),t.push(` heapUsed ${NQ(e.heapUsedBytes)}`),t.push(` heapTotal ${NQ(e.heapTotalBytes)}`),t.push(` external ${NQ(e.externalBytes)}`),t.push(` arrayBuffers ${NQ(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${PQ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${PQ(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(` fileEvents ${Uc(e.fileEvents)}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${NQ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${NQ(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${NQ(e.renderCache.accountedBytes)} / ${NQ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(` pending ${e.menuIdle.pending}`),t.push(``),t.push(`journalTurns`),t.push(` holder ${e.journalTurns.holder??`-`}`),t.push(` held ${e.journalTurns.heldMs}ms`),t.push(` queued ${e.journalTurns.queued}`),t.push(` gathers ${e.journalTurns.gathers}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(` dirs ${e.watchers.dirs.active} open (${e.watchers.dirs.opened} opened, ${e.watchers.dirs.closed} closed)`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`),t.push(` draining ${e.subprocesses.draining} (${e.subprocesses.drainedBytes} bytes dropped, ${e.subprocesses.drainsCut} cut)`),t.push(` pipeErrors ${e.subprocesses.pipeErrors}`);let o=Object.entries(e.subprocesses.byCategory),s=Object.entries(e.subprocesses.refused).map(([e,t])=>[`${e} refused`,t]),c=[...o,...s].reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(c)} ${r}${o}`)}for(let[e,n]of s)t.push(` ${e.padEnd(c)} ${n}`);return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
475
475
  `)+`
476
476
  `}const LQ=e=>({kind:`ok`,value:e}),RQ=e=>({kind:`failed`,reason:e});var zQ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const BQ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function VQ(e){return BQ.test(e)?e:null}function HQ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return LQ(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return LQ({app:n,missing:RQ(`its script could not be read (${r.reason})`)});let i=ls(r.value);return LQ({app:n,missing:i===null?RQ("its script is not one `cc-candybar install` wrote"):LQ([i.node,i.script].filter(t=>!e.exists(t)))})}async function UQ(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function WQ(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Si}://${Ki}/${n}`);return(r===null?await UQ(e,n):null)??{kind:`lost`,unopened:r,opener:HQ(e)}}function GQ(e,t,n,r){let i=e.launchSync({bin:n,args:[...r],category:t,timeoutMs:5e3});return i.ok?LQ(i.stdout):RQ(i.stderr.trim()||i.error||i.reason)}const KQ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Si}://probe"));u.isNil() ? "" : u.path.js`;async function qQ(e){let t=await DQ(e);if(t.kind!==`ok`)return RQ(Kn(t).split(`
477
477
  `).join(` — `));let n=OQ(t.value,[`handlerProbes`]);if(n!==null)return RQ(n);let{version:r,handlerProbes:i}=t.value;return LQ({version:r,arrivals:i})}function JQ(e,t){let{host:n,clock:r}=t;return{platform:process.platform,sockets:{own:qt(n),handler:Jt()},now:()=>r.now(),nonce:ce,daemon:()=>qQ(t),open:t=>{let n=GQ(e,`doctor.open`,`/usr/bin/open`,[`-g`,t]);return n.kind===`ok`?null:n.reason},pause:()=>_t(r,100),opener:()=>{let t=GQ(e,`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,KQ]);if(t.kind===`failed`)return t;let n=t.value.trim();return LQ(n===``?null:n)},script:t=>GQ(e,`doctor.osadecompile`,`/usr/bin/osadecompile`,[us(t)]),exists:l.existsSync}}const YQ=/^─{20,}/,XQ=/^❯(\s|$)/,ZQ=/›\s*stashed$/;function QQ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>YQ.test(e)?[t]:[]).at(-2);return n===void 0||!XQ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function $Q(e){if(e.inMode)return{kind:`in-mode`};let t=QQ(e);return t===null?{kind:`no-prompt`}:ZQ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function e$(e){return/^❯\s*\S/u.test(QQ(e)?.prompt??``)}const t$=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function n$(e){return e.screen.some(e=>t$.test(e))}const r$={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function i$(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}async function a$(e,t,n){let r=i$(t);if(r.kind===`refused`)return r;let i=r.hint,a=$Q(await e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:r$[a.kind]};let o=await e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}async function o$(e,t,n,r,i){let a=await nc(e,t,n,r,i);if(a.kind===`failed`)throw Error(a.reason);return a}async function s$(e,t){let n=await o$(e,t,`claude-input.read`,[`display`,`-p`,`-t`,t.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,t.pane]);if(n.kind===`rate-limited`)throw Error(n.reason);let[r=``,...i]=n.stdout.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.180.8",
3
+ "version": "1.180.10",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -111,9 +111,9 @@
111
111
  "yaml": "^2.9.1"
112
112
  },
113
113
  "optionalDependencies": {
114
- "@promptctl/cc-candybar-darwin-arm64": "1.180.8",
115
- "@promptctl/cc-candybar-darwin-x64": "1.180.8",
116
- "@promptctl/cc-candybar-linux-arm64": "1.180.8",
117
- "@promptctl/cc-candybar-linux-x64": "1.180.8"
114
+ "@promptctl/cc-candybar-darwin-arm64": "1.180.10",
115
+ "@promptctl/cc-candybar-darwin-x64": "1.180.10",
116
+ "@promptctl/cc-candybar-linux-arm64": "1.180.10",
117
+ "@promptctl/cc-candybar-linux-x64": "1.180.10"
118
118
  }
119
119
  }