@promptctl/cc-candybar 1.160.8 → 1.160.9
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.
- package/dist/index.mjs +3 -3
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
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,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";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{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));const Me=()=>!!process.env.CC_CANDYBAR_DEBUG;function Ne(e){return Me()?`[DEBUG] ${e()}\n`:``}function E(e,...t){Me()&&console.error(`[DEBUG] ${e}`,...t)}const Pe=(e,t)=>E(t),Fe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ie(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Le(e){return Fe.test(e)?e:Ie(e)}function Re(e){return`${e.dir===void 0?``:`cd ${Le(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Le(t)} `).join(``)}${[e.program,...e.args].map(Le).join(` `)}`}const ze=`cc-extra`;function Be(e){return s.join(s.dirname(e),ze,`src`,`bun-attach.js`)}function Ve(e){return s.join(s.dirname(e),`bun-graph.js`)}const He=`attach-preload.cjs`;function Ue(e){return s.join(s.dirname(e),He)}function We(e,t){return Re({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ge=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ke(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function qe(e,t,n=Ge){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?qe(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Ke(r,i)]]})}function Je(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ye(e){return Je(qe(e,e))}const Xe=[`Cargo.toml`,`Cargo.lock`,`src`];function Ze(e){return Je(qe(e,e,e=>Xe.includes(e)))}const Qe=e=>e.slice(0,7),$e=`1.160.8`;function et(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function tt(){let e=nt();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:$e,digest:e}}function nt(){return`317c482c2bb7bc66650f05aaa591e15cfb77eb7080443f82a615969ed01287c6`}function rt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function it(e,t){try{let n=et(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ye(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:rt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function at(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const ot={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},st=new Map;function ct(e){let t=ot[e];if(t===void 0)return{allowed:!0};let n=st.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function lt(e){st.set(e,Date.now())}function ut(e){return e.env??process.env}function dt(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`}}let ft=null;function pt(e){ft=e}function mt(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function ht(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();return ft?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ft?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ft?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{mt(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:at(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function gt(e){let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();ft?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ft?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:at(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ft?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(t,e.cwd)}}}function _t(e){let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();ft?.onStart(e.category);let r=vt(e);return ft?.onEnd(e.category,Date.now()-n),r}function vt(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function D(e,t,n){let r=yt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function yt(e){return bt(e).at(-1)}function bt(e){let t=[e];for(let e=0;e<xt;e++){let e=t[t.length-1],n;try{n=p.lstatSync(e)}catch(e){let{code:n}=e;if(n===`ENOENT`||n===`ENOTDIR`)return t;throw e}if(!n.isSymbolicLink())return t;t.push(s.resolve(p.realpathSync(s.dirname(e)),p.readlinkSync(e)))}throw Error(`${e}: more than ${xt} symbolic links`)}const xt=40;function St(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Ct(e=process.env){let t=St(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function wt(){let e=St(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function Tt(){return Ct()}function Et(){return process.env.CC_CANDYBAR_SOCKET||Dt()}function Dt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Ot(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.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 kt(e){Ot(s.dirname(e));for(let t of[e,At(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function At(e){return`${e}.lease`}function jt(){return At(Et())}function Mt(){return s.join(Ct(),`session-state.json`)}function Nt(){return s.join(Ct(),`settings-history.json`)}function Pt(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Ft(){return s.join(Ct(),`spawn.lock`)}function It(){return s.join(Ct(),`spawn.cooldown`)}function Lt(){return s.join(Ct(),`spawn.backoff`)}function Rt(){return s.join(Ct(),`diagnostics`)}function zt(e=process.env){return s.join(Ct(e),`daemon.log`)}const Bt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Vt(e){return Object.fromEntries(Bt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Ht=[`native`,`node`,`frames`];function Ut(e,t){return{kind:e,bundle:t,source:null}}const Wt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Gt(e){let t=k(e.termCols),n=k(e.termRows),r=$t(e.ssh),i=Zt(e.tmux),a=Xt(e.configEnv),o=Xt(e.claudeConfigDir),s=Yt(e.terminalEnv),c=sn(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 Kt(e,t){return Wt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function O(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 qt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Jt(e){let t=Object.keys(qt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[qt[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,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";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{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));const Me=()=>!!process.env.CC_CANDYBAR_DEBUG;function Ne(e){return Me()?`[DEBUG] ${e()}\n`:``}function E(e,...t){Me()&&console.error(`[DEBUG] ${e}`,...t)}const Pe=(e,t)=>E(t),Fe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ie(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Le(e){return Fe.test(e)?e:Ie(e)}function Re(e){return`${e.dir===void 0?``:`cd ${Le(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Le(t)} `).join(``)}${[e.program,...e.args].map(Le).join(` `)}`}const ze=`cc-extra`;function Be(e){return s.join(s.dirname(e),ze,`src`,`bun-attach.js`)}function Ve(e){return s.join(s.dirname(e),`bun-graph.js`)}const He=`attach-preload.cjs`;function Ue(e){return s.join(s.dirname(e),He)}function We(e,t){return Re({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ge=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ke(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function qe(e,t,n=Ge){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?qe(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Ke(r,i)]]})}function Je(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ye(e){return Je(qe(e,e))}const Xe=[`Cargo.toml`,`Cargo.lock`,`src`];function Ze(e){return Je(qe(e,e,e=>Xe.includes(e)))}const Qe=e=>e.slice(0,7),$e=`1.160.9`;function et(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function tt(){let e=nt();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:$e,digest:e}}function nt(){return`ba807754f1a7394ab28c9dd2536a02af74555fc3d52300c794d7efaa5f0cfe12`}function rt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function it(e,t){try{let n=et(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ye(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:rt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function at(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const ot={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},st=new Map;function ct(e){let t=ot[e];if(t===void 0)return{allowed:!0};let n=st.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function lt(e){st.set(e,Date.now())}function ut(e){return e.env??process.env}function dt(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`}}let ft=null;function pt(e){ft=e}function mt(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function ht(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();return ft?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ft?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ft?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{mt(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:at(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function gt(e){let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();ft?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ft?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:at(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ft?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(t,e.cwd)}}}function _t(e){let t=ct(e.category);if(!t.allowed)return dt(e.category,t.minIntervalMs,t.sinceLastMs);lt(e.category);let n=Date.now();ft?.onStart(e.category);let r=vt(e);return ft?.onEnd(e.category,Date.now()-n),r}function vt(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ut(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:at(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function D(e,t,n){let r=yt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function yt(e){return bt(e).at(-1)}function bt(e){let t=[e];for(let e=0;e<xt;e++){let e=t[t.length-1],n;try{n=p.lstatSync(e)}catch(e){let{code:n}=e;if(n===`ENOENT`||n===`ENOTDIR`)return t;throw e}if(!n.isSymbolicLink())return t;t.push(s.resolve(p.realpathSync(s.dirname(e)),p.readlinkSync(e)))}throw Error(`${e}: more than ${xt} symbolic links`)}const xt=40;function St(e,t){let n=e[t];return n&&n.length>0?n:void 0}function Ct(e=process.env){let t=St(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function wt(){let e=St(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function Tt(){return Ct()}function Et(){return process.env.CC_CANDYBAR_SOCKET||Dt()}function Dt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Ot(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.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 kt(e){Ot(s.dirname(e));for(let t of[e,At(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function At(e){return`${e}.lease`}function jt(){return At(Et())}function Mt(){return s.join(Ct(),`session-state.json`)}function Nt(){return s.join(Ct(),`settings-history.json`)}function Pt(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Ft(){return s.join(Ct(),`spawn.lock`)}function It(){return s.join(Ct(),`spawn.cooldown`)}function Lt(){return s.join(Ct(),`spawn.backoff`)}function Rt(){return s.join(Ct(),`diagnostics`)}function zt(e=process.env){return s.join(Ct(e),`daemon.log`)}const Bt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Vt(e){return Object.fromEntries(Bt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Ht=[`native`,`node`,`frames`];function Ut(e,t){return{kind:e,bundle:t,source:null}}const Wt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Gt(e){let t=k(e.termCols),n=k(e.termRows),r=$t(e.ssh),i=Zt(e.tmux),a=Xt(e.configEnv),o=Xt(e.claudeConfigDir),s=Yt(e.terminalEnv),c=sn(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 Kt(e,t){return Wt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function O(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 qt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Jt(e){let t=Object.keys(qt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[qt[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
3
3
|
`)}function Yt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Bt.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 Xt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Zt(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 Qt=1e4;function k(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Qt?Qt:t}function $t(e){return typeof e==`boolean`?e:void 0}function en(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var tn=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function nn(e){return rn(JSON.stringify(e))}function rn(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function an(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 tn(`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 tn(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function on(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=an(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(nn(t))})}function sn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Xt(n);return Ht.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function cn(e,t,n){let r=null;try{r=await pn(Et(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await on(r,{v:3,...a},i);return dn(a.kind,o,n)}catch(e){return fn(e)}finally{r&&r.destroy()}}function ln(e,t){return typeof e==`string`?e:t}function un(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function dn(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=ln(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:un(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,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 fn(e){if(e instanceof tn||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 t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,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 pn(e,t){return new Promise((n,r)=>{let i=ue.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function mn(e){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}`}}const hn={connectMs:50,budgetMs:150},gn={connectMs:50,budgetMs:200};function _n(e){let t=e.output;return typeof t==`string`?t:void 0}function vn(e){return dn(`render`,e,_n)}function yn(e,t,n,r){return cn(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),hn,_n)}function bn(e,t){return cn(()=>({kind:`pane-session`,socket:e,pane:t}),gn,e=>`paneSession`in e?e.paneSession:void 0)}function xn(e,t){return cn(()=>({kind:`click`,verb:e,value:t,clientVersion:$e}),gn,_n)}let Sn=null;function Cn(){if(Sn!==null){try{p.closeSync(Sn.fd)}catch{}Sn=null}}async function wn(e){let t=await p.promises.stat(e).catch(()=>null);if(Sn!==null&&Sn.path===e&&t!==null&&Sn.id===Tn(t))return{held:Sn,size:t.size};Cn(),await p.promises.mkdir(s.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>p.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>p.fstat(n,(n,r)=>n===null?e(r):t(n)));return Sn={path:e,fd:n,id:Tn(r)},{held:Sn,size:r.size}}function Tn(e){return`${e.dev}:${e.ino}`}function En(e,t){return new Promise((n,r)=>p.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function Dn(e){for(let t=2;t>=1;t--)await p.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await p.promises.rename(e,`${e}.1`).catch(()=>{})}let On=[],A=0,kn=0,An=0,jn=null,Mn=!1;const Nn=[];let Pn=!1,Fn=!1;function j(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;if(Fn||(Fn=!0,process.on(`exit`,()=>{Pn=!0,Hn(!0,Bn)})),On.push(n),A+=Buffer.byteLength(n),A>4194304){let e=0;for(;A>4194304/2&&e<On.length-1;){let t=Buffer.byteLength(On[e]);A-=t,An+=t,e++}On.splice(0,e),kn+=e}Pn?Hn(!0,Bn):Mn||Ln()}function In(){Hn(!1,Vn)}async function Ln(){Mn=!0;try{for(;On.length>0;){let e=Rn();jn={bytes:Buffer.from(e),state:{kind:`taken`}};try{await zn(zt(),jn)}catch(t){Cn(),jn.state.kind!==`landed`&&Wn(e,t)}finally{jn=null}}}finally{Mn=!1;for(let e of Nn.splice(0))e()}}function Rn(){let e=(kn===0?``:`${new Date().toISOString()} [warn] log: ${kn} earlier line(s) dropped (${An} bytes): more than 4194304 bytes were waiting for the disk\n`)+On.join(``);return On=[],A=0,kn=0,An=0,e}async function zn(e,t){let{held:n,size:r}=await wn(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await En(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){Cn();let e=await p.promises.stat(n.path).catch(()=>null);e!==null&&Tn(e)===n.id&&await Dn(n.path)}}const Bn=1e3,Vn=2e3;function Hn(e,t){let n=jn,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=Un(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Wn(n.bytes.toString(),t)}}if(r.length===0&&On.length===0)return;let a=Buffer.concat([r,Buffer.from(Rn())]);try{let e=zt();p.mkdirSync(s.dirname(e),{recursive:!0}),p.appendFileSync(e,a),i!==null&&n!==null&&Tn(p.fstatSync(i.fd))===Tn(p.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Wn(a.toString(),e)}}function Un(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=p.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Wn(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Gn=5e3;function Kn(e){let t=[];for(let n of e){let e=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(`
|
|
4
4
|
`)}const qn=`/usr/bin/footprint`;function Jn(e,t){return e===`darwin`?[Qn(qn,[`-p`,String(t)]),Qn(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[$n(`/proc/self/smaps_rollup`),$n(`/proc/self/status`)]:[]}function Yn(e,t){return e===`darwin`?Xn(t,e=>ht({bin:qn,args:e,timeoutMs:Gn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Xn(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}`}${er(r.stderr)}`};let i=Zn(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 Zn(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Qn(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=gt({bin:e,args:[...t],timeoutMs:Gn,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${er(n.stderr)}`}}}}function $n(e){return{name:e,read:()=>{try{let t=p.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 er(e){let t=e.split(`
|
|
5
5
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const tr=`CC_CANDYBAR_RSS_LIMIT_MB`;function nr(e){let t=e[tr];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${tr} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function rr(e){return nr(e)*2}const ir=1024*1024,M=e=>Math.round(e/ir);function ar(e){return nr(e)*ir}const or={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function sr(e,t){return e>t}function cr(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 lr=.75;function ur(e,t){return e>t*lr}function dr(e,t,n){let{prefix:r,suffix:i}=or[t];return s.join(e,`${r}${n}${i}`)}function fr(e){for(let t of Object.keys(or)){let{prefix:n,suffix:r}=or[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function pr(e){let t=e.limitBytes??1024*ir,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null;function o(){return a??=s().finally(()=>{a=null}),a}async function s(){if(r)return!0;let{rss:a,heapTotal:o}=e.memoryBytes(),s=cr(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${gr(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${mr(s)} > limit ${M(t)} MB (rss ${M(a)} MB, v8 heap ${M(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return _r(e.log,`memory report`,()=>{let t=dr(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),_r(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=dr(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),_r(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of vr(e.listArtifacts()).slice(n))for(let n of Object.values(t))_r(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&ur(i.charge.bytes,t)?`${mr(i.charge)} approaching limit ${M(t)} MB (v8 heap ${M(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:vr(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function u(t=6e4){let n,r=!0,i=async()=>{try{if(await o())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}r&&(n=setTimeout(()=>void i(),t),n.unref())};return i(),{disarm:()=>{r=!1,clearTimeout(n)}}}return{check:o,describeNextRestart:c,serving:l,arm:u}}function mr(e){return e.kind===`charged`?`${e.measure} ${M(e.bytes)} MB`:`rss ${M(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${M(e.gap)} MB gap`} (standing in: ${e.unread})`}function hr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function gr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${M(e.gap)}MB`:``;return`measure=${hr(e)} charge=${M(e.bytes)}MB rss=${M(t)}MB heap=${M(n)}MB limit=${M(r)}MB${i}`}function _r(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function vr(e){let t=new Map;for(let n of e){let e=s.basename(n),r=fr(e);if(r===null)continue;let{prefix:i,suffix:a}=or[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(or);return[...t].sort(([e],[t])=>sr(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function yr(e,t,n={}){let r=Tt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:j,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Yn(process.platform,process.pid),captureMemoryReport:()=>Kn(Jn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>de.writeHeapSnapshot(e),writeLogNow:In,listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>fr(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function br(e={}){if(Ir()!==null)return;let n=e.spawn??Rr,r=Nr();if(r.kind===`contended`){let e=Sr();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),xr(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),xr(n);return}try{xr(n)}finally{Fr()}}function xr(e){kr()&&Cr(e)}function Sr(){try{let e=p.statSync(Ft());return Date.now()-e.mtimeMs}catch{return null}}function Cr(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -186,8 +186,8 @@ Config tooling:
|
|
|
186
186
|
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:cW(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const dW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function fW(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?dW[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const pW={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},mW=Object.keys(pW);function hW(e,t){let n=fW(t.color),r=fW(t.bgcolor),i={};for(let e of mW){if(t[e]!==!0)continue;let n=pW[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const gW=new V;function _W(e){return{ok:!0,band:new Up().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(hW(t.slice(r,i.start),gW)),n.push(hW(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(hW(t.slice(r),gW)),n})}}function vW(e){let t=uW(vn(e)).output;try{return _W(t)}catch(e){return _W(`${By}${zy}⚠ cc-candybar ${Ly(e instanceof Error?e.message:String(e))}${Vy}\n`)}}function yW(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const bW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function xW(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:bW[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const SW={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},CW=Object.keys(SW);function wW(e){return e.replaceAll(`#`,`##`)}function TW(e){let t=CW.filter(t=>e[t]===!0).map(e=>{let t=SW[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${xW(e.color)}`,`bg=${xW(e.bgcolor)}`,...t].join(`,`)}]`}const EW=new V;function DW(e){let t={},n=(e,n)=>{let r=TW(n)+wW(e);if(n.link===void 0)return r;let i=yW(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new Up().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),EW)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),EW)),r.join(``)}),links:t}}function OW(e){let t=uW(vn(e)).output;try{return DW(t)}catch(e){return DW(`${By}${zy}⚠ cc-candybar ${Ly(e instanceof Error?e.message:String(e))}${Vy}\n`)}}const kW={band:e=>JSON.stringify(vW(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:OW(e)})};function AW(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function jW(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function MW(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?I(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const NW={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},PW={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function FW(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}const IW={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function LW(e){return Object.keys(IW).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${IW[t]}: ${n.reason}`]:[]})}function RW(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(zW(e,t))}function zW(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??BW(t.stderr)].filter(Boolean).join(`, `)}`}function BW(e){return e.trim().split(`
|
|
187
187
|
`,1)[0]??``}function VW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function HW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const UW={github:`gh`,gitlab:`glab`};function WW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const GW=/^[A-Za-z]:[\\/]/;function KW(e){let t=e.trim();if(GW.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function qW(e){return KW(e)?.host||null}function JW(e){let t=qW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const YW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function XW(e){let t=RW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?ZW(t.value):[]}}function ZW(e){let t=new Map;for(let n of e.split(`
|
|
188
188
|
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function QW(e){return e.urls.find(e=>rG(e)!==null)??e.urls[0]??null}function $W(e){return e.find(e=>e.name===`origin`)??e[0]??null}function eG(e){let t=$W(e);return t?QW(t):null}function tG(e){let t=$W(e);return t?t.urls.find(e=>JW(e)!==null)??QW(t):null}function nG(e){let t=(KW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function rG(e){let t=KW(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function iG(e){let t=eG(e);return t===null?null:rG(t)}function aG(e,t,n,r){return t.ok?r(t.stdout):WW(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??BW(t.stderr)].filter(Boolean).join(`, `)}`)}function oG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sG(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
189
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function cG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oG(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=FW(`gh pr view`,NW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function lG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oG(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=FW(`glab mr view`,PW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function uG(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var dG=class{isGitRepo(e){return KV(e)}async execGitAsync(e,t){return ht({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=qV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=VW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=VW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=VW(s,iG)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return HW(RW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=HW(RW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){
|
|
190
|
-
`).length:0)}async getRemotesAsync(e){let t=uG(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return XW(await this.execGitAsync(YW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=eG(e);return(n===null?null:nG(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=tG(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return ht({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JW(t);return n===`github`?aG(`gh pr view`,await this.execForgeAsync(UW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,cG):n===`gitlab`?aG(`glab mr view`,await this.execForgeAsync(UW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,lG):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=RW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(sG(t.value)):t}};const fG=(e,t)=>E(t);function pG(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const mG=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var hG=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??fG}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:t.dirs.map(e=>({path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=pG(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(mG(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function gG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var _G=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function vG(){return J.observable.box(yG(`unread`),{deep:!1})}function yG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function bG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function xG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(yG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function SG(e,t){e.reading.get().kind===`pending`&&bG(e,t)}function CG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function wG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function TG(e){for(;;){let t=e();if(!CG(t))return t;await t.landed}}function EG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function DG(e){return{current:()=>e}}function OG(e){return TG(()=>e.current())}const kG=`pass`,AG={okMs:5*6e4,failedMs:45e3};function jG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function MG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function NG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function PG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{dirs:t}}function FG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function IG(e){e.missed=!0,xG(e,`unread`)}function LG(e,t){return e.missed&&e.reading.get().kind===`pending`&&bG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function RG(e,t){let n=wG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:wG(t)})}function zG(e){return t=>I(`${e} threw: ${String(t)}`)}var BG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new dG,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new Bk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new hG({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return DG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>RG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new Rk,watcher:this.watchers.acquire(`git:${e}`,PG(n),()=>this.changed(e)),period:new _G(()=>{r.refresh.share(kG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(kG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&IG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(kG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:vG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=NG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(MG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(zG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,bG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of LW(n.value))s.add(e)});let c=FG(a),l=i===null||r.length===0?`-`:c===void 0?LG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,jG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new _G(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:vG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(zG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(IG(t),`owed`):(xG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,bG(t,a.outcome),t.period.landed(gG(AG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(zG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${L(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(bG(t,i),t.period.landed(gG(AG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())SG(n,t);e.pr!==null&&SG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},VG=class{static CACHE_DIR=wt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const HG={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var UG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await VG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await VG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(HG).length} models`),this.executionCache=HG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(HG).length} models`),HG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const WG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function GG(e){if(typeof e==`string`)return WG.exec(e)?.[1]}function KG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function qG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function JG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=KG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?GG(qG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function YG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function XG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await ZG(za(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function ZG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function QG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await za(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Ga(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=oK(i,t,s.value);let c=rK(Ka(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function $G(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(tK(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=qG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||eK.test(r)?`claude-code`:`prompt`}const eK=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function tK(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function nK(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=$G(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:JG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function rK(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function iK(e){let t=rK(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return nK(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function aK(e){let t=[];for(let n of e.split(`
|
|
189
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function cG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oG(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=FW(`gh pr view`,NW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function lG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oG(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=FW(`glab mr view`,PW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function uG(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var dG=class{isGitRepo(e){return KV(e)}async execGitAsync(e,t){return ht({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=qV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=VW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=VW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=VW(s,iG)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return HW(RW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=HW(RW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){try{let t=p.readFileSync(s.join(e,`commondir`),`utf-8`).trim();if(t)return s.resolve(e,t)}catch{}return e}getStashCount(e){let t=s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
|
|
190
|
+
`).length:0)}async getRemotesAsync(e){let t=uG(s.join(this.resolveCommonGitDir(this.resolveGitDir(e)),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return XW(await this.execGitAsync(YW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=eG(e);return(n===null?null:nG(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=tG(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return ht({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JW(t);return n===`github`?aG(`gh pr view`,await this.execForgeAsync(UW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,cG):n===`gitlab`?aG(`glab mr view`,await this.execForgeAsync(UW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,lG):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=RW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(sG(t.value)):t}};const fG=(e,t)=>E(t);function pG(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const mG=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var hG=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??fG}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:t.dirs.map(e=>({path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=pG(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1,recursive:r.recursive===!0},(e,n)=>{i&&(!n||!i.has(n))||t(mG(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function gG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var _G=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function vG(){return J.observable.box(yG(`unread`),{deep:!1})}function yG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function bG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function xG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(yG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function SG(e,t){e.reading.get().kind===`pending`&&bG(e,t)}function CG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function wG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function TG(e){for(;;){let t=e();if(!CG(t))return t;await t.landed}}function EG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function DG(e){return{current:()=>e}}function OG(e){return TG(()=>e.current())}const kG=`pass`,AG={okMs:5*6e4,failedMs:45e3};function jG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function MG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function NG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function PG(e,t){return{dirs:[{path:e,filenames:[`HEAD`,`index`]},{path:s.join(t,`refs`,`heads`),recursive:!0}]}}function FG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function IG(e){e.missed=!0,xG(e,`unread`)}function LG(e,t){return e.missed&&e.reading.get().kind===`pending`&&bG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function RG(e,t){let n=wG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:wG(t)})}function zG(e){return t=>I(`${e} threw: ${String(t)}`)}var BG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new dG,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new Bk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new hG({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return DG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>RG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r=this.inner.resolveCommonGitDir(n),i={root:e,refresh:new Rk,watcher:this.watchers.acquire(`git:${e}`,PG(n,r),()=>this.changed(e)),period:new _G(()=>{i.refresh.share(kG,()=>this.refreshPass(i))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,i),i}changedPass(e,t){e.asked.add(t),e.refresh.run(kG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&IG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(kG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:vG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=NG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(MG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(zG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,bG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of LW(n.value))s.add(e)});let c=FG(a),l=i===null||r.length===0?`-`:c===void 0?LG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,jG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new _G(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:vG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(zG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(IG(t),`owed`):(xG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,bG(t,a.outcome),t.period.landed(gG(AG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(zG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${L(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(bG(t,i),t.period.landed(gG(AG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())SG(n,t);e.pr!==null&&SG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},VG=class{static CACHE_DIR=wt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const HG={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var UG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await VG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await VG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(HG).length} models`),this.executionCache=HG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(HG).length} models`),HG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const WG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function GG(e){if(typeof e==`string`)return WG.exec(e)?.[1]}function KG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function qG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function JG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=KG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?GG(qG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function YG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function XG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await ZG(za(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function ZG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function QG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await za(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Ga(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=oK(i,t,s.value);let c=rK(Ka(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function $G(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(tK(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=qG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||eK.test(r)?`claude-code`:`prompt`}const eK=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function tK(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function nK(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=$G(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:JG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function rK(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function iK(e){let t=rK(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return nK(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function aK(e){let t=[];for(let n of e.split(`
|
|
191
191
|
`)){let e=iK(n);e&&t.push(e)}return t}function oK(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function sK(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function cK(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Ga(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=oK(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,Ka(c,e=>aK(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var lK=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}},uK=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>wG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,xG(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:vG(),holders:0,flight:null,changed:!1,superseding:0,revisit:dK(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();pK(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{bG(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),SG(e,I(`${this.spec.name} entry dropped`))}};function dK(e,t){if(e===null)return new fK(t.holdReturned);let n=new _G(t.period);return{landed:t=>n.landed(gG(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var fK=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function pK(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function mK(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const hK={okMs:60*1e3,failedMs:10*1e3},gK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},_K={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function vK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function yK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function bK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const xK={entries:0,cost:0,breakdown:bK(),days:new Map};async function SK(e,t){let n=vK(new Date(yK())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await UG.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=vK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...gK};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function CK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function wK(e){let t=0,n=0,r=bK(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...gK};CK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:_K,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function TK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function EK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!TK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...gK};CK(r,t),n.set(e,r)}return n}async function DK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function OK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function kK(e,t){(0,J.runInAction)(()=>e.set(t))}var AK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new lK;scans;daySets=new Map;speedFlight=new lK;requestFlight=new lK;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Pe,this.ledger=e.ledger??new Bk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new uK({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${L(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??hK,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Fa(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:P(OK(t.kind===`ok`?t.value.sessionInfo:_K,e))},speed:t=>this.observed(e,r,t),today:async e=>{await OG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Ma;let r=n.failure.get();return r===null?P(OK(n.record?.sessionInfo??_K,t)):I(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${L(e)}`,`request`,a,Date.now()-i),kK(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=YG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=vK(mk(n)),o={...gK},s=e.sums.get(a);s!==void 0&&CK(o,s);let c=TK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&CK(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return F;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return kK(this.hold(e).speed,t),t;let r=mK(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=P({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return kK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Ma:F}async ingest(e,t,n,r){if(!e)return F;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,P(i);if(!t)return i?P(i):F;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),P(c)):l===void 0?P(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new fS(`today over ${e.join(`,`)}`,()=>EK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await QG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of sK(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await cK(e,r,xK,SK);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of sK(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...wK(i),mainStamp:a})}async scan(e){try{let t=yK(),n=await XG(e),r=[];for(let e of n){let n=await ZG(za(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await ZG(Ba(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ia(a)})}}let i=[],a={hits:0,misses:0};return await DK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${L(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=vK(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},jK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},MK=class{sessions;constructor(e,t,n,r=Pe,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new jK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Fa(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await cK(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${L(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of sK(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Ma}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function NK(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var PK=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new MK(void 0,NK,(e.ledger??new Bk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,FK(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,FK(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function FK(e){return e.context_window?.context_window_size??2e5}const IK={messageCount:0,nonPrompts:0,recent:[]},LK=new Set([`turn`,`interrupt`,`claude-code`]);function RK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!LK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function zK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var BK=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new MK(IK,RK,(e.ledger??new Bk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?VK(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:VK(e,n,r)}};function VK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:zK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const HK={command:null,todos:[],pending:[],done:[]};function UK(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function WK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function GK(e,t){if(t.isSidechain)return e;let n=WK(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=UK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function KK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>UK(e,t.name),[]),done:e.done}}var qK=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new MK(HK,GK,(e.ledger??new Bk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return JK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:JK(e,t)}};function JK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(KK(t.value))}function YK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function XK(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function ZK(e,t,n,r){return XK(gt(YK(e,t,n,r)),n)}async function QK(e,t,n,r){return XK(await ht(YK(e,t,n,r)),n)}const $K=3e4;var eq=class{names;constructor(e={}){let t=e.logger??Pe;this.names=new uK({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${L(e.pane)} socket=${L(e.socket)}`,read:tq,every:{okMs:$K,failedMs:$K},maxEntries:64,logger:t,ledger:e.ledger??new Bk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function tq(e){let t=await QK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}const nq=6e4,rq={okMs:nq,failedMs:nq};function iq(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function aq(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var oq=class{name;user;constructor(e={}){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:rq,maxEntries:1,logger:t,ledger:e.ledger??new Bk(t)};this.name=new uK({...n,name:`host.name`,read:()=>aq(`name`,()=>iq(C.hostname()))}),this.user=new uK({...n,name:`host.user`,read:()=>aq(`user`,()=>C.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},sq=class{known=new jK(64);refreshes;constructor(e=Pe,t=new Bk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=cq(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=wP(e);return this.refreshes.recorded(`path=${L(e)} stamp=${L(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Ma}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function cq(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ia(t)}catch(e){return`unread:${e.code??`error`}`}}const lq=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function uq(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var dq=class{known=new jK(256);refreshes;constructor(e=Pe,t=new Bk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Fa(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Ma}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await fq(t);return this.refreshes.recorded(`sid=${L(e)} stamp=${L(n)}`,`request`,i,Date.now()-r),i}};async function fq(e){let t=await pq(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function pq(e){for(let t of[65536,1048576]){let n=await Ya(e,t);if(n.kind!==`ok`)return n;let r=mq(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function mq(e,t){let n=e.toString(`utf8`).split(`
|
|
192
192
|
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!lq.test(t))continue;let r=uq(t);if(r!=null)return r}return null}var hq=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const gq=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},_q=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,vq=e=>dV(e),yq=e=>s.join(e.storage.folder,vq(e.sessionId)),bq=e=>JSON.stringify([e.folder,e.generation]),xq=(e,t)=>e.folder===t.folder&&e.generation===t.generation,Sq=(e,t)=>`cannot refresh: ${e.folder}: its watch has delivered no event since ${new Date(t).toISOString()}, not even for the files the daemon wrote there to test it; the OS is not delivering its file events`;var Cq=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;stalls=0;probes=0;probeFailures=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??gq,this.sessions=new uK({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${L(yq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Bk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!_q(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${L(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(bq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost,stalled:[...this.watched.values()].filter(e=>e.health.kind!==`faulted`&&e.delivery.kind===`stalled`).length,stalls:this.stalls,probes:this.probes,probeFailures:this.probeFailures}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${bq(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),probe:setInterval(()=>void this.tick(i),3e4),health:{kind:`watching`},delivery:{kind:`delivering`,unreported:[]}};i.sweep.unref(),i.probe.unref(),this.watched.set(bq(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return this.sweep(e),this.tick(i),i}closed(e){let t=bq(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),clearInterval(e.probe),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>xq(e.storage,n);switch(t.kind!==`failed`&&this.delivered(e),t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(vq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&_q(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${L(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>xq(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${L(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>xq(e.storage,r)))}async tick(e){if(this.judged(e,()=>this.stalled(e)),e.health.kind!==`watching`)return;let t=Date.now();this.awaiting(e,e=>[...e,t]);try{await p.promises.writeFile(s.join(e.key.folder,`.cc-candybar-watch-probe`),String(t)),this.probes++}catch(n){this.awaiting(e,e=>e.filter(e=>e!==t)),this.probeFailures++,this.logger(`warn`,`plugin storage probe failed folder=${L(e.key.folder)} generation=${e.key.generation} reason=${JSON.stringify(n.message)}`)}}awaiting(e,t){let{delivery:n}=e;n.kind!==`stalled`&&(e.delivery={kind:`delivering`,unreported:t(n.unreported)})}stalled(e){let{delivery:t}=e;if(t.kind===`stalled`||t.unreported.length<2)return;let n=t.unreported[0];e.delivery={kind:`stalled`,since:n},this.stalls++,this.logger(`warn`,`plugin storage stalled folder=${L(e.key.folder)} generation=${e.key.generation} since=${new Date(n).toISOString()}`),this.sessions.changed(t=>xq(t.storage,e.key))}delivered(e){let{delivery:t}=e;e.delivery={kind:`delivering`,unreported:[]},t.kind===`stalled`&&(this.logger(`info`,`plugin storage recovered folder=${L(e.key.folder)} generation=${e.key.generation} stalled=${Date.now()-t.since}ms`),this.sessions.changed(t=>xq(t.storage,e.key)))}standing(e){let t=this.watched.get(bq(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:return t.delivery.kind===`stalled`?Sq(e,t.delivery.since):null;case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return I(t);let n=yq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Lk(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${L(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&vq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function wq(e){let{logger:t,ledger:n}=e;return{hostService:new oq({logger:t,ledger:n}),gitProvider:new BG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new AK({logger:t,ledger:n}),contextProvider:new PK({logger:t,ledger:n}),metricsProvider:new BK({logger:t,ledger:n}),activityProvider:new qK({logger:t,ledger:n}),tmuxService:new eq({logger:t,ledger:n}),autoCompact:new sq(t,n),cacheExpiry:new dq(t,n),managedStorage:new Cq({watchers:e.watchers,logger:t,ledger:n}),faults:new hq,log:e.logger}}function Tq(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&D(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const Eq=`repo-configs.json`;function Dq(e=Ct()){return s.join(e,Eq)}const Oq=(e=Ct())=>Tq(e,Eq,{},eH);function kq(e,t,n){return{sessionId:e,action:pi,declaration:t,evaluated:n}}function Aq(e,t,n){return e.awaiting.map(e=>{let r=`${e} has a cc-candybar config — run it?`,i=XV.map(r=>wb(`[${r===`approved`?`approve`:`decline`}]`,_i([{verb:pi,args:[t,e,r,n.sign(kq(t,e,r))]}])));return{severity:Sb,message:r,lines:[[wb(r,_i([{verb:qr,args:[r]}])),...i]]}})}function jq(e){return Math.max(1,e-2)}function Mq(e,t,n){return Re({dir:e.project_dir,env:n===void 0?[]:[[Za,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function Nq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function Pq(e){return{...Object.fromEntries(_y.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:KH(e.preset)}}}const Fq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function Iq(e,t){if(!t)return`-`;if(Na(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return Na(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const Lq=10*1e3;function Rq(e,t){if(!(t<60))return e*3600/t}function zq(e,t,n,r){let i=r-t;if(i<50||i>Lq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Bq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=zq(t.input,t.atMs,n.input,n.atMs),i=zq(t.output,t.atMs,n.output,n.atMs),a=zq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function Vq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>Lq)continue;let o=zq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Hq(e,t){let n=cx(e,t),r=[...qg.flatMap(e=>{let t=n[e];return Jg(t)?[t]:[]})];for(let n of A_(sx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...Uq(e,n.name));return Gq(e,r)}function Uq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function Wq(e,t,n){return Gq(e,[...Uq(e,t),...n])}function Gq(e,t){let n=pB(e),r=new Map(Jx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=dB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Kq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=Hq(e,n);return t.set(n,i),i}}function qq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Jq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(Fq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Yq=new WeakMap;function Xq(e){let t=Yq.get(e);return t===void 0&&(t=Zq(e),Yq.set(e,t)),t}function Zq(e){let t=t=>qq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function Qq(e){return jq(e.termCols??120)}function $q(e){return eo($a(e.claudeConfigDir))}function eJ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function tJ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Xq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(mk(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window($q(a)))])}function nJ(e,t){return[...t.keys()].filter(t=>e.has(t))}function rJ(e,t){let n=DG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function iJ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Jq(n),t.workspace?.project_dir]}function aJ(e,t,n,r,i){let a=Xq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return DG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),DG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...iJ(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(nJ(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function oJ(e){let{hookData:t,deps:n}=e,r=Xq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored($q(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function sJ(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function cJ(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Xq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return Ma;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?Ma:xJ(n.git,()=>Ma),m=n.tmuxSession.kind===`pending`?Ma:d(n.tmuxSession),h=n.hostName.kind===`pending`?Ma:d(n.hostName),g=n.hostUser.kind===`pending`?Ma:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?Ma:gJ(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?Ma:dJ(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,fJ),x=u(n.usage,e=>yJ({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>yJ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,_J),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=bJ(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:bJ(r.workspace.current_dir)??``,project_dir:bJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>bJ(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...Pq(a),history:t.history,navigation:{back:t.back},term:{cols:Qq(i)},...c,...s!==null&&{configPath:s},resumeCommand:Mq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:uJ(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Ma:t})}}function lJ(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function uJ(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function dJ(e,t){let n=e!=null&&t!=null?Rq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function fJ(e){let t=Bq(e),n=Vq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function pJ(e,t){return cJ(e,t,oJ(e))}function mJ({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return Ma;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?Ma:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function hJ(e,t,n){await tJ(e,t,n),await TG(()=>{let t=sJ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function gJ(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return TP(e.value,t)}}function _J(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=vJ(e.running),i=vJ(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function vJ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function yJ(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function bJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function xJ(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(jW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:MW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function SJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const CJ={kind:`hidden`},wJ={kind:`shown`};function TJ(e,t){try{return SJ(e,t)?wJ:CJ}catch(e){let t=lS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function EJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function DJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function OJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function kJ({text:e,placement:t,lead:n,trail:r}){return{text:AJ(e),placement:t,...n!==void 0&&{lead:AJ(n)},...r!==void 0&&{trail:AJ(r)}}}function AJ(e){let t=e.blankCopy(e.plain);t.style=Ky(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Ky(i).clearMetaAndLinks(),n,r);return t}function jJ(e){let t=OJ(e);if(t.length===1)return e.text;let n=EJ(t);return n.style=e.text.style,n}function MJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=EJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:EJ([d,...c],a)},...l.length>0&&{trail:EJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(DJ(u,n,p),[{text:u,...f}])}const NJ=RegExp(`\\x1b\\[[0-9;]*m|${tf.source}`,`g`);function PJ(e){return Math.max(0,...e.split(`
|
|
193
193
|
`).map(e=>Ks(e.replace(NJ,``))))}function FJ(e,t){let n=()=>e.map(e=>({owner:jJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=_b(e.map(jJ),t).split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptctl/cc-candybar",
|
|
3
|
-
"version": "1.160.
|
|
3
|
+
"version": "1.160.9",
|
|
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",
|
|
@@ -102,9 +102,9 @@
|
|
|
102
102
|
"typescript": "^5.0.0"
|
|
103
103
|
},
|
|
104
104
|
"optionalDependencies": {
|
|
105
|
-
"@promptctl/cc-candybar-darwin-arm64": "1.160.
|
|
106
|
-
"@promptctl/cc-candybar-darwin-x64": "1.160.
|
|
107
|
-
"@promptctl/cc-candybar-linux-arm64": "1.160.
|
|
108
|
-
"@promptctl/cc-candybar-linux-x64": "1.160.
|
|
105
|
+
"@promptctl/cc-candybar-darwin-arm64": "1.160.9",
|
|
106
|
+
"@promptctl/cc-candybar-darwin-x64": "1.160.9",
|
|
107
|
+
"@promptctl/cc-candybar-linux-arm64": "1.160.9",
|
|
108
|
+
"@promptctl/cc-candybar-linux-x64": "1.160.9"
|
|
109
109
|
}
|
|
110
110
|
}
|