@promptctl/cc-candybar 1.155.1 → 1.155.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +4 -4
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,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,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){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()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(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 Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.155.1`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`0d50a47e644047e46ab0d765857879dbb6d42b468c4ba6b36c2f561e10c2ecf8`}function Ze(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 Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.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 rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(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 ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(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),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(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:$e(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 ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.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:$e(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 ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(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 O(e,t,n){let r=pt(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 pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(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 xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){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 Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(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&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(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 Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[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,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){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()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(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 Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.155.2`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`10532d8ba03382a96c64bc6cc44cb3c8752f8e03051207351fe9557b26b4fda7`}function Ze(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 Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.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 rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(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 ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(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),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(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:$e(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 ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.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:$e(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 ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(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 O(e,t,n){let r=pt(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 pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(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 xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){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 Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(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&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(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 Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[t](n.join(`, `))]});return t.length===0?null:t.join(`
3
3
  `)}function Wt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Mt.filter(e=>t[e]!==void 0);return n.every(e=>Gt(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function A(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Pt.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 Gt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Kt(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 Jt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>qt?qt:t}function Yt(e){return typeof e==`boolean`?e:void 0}function Xt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var j=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Zt(e){return Qt(JSON.stringify(e))}function Qt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function $t(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 j(`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 j(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function en(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),c=$t(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(Zt(t))})}function tn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Gt(n);return It.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function nn(e,t,n){let r=null;try{r=await cn(vt(),t.connectMs);let i=await en(r,{v:3,...e},t.budgetMs);return on(e.kind,i,n)}catch(e){return sn(e)}finally{r&&r.destroy()}}function rn(e,t){return typeof e==`string`?e:t}function an(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function on(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=rn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:an(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 sn(e){if(e instanceof j||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 cn(e,t){return new Promise((n,r)=>{let i=E.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 ln(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 un={connectMs:50,budgetMs:150},dn={connectMs:50,budgetMs:200};function fn(e){let t=e.output;return typeof t==`string`?t:void 0}function pn(e){return on(`render`,e,fn)}function mn(e,t,n,r){return nn({kind:`render`,hookData:e,args:t,cwd:n,...r},un,fn)}function hn(e,t){return nn({kind:`pane-session`,socket:e,pane:t},dn,e=>`paneSession`in e?e.paneSession:void 0)}function gn(e,t){return nn({kind:`click`,verb:e,value:t,clientVersion:qe},dn,fn)}let _n=null;function vn(e){if(_n!==null)return _n;p.mkdirSync(s.dirname(e),{recursive:!0});try{_n=p.statSync(e).size}catch{_n=0}return _n}function yn(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,r=`${e}.${t+1}`;try{p.renameSync(n,r)}catch{}}try{p.renameSync(e,`${e}.1`)}catch{}_n=0}function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=jt(),t=vn(e);p.appendFileSync(e,n),_n=t+Buffer.byteLength(n,`utf8`),_n>=5242880&&yn(e)}catch(e){_n=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const bn=5e3;function xn(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 Sn=`/usr/bin/footprint`;function Cn(e,t){return e===`darwin`?[En(Sn,[`-p`,String(t)]),En(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Dn(`/proc/self/smaps_rollup`),Dn(`/proc/self/status`)]:[]}function wn(e,t){return e===`darwin`?Tn(t,e=>lt({bin:Sn,args:e,timeoutMs:bn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Tn(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}`}${On(r.stderr)}`};let i=N(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 N(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function En(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=ut({bin:e,args:[...t],timeoutMs:bn,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}`}${On(n.stderr)}`}}}}function Dn(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 On(e){let t=e.split(`
5
5
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const kn=`CC_CANDYBAR_RSS_LIMIT_MB`;function An(e){let t=e[kn];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${kn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function jn(e){return An(e)*2}const Mn=1024*1024,Nn=e=>Math.round(e/Mn);function Pn(e){return An(e)*Mn}const Fn={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function In(e,t){return e>t}function Ln(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}}function Rn(e,t){return e>t*.75}function zn(e,t,n){let{prefix:r,suffix:i}=Fn[t];return s.join(e,`${r}${n}${i}`)}function Bn(e){for(let t of Object.keys(Fn)){let{prefix:n,suffix:r}=Fn[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Vn(e){let t=e.limitBytes??512*Mn,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=Ln(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${Wn(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${Hn(s)} > limit ${Nn(t)} MB (rss ${Nn(a)} MB, v8 heap ${Nn(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return Gn(e.log,`memory report`,()=>{let t=zn(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Gn(e.log,`heap snapshot`,()=>{let t=zn(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Gn(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of Kn(e.listArtifacts()).slice(n))for(let n of Object.values(t))Gn(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&Rn(i.charge.bytes,t)?`${Hn(i.charge)} approaching limit ${Nn(t)} MB (v8 heap ${Nn(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:Kn(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 Hn(e){return e.kind===`charged`?`${e.measure} ${Nn(e.bytes)} MB`:`rss ${Nn(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Nn(e.gap)} MB gap`} (standing in: ${e.unread})`}function Un(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Wn({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Nn(e.gap)}MB`:``;return`measure=${Un(e)} charge=${Nn(e.bytes)}MB rss=${Nn(t)}MB heap=${Nn(n)}MB limit=${Nn(r)}MB${i}`}function Gn(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Kn(e){let t=new Map;for(let n of e){let e=s.basename(n),r=Bn(e);if(r===null)continue;let{prefix:i,suffix:a}=Fn[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Fn);return[...t].sort(([e],[t])=>In(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function qn(e,t,n={}){let r=_t();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:wn(process.platform,process.pid),captureMemoryReport:()=>xn(Cn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>se.writeHeapSnapshot(e),listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Bn(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function Jn(e={}){if(ur()!==null)return;let n=e.spawn??dr,r=sr();if(r.kind===`contended`){let e=Xn();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Yn(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Yn(n);return}try{Yn(n)}finally{lr()}}function Yn(e){rr()&&Zn(e)}function Xn(){try{let e=p.statSync(Dt());return Date.now()-e.mtimeMs}catch{return null}}function Zn(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -73,7 +73,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
73
73
  `,1)[0]??``}function ND(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function PD(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const FD={github:`gh`,gitlab:`glab`};function ID(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const LD=/^[A-Za-z]:[\\/]/;function RD(e){let t=e.trim();if(LD.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 zD(e){return RD(e)?.host||null}function BD(e){let t=zD(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const VD=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function HD(e){let t=AD(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?UD(t.value):[]}}function UD(e){let t=new Map;for(let n of e.split(`
74
74
  `)){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 WD(e){return e.urls.find(e=>YD(e)!==null)??e.urls[0]??null}function GD(e){return e.find(e=>e.name===`origin`)??e[0]??null}function KD(e){let t=GD(e);return t?WD(t):null}function qD(e){let t=GD(e);return t?t.urls.find(e=>BD(e)!==null)??WD(t):null}function JD(e){let t=(RD(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function YD(e){let t=RD(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 XD(e){let t=KD(e);return t===null?null:YD(t)}function ZD(e,t,n,r){return t.ok?r(t.stdout):ID(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??MD(t.stderr)].filter(Boolean).join(`, `)}`)}function QD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $D(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
75
75
  `)){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)`?I:F(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=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({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 eO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!QD(t))return L(`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 L(`gh pr view: missing number/state/url/headRefOid`);let o=kD(`gh pr view`,DD,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function tO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!QD(t))return L(`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 L(`glab mr view: missing iid/state/web_url/sha`);let o=kD(`glab mr view`,OD,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function nO(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var rO=class{isGitRepo(e){return SD(e)}async execGitAsync(e,t){return lt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}async findGitRoot(e){let t=CD(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`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=await 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=ND(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(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=ND(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=ND(s,XD)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(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`))?F(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return PD(AD(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(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.readCommitTimestampMs(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 readCommitTimestampMs(e,t){let n=PD(AD(`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)*1e3;return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`):F(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return F(r?r.split(`
76
- `).length:0)}async getRemotesAsync(e){let t=nO(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 HD(await this.execGitAsync(VD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=KD(e);return(n===null?null:JD(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=qD(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=BD(t);return n===`github`?ZD(`gh pr view`,await this.execForgeAsync(FD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,eO):n===`gitlab`?ZD(`glab mr view`,await this.execForgeAsync(FD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,tO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=AD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F($D(t.value)):t}};const iO=(e,t)=>D(t);var aO=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??iO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,r.lastTouched=Date.now(),this.slots.delete(e),this.slots.set(e,r),this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t,lastTouched:Date.now()};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.evictIfNeeded(),this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}evictIfNeeded(){for(;this.slots.size>this.maxWatchers;){let e=this.slots.keys().next().value;if(e===void 0)break;let t=this.slots.get(e);this.closeSlot(t),this.slots.delete(e),this.counters&&this.counters.watchersEvicted++;try{t.onInvalidate()}catch{}this.logger(`info`,`watcher LRU evict ${e}`)}}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},oO=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const sO={showSha:!0,showStashCount:!0};function cO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function lO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function uO(e,t){return e.head!==t.head||e.index!==t.index}function dO(e){let t=[],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[s.join(e,`HEAD`),s.join(e,`index`)],dirs:t}}var fO=class extends rO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new oO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new rO,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new aO({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){return{size:this.entries.size,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${cO(t)}`,r=Date.now(),i=this.entries.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(F(i.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=lO(i),o=await this.inner.getGitInfo(e,n);if(o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch)),this.dropEntry(t);let c=this.watchers.acquire(`git:${e}`,dO(i),()=>this.invalidateRepo(e));return this.entries.set(t,{info:s,computedAt:r,mtime:a,watcher:c,repoRoot:e}),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return I;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,dO(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...sO});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(r.watcher.release(),this.entries.delete(n),t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} dropped=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...sO}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){let n=e.get(t.repoRoot);n||(n=lO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),uO(t.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const pO=/\r\n|\r|\n/g,mO=e=>F(e.replace(pO,` `).trim());function hO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(pO,` `))}}const gO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}},_O=e=>e.getTime()/1e3,vO=e=>new Date(e*1e3);function yO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function bO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const xO=`session.id`;function SO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function CO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function wO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const TO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],EO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],DO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],OO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function kO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>TO[e.getMonth()]],[`Monday`,e=>DO[e.getDay()]],[`Jan`,e=>EO[e.getMonth()]],[`Mon`,e=>OO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const AO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function jO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=AO[t];try{return zO(r,e)}catch{return BO(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function MO(e){try{return b(e)}catch{return e}}function NO(e){try{return ee(e).isDirectory()}catch{return!1}}function PO(e){let t=MO(e);return NO(t)?{dir:t,name:null,leaf:!0}:_b(t)}const FO=e=>`${e.dir}\0${e.name??``}`;var IO=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:PO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=PO(e);if(t.watcher!==null&&FO(n)===FO(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},LO=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function RO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function zO(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?wb(e):t===`number`?Tb(e):Eb(e)}function BO(e){return e===`number`?0:e===`boolean`?!1:``}var VO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new IO;ttlMgr=new LO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new oO;abort=new AbortController;drawn=xb.observable.box(B.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=xb.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return vO(e)};engine=_D({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new fO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Cb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,SO(t,n.cwd,this.abort.signal),yO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,CO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,mO,t.default,n);case`regex`:return this.scalarPublisher(e,hO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=wO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=wO(s,gO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(vD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>kO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Ob(t)?new Db(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=AO[t.field],r=t.varDefault===void 0?BO(n):zO(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,jO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(xO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(xO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=RO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,zO(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(vD(this.store)).map(e=>e.plain).join(``))}catch(e){return Ob(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,xb.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,xb.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,zO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,BO(t))}}defaultFor(e){try{return zO(this.defaultEmptyValue,e)}catch{return BO(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function HO(e,t){let n=X_[e],r=iv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const UO=Object.fromEntries([...fv].map(([e,t])=>[t,HO(e,t)])),WO={subscribers:`number`,fps:`number`,shown:`boolean`},GO=Object.keys(WO),KO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[xO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...UO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(E_.flatMap(e=>GO.map(t=>[A_(e,t),{kind:`input`,path:A_(e,t),type:WO[t],default:k_[t]}]))),[O_(`by`)]:{kind:`input`,path:O_(`by`),default:D_.by},[O_(`fps`)]:{kind:`input`,path:O_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},qO=`ne .tmux.pane ""`;function JO(e,t,n){let r=new Set,i=e=>{for(let t of sb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of _g(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(xO);for(let t of Object.values(e.actions)){r.add(xO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?pv.get(t.set):void 0,n=`persist`in t?fv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function YO(e,t,n){let r=hb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of JO(e,t,n.helpers)){if(mb(a,r))continue;let e=KO[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function XO(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ZO=`groups.`,QO=`menus.`,$O=`edit.`,X=`candybar.`,ek=[ZO,QO,$O,X];function tk(e){return ek.some(t=>e.startsWith(t))}function nk(e){let t=XO(e);return ek.find(e=>t.startsWith(XO(e)))}function rk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function ik(e){return e}function ak(e,t,n){return n===void 0?QO+XO(e)+`.`+XO(t):ok(n)}function ok(e){return QO+XO(e)}function sk(e,t){return e+`.`+t}function ck(e){return e+`.page`}const lk=[`closeOnPick`,`paged`,`key`,`distribution`],uk=e=>lk.includes(e),dk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Am.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function fk(e){for(let t of Object.keys(e))if(!uk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${dk}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!jm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Am.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Nm(r)}}const pk=e=>`from`in e?e.from:e.themes;function mk(e,t,n){return e===`bool`?lg(t)!==null:`min`in e?ug(t,e)!==null:Ky(pk(e),n).members.includes(t)}function hk(e,t){if(e===`bool`)return sg.join(` or `);if(!(`min`in e)){let n=pk(e),{members:r}=Ky(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function gk(e){return{label:e.label,domain:_k(e.domain)}}function _k(e){return e===`theme`?{themes:Uy}:e===`bool`||`min`in e?e:{from:e}}function vk(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...sg]}},variables:{}};if(`from`in o)return yk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return yk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function yk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=sk(n,t),s=`${t}.open`,c=ck(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const bk=Object.fromEntries(Object.entries(X_).map(([e,t])=>[e,t.spec]));function xk(e){return X_[e].domain}function Sk(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function Ck(e){return Sk(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function wk(e){return Sk(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function Tk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Lh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Ek={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Dk={noun:`globals key`,fields:bk,removed:Ek},Ok={preset:Ck(`a preset`),menuGlyph:wk(`a preset`)},kk={noun:`preset globals key`,fields:{...bk,...Ok},removed:Ek};function Ak(e){return Bk(e)&&!(e in Ok)}const jk=`is decided later than any rule could be settled`,Mk={noun:`editGlobals key`,removed:Ek,fields:{...bk,preset:Ck(`the editGlobals fragment`),menuGlyph:wk(`the editGlobals fragment`),palette:Tk(bk.palette,`the editGlobals fragment`,jk),style:Tk(bk.style,`the editGlobals fragment`,jk),effect:Tk(bk.effect,`the editGlobals fragment`,jk)}},Nk={noun:`theme default key`,fields:{...Object.fromEntries(ev.map(e=>[e,bk[e]])),style:Tk(bk.style,`a theme's default`,`is the look that theme wears by name`)}};function Pk(e,t){if(!Qg(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${$g(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Oh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=e_(e,Nk,t,i);a!==null&&(n[r]=a)}return n}function Fk(e,t,n){return n===void 0?{}:e_(e,Dk,t,n)??{}}function Ik(e,t,n){return e_(e,kk,t,n)??{}}function Lk(){return x_(kk)}function Rk(e,t,n){return e_(e,Mk,t,n)??{}}const zk=new Set(Object.keys(bk));function Bk(e){return zk.has(e)}function Vk(e){return Object.hasOwn(Ek,e)?Ek[e]:void 0}function Hk(){return[...zk]}const Uk=new Map(Object.entries(X_).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Wk(e){let t=new Map;for(let[n,r]of Uk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Gk=/^segments\.([^.]+)\.palette$/,Kk=/^presets\.(.+)\.root$/,qk=/^presets\.(.+)\.globals\.([^.]+)$/,Jk=/^themeDefaults\.(.+)\.([^.]+)$/;function Yk(e){return`presets.${e}.root`}function Xk(e,t){return`themeDefaults.${e}.${t}`}const Zk=e=>ev.includes(e);function Qk(e,t){return`presets.${e}.globals.${t}`}function $k(e){if(Bk(e))return{scope:`globals`,field:e};let t=Gk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=qk.exec(e);if(n&&Ak(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=Jk.exec(e);if(r&&Zk(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Kk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function eA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const tA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],nA=[...tA,`other`],rA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},iA=xS({fromString:e=>e}),aA=`edit.mode`,oA=`edit.configure`,sA=`edit.toggle`,cA=`edit.unconfigure`,lA=[sA,cA],uA=`arrange`,dA=`${$O}draft.`;function fA(e,t){return`${e}:${t}`}const pA={variable:aA,key:aA,member:uA},mA=$r(pA);function hA(e){try{return iA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function gA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&hA(e))return!0;return!1}function _A(e,t){if(rk(e,t,$O,`edit mode`),!gA(t))return;let{variables:n,actions:r}=vA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function vA(){return{variables:{[aA]:ii(aA,P),[oA]:ii(oA,P)},actions:{[sA]:ai(aA,uA),[cA]:{set:oA,to:P}}}}const yA=`open`;function bA(e,t,n,r){let i={variable:e,key:e,member:yA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,yA),r.segments[e]={template:ti(e,`(?)`,`✕`),...xA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function xA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const SA=`none`;function CA(e){return Pc(e,`background`)}var wA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function TA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=EA(n,i),l=c!==SA,u=l?c===void 0?o:DA(a,c,`bg`):CA(a);e.bg=u;let d=EA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:DA(a,d,`fg`);return new H({...l&&{bgcolor:V.fromRgba(u)},...f!==void 0&&{color:V.fromRgba(f)}})}function EA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function DA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new wA(t,n,e.message):e}}const OA=`🔧`,kA={help:[`-h`,`--help`],version:[`-V`,`--version`]},AA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],jA=Object.fromEntries(AA.map(e=>[e.member,e.label])),MA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},NA=Object.keys(MA),PA=mv(e=>sv[e].place),FA=e=>Object.hasOwn(MA,e),IA=e=>FA(e)?IA(PA[MA[e].beside]):e,LA=e=>FA(e)?`${LA(PA[MA[e].beside])} › ${MA[e].trigger}`:e===`door`?`first line`:jA[e],RA=e=>LA(PA[e]),zA=e=>`${T_[e].label} is off — turn it on in the settings menu's ${RA(T_[e].setting)}, or set globals.${T_[e].setting}: true`,BA=[...new Set(Object.values(T_).map(e=>RA(e.setting)))].join(` or `),VA=[`✚ inserts`,`✖ removes`,`${OA} configures`,`↺ resets layout`],HA={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},UA=`
76
+ `).length:0)}async getRemotesAsync(e){let t=nO(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 HD(await this.execGitAsync(VD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=KD(e);return(n===null?null:JD(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=qD(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=BD(t);return n===`github`?ZD(`gh pr view`,await this.execForgeAsync(FD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,eO):n===`gitlab`?ZD(`glab mr view`,await this.execForgeAsync(FD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,tO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=AD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F($D(t.value)):t}};const iO=(e,t)=>D(t);var aO=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??iO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),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()}},oO=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const sO={showSha:!0,showStashCount:!0};function cO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function lO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function uO(e,t){return e.head!==t.head||e.index!==t.index}function dO(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{files:[],dirs:t}}var fO=class extends rO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new oO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new rO,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new aO({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.entries.values())t.value.kind===`expired`&&e++;return{size:this.entries.size,expired:e,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${cO(t)}`,r=Date.now(),i=this.entries.get(n);if(i?.value.kind===`fresh`&&r-i.value.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(F(i.value.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=lO(i),o=await this.inner.getGitInfo(e,n);if(o.kind===`absent`&&this.dropRepo(e),o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch));let c={kind:`fresh`,info:s,computedAt:r,mtime:a},l=this.entries.get(t)??{value:c,watcher:this.watchers.acquire(`git:${e}`,dO(i),()=>this.invalidateRepo(e)),repoRoot:e};return l.value=c,this.entries.delete(t),this.entries.set(t,l),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return I;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,dO(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...sO});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let n of this.entries.values())n.repoRoot===e&&n.value.kind===`fresh`&&(n.value={kind:`expired`},t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} expired=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...sO}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}dropRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(this.dropEntry(n),t++);t>0&&this.logger(`info`,`gitCache drop ${e} entries=${t}`)}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){if(t.value.kind===`expired`)continue;let n=e.get(t.repoRoot);n||(n=lO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),uO(t.value.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const pO=/\r\n|\r|\n/g,mO=e=>F(e.replace(pO,` `).trim());function hO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(pO,` `))}}const gO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}},_O=e=>e.getTime()/1e3,vO=e=>new Date(e*1e3);function yO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function bO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const xO=`session.id`;function SO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function CO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function wO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const TO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],EO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],DO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],OO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function kO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>TO[e.getMonth()]],[`Monday`,e=>DO[e.getDay()]],[`Jan`,e=>EO[e.getMonth()]],[`Mon`,e=>OO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const AO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function jO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=AO[t];try{return zO(r,e)}catch{return BO(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function MO(e){try{return b(e)}catch{return e}}function NO(e){try{return ee(e).isDirectory()}catch{return!1}}function PO(e){let t=MO(e);return NO(t)?{dir:t,name:null,leaf:!0}:_b(t)}const FO=e=>`${e.dir}\0${e.name??``}`;var IO=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:PO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=PO(e);if(t.watcher!==null&&FO(n)===FO(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},LO=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function RO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function zO(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?wb(e):t===`number`?Tb(e):Eb(e)}function BO(e){return e===`number`?0:e===`boolean`?!1:``}var VO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new IO;ttlMgr=new LO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new oO;abort=new AbortController;drawn=xb.observable.box(B.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=xb.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return vO(e)};engine=_D({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new fO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Cb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,SO(t,n.cwd,this.abort.signal),yO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,CO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,mO,t.default,n);case`regex`:return this.scalarPublisher(e,hO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=wO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=wO(s,gO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(vD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>kO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Ob(t)?new Db(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=AO[t.field],r=t.varDefault===void 0?BO(n):zO(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,jO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(xO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(xO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=RO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,zO(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(vD(this.store)).map(e=>e.plain).join(``))}catch(e){return Ob(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,xb.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,xb.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,zO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,BO(t))}}defaultFor(e){try{return zO(this.defaultEmptyValue,e)}catch{return BO(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function HO(e,t){let n=X_[e],r=iv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const UO=Object.fromEntries([...fv].map(([e,t])=>[t,HO(e,t)])),WO={subscribers:`number`,fps:`number`,shown:`boolean`},GO=Object.keys(WO),KO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[xO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...UO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(E_.flatMap(e=>GO.map(t=>[A_(e,t),{kind:`input`,path:A_(e,t),type:WO[t],default:k_[t]}]))),[O_(`by`)]:{kind:`input`,path:O_(`by`),default:D_.by},[O_(`fps`)]:{kind:`input`,path:O_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},qO=`ne .tmux.pane ""`;function JO(e,t,n){let r=new Set,i=e=>{for(let t of sb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of _g(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(xO);for(let t of Object.values(e.actions)){r.add(xO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?pv.get(t.set):void 0,n=`persist`in t?fv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function YO(e,t,n){let r=hb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of JO(e,t,n.helpers)){if(mb(a,r))continue;let e=KO[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function XO(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const ZO=`groups.`,QO=`menus.`,$O=`edit.`,X=`candybar.`,ek=[ZO,QO,$O,X];function tk(e){return ek.some(t=>e.startsWith(t))}function nk(e){let t=XO(e);return ek.find(e=>t.startsWith(XO(e)))}function rk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function ik(e){return e}function ak(e,t,n){return n===void 0?QO+XO(e)+`.`+XO(t):ok(n)}function ok(e){return QO+XO(e)}function sk(e,t){return e+`.`+t}function ck(e){return e+`.page`}const lk=[`closeOnPick`,`paged`,`key`,`distribution`],uk=e=>lk.includes(e),dk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Am.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function fk(e){for(let t of Object.keys(e))if(!uk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${dk}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!jm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Am.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Nm(r)}}const pk=e=>`from`in e?e.from:e.themes;function mk(e,t,n){return e===`bool`?lg(t)!==null:`min`in e?ug(t,e)!==null:Ky(pk(e),n).members.includes(t)}function hk(e,t){if(e===`bool`)return sg.join(` or `);if(!(`min`in e)){let n=pk(e),{members:r}=Ky(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function gk(e){return{label:e.label,domain:_k(e.domain)}}function _k(e){return e===`theme`?{themes:Uy}:e===`bool`||`min`in e?e:{from:e}}function vk(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...sg]}},variables:{}};if(`from`in o)return yk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return yk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function yk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=sk(n,t),s=`${t}.open`,c=ck(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const bk=Object.fromEntries(Object.entries(X_).map(([e,t])=>[e,t.spec]));function xk(e){return X_[e].domain}function Sk(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function Ck(e){return Sk(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function wk(e){return Sk(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function Tk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Lh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Ek={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Dk={noun:`globals key`,fields:bk,removed:Ek},Ok={preset:Ck(`a preset`),menuGlyph:wk(`a preset`)},kk={noun:`preset globals key`,fields:{...bk,...Ok},removed:Ek};function Ak(e){return Bk(e)&&!(e in Ok)}const jk=`is decided later than any rule could be settled`,Mk={noun:`editGlobals key`,removed:Ek,fields:{...bk,preset:Ck(`the editGlobals fragment`),menuGlyph:wk(`the editGlobals fragment`),palette:Tk(bk.palette,`the editGlobals fragment`,jk),style:Tk(bk.style,`the editGlobals fragment`,jk),effect:Tk(bk.effect,`the editGlobals fragment`,jk)}},Nk={noun:`theme default key`,fields:{...Object.fromEntries(ev.map(e=>[e,bk[e]])),style:Tk(bk.style,`a theme's default`,`is the look that theme wears by name`)}};function Pk(e,t){if(!Qg(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${$g(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Oh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=e_(e,Nk,t,i);a!==null&&(n[r]=a)}return n}function Fk(e,t,n){return n===void 0?{}:e_(e,Dk,t,n)??{}}function Ik(e,t,n){return e_(e,kk,t,n)??{}}function Lk(){return x_(kk)}function Rk(e,t,n){return e_(e,Mk,t,n)??{}}const zk=new Set(Object.keys(bk));function Bk(e){return zk.has(e)}function Vk(e){return Object.hasOwn(Ek,e)?Ek[e]:void 0}function Hk(){return[...zk]}const Uk=new Map(Object.entries(X_).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Wk(e){let t=new Map;for(let[n,r]of Uk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Gk=/^segments\.([^.]+)\.palette$/,Kk=/^presets\.(.+)\.root$/,qk=/^presets\.(.+)\.globals\.([^.]+)$/,Jk=/^themeDefaults\.(.+)\.([^.]+)$/;function Yk(e){return`presets.${e}.root`}function Xk(e,t){return`themeDefaults.${e}.${t}`}const Zk=e=>ev.includes(e);function Qk(e,t){return`presets.${e}.globals.${t}`}function $k(e){if(Bk(e))return{scope:`globals`,field:e};let t=Gk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=qk.exec(e);if(n&&Ak(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=Jk.exec(e);if(r&&Zk(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Kk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function eA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const tA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],nA=[...tA,`other`],rA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},iA=xS({fromString:e=>e}),aA=`edit.mode`,oA=`edit.configure`,sA=`edit.toggle`,cA=`edit.unconfigure`,lA=[sA,cA],uA=`arrange`,dA=`${$O}draft.`;function fA(e,t){return`${e}:${t}`}const pA={variable:aA,key:aA,member:uA},mA=$r(pA);function hA(e){try{return iA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function gA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&hA(e))return!0;return!1}function _A(e,t){if(rk(e,t,$O,`edit mode`),!gA(t))return;let{variables:n,actions:r}=vA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function vA(){return{variables:{[aA]:ii(aA,P),[oA]:ii(oA,P)},actions:{[sA]:ai(aA,uA),[cA]:{set:oA,to:P}}}}const yA=`open`;function bA(e,t,n,r){let i={variable:e,key:e,member:yA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,yA),r.segments[e]={template:ti(e,`(?)`,`✕`),...xA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function xA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const SA=`none`;function CA(e){return Pc(e,`background`)}var wA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function TA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=EA(n,i),l=c!==SA,u=l?c===void 0?o:DA(a,c,`bg`):CA(a);e.bg=u;let d=EA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:DA(a,d,`fg`);return new H({...l&&{bgcolor:V.fromRgba(u)},...f!==void 0&&{color:V.fromRgba(f)}})}function EA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function DA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new wA(t,n,e.message):e}}const OA=`🔧`,kA={help:[`-h`,`--help`],version:[`-V`,`--version`]},AA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],jA=Object.fromEntries(AA.map(e=>[e.member,e.label])),MA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},NA=Object.keys(MA),PA=mv(e=>sv[e].place),FA=e=>Object.hasOwn(MA,e),IA=e=>FA(e)?IA(PA[MA[e].beside]):e,LA=e=>FA(e)?`${LA(PA[MA[e].beside])} › ${MA[e].trigger}`:e===`door`?`first line`:jA[e],RA=e=>LA(PA[e]),zA=e=>`${T_[e].label} is off — turn it on in the settings menu's ${RA(T_[e].setting)}, or set globals.${T_[e].setting}: true`,BA=[...new Set(Object.values(T_).map(e=>RA(e.setting)))].join(` or `),VA=[`✚ inserts`,`✖ removes`,`${OA} configures`,`↺ resets layout`],HA={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},UA=`
77
77
  cc-candybar - Beautiful powerline statusline for Claude Code
78
78
 
79
79
  Usage: cc-candybar [options]
@@ -202,7 +202,7 @@ print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
202
202
  `)){n.push(r);continue}let e=r.split(`
203
203
  `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function $G(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function eK(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function tK(e){return{...e,cells:e.cells.map(CW)}}function nK(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,...rK(e,r)]}function rK(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function iK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:nK(e.direction,e.children.map((t,i)=>n(t,[...r,aK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function aK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:fg[e.direction]}}const oK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Nm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,vg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),nK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,aK(e,r))))}},sK={drop:e=>e.place,above:()=>`above`},cK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},lK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:pg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,yg(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,uK(e,t))};function uK(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=bD(t.scope,e.settings);if(t.gate.kind===`failed`)return dK(e,a,t,t.gate.message);try{if(!gW(i.when,a))return[];let n=hy(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:CA(n)},s=e.opens!==void 0&&gW(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:sK[g.placement](e)})),v=QG(AW(l,m)).map((e,t)=>({cells:EW(e,{...h,lead:t===0?AW(u,m):[],trail:t===0?AW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:EW(AW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>EW(AW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?cK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(SW(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],C=_.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...S,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(ne)].flatMap(SW)),[...re,...C]}catch(n){return dK(e,a,t,n.message??String(n))}}function dK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:EW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:CA(n.palette)},lead:fK(e.lead,e,t,n),trail:fK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function fK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const pK={container:oK,segment:lK};function mK(e){return pK[e]}function hK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:bO(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function gK(e,t){switch(Sg(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function _K(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:hK(n.cache),parse:gK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:hK(n.cache),parse:gK(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function vK(e,t){let n=rx.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function yK(e,t,n){let{compiled:r,loadWarnings:i}=xK(e,t,n.cwd,bK);return{...r,loadWarnings:i}}const bK=(e,t)=>TK(t);function xK(e,t,n,r){let i=SK(e),a=CK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:wK(e,t,n)}}function SK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of pv)n in t&&r.set(e,n);for(let[t,n]of Og(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function CK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function wK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{_K(t,i,a,n)}catch(e){r.push(`Variable "${i}": ${e.message??String(e)}`)}for(let[i,a]of Object.entries(e.segments))if(a.vars)for(let[e,o]of Object.entries(a.vars))try{_K(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function TK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>NW(n,`now`).registry.now(),i=()=>NW(n,`drawnAt`).registry.drawnAt(),a=pG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Iy(e.presets),l=nF(e),u=_D({extraFuncs:{...XW(n),...TG(n,a),...kG(n,a),...RG(n,a),...NG(n,a,r),...UG(n,a),...qG(o),...XG(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=vK(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map(t);n.compiled=LW(f,e.actions,h,l);let g=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};g[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let _=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},v=t=>{let r=Mg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Rg(t,e,a,t=>String(NW(n,`setting ${e}`).store.read(t.variable)))});return Object.freeze(i)},y=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:_(e.when,t,`when`),parse:(e,n)=>_(e,t,n),compileChild:y,placementSettings:v};return mK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=zy(e,t);b.set(t,y(n,r))}let ee=new Map(Ih.map(e=>[e,new Map])),x=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of x)for(let n of Ih){let r=t[n];if(!Lh(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:EK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function EK(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function DK(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function OK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Kh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Gh[e]}}function kK(e,t){return e.kind===`decided`?e.name:Gh[t]}function AK(e){return jK(e).filter(e=>!e.name.startsWith($O)).map(e=>e.id)}function jK(e){return e.kind===`container`?e.children.flatMap(jK):[e,...e.opens===void 0?[]:jK(e.opens.body)]}function MK(...e){return NK(...e).text}function NK(e,t,n,r,i,a,o,s,c=HB(e,()=>null,()=>!1)){try{var l=na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set;r.renderAt(a),r.drawAt(ng(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Gv(o),padding:o.padding,seamCols:Kv(o),look:void 0,layout:void 0};l.u(IW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Dm[c.variation],shade:Tm[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(kK(_,`palette`),kK(v,`style`),kK(y,`effect`)));let S=vD(n),te=zh(_,e=>{let n=DK(t,`palette`,e);return by(OK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=zh(v,n=>Hh(OK(`style`,DK(t,`style`,n),S,p),e.styles)),C=zh(y,e=>Xh(OK(`effect`,DK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=_y(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Lv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:eK,hold:tK});u?.clear();let w=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},T=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Eh(i,a,c),f=mG(t.activeSegment,e.name,e.id,i,d,l,u),p=TA(f,c,o.bg,o.fg,n),h=()=>ph(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)m.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:p,get trigger(){return QW(i,h().state,c)},get band(){return QW(i,h().plane,c)},get close(){return tG(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},oe=(e,t,r)=>{let i=t?yW(e.when,S):_W,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${AK(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:S,palette:ie,gate:a,padding:o.padding,region:r,perSegmentSink:u,onSegmentError:d,evaluateSegment:T,lookupSegment:w,renderChild:(e,t,n)=>oe(e,t,wh(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,Th(n)),closeDisclosure:e=>ZW(n,e),placed:ae.placed};return mK(e.kind).render(e,s)},E=t.roots.get(g);if(E===void 0)throw Error(`Preset "${g}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${Py}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=yW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(pF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return gW(t.segments[e.name].when,bD(S,e.settings))}catch{return!0}};h.layout=()=>iK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=pF(e);return r===void 0?[]:[{name:r,address:t,palette:hy(n.theme,ie)}]}));let ce=$G(oe(E,!0,Ch(ee))).map(({line:e,row:t})=>{let n=kW(e.cells,o);return Xv(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||jK(E).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:ce.map(e=>e.text).join(`
204
204
  `),motion:le}}catch(e){l.e=e}finally{l.d()}}function*PK(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*FK(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of Iy(e.presets)){for(let n of _g(zy(e,t).node))n.when!==void 0&&(yield n.when);let n=By(e,t);for(let e of Ih){let t=n[e];Lh(t)&&(yield t)}}for(let[,t]of PK(e))t.kind===`template`&&(yield t.template),wg(t)&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function IK(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function LK(e,t){let n=new Set,r=new Set,i=new Set;for(let e of FK(t)){for(let r of sb(e,t.helpers).keys())n.add(r);for(let{name:n}of db(e,t.helpers))r.add(n);for(let n of fb(e,t.helpers))i.add(n)}for(let[,e]of PK(t))if(wg(e)&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Iy(t.presets))for(let n of _g(zy(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>IK(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!tk(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(PK(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var RK=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,WK(e,t,n,`initial value`),this.cell=xb.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){WK(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},zK=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,xb.computed)(()=>{let e=n();return WK(this.name,this.type,e,`computed result`),e},{keepAlive:!0}),typeof this.cell.suspend_!=`function`)throw TypeError(`Variable "${e}": this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`Variable "${e}": this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}lastUpdatedMs(){return null}},BK=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=xb.observable.box(UK(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=UK(e);HK(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function VK(e){return JSON.stringify(e)}function HK(e,t){return VK(e)===VK(t)}function UK(e){return e.kind===`ok`?{kind:`ok`,value:Sb(e.value)}:e}function WK(e,t,n,r){let i=Cb(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var GK=class{nodes=xb.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new RK(e,t,n))}defineDocument(e,t){this.declare(e,new BK(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new zK(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,xb.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,xb.runInAction)(()=>n.set(t))}runInAction(e){(0,xb.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return VK(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,xb.runInAction)(()=>{for(let t of this.nodes.values())t instanceof zK&&(t.release(),e++)}),e}disposed=!1;requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}declare(e,t){if(this.disposed)throw Error(`Variable "${e}": cannot declare on a disposed store`);if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`);(0,xb.runInAction)(()=>this.nodes.set(e,t))}};function KK(e){return Math.floor(e/4)}function qK(e,{plugins:t,config:n}){let{checkout:r,loaded:i,dropped:a,unreached:o}=t,s=r===null?`-`:`${r.git?`git`:`dir`}:${r.root}`,c=e=>{let t=yz(e),r=t===void 0?void 0:n.variables[xz(t)];return r?.kind===`file`?r.path:`none`};return`config load ${e.join(` < `)||`<default>`}: plugins loaded=${i.length} dropped=${a.length} unplaced=${o.length} checkout=${s}`+i.map(e=>` +${e} data=${c(e)}`).join(``)+a.map(e=>` -${e.path} (${e.reason})`).join(``)+o.map(e=>` ~${e.path} (${e.reason})`).join(``)}function JK(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function YK(e,t,n){return e+`\0`+t+`\0`+(n??``)}function XK(e,t){return new Set(Iy(e.presets).filter(n=>zy(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function ZK(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...Xz(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=_b(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=_b(s.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function QK(e){return e.filter(Boolean).join(`
205
- `)||null}function $K(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=dB(t.layers,PB,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??PB,l=a.find(e=>e.path===t.home)?.raw??{},u=new GK,d=new VO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=xK(o,d,e,r.compile??bK),n.push(...f.loadWarnings),wV(o),IF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:rW(o),lastRenderCellsBySegment:new Map,authoredRoots:XK(c,l),fileHeldSettings:uV(l),unused:[...new Map(a.flatMap(e=>LK(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function eq(e,t,n,r){let i=Qz(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[rB(e,t),tB(i)],s,c=null;try{s=$K(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Hg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:QK(o),state:null,error:e instanceof Hg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:QK(o),state:s,error:null}}function tq(e,t,n){return $K(e,{layers:[],home:``,projectDir:t},[],n)}var nq=class{entries=new Map;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??TK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=YK(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=eq(e,t,n,this.deps);a.state!==null&&this.log(`info`,qK(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??tq(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++;let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&(r.watcher?.release(),this.entries.delete(n),this.retire(r.state,`evict`))}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,JK(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=eq(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,qK(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=ZK(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const rq=16384;var iq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;watchersEvicted=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<rq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%rq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,evicted:this.watchersEvicted},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function aq(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const oq={load:()=>({}),save:()=>{},flush:()=>{}};var sq=class{sessions;storage;head=0;atom=(0,xb.createAtom)(`SessionState`);constructor(e=oq,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,xb.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,xb.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,xb.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function cq(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var lq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return cq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const uq=new Set([`1`,`true`]),dq=new Set([`0`,`false`,``]);function fq(e,t){let n=Lq(e),r=n.scope===`segment-palette`?`string`:iv(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(uq.has(t))return`true`;if(dq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function pq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function mq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function hq(e){return/^\s*$/.test(e)?null:_i(e)}function gq(e,t){return e!==null&&yi(e,t)!==void 0}function _q(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(_q),...i}}return e}function vq(e){if(!Ey(e))return _q(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,_q(t)])),...n}}const yq=MB,bq=yq.segments,xq=yq.presets,Sq=yq.root;function Cq(e,t,n,r){if(!gq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function wq(e,t){let n=eA(t);return t.scope===`segment-palette`&&Cq(e,[`segments`,t.segment],bq[t.segment],n.join(`.`)),n}function Tq(e){return _i(Di(e))}function Eq(){return Object.entries(Sq.rows).map(([e,t])=>{let n=_q(t);return{path:[`root`],fragment:Tq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Dq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Oq(e,t){if(t===void 0)return null;let n=vq(t);return{path:e,fragment:Tq(n),unit:{path:e,value:n}}}function kq(e,t){let n=[`presets`,t],r=[...n,`root`],i=xq[t];Cq(e,n,i,r.join(`.`));let a=Dq(e,r)??Oq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Aq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function jq(e,t){return[...Eq(),Dq(e,[`root`]),kq(e,t)].filter(e=>e!==null).reduce(Aq,new Map)}function Mq(e,t,n){for(let{node:r,...i}of jq(e,t).values())if(Xi(r,n))return i;throw new J(`${Nq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Nq(e,t){return kq(e,t)?.path??[`root`]}function Pq(e,t){return t.scope===`preset-root`?Nq(e,t.preset):eA(t)}function Fq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Iq(e){let t=$k(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Lq(e){let t=Iq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Rq(e,t,n,r,i){i(t,n,Yq(t,r)),mq(t.path,r,e.logger),e.record(t.path,n,r)}function zq(e,t,n){let r=Hq(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const Bq=()=>{};function Vq(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function Hq(e,t,n){let r=Uq(e,t);if(r===null)return[];let i=new Set(qq(Kq(r),Kq(n)));return qq(Gq(e,r),Gq(e,n)).filter(e=>!i.has(e))}function Uq(e,t){try{return Wq(e,t)}catch(e){if(e instanceof Hg)return null;throw e}}function Wq(e,t){return dB(t===null?e.above:[e.path,...e.above],PB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Gq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Kq(e){return e.layers.at(-1)?.config??e.base}function qq(e,t,n=``){return!Jq(e)||!Jq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>qq(e[r],t[r],n===``?r:`${n}.${r}`))}function Jq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yq(e,t){try{return Wq(e,t)}catch(e){throw e instanceof Hg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function Xq(e,t){let n=Lq(t),r=hq(pq(e)??``),i=r===null?void 0:yi(r,eA(n));return i!==void 0&&`value`in i?i.value:void 0}function Zq(e,t,n){Qq(e,t,n,[])}function Qq(e,t,n,r){let i=pq(t.path),a=n.reduce((e,[t,n])=>Vi(e,wq(hq(e),Lq(t)),fq(t,n),Ti),i??``);Rq(e,t,i,Vq(t,()=>$q(a,t.path,r,e=>e)),zq)}function $q(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Mq(hq(s),n,i),l=ea(Fq(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function eJ(e,t,n){let r=hq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of jq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(kq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function tJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!IB(t[1])?2:0)}function nJ(e,t,n){let r=n.map(Iq),i=pq(t.path);if(i===null)return;let a=r.reduce((e,t)=>tJ(e,Pq(hq(e),t)),i);a!==i&&Rq(e,t,i,a,Bq)}function rJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function iJ(e,t){let n=new Set([...FB,...rJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(XO));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(XO(e)))}function aJ(e,t,n,r,i,a){let o=pq(t.path),s=hq(o??``),c=iJ(s,t),l=[`presets`,c],u=Vq(t,()=>kq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=Qk(c,e);return[wq(s,Lq(n)),fq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Rq(e,t,o,Vq(t,()=>$q(p,t.path,a.map(e=>({...e,preset:c})),eJ)),zq),c}function oJ(e,t,n,r){let i=pq(t.path);Rq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),zq)}function sJ(e,t,n){if(IB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=pq(t.path),a=hq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);Rq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>tJ(e,t),i),Bq)}function cJ(e,t,n,r){let i=Iq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=pq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Vq(t,()=>Mq(hq(a??``),i.preset,o)),c=Fq(a??``,s),{after:l,placed:u}=lJ(c,s.path,r,()=>{let e=Yq(t,c).config;return Iy(e.presets).map(t=>zy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Rq(e,t,a,l,zq),u}function lJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=CF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const uJ={load:()=>({}),save:()=>{}},dJ=new Set(lv.map(e=>e.sessionKey)),fJ=e=>dJ.has(e)||e.startsWith(dA),pJ=8*1024*1024,mJ={past:[],future:[]},hJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var gJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=uJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??mJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??mJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(hJ(n));r.set(hJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:aq(this.sessionState,e=>fJ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:wJ(i,n),o=r.get(e),s=o===void 0?a:OJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,EJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(hJ)),a=n.net.filter(e=>!i.has(hJ(e))),o=yJ(kJ(DJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(jJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=yJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...xJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(hJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:kJ(n,t),future:kJ(i,t),...a!==void 0&&{savepoint:{at:kJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(hJ(e))),below:kJ(a.below,t)}}}),new J(`${r}: ${o.map(jJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):pq(t.file)}write(e,t,n){t.kind===`file`?mq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||_J(n)>pJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,vJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${pJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function _J(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function vJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...xJ(n,1,[])}:{past:e,future:t.slice(1),...xJ(n,0,[])}}function yJ(e){return e.slice(-50)}const bJ=e=>e===pA.member;function xJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:SJ(e.net,n),below:e.below}}}function SJ(e,t){let n=new Map(e.map(e=>[hJ(e),e]));for(let e of t){let t=n.get(hJ(e));n.set(hJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const CJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function wJ(e,t){let n=[...e.past,t],r=yJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...xJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...TJ(e.future,a),...i.below]},n.length-r.length,t)}}function TJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function EJ(e,t){return{past:e.past.slice(0,-1),future:yJ([...e.future,t]),...xJ(e.savepoint,0,CJ(t))}}function DJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...TJ(r,t.at-i.length),...t.below]}function OJ(e,t){if(bJ(t.after)&&!bJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!bJ(t.after)&&bJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function kJ(e,t){return e.map(e=>e.filter(e=>!t.has(hJ(e)))).filter(e=>e.length>0)}function AJ(e){return e.map(jJ).join(`, `)}function jJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function MJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function NJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(MJ))}function PJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(MJ)&&NJ(t.below)}function FJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return NJ(t.past)&&NJ(t.future)&&(t.savepoint===void 0||PJ(t.savepoint))}function IJ(e,t){let n=e=>e.kind===`file`||fJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function LJ(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(FJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,IJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const RJ=e=>!fJ(e)&&!WM(e)&&e!==`update.dismissed`;var zJ=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:aq(e,RJ,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,xb.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const BJ=`click.error`;function VJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,BJ,JSON.stringify(i))}function HJ(e,t,n){let r=UJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,BJ,JSON.stringify({...r,answered:!0}))}function UJ(e,t){let n=e.get(t,BJ);return n===null?null:GJ(n)}function WJ(e,t,n,r){let i=UJ(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function GJ(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function KJ(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&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const qJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function JJ(e){let t=e=>({kind:`failed`,reason:e});if(!qJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!qJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Aj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Aj.join(` or `)}`)}return{kind:`ok`,value:e}}function YJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const XJ=e=>KJ(e,`doctor-marks.json`,{},JJ),ZJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},QJ=(e,t)=>e.includes(t)?e:[...e,t],$J=e=>KJ(e,`doctor-clicked-terminals.json`,[],ZJ);var eY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const tY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},nY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),rY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=nY(e,t);return r===void 0?n:r.projectDir},iY=(e,t)=>nY(e,t).map(({role:t,frame:n,since:r,redrawn:i,projectDir:a,claudeConfigDir:o})=>({role:t,frame:n,projectDir:a,claudeConfigDir:o,redraws:JA(i,r,e.kind===`recent`?Math.min(...i):0)}));function aY(e){let t=new Map;for(let n of e.split(`
205
+ `)||null}function $K(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=dB(t.layers,PB,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??PB,l=a.find(e=>e.path===t.home)?.raw??{},u=new GK,d=new VO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=xK(o,d,e,r.compile??bK),n.push(...f.loadWarnings),wV(o),IF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:rW(o),lastRenderCellsBySegment:new Map,authoredRoots:XK(c,l),fileHeldSettings:uV(l),unused:[...new Map(a.flatMap(e=>LK(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function eq(e,t,n,r){let i=Qz(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[rB(e,t),tB(i)],s,c=null;try{s=$K(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Hg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:QK(o),state:null,error:e instanceof Hg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:QK(o),state:s,error:null}}function tq(e,t,n){return $K(e,{layers:[],home:``,projectDir:t},[],n)}var nq=class{entries=new Map;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??TK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=YK(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=eq(e,t,n,this.deps);a.state!==null&&this.log(`info`,qK(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??tq(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++;let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&(r.watcher?.release(),this.entries.delete(n),this.retire(r.state,`evict`))}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,JK(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=eq(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,qK(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=ZK(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const rq=16384;var iq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<rq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%rq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,expired:0,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function aq(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const oq={load:()=>({}),save:()=>{},flush:()=>{}};var sq=class{sessions;storage;head=0;atom=(0,xb.createAtom)(`SessionState`);constructor(e=oq,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,xb.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,xb.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,xb.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function cq(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var lq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return cq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const uq=new Set([`1`,`true`]),dq=new Set([`0`,`false`,``]);function fq(e,t){let n=Lq(e),r=n.scope===`segment-palette`?`string`:iv(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(uq.has(t))return`true`;if(dq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function pq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function mq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function hq(e){return/^\s*$/.test(e)?null:_i(e)}function gq(e,t){return e!==null&&yi(e,t)!==void 0}function _q(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(_q),...i}}return e}function vq(e){if(!Ey(e))return _q(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,_q(t)])),...n}}const yq=MB,bq=yq.segments,xq=yq.presets,Sq=yq.root;function Cq(e,t,n,r){if(!gq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function wq(e,t){let n=eA(t);return t.scope===`segment-palette`&&Cq(e,[`segments`,t.segment],bq[t.segment],n.join(`.`)),n}function Tq(e){return _i(Di(e))}function Eq(){return Object.entries(Sq.rows).map(([e,t])=>{let n=_q(t);return{path:[`root`],fragment:Tq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Dq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Oq(e,t){if(t===void 0)return null;let n=vq(t);return{path:e,fragment:Tq(n),unit:{path:e,value:n}}}function kq(e,t){let n=[`presets`,t],r=[...n,`root`],i=xq[t];Cq(e,n,i,r.join(`.`));let a=Dq(e,r)??Oq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Aq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function jq(e,t){return[...Eq(),Dq(e,[`root`]),kq(e,t)].filter(e=>e!==null).reduce(Aq,new Map)}function Mq(e,t,n){for(let{node:r,...i}of jq(e,t).values())if(Xi(r,n))return i;throw new J(`${Nq(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function Nq(e,t){return kq(e,t)?.path??[`root`]}function Pq(e,t){return t.scope===`preset-root`?Nq(e,t.preset):eA(t)}function Fq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Iq(e){let t=$k(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Lq(e){let t=Iq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Rq(e,t,n,r,i){i(t,n,Yq(t,r)),mq(t.path,r,e.logger),e.record(t.path,n,r)}function zq(e,t,n){let r=Hq(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const Bq=()=>{};function Vq(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function Hq(e,t,n){let r=Uq(e,t);if(r===null)return[];let i=new Set(qq(Kq(r),Kq(n)));return qq(Gq(e,r),Gq(e,n)).filter(e=>!i.has(e))}function Uq(e,t){try{return Wq(e,t)}catch(e){if(e instanceof Hg)return null;throw e}}function Wq(e,t){return dB(t===null?e.above:[e.path,...e.above],PB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Gq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Kq(e){return e.layers.at(-1)?.config??e.base}function qq(e,t,n=``){return!Jq(e)||!Jq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>qq(e[r],t[r],n===``?r:`${n}.${r}`))}function Jq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Yq(e,t){try{return Wq(e,t)}catch(e){throw e instanceof Hg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function Xq(e,t){let n=Lq(t),r=hq(pq(e)??``),i=r===null?void 0:yi(r,eA(n));return i!==void 0&&`value`in i?i.value:void 0}function Zq(e,t,n){Qq(e,t,n,[])}function Qq(e,t,n,r){let i=pq(t.path),a=n.reduce((e,[t,n])=>Vi(e,wq(hq(e),Lq(t)),fq(t,n),Ti),i??``);Rq(e,t,i,Vq(t,()=>$q(a,t.path,r,e=>e)),zq)}function $q(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Mq(hq(s),n,i),l=ea(Fq(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function eJ(e,t,n){let r=hq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of jq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(kq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function tJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!IB(t[1])?2:0)}function nJ(e,t,n){let r=n.map(Iq),i=pq(t.path);if(i===null)return;let a=r.reduce((e,t)=>tJ(e,Pq(hq(e),t)),i);a!==i&&Rq(e,t,i,a,Bq)}function rJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function iJ(e,t){let n=new Set([...FB,...rJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(XO));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(XO(e)))}function aJ(e,t,n,r,i,a){let o=pq(t.path),s=hq(o??``),c=iJ(s,t),l=[`presets`,c],u=Vq(t,()=>kq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=Qk(c,e);return[wq(s,Lq(n)),fq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Rq(e,t,o,Vq(t,()=>$q(p,t.path,a.map(e=>({...e,preset:c})),eJ)),zq),c}function oJ(e,t,n,r){let i=pq(t.path);Rq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),zq)}function sJ(e,t,n){if(IB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=pq(t.path),a=hq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);Rq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>tJ(e,t),i),Bq)}function cJ(e,t,n,r){let i=Iq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=pq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Vq(t,()=>Mq(hq(a??``),i.preset,o)),c=Fq(a??``,s),{after:l,placed:u}=lJ(c,s.path,r,()=>{let e=Yq(t,c).config;return Iy(e.presets).map(t=>zy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Rq(e,t,a,l,zq),u}function lJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=CF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const uJ={load:()=>({}),save:()=>{}},dJ=new Set(lv.map(e=>e.sessionKey)),fJ=e=>dJ.has(e)||e.startsWith(dA),pJ=8*1024*1024,mJ={past:[],future:[]},hJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var gJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=uJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??mJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??mJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(hJ(n));r.set(hJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:aq(this.sessionState,e=>fJ(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:wJ(i,n),o=r.get(e),s=o===void 0?a:OJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,EJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(hJ)),a=n.net.filter(e=>!i.has(hJ(e))),o=yJ(kJ(DJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(jJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=yJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...xJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(hJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:kJ(n,t),future:kJ(i,t),...a!==void 0&&{savepoint:{at:kJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(hJ(e))),below:kJ(a.below,t)}}}),new J(`${r}: ${o.map(jJ).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):pq(t.file)}write(e,t,n){t.kind===`file`?mq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||_J(n)>pJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,vJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${pJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function _J(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function vJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...xJ(n,1,[])}:{past:e,future:t.slice(1),...xJ(n,0,[])}}function yJ(e){return e.slice(-50)}const bJ=e=>e===pA.member;function xJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:SJ(e.net,n),below:e.below}}}function SJ(e,t){let n=new Map(e.map(e=>[hJ(e),e]));for(let e of t){let t=n.get(hJ(e));n.set(hJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const CJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function wJ(e,t){let n=[...e.past,t],r=yJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...xJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...TJ(e.future,a),...i.below]},n.length-r.length,t)}}function TJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function EJ(e,t){return{past:e.past.slice(0,-1),future:yJ([...e.future,t]),...xJ(e.savepoint,0,CJ(t))}}function DJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...TJ(r,t.at-i.length),...t.below]}function OJ(e,t){if(bJ(t.after)&&!bJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!bJ(t.after)&&bJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function kJ(e,t){return e.map(e=>e.filter(e=>!t.has(hJ(e)))).filter(e=>e.length>0)}function AJ(e){return e.map(jJ).join(`, `)}function jJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function MJ(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function NJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(MJ))}function PJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(MJ)&&NJ(t.below)}function FJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return NJ(t.past)&&NJ(t.future)&&(t.savepoint===void 0||PJ(t.savepoint))}function IJ(e,t){let n=e=>e.kind===`file`||fJ(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function LJ(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(FJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,IJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const RJ=e=>!fJ(e)&&!WM(e)&&e!==`update.dismissed`;var zJ=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:aq(e,RJ,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,xb.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const BJ=`click.error`;function VJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,BJ,JSON.stringify(i))}function HJ(e,t,n){let r=UJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,BJ,JSON.stringify({...r,answered:!0}))}function UJ(e,t){let n=e.get(t,BJ);return n===null?null:GJ(n)}function WJ(e,t,n,r){let i=UJ(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function GJ(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function KJ(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&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const qJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function JJ(e){let t=e=>({kind:`failed`,reason:e});if(!qJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!qJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Aj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Aj.join(` or `)}`)}return{kind:`ok`,value:e}}function YJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const XJ=e=>KJ(e,`doctor-marks.json`,{},JJ),ZJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},QJ=(e,t)=>e.includes(t)?e:[...e,t],$J=e=>KJ(e,`doctor-clicked-terminals.json`,[],ZJ);var eY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const tY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},nY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),rY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=nY(e,t);return r===void 0?n:r.projectDir},iY=(e,t)=>nY(e,t).map(({role:t,frame:n,since:r,redrawn:i,projectDir:a,claudeConfigDir:o})=>({role:t,frame:n,projectDir:a,claudeConfigDir:o,redraws:JA(i,r,e.kind===`recent`?Math.min(...i):0)}));function aY(e){let t=new Map;for(let n of e.split(`
206
206
  `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*oY(e,t){let n=new Set;for(let r=e.get(t);r!==void 0&&!n.has(r.pid);)n.add(r.pid),yield r,r=e.get(r.ppid)}const sY={pullRequests:e=>oW(e).showPullRequest===!0,rateLimits:e=>aW(e,`block`)||aW(e,`weekly`),memento:e=>aW(e,`memento`)};function cY(e,t){let n=new Map;for(let r of _g(zy(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>Dg(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,tW(e,t,n.get(t))])),a=e=>r.filter(t=>sY[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`),memento:a(`memento`)}}
207
207
  /*!
208
208
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -485,7 +485,7 @@ function run(argv) {
485
485
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
486
486
  `)){let t=PH(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function _X(e){let t=va(e,jj+1);return t.kind===`ok`?F(gX(t.value.buf,t.value.fromStart)):t}function vX(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const yX={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function bX(e){if(CD(e)===void 0)return{kind:`ok`,value:null};let t=HD(ut({bin:`git`,args:[...VD],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=qD(t.value);if(n===null)return{kind:`ok`,value:null};let r=BD(n);if(r===null)return{kind:`ok`,value:null};let i=FD[r],a=yX[r],o=a.loginHost(zD(n)),s=ut({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return xX(i,o,a.nonZero,s)}function xX(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):ID(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:MD(r.stderr)}):{kind:`failed`,reason:jD(e,r)}}function SX(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
487
487
  `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const CX=e=>tX(()=>ja(e));function wX(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Sa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:CX(e),bars:t.map(({role:e,frame:t,redraws:n})=>({role:e,frame:t,redraws:n}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}function TX(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function EX(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:bj(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:yj(t),tmuxClient:t}}}}function DX(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(lj(s))return{kind:`bundling`,name:s,version:c};if(!uj(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function OX(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:qe};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function kX(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function AX(e,t,n,r,i){return{pullRequests:kX(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:kX(t.rateLimits,()=>i),memento:kX(t.memento,()=>({located:e.memento(r,n.projectDir),claudeConfigDir:r}))}}function jX(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}function MX(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=HB(d.config,r,()=>!1),p=TX(e,t.tmux),m=EX(p,t.terminalEnv),h=[...new Set([...Yv(f),...Jv(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:DX(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:SX(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:AX(e,cY(d.config,f.preset),n,xa(t.claudeConfigDir),a),transcripts:vX(e,o),claudeSettings:wX({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Sa(xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function NX(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;O(e,Vi(Ea(e),t.path,JSON.stringify(t.value),Ei));let r=e=>({...e,sources:CX(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||In(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const PX={connectMs:200,budgetMs:500};async function FX(e){let n=e.includes(`--json`),r=await IX();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${ln(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
488
- `);let i=LX(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(GX(r.value))}function IX(){return nn({kind:`stats`},PX,e=>`stats`in e?e.stats:void 0)}function LX(e,t=RX){let n=iq.referenceSnapshot(),r=zX(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=VX(e.version,e.sourceDigest??null),a=VX(qe,Xe());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const RX=Object.keys(iq.referenceSnapshot());function zX(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!BX(e))return[];if(!BX(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...zX(e[i],t[i],a)):r.push(a)}return r}function BX(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VX(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function HX(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function UX(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function WX(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function GX(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${VX(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${WX(e.uptimeSec)}`),t.push(` rss ${HX(e.rssBytes)}`),t.push(` heapUsed ${HX(e.heapUsedBytes)}`),t.push(` heapTotal ${HX(e.heapTotalBytes)}`),t.push(` external ${HX(e.externalBytes)}`),t.push(` arrayBuffers ${HX(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` hit rate ${UX(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${UX(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${HX(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${HX(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` accounted ${HX(e.renderCache.accountedBytes)} / ${HX(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` evicted ${e.watchers.evicted}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
488
+ `);let i=LX(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(GX(r.value))}function IX(){return nn({kind:`stats`},PX,e=>`stats`in e?e.stats:void 0)}function LX(e,t=RX){let n=iq.referenceSnapshot(),r=zX(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=VX(e.version,e.sourceDigest??null),a=VX(qe,Xe());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const RX=Object.keys(iq.referenceSnapshot());function zX(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!BX(e))return[];if(!BX(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...zX(e[i],t[i],a)):r.push(a)}return r}function BX(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VX(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function HX(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function UX(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function WX(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function GX(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${VX(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${WX(e.uptimeSec)}`),t.push(` rss ${HX(e.rssBytes)}`),t.push(` heapUsed ${HX(e.heapUsedBytes)}`),t.push(` heapTotal ${HX(e.heapTotalBytes)}`),t.push(` external ${HX(e.externalBytes)}`),t.push(` arrayBuffers ${HX(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` expired ${e.gitCache.expired}`),t.push(` hit rate ${UX(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` invalidations ${e.gitCache.invalidations}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${UX(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${HX(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${HX(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` accounted ${HX(e.renderCache.accountedBytes)} / ${HX(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
489
489
  `)+`
490
490
  `}const KX=e=>({kind:`ok`,value:e}),qX=e=>({kind:`failed`,reason:e});var JX=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const YX=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function XX(e){return YX.test(e)?e:null}function ZX(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return KX(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return KX({app:n,missing:qX(`its script could not be read (${r.reason})`)});let i=to(r.value);return KX({app:n,missing:i===null?qX("its script is not one `cc-candybar install` wrote"):KX([i.node,i.script].filter(t=>!e.exists(t)))})}async function QX(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function $X(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${fr}://${Lr}/${n}`);return(r===null?await QX(e,n):null)??{kind:`lost`,unopened:r,opener:ZX(e)}}function eZ(e,t,n){let r=ut({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?KX(r.stdout):qX(r.stderr.trim()||r.error||r.reason)}const tZ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${fr}://probe"));u.isNil() ? "" : u.path.js`;async function nZ(){let e=await IX();if(e.kind!==`ok`)return qX(ln(e).split(`
491
491
  `).join(` — `));let t=LX(e.value,[`handlerProbes`]);if(t!==null)return qX(t);let{version:n,handlerProbes:r}=e.value;return KX({version:n,arrivals:r})}function rZ(){return{platform:process.platform,sockets:{own:vt(),handler:yt()},now:Date.now,nonce:ne,daemon:nZ,open:e=>{let t=eZ(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=eZ(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,tZ]);if(e.kind===`failed`)return e;let t=e.value.trim();return KX(t===``?null:t)},script:e=>eZ(`doctor.osadecompile`,`/usr/bin/osadecompile`,[no(e)]),exists:p.existsSync}}const iZ=/^─{20,}/,aZ=/^❯(\s|$)/,oZ=/›\s*stashed$/;function sZ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>iZ.test(e)?[t]:[]).at(-2);return n===void 0||!aZ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function cZ(e){if(e.inMode)return{kind:`in-mode`};let t=sZ(e);return t===null?{kind:`no-prompt`}:oZ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function lZ(e){return/^❯\s*\S/u.test(sZ(e)?.prompt??``)}const uZ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function dZ(e){return e.screen.some(e=>uZ.test(e))}const fZ={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function pZ(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function mZ(e,t,n){let r=pZ(t);if(r.kind===`refused`)return r;let i=r.hint,a=cZ(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:fZ[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function hZ(e,t,n,r){let i=hU(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function gZ(e){let t=hZ(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.155.1",
3
+ "version": "1.155.2",
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",
@@ -104,9 +104,9 @@
104
104
  "typescript": "^5.0.0"
105
105
  },
106
106
  "optionalDependencies": {
107
- "@promptctl/cc-candybar-darwin-arm64": "1.155.1",
108
- "@promptctl/cc-candybar-darwin-x64": "1.155.1",
109
- "@promptctl/cc-candybar-linux-arm64": "1.155.1",
110
- "@promptctl/cc-candybar-linux-x64": "1.155.1"
107
+ "@promptctl/cc-candybar-darwin-arm64": "1.155.2",
108
+ "@promptctl/cc-candybar-darwin-x64": "1.155.2",
109
+ "@promptctl/cc-candybar-linux-arm64": "1.155.2",
110
+ "@promptctl/cc-candybar-linux-x64": "1.155.2"
111
111
  }
112
112
  }