@promptctl/cc-candybar 1.154.0 → 1.155.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs 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.154.0`;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`e63da1c35e83321daee55bd8bb54bce75ae8d765951697f418135777ddd84924`}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.0`;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`8095a85f9fe45dc26096e11dcae7f4cdd5ea2bb7619cfc34ce9a218735e60f6e`}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){return e>t*.75}function Rn(e,t,n){let{prefix:r,suffix:i}=Fn[t];return s.join(e,`${r}${n}${i}`)}function zn(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 Bn(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=await e.memoryCharge(a),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${Un(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${Vn(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 Wn(e.log,`memory report`,()=>{let t=Rn(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Wn(e.log,`heap snapshot`,()=>{let t=Rn(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Wn(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of Gn(e.listArtifacts()).slice(n))for(let n of Object.values(t))Wn(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&Ln(i.charge.bytes,t)?`${Vn(i.charge)} approaching limit ${Nn(t)} MB (v8 heap ${Nn(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:Gn(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 Vn(e){return e.kind===`charged`?`${e.measure} ${Nn(e.bytes)} MB`:`rss ${Nn(e.bytes)} MB (standing in: ${e.unread})`}function Hn(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Un({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)}`:``;return`measure=${Hn(e)} charge=${Nn(e.bytes)}MB rss=${Nn(t)}MB heap=${Nn(n)}MB limit=${Nn(r)}MB${i}`}function Wn(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Gn(e){let t=new Map;for(let n of e){let e=s.basename(n),r=zn(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 Kn(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=>zn(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function qn(e={}){if(lr()!==null)return;let n=e.spawn??ur,r=or();if(r.kind===`contended`){let e=Yn();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Jn(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Jn(n);return}try{Jn(n)}finally{cr()}}function Jn(e){nr()&&Xn(e)}function Yn(){try{let e=p.statSync(Dt());return Date.now()-e.mtimeMs}catch{return null}}function Xn(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -52,7 +52,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
52
52
  `,` `),e.expandTabs()}var qf=class{renderable;effect;t;key;theme;constructor(e,t,n){if(this.renderable=e,this.effect=t,!Number.isFinite(n.t))throw RangeError(`Effected needs a finite t, got ${n.t}`);this.t=n.t,this.key=n.key,this.theme=n.theme}render(e){let t=Vu(this.renderable,e);return e.colorSystem===null?t:this._moved(t,e)}*contents(){yield this.renderable}*_moved(e,t){let n=t.colorSystem??z.TRUECOLOR,r=Yf(e,n,this.theme),i=Xf(r),a=this.effect(Qf(r,()=>i,n,this.theme));yield*W.applyStyle(this._recolored(i,a.at(this.t),n),new H({nextChange:a.nextChange(this.t)}))}*_recolored(e,t,n){for(let{segment:r,look:i,glyphs:a}of e){if(i===void 0){yield r;continue}let{style:e,wire:o,slots:s,pair:c}=i,{terminal:l}=c,u={fg:c.fg,bg:c.bg},d=[];for(let{glyph:e,cell:r}of a){let i=r===void 0?s:ep(t(u,{...r,seed:this.seed(r.row,r.col),terminal:l,reverse:c.reverse}),c.reverse),a=d[d.length-1],f=a!==void 0&&ap(a.colors,i)?a.drawn:this.respec(o,s,i,n);a!==void 0&&np(a.drawn,f)?(a.text+=e,a.cells+=L(e),a.colors=i):d.push({text:e,cells:L(e),colors:i,drawn:f})}if(d.every(e=>np(e.drawn,o))){yield r;continue}let f=0;for(let t of d){let n=e.shiftedBy(f),r=np(t.drawn,o)?n:n.add(H.fromColor(t.drawn.color,t.drawn.bgcolor));yield new W(t.text,r),f+=t.cells}}}measure(e){return Ku.get(e,this.renderable)}static shows(e,t,n,r){let i=ep(e,e.reverse),a=tp(i,ep(t,e.reverse),n,r);return ep({fg:a.fg?.getTruecolor(r,!0)??i.fg,bg:a.bg?.getTruecolor(r,!1)??i.bg},e.reverse)}respec(e,t,n,r){let i=tp(t,n,r,this.theme);return{color:i.fg??e.color,bgcolor:i.bg??e.bgcolor}}seed(e,t){return Number.parseInt($u(`${this.key}:${e}:${t}`),16)/4294967296}};const Jf=B.default();function Yf(e,t,n){return[...e].map(e=>{if(e.isControl)return{segment:e,look:void 0};let r=e.style??H.null(),i=r.drawnColors(t),a={fg:(i.color??Jf).getTruecolor(n,!0),bg:(i.bgcolor??Jf).getTruecolor(n,!1)},o=r.reverse===!0,s=ep({fg:i.color?.isDefault??!0,bg:i.bgcolor?.isDefault??!0},o);return{segment:e,look:{style:r,wire:i,slots:a,pair:{...ep(a,o),terminal:s,reverse:o}}}})}function Xf(e){let t=0,n=0;return e.map(({segment:e,look:r})=>{if(r===void 0)return{segment:e,look:r,glyphs:[]};let i=r.style.anchor,a=0;return{segment:e,look:r,glyphs:[...ss(e.text)].map(e=>{let r=e===`
53
53
  `?void 0:{row:t,col:n,anchor:i&&pu(i,a)};return[t,n]=e===`
54
54
  `?[t+1,0]:[t,n+L(e)],a+=L(e),{glyph:e,cell:r}})}})}function Zf(e){return[e.underline,e.underline2,e.strike,e.overline,e.frame,e.encircle].some(e=>e===!0)}function Qf(e,t,n,r){let i=r.backgroundColor.hex,a,o=()=>t().flatMap(({look:e,glyphs:t})=>{if(e===void 0)return[];let n=e.pair.bg.hex!==i||Zf(e.style);return t.flatMap(({glyph:e,cell:t})=>t!==void 0&&(e.trim()!==``||n)?[t]:[])}),s=e.flatMap(({segment:e,look:t})=>t!==void 0&&e.text.trim()!==``&&!mu(t.style.anchor,xd)?[t.pair]:[]),c=[...new Map(s.map(e=>[`${e.fg.hex}/${e.bg.hex}/${e.terminal.fg}/${e.terminal.bg}/${e.reverse}`,e])).values()],l=e=>c.flatMap(t=>t.terminal[e]?[]:[t[e].hex]);return{cells:()=>a??=o(),pairs:c,colors:new Set([...l(`fg`),...l(`bg`)]),fills:new Set(l(`bg`)),depth:n,theme:r}}function $f(e,...t){let n=new Set(t),r=e=>Cd(e.anchor,n),i=({fg:e,bg:t})=>e||t,a=e=>({...e,cells:()=>e.cells().filter(e=>i(r(e)))});return t=>iu.map(e(a(t)),e=>(t,n)=>{let a=r(n);if(!i(a))return t;let o=e(t,n);return{fg:a.fg?o.fg:t.fg,bg:a.bg?o.bg:t.bg}})}function ep(e,t){return t?{fg:e.bg,bg:e.fg}:e}function tp(e,t,n,r){let i=t.bg.compositeOver(Ss),a=t.fg.compositeOver(i);return{fg:B.matchMove(e.fg,a,n,r,!0),bg:B.matchMove(e.bg,i,n,r,!1)}}function np(e,t){return rp(e.color,t.color,!0)&&rp(e.bgcolor,t.bgcolor,!1)}function rp(e,t,n){return e===t||ip(e,n)===ip(t,n)}function ip(e,t){return e?.getAnsiCodes(t).join(`;`)??``}function ap(e,t){return op(e.fg,t.fg)&&op(e.bg,t.bg)}function op(e,t){return e.red===t.red&&e.green===t.green&&e.blue===t.blue&&e.alpha===t.alpha}const sp=(()=>{let e=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];return[...e,...e]})(),cp=e=>e*e*e*(e*(e*6-15)+10),lp=(e,t,n)=>e+n*(t-e);function up(e,t,n,r){let i=e&15,a=i<8?t:n,o=i<4?n:i===12||i===14?t:r;return(i&1?-a:a)+(i&2?-o:o)}function dp(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=r&255,s=i&255,c=a&255;e-=r,t-=i,n-=a;let l=cp(e),u=cp(t),d=cp(n),f=sp[o]+s,p=sp[f]+c,m=sp[f+1]+c,h=sp[o+1]+s,g=sp[h]+c,_=sp[h+1]+c;return lp(lp(lp(up(sp[p],e,t,n),up(sp[g],e-1,t,n),l),lp(up(sp[m],e,t-1,n),up(sp[_],e-1,t-1,n),l),u),lp(lp(up(sp[p+1],e,t,n-1),up(sp[g+1],e-1,t,n-1),l),lp(up(sp[m+1],e,t-1,n-1),up(sp[_+1],e-1,t-1,n-1),l),u),d)}function fp(e,t,n,r){let i=0,a=1,o=0;for(let s=0;s<r;s++){let r=2**s;i+=a*dp(e*r,t*r,n*r),o+=a,a/=2}return i/o}function pp(e,t){let n=Math.sin(e*12.9898+t*78.233)*43758.5453;return n-Math.floor(n)}function mp(e,t,n){let r=Math.min(1,Math.max(0,(n-e)/(t-e)));return r*r*(3-2*r)}const hp=Array.from({length:48},(e,t)=>(t+1)/48);function gp(e,t){return Math.min(ws(e.fg,e.bg),4.5)-(t===z.TRUECOLOR?.01:0)}const _p=[`fg`,`bg`];function vp({pairs:e,depth:t,theme:n},r,i){let a=(e,t)=>e.terminal[t]?void 0:e[t].hex,o=new Map(e.flatMap(e=>_p.flatMap(t=>{let n=a(e,t);return n===void 0?[]:[[n,e[t]]]}))),s=new Map([...r].filter(e=>!o.has(e)).map(e=>[e,1])),c=e=>V.fromRgba(o.get(e)).l;for(let l of[...r].filter(e=>o.has(e)).sort((e,t)=>c(t)-c(e))){let r=e.flatMap(e=>{let t=_p.find(t=>a(e,t)===l);if(t===void 0)return[];let n=a(e,t===`fg`?`bg`:`fg`);return[[e,t,n===void 0?0:s.get(n)??0]]}),o=e=>r.every(([r,a,o])=>{let s=gp(r,t),c=(t,n)=>Tp(i,r[t],(t===a?e:o)*n);return hp.every(e=>{let i=qf.shows(r,{fg:c(`fg`,e),bg:c(`bg`,e)},t,n);return ws(i.fg,i.bg)>=s})}),[c,u]=o(1)?[1,1]:[0,1];for(let e=0;e<20&&u-c>.001;e++){let e=(c+u)/2;[c,u]=o(e)?[e,u]:[c,e]}s.set(l,c)}return s}function yp(e,t){let n=new WeakMap;return Cp(Sp(e,r=>{let i=t??r.colors,a=[bp(r),`|`,...i].join(` `),o=n.get(r.theme)??new Go;return n.set(r.theme,o),o.get(a,()=>vp(r,i,e.touch))}))}function bp({depth:e,pairs:t}){return[e,...t.map(xp)].join(` `)}function xp({fg:e,bg:t,terminal:n,reverse:r}){return`${e.hex}/${t.hex}/${n.fg}/${n.bg}/${r}`}function Sp(e,t){return n=>{let r=t(n);return iu.continuous(t=>{let i=e.field(t,n);return({fg:t,bg:n},a)=>{let o=Math.round(kp(i(a))*48)/48,s=(t,n)=>Tp(e.touch,t,(n?0:r.get(t.hex)??0)*o);return{fg:s(t,a.terminal.fg),bg:s(n,a.terminal.bg)}}})}}function Cp(e){return t=>wp(t.depth)?iu.constant(e=>e):e(t)}function wp(e){switch(e){case z.DEFAULT:case z.STANDARD:case z.WINDOWS:return!0;case z.EIGHT_BIT:case z.TRUECOLOR:return!1}}function Tp(e,t,n){return n===0?t:e(t,n)}function Ep(e){if(!(Number.isFinite(e.seconds)&&e.seconds>0))throw RangeError(`curve: seconds must be a positive number of seconds, got ${e.seconds}`);if(!(e.swing>=0&&e.swing<=1))throw RangeError(`curve: swing must be in [0, 1], got ${e.swing}`)}const Dp={shimmer:{seconds:109,ease:Kl.linear,swing:.9},pulse:{seconds:43,ease:Kl.linear,swing:.85},sparkle:{seconds:139,ease:Kl.linear,swing:.95},wheel:{seconds:907,ease:Kl.linear,swing:1},fade:{seconds:20,ease:Kl[`ease-in-out`],swing:1},dissolve:{seconds:30,ease:Kl[`ease-in-out`],swing:1}},Op={sun:new R(255,228,176),firefly:new R(222,245,140)},kp=e=>Math.min(1,Math.max(0,e));function Ap(e,t,n){if(!(n>=0&&n<=1))throw RangeError(`blend: w must be in [0, 1]; got ${n}`);let r=Math.PI/180,i=(1-n)*e.c*Math.cos(e.h*r)+n*t.c*Math.cos(t.h*r),a=(1-n)*e.c*Math.sin(e.h*r)+n*t.c*Math.sin(t.h*r);return new V((1-n)*e.l+n*t.l,Math.hypot(i,a),Math.atan2(a,i)/r,e.alpha)}function jp(e){let t=V.fromRgba(e);return(e,n)=>{let r=V.fromRgba(e);return Ap(r,new V(Math.max(r.l,t.l),t.c,t.h,t.alpha),n).toRgba()}}const Mp=(e,t)=>t*e[e.length-1][0];function Np(e,t,n){let r=t/n,i=e.findIndex(([e])=>r<e);if(!(r>0)||i<0)return 0;let[a,o]=i===0?[0,0]:e[i-1],[s,c]=e[i];return n*(o+(c-o)*(1-Math.cos(Math.PI*(r-a)/(s-a)))/2)}function Pp(e,t,n){let r=Mp(e,n),i=t=>{let r=0;for(let i=0;i<24;i++)r+=Np(e,(i+.5)/24*t,n);return r*t};return i(Math.min(Math.max(t,0),r))/i(r)}const Fp=[[.24,1],[.6,0]];function Ip(e,t,n){Ep(e);let r=.9+.2*pp(n,3.1),i=t=>.1*dp(t/(3*e.seconds),.5,.5+n),a=i(0);return{touch:jp(t),field:t=>{let o=r*t/e.seconds+i(t)-a,s=Math.floor(o),c=.7+.3*mp(-.5,.5,dp(s*.37,2.1,n)),l=.5-.5*Math.cos(2*Math.PI*(o-s)),u=e.swing*e.ease(c*l);return()=>u}}}const Lp=e=>Math.abs(e)>=1?0:(1-e*e)**3;function Rp(e,t,n,r){Ep(e);let i=e.seconds,a=i/2,o=e=>mp(-.4,.4,dp(e/7,3.3,5.5+r)),s=.7,c=.51,l=.4,u=(e,n,u)=>{let d=o(e),f=(pp(e,7.5+r)<.35+.6*d)*(.3+.7*d*(.6+.4*pp(e,8.5+r))),p=i*u/80*(c+l*pp(e,5.5+r)),m=kp((n-(e+s*pp(e,6.5+r))*a)/p);return{strength:f,centre:m*u-t+.06*u*Math.sin(Math.PI*m)*dp(m,2.7,e+r)}},d=(e,t)=>{let n=s+(c+l)*i*t/80/a,r=Math.floor(e/a),o=[];for(let i=Math.max(0,Math.ceil(r-n));i<=r;i++)o.push(u(i,e,t));return o},f=(e,t,n)=>Math.exp(-((dp(e,t,n)/.8)**2));return{touch:jp(n),field:(n,i)=>{let[a,o]=Wp(i.cells().map(e=>e.col)),s=d(n,o-a+1+2*t);return i=>{let o=0;for(let{strength:e,centre:n}of s)o=Math.max(o,e*Lp((i.col-a-n)/t));let c=i.row+r,l=.8*dp(i.col*.05,c*.3+1.3,n*.02),u=(f(i.col*.21+l,c*.9,n*.022)*f(i.col*.33+9.1-l,c*.7,n*.018+4.2))**2;return e.swing*e.ease(o*(.1+.6*u))}}}}function zp(e,t,n){Ep(e);let r=e.seconds,i=22.1,a=3.1,o=(e,t,i,a,o)=>{let s=e*4.9+t*31.7+.3+n,c=e+.5+.7*dp(e*1.7+.2,.3+t*2.9,.5+n),l=i+pp(e+t*1013,.7+n)*r,u=Math.floor(l/r),d=pp(u,s+1)<.15?0:1,f=.5+.5*pp(u,s+2),p=pp(u,s+3)*(1-Mp(Fp,f)),m=l/r-u-p;return{x:a+c*8+5*(2*pp(u,s+4)-1)+5*f*(2*pp(u,s+5)-1)*Pp(Fp,m,f)+1.5*dp(s,.1,i*.035),y:o+t*3+.6*dp(s,2.2,i*.035),glow:d*Np(Fp,m,f)}};return{touch:jp(t),field:(t,n)=>{let r=n.cells(),[s,c]=Wp(r.map(e=>e.col)),[l,u]=Wp(r.map(e=>e.row)),d=e=>(e-s)/8-.5,f=e=>(e-l)/3,[p,m]=[Math.ceil(d(s-i)),Math.floor(d(c+i))],[h,g]=[Math.ceil(f(l-a)),Math.floor(f(u+a))],_=Array.from({length:g-h+1},(e,n)=>Array.from({length:m-p+1},(e,r)=>o(p+r,h+n,t,s,l)));return t=>{let n=0,[r,o]=[Math.max(p,Math.ceil(d(t.col-i))),Math.min(m,Math.floor(d(t.col+i)))],[s,c]=[Math.max(h,Math.ceil(f(t.row-a))),Math.min(g,Math.floor(f(t.row+a)))];for(let e=s;e<=c;e++)for(let i=r;i<=o;i++){let r=_[e-h][i-p];n=Math.max(n,r.glow*Lp(Math.hypot(t.col-r.x,2*(t.row-r.y))/5))}return e.swing*e.ease(n)}}}}function Bp(e,t){return n=>{let r=V.fromRgba(n.theme.backgroundColor);return iu.continuous(i=>{let a=e(i,n);return(e,n)=>{let i=t*(1-kp(a(n)));if(i===0)return e;let o=Ap(V.fromRgba(e.bg),r,i);return{fg:Ap(V.fromRgba(e.fg),o,i).toRgba(),bg:o.toRgba()}}})}}function Vp(e){let t=new Map;return n=>{let r=`${n.row}:${n.col}`,i=t.get(r)??kp(.5+1.1*fp(n.col*.09+1.4*dp(n.col*.035,n.row*.2+2.6,e+.5),n.row*.45,e,3));return t.set(r,i),i}}function Hp(e,t){let n=t=>t>=e.seconds;return{effect:r=>{let i=t(r);return{at:e=>i.at(e),nextChange:e=>n(e)?1/0:i.nextChange(e),lastChange:t=>n(t)?e.seconds:i.lastChange(t)}},done:n}}function Up(e,t){let n=new Map,r=e=>`${e.row}:${e.col}`;return i=>{let[a,o]=Wp(i.map(t)),s=(o>a?.55:0)*e.seconds,c=ru.once(0,e.seconds-s),l=e=>{let n=o>a?kp((t(e)-a)/(o-a)):0;return{along:n,progress:e=>c(e-n*s)}};for(let e of i){let t=r(e);n.set(t,n.get(t)??l(e))}return e=>n.get(r(e))??l(e)}}function Wp(e){let t=e[0]??0,n=t;for(let r of e)t=Math.min(t,r),n=Math.max(n,r);return[t,n]}function Gp(e,t){Ep(e);let n=Up(e,Vp(1.7+t));return Hp(e,Bp((t,r)=>{let i=n(r.cells());return n=>e.ease(i(n).progress(t))},e.swing))}const Kp={depth:.4,from:.5,to:.95,maskFrom:.35,maskTo:.75,late:.6};function qp(e,t){Ep(e);let n=Vp(9.3+t),r=Up(e,Vp(4.2+t)),{depth:i,from:a,to:o,maskFrom:s,maskTo:c,late:l}=Kp;return Hp(e,Bp((t,u)=>{let d=r(u.cells());return r=>{let{along:u,progress:f}=d(r),p=e.ease(f(t)),m=kp((p-a)/(o-a)),h=i*mp(s,c,n(r))*(1-l+l*u)*Math.sin(Math.PI*m)**2;return 1-p+h}},e.swing))}const Jp=[211,337];function Yp(e,t){Ep(e);let n=e.seconds,r=e=>pp(Number.parseInt(e.slice(1),16)*1e-4,17.3+t),i=(e,n)=>dp(n/Jp[0],5.9+97*e,t)+.5*dp(n/Jp[1],2.3+89*e,t+7.1),a=(t,a)=>{let o=r(t);return 360*a/n+e.swing*180*((i(o,a)-i(o,0))/1.5)},o=new WeakMap;return Cp(e=>{let{colors:t,fills:n,depth:r,theme:i}=e,s=(e,n)=>!e&&t.has(n.hex),c=(e,t,r)=>n.has(e.hex)||!r?e.hex:t.hex,l=(e,t)=>`${e.hex} ${t}`,u=o.get(i)??new Go;o.set(i,u);let d=u.get(bp(e),()=>tm(e.pairs,r,(e,t)=>{let n=t===`fg`?`bg`:`fg`;return s(e.terminal[t],e[t])?l(e[t],c(e[t],e[n],s(e.terminal[n],e[n]))):void 0})),f=im(r,i);return iu.continuous(e=>{let t=new Map,n=(t,n)=>{let i=Xp(t,a(n,e));return am(i.looks,t,r===z.TRUECOLOR?i.either.map(nm):f,d.get(l(t,n))??Qp)},i=(e,r)=>{let i=t.get(l(e,r))??n(e,r);return t.set(l(e,r),i),i};return(e,t)=>{let n={fg:s(t.terminal.fg,e.fg),bg:s(t.terminal.bg,e.bg)},r=(e,t,n,r)=>t?i(e,c(e,n,r)):e;return{fg:r(e.fg,n.fg,e.bg,n.bg),bg:r(e.bg,n.bg,e.fg,n.fg)}}})})}function Xp(e,t){if(t===0)return{looks:e,either:[e]};let n=V.fromRgba(e),r=Cs(e),i=e=>new V(e,n.c,n.h+t,n.alpha).toRgba(),[a,o]=[0,1];for(let e=0;e<24;e++){let e=(a+o)/2;[a,o]=Cs(i(e))<r?[e,o]:[a,e]}return{looks:i(o),either:[i(a),i(o)]}}const Zp=e=>Math.log(ws(e,new R(0,0,0))),Qp={lo:-1/0,hi:1/0},$p={lo:1/0,hi:-1/0},em=Math.log(1.031);function tm(e,t,n){let r=new Map;for(let i of e.filter(e=>gp(e,t)>1)){let e=(Math.log(ws(i.fg,i.bg))-Math.log(gp(i,t)))/_p.filter(e=>n(i,e)!==void 0).length;for(let t of _p){let a=n(i,t);if(a===void 0)continue;let[o,s]=[Zp(i[t]),Zp(i[t===`fg`?`bg`:`fg`])],{lo:c,hi:l}=r.get(a)??Qp;r.set(a,o>=s?{lo:Math.max(c,o-e),hi:l}:{lo:c,hi:Math.min(l,o+e)})}}return new Map([...r].map(([e,{lo:t,hi:n}])=>[e,n-t<em?$p:{lo:t,hi:n}]))}const nm=e=>({color:e,looks:V.fromRgba(e),stop:Zp(e)}),rm=new WeakMap;function im(e,t){let n=B.indexed(e,t),r=rm.get(n)??n.map(([,e])=>nm(e));return rm.set(n,r),r}function am(e,t,n,{lo:r,hi:i}){return om(e,[nm(t),...n.filter(({stop:e})=>e>=r&&e<=i)]).color}function om(e,t){let n=V.fromRgba(e),r;for(let e of t){let t=n.deltaE(e.looks);(r===void 0||t<r[1])&&(r=[e,t])}return r?.[0]}const sm={loops:{shimmer:(e,t=Dp.shimmer)=>yp(Rp(t,24,Op.sun,e.z)),pulse:(e,t=Dp.pulse)=>yp(Ip(t,Op.sun,e.z)),sparkle:(e,t=Dp.sparkle)=>yp(zp(t,Op.firefly,e.z)),wheel:(e,t=Dp.wheel)=>Yp(t,e.z)},transitions:{fade:(e,t=Dp.fade)=>Gp(t,e.z),dissolve:(e,t=Dp.dissolve)=>qp(t,e.z)}};var cm=class{beat;width;_shown;constructor(e){this.beat=nu(e.map(e=>e.seconds));let t=e.map(e=>Kf(e.text.copy())),n=t.map(e=>e.cellLength);this.width=Math.max(...n),this._shown=t.map((e,t)=>(e.noWrap=!0,e.overflow=`crop`,e.padRight(this.width-n[t])))}at(e){return this._shown[this.beat.at(e)].copy()}nextChange(e){return this.beat.nextChange(e)}lastChange(e){return this.beat.lastChange(e)}};function lm(e,t){return e.at(t).copy().stylize(new H({nextChange:e.nextChange(t)}))}function um(e,t){let n=[...Vu(e,t)],r=0;for(let e of n)r+=e.cellLength;return{segments:n,width:r}}const dm={segments:[],width:0},fm={left:()=>0,justify:()=>0,center:e=>Math.floor(e/2),right:e=>e};function pm(e,t){return fm[e](t)}function mm(e,t,n,r){let i=Math.max(0,r-1),a=e===`justify`&&!t&&i>0&&n>0?n:0,o=i>0?Math.floor(a/i):0,s=a-o*i;return Array.from({length:i},(e,t)=>o+ +(t<s))}var hm=class{items;joiner;gap;align;constructor(e,t){this.items=e,this.joiner=t?.joiner,this.gap=t?.gap??0,this.align=t?.align??`left`}contents(){return this.items}*render(e){let t=this.items;if(t.length===0)return;let n=Math.max(1,e.maxWidth),r=this.gap,i=this.joiner,a=t.map(t=>um(Td(t),e)),o=n=>i?um(wd(i,null,t[n],{index:n}),e):dm,s=n=>i?um(wd(i,t[n],null,{index:n+1}),e):dm,c=(n,r)=>i?um(wd(i,t[n],t[r],{index:r}),e):dm,l=[],u=null,d=r>0?{segments:[new W(` `.repeat(r))],width:r}:dm;for(let e=0;e<t.length;e++){let t=a[e];if(u===null){let n=o(e),r=s(e),i=n.width>0?[n,t]:[t],a=[i.length-1];u={blocks:i,width:n.width+t.width,lastIndex:e,itemBlockIndices:a},u.endCap=r;continue}let i=u.lastIndex,f=c(i,e),p=s(e),m=(r>0?r:0)+f.width+(r>0?r:0)+t.width;if(u.width+m+p.width<=n)r>0&&u.blocks.push(d),f.width>0&&u.blocks.push(f),r>0&&u.blocks.push(d),u.blocks.push(t),u.itemBlockIndices.push(u.blocks.length-1),u.width+=m,u.lastIndex=e,u.endCap=p;else{let n=u.endCap;n.width>0&&u.blocks.push(n),u.width+=n.width,l.push(u);let r=o(e),i=s(e),a=r.width>0?[r,t]:[t],c=[a.length-1];u={blocks:a,width:r.width+t.width,lastIndex:e,itemBlockIndices:c},u.endCap=i}}let f=u;{let e=f.endCap;e.width>0&&f.blocks.push(e),f.width+=e.width,l.push(f)}let p=this.align;for(let e=0;e<l.length;e++){let t=l[e],r=e===l.length-1,i=Math.max(0,n-t.width),a=pm(p,i),o=mm(p,r,i,t.itemBlockIndices.length),s=new Map;t.itemBlockIndices.forEach((e,t)=>s.set(e,t)),a>0&&(yield new W(` `.repeat(a)));for(let e=0;e<t.blocks.length;e++){let n=s.get(e);if(n!==void 0&&n>0){let e=o[n-1];e>0&&(yield new W(` `.repeat(e)))}yield*t.blocks[e].segments}yield W.line()}}measure(e){let t=this.items;if(t.length===0)return{minimum:0,maximum:0};let n=0,r=0;for(let i=0;i<t.length;i++){let a=um(t[i],e).width,o=this.joiner?um(wd(this.joiner,null,t[i],{index:i}),e).width:0,s=this.joiner?um(wd(this.joiner,t[i],null,{index:i+1}),e).width:0;n=Math.max(n,a+o+s),r+=a,i>0&&(r+=this.gap*2,this.joiner&&(r+=um(wd(this.joiner,t[i-1],t[i],{index:i}),e).width))}return this.joiner&&(r+=um(wd(this.joiner,null,t[0],{index:0}),e).width,r+=um(wd(this.joiner,t[t.length-1],null,{index:t.length}),e).width),{minimum:n,maximum:r}}};function gm(){let e=new WeakMap;return(t,n,r)=>{let i=e.get(t);i===void 0&&(i=new Map,e.set(t,i));let a=i.get(n);if(a!==void 0)return a;let o=r();return i.set(n,o),o}}const _m=[`primary`,`secondary`,`accent`],vm=[`darken-3`,`darken-2`,`darken-1`,`base`,`lighten-1`,`lighten-2`,`lighten-3`],ym={"darken-3":`-darken-3`,"darken-2":`-darken-2`,"darken-1":`-darken-1`,base:``,"lighten-1":`-lighten-1`,"lighten-2":`-lighten-2`,"lighten-3":`-lighten-3`,muted:`-muted`},bm=(e,t)=>`${e}${ym[t]}`,xm=(e,t,n,r)=>eh(e,n,r),Sm=(e,t,n,r)=>nh(e,Wm(e,`text-${t}`),n,r),Cm=e=>({tones:[vm[e],vm[e+2],vm[e+1]],text:xm}),wm={muted:{tones:[`muted`],text:Sm},deepest:Cm(0),deeper:Cm(1),middle:Cm(2),brighter:Cm(3),brightest:Cm(4)},Tm=1/0,Em={accent:{hues:[`secondary`,`accent`],run:Tm},duo:{hues:[`primary`,`secondary`],run:Tm},mono:{hues:[`primary`],run:Tm},alt:{hues:[`secondary`,`accent`],run:3}},Dm=e=>e.variation.hues.flatMap(t=>e.shade.tones.map(e=>({hue:t,shade:e}))),Om=e=>{let t=0,n=.5;for(let r=e;r>0;r>>=1,n/=2)t+=n*(r&1);return t},km=[`van-der-corput`,`golden-angle`,`ends-interleaved`,`monotonic`,`uniform`],Am=e=>typeof e==`string`&&km.includes(e),jm={"van-der-corput":Om,"golden-angle":e=>e*.6180339887498949%1,"ends-interleaved":(e,t)=>((e%2==0?e/2:t-1-(e-1)/2)+.5)/t,monotonic:(e,t)=>(e+.5)/t,uniform:()=>.5},Mm=e=>jm[e??`van-der-corput`];function Nm(e){let t=0,n=1;for(let{index:r,count:i,distribution:a}of e)t+=a(r,i)*n,n*=.37;return t%1}const Pm=(e,t)=>Math.floor(e*t),Fm=(e,t)=>Math.round(e*t)%t;function Im(e){return e===void 0?0:e.distribution(e.index,e.count)}function Lm(e,t,n){let r=e[n(Im(t),e.length)];if(r===void 0)throw Error(`vocabularySelect: empty vocabulary`);return r}function Rm(e){let t=e.findIndex(e=>e.axis===`cell`),n=t===-1?e:e.slice(0,t);return{row:n.at(-1),cell:e[n.length]}}const zm=(e,t)=>Pm(Im(t),e.hues.length);function Bm(e,t){let{row:n,cell:r}=Rm(t);return Vm(e,n,r)}function Vm(e,t,n){let{hues:r,run:i}=e.variation,a=n===void 0?0:Math.floor(n.index/i),o=r[(zm(e.variation,t)+a)%r.length];if(o===void 0)throw Error(`decorEntryFor: empty variation`);return{hue:o,shade:Lm(e.shade.tones,n,Fm)}}function Hm(e,t){let{row:n,cell:r}=Rm(t),i=r===void 0?[void 0]:Array.from({length:r.count},(e,t)=>({...r,index:t}));return[...new Map(i.map(t=>Vm(e,n,t)).map(e=>[bm(e.hue,e.shade),e])).values()].sort((e,t)=>_m.indexOf(e.hue)-_m.indexOf(t.hue)||Um.indexOf(e.shade)-Um.indexOf(t.shade))}const Um=[...vm,`muted`];function Wm(e,t){let n=e.get(t);if(n===void 0)throw Error(`palette "${e.name}" has no "${t}" role; decoration needs it`);return n}const Gm=(e,t)=>Wm(e,bm(t.hue,t.shade)),Km=2.2,qm=(e,t)=>t.map(t=>Gm(e,t)),Jm=e=>t=>Wc(t,e),Ym=Jm(z.TRUECOLOR);function Xm(e,t,n,r){return Zm(e,`${t}|${n.map(e=>e.hex).join(`+`)}|${r}`,()=>Qm(e,t,n,r))}const Zm=gm();function Qm(e,t,n,r){let i=n.map(Ym),a=Wm(e,t),o=new R(0,0,0),s=new R(255,255,255),c=(e,t)=>V.fromRgba(a).mixAxes(V.fromRgba(e),{l:t,c:0,h:0,alpha:0}).toRgba(),l=e=>Array.from({length:12},(t,n)=>c(e,(n+1)/12)),u=l(o),d=[a,...l(s).flatMap((e,t)=>[e,u[t]])],f=e=>{let t=Jm(e),n=i.map(t);return e=>Math.min(1/0,...n.map(n=>ws(t(e),n)))},p=f(z.TRUECOLOR),m=f(r),h=e=>Uc(e,r,(e,t)=>i.every(n=>ws(e,t(n))>=Km)),g=e=>p(e)>=2.2&&h(e)!==void 0,_=(e,t)=>{let n=n=>ws(Ym(n),e)-ws(Ym(n),t),r=n(a)<0?o:s,i=r===o?1:-1,[l,u]=[0,1];for(let e=0;e<40;e++){let e=(l+u)/2;i*n(c(r,e))>0?u=e:l=e}return[c(r,l),c(r,u)]},v=()=>{let e=[...i].sort((e,t)=>Cs(e)-Cs(t));return e.slice(1).flatMap((t,n)=>_(t,e[n]))},y=d.find(g)??[...d,...v()].reduce((e,t)=>m(t)>m(e)?t:e),b=h(y)??y,ee=m(b);return{anchor:y,state:b,short:ee>=2.2?null:ee}}const $m=4.5;function eh(e,t,n){return th(e,`${t.hex}|${n}`,()=>{let r=Vc(t);return nh(e,[`background`,`foreground`].map(t=>Wm(e,t)).reduce((e,t)=>ws(r,t)<ws(r,e)?t:e),t,n)})}const th=gm();function nh(e,t,n,r){return rh(e,`${t.hex}|${n.hex}|${r}`,()=>Hc(t,n,$m,r))}const rh=gm();function ih(e,t,n){return t.depth===0?qm(e,t.ground):ah(e,t,n)}const ah=(e,t,n)=>t.depth===0?[]:[gh(e,{...t,depth:t.depth-1},n).plane],oh=(e,{short:t},n)=>t===null?[]:[`theme "${e.name}": no open-trigger colour stands ${Km}:1 off every cell beside it — the nearest stands ${t.toFixed(2)}:1 as drawn at depth ${z[n]}; another shade or variation clears it`],sh=(e,t,n)=>t>=dh.triggerPlane?[]:[`theme "${e.name}": an open band's plane stands ΔE ${t.toFixed(3)} off the trigger that opened it as drawn at depth ${z[n]}, under the ${dh.triggerPlane} that tells them apart; another style clears it`],ch={base:.42,perDepth:.14,cap:.75},lh={floor:.12,span:.8};function uh(e,t){return _m[(_m.indexOf(e)+t)%_m.length]}const dh={triggerPlane:.1,nestedPlane:.035};function fh(e,t,n){return ph(e,`${mh(t)}|${n}`,()=>{let r=Xm(e,uh(t.hue,t.depth),ih(e,t,n),n),{state:i}=r,a=bh(e,t,i,n),o=Uc(gh(e,t,n).plane,n,(e,t)=>a.every(n=>n(e,t)));if(o===void 0)throw Error(`palette "${e.name}": the ${t.hue} band at depth ${t.depth} cannot keep its floors on the colours drawn at depth ${z[n]}`);let s=Jm(n);return{state:i,plane:o,shortfalls:n===z.DEFAULT?[]:[...oh(e,r,n),...sh(e,hh(s(i),s(o)),n)]}})}const ph=gm(),mh=({hue:e,depth:t,ground:n})=>`${e}|${t}|${n.map(e=>bm(e.hue,e.shade)).join(`+`)}`,hh=(e,t)=>V.fromRgba(e).deltaE(V.fromRgba(t));function gh(e,t,n){return _h(e,`${mh(t)}|${n}`,()=>vh(e,t,n))}const _h=gm();function vh(e,t,n){let{anchor:r}=Xm(e,uh(t.hue,t.depth),ih(e,t,n),n),i=Math.min(ch.cap,ch.base+ch.perDepth*t.depth),a=(t,n)=>rc(r,Wm(e,t),n),o=ah(e,t,n),s=e=>hh(Ym(r),Ym(e))>=dh.triggerPlane&&o.every(t=>hh(Ym(t),Ym(e))>=dh.nestedPlane),c=a(`background`,i);return{state:r,plane:[c,a(`foreground`,i),a(`background`,ch.cap),a(`foreground`,ch.cap),...yh.toSorted((e,t)=>Math.abs(e-i)-Math.abs(t-i)).flatMap(e=>[a(`background`,e),a(`foreground`,e)])].find(s)??c}}const yh=Array.from({length:12},(e,t)=>(t+1)/12);function bh(e,t,n,r){let{hue:i,depth:a,ground:o}=t,s=t=>gh(e,{hue:i,depth:t,ground:o},r).state,c=t=>gh(e,{hue:i,depth:t,ground:o},r).plane,l=c(a),u=(e,t)=>hh(Ym(l),Ym(t))>=e?e:0,d=Xm(e,uh(i,a+1),ih(e,{hue:i,depth:a+1,ground:o},r),r),f=ws(Ym(l),Ym(d.anchor))>=2.2?Km:0,p=(e,t)=>(n,r)=>hh(n,r(e))>=t;return[p(n,u(dh.triggerPlane,s(a))),(e,t)=>ws(e,t(d.state))>=f,...a>0?[p(fh(e,{hue:i,depth:a-1,ground:o},r).plane,u(dh.nestedPlane,c(a-1)))]:[]]}function xh(e,t,n,r){let i=fh(e,t,r),a=gh(e,t,r),o=e=>rc(a.plane,a.state,e),s=lh.floor+lh.span*Nm(n),c=lh.floor+lh.span/2,l=(e,t)=>e.hex!==t(i.plane).hex&&e.hex!==t(i.state).hex;for(let e=0;e<=12;e++){let t=Uc(o(s+(c-s)*e/12),r,l);if(t!==void 0)return t}return o(s)}const Sh=e=>({kind:`bar`,decor:e,address:[]}),Ch=(e,t)=>({...e,address:[...e.address,t]}),wh=e=>({kind:`band`,band:e,address:[]});function Th(e,t,n){switch(t.kind){case`bar`:{let{decor:r,address:i}=t,a=Bm(r,i),o=Gm(e,a),s;return{tint:o,text:r.shade.text(e,a.hue,o,n),disclosure:{hue:`accent`,depth:0,get ground(){return s??=Hm(r,i)}}}}case`band`:{let{band:r,address:i}=t,a=xh(e,r,i,n);return{tint:a,text:eh(e,a,n),disclosure:{...r,depth:r.depth+1}}}}}const Eh=new Map([[`dark`,`textual-dark`],[`light`,`textual-light`]]);function Dh(e){let t=typeof e==`string`?Eh.get(e):void 0;return t===void 0?``:` — "${e}" was retired; write "${t}", the same palette`}const Oh=`textual-dark`;function kh(e,t,n,r,i){let a=t===null?null:i(t);return e??a??n??r}function Ah(){return dl()}function jh(){return[`bar`,...Ah()]}let Mh;function Nh(e){return Mh??=new Set(jh()),Mh.has(e)}function Ph(e,t,n,r,i){let a=e=>Object.prototype.hasOwnProperty.call(i,e)?e:null;return kh(e===void 0?null:a(e),t,a(n??r),r,a)}const Fh=[`style`,`palette`,`effect`];function Ih(e){return e!==void 0&&e.includes(`{{`)}function Lh(e,t,n,r,i){let a=Ih(n)?{kind:`expression`,source:n}:i(n??r.name);return kh(e===void 0?null:i(e),t,a,r,i)}function Rh(e,t){return e.kind===`decided`?e:t(e.source)}const zh=`none`;function Bh(e,t){let n=t[e];return n===void 0?null:{kind:`decided`,name:e,value:n}}function Vh(e,t){return Bh(e,t)??Bh(`none`,t)??{kind:`decided`,name:`none`,value:xc}}function Hh(e,t,n,r){return Lh(e,t,n,Vh(zh,r),e=>Bh(e,r))}const Uh=`none`,Wh={style:zh,palette:Oh,effect:Uh};function Gh(e,t,n){return`${e} rendered "${Wh[t]}": ${n}`}const Kh=Object.freeze([Uh,...Object.keys(sm.loops)]),qh=Object.freeze([`bar`,...Kh]);function Jh(e){let t=Kh.find(t=>t===e);return t===void 0?null:{kind:`decided`,name:e,value:t}}function Yh(e){return Jh(e)??{kind:`decided`,name:`none`,value:`none`}}function Xh(e,t,n){return Lh(e,t,n,Yh(Uh),Jh)}const Zh=Object.freeze(Object.keys(jf)),Qh=[`powerline`,`capsule`,`plain`];function $h(e){return Qh.includes(e)}const eg=[`truecolor`,`256`,`ansi`,`none`];function tg(e){return Ls(e)??z.DEFAULT}const ng=Object.keys(Em),rg=Object.keys(wm),ig=`true`,ag=`false`,og=[ig,ag],sg={min:0,max:16};function cg(e){return e===`true`?!0:e===`false`?!1:null}function lg(e,t){let n=Number(e);return Number.isInteger(n)&&String(n)===e&&n>=t.min&&n<=t.max?n:null}const ug=[`vertical`,`horizontal`],dg={vertical:`row`,horizontal:`cell`};function fg(e){return e.id??e.name}function pg(e){return[...gg(e)].flatMap(e=>e.kind===`segment`?[fg(e)]:[])}function mg(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e}-${n}`);)n++;return`${e}-${n}`}function hg(e,t){return e.opens===void 0?e:{...e,opens:{...e.opens,body:t(e.opens.body)}}}function*gg(e){yield e;for(let t of bg(e))yield*gg(t)}const _g=(e,t)=>`${e}.children[${t}]`,vg=e=>`${e}.opens.body`;function*yg(e,t){if(yield[e,t],e.kind===`container`)for(let[n,r]of e.children.entries())yield*yg(r,_g(t,n));else e.opens!==void 0&&(yield*yg(e.opens.body,vg(t)))}function bg(e){return e.kind===`container`?e.children:e.opens===void 0?[]:[e.opens.body]}function xg(e){return e===void 0||`text`in e?`text`:`regex`in e?`regex`:`json`}const Sg=[`ttl`,`watch_file`,`depends_on`,`key`,`never`];function Cg(e){return e.kind===`file`||e.kind===`shell`}const wg=[`branch`,`sha`,`dirty`,`ahead`,`behind`,`stash`],Tg=[`fail`,`ignore`];function Eg(e){return e.missingData??`fail`}function*Dg(e){for(let[t,n]of Object.entries(e.variables))n.kind===`state`&&(yield[t,n]);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))r.kind===`state`&&(yield[`${t}.${e}`,r])}const Og=`theme`,kg=`effect`,Ag=[Og,kg];function jg(e){return{...e.settings,[Og]:{label:Og,domain:`theme`,default:e.palette??`bar`},[kg]:{label:kg,domain:qh,default:`bar`}}}function Mg(e){let t=e?.domain;return typeof t==`object`&&`min`in t?t:void 0}function Ng(e,t){return Object.entries(e).flatMap(([n,r])=>{let i=Mg(r)?.atLeast;if(i===void 0)return[];let a=t[n],o=t[i];return a>=o?[]:[{setting:n,message:`"${n}" (${a}) is below "${i}" (${o}) — ${r.label} must be at least ${e[i].label}`}]})}function Pg(e,t){let{domain:n}=e;return n===`bool`?typeof t==`boolean`:n===`theme`?typeof t==`string`&&Nh(t):`min`in n?typeof t==`number`&&Number.isInteger(t)&&t>=n.min&&t<=n.max:typeof t==`string`&&n.includes(t)}function Fg(e){return String(e)}function Ig(e,t){let{domain:n}=e;if(typeof n==`object`&&`min`in n)return lg(t,n)??void 0;let r=n===`bool`?t===`true`?!0:t===`false`?!1:t:t;return Pg(e,r)?r:void 0}function Lg(e,t,n,r){let i=e.settings?.[t]??n.default,a=e.drafts?.[t],o=a===void 0?null:r(a);return(o===null?void 0:Ig(n,o))??i}function Rg(e){let{domain:t}=e;return t===`bool`?`true or false`:t===`theme`?`"bar" (the bar's own theme) or an installed theme name`:`min`in t?`an integer from ${t.min} to ${t.max}`:`one of ${t.map(e=>JSON.stringify(e)).join(`, `)}`}const zg=[`left`,`center`,`right`],Bg=[`right`,`left`,`middle`];var Vg=class extends Error{file;issues;warnings;constructor(e,t,n=[]){super(Gg(e,t)),this.name=`ConfigError`,this.file=e,this.issues=t,this.warnings=n}};function K(e,t){let n=0,r;for(let i of t){if(i===``||/^\d+$/.test(i))continue;let t=Hg(e,n,i);if(t===-1)return r===void 0?void 0:Ug(e,r);n=t,r=t}return r===void 0?void 0:Ug(e,r)}function Hg(e,t,n){let r=n.replace(/[\\^$.*+?()[\]{}|]/g,`\\$&`),i=RegExp(`(?:["']${r}["']|\\b${r}\\b)\\s*:`,`g`);i.lastIndex=t;let a=i.exec(e);return a?a.index:-1}function Ug(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e.charCodeAt(r)===10&&n++;return n}function Wg(e,t){try{return _i(t),null}catch(n){if(!(n instanceof di))throw n;return`${e}:${Ug(t,n.offset)}: ${n.reason} — the settings menu cannot edit this file until it is fixed`}}function Gg(e,t){if(t.length===0)return`${e}: invalid config (no details)`;let n=[`Invalid config in ${e} (${t.length} issue${t.length===1?``:`s`}):`];for(let e of t){let t=[];e.line!==void 0&&t.push(`line ${e.line}${e.col===void 0?``:`:${e.col}`}`),e.path&&t.push(e.path);let r=t.length>0?`[${t.join(` • `)}] `:``;n.push(` ${r}${e.message}`)}return n.join(`
55
- `)}function Kg(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),r])}),null)}function qg(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),`default`])});return}return i}}function Jg(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),r])});return}return i}}function Yg(e,t,n){let r=Jg(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Dh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[...t.split(`.`),`palette`])});return}return r}}function Xg(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${q(a)}`,line:K(e.source,[...t.split(`.`),r])});return}return a}}function Zg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qg(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function q(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function $g(e,t,n,r){return Zg(r)?(r_(e,n,r,t.noun,new Set(Object.keys(t.fields)),e_(e,t.removed??{},n,r)),t_(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null)}function e_(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)i_(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function t_(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const n_=new Set;function r_(e,t,n,r,i,a=n_){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:K(e.source,[...t.split(`.`),o])})}function i_(e,t,n){return e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))}),null}function a_(e,t,n,r){if(!Zg(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:K(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:K(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:K(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function o_(e,t,n,r){if(!Zg(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Qg(i)}`,line:K(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:K(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return r_(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function s_(e,t,n){return{json:x_(y_(n),e,t),keys:new Set([e,...Object.keys(n)])}}function c_(e){return(...t)=>e()(...t)}function l_(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:K(n.source,o.split(`.`))}),null}return a}}function u_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Jg(e,t,r,n)}}function d_(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Qg(i)}`,line:K(e.source,[n])});return}return i}}}}function f_(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${q(o)}`,line:K(e.source,[i])});return}return o}}}}function p_(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${q(a)}`,line:K(e.source,[r])});return}return a}}}}function m_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Yg(e,t,r)}}function h_(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Kg(e,t,r,n)??void 0}}function g_(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function __(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Kg(e,t,r,n);if(i===null)return;let a=g_(`${t}.${n}`,i);return a===null?i:i_(e,`${t}.${n}`,a)??void 0}}}function v_(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Xg(t,n,i,r,e)}}function y_(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function b_(e){return y_(e.fields)}function x_(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function S_(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function C_(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const w_={band:{setting:`experimentalBand`,label:`🧪 band (A)`,elsewhere:`the band above the prompt`},statusline:{setting:`experimentalStatusline`,label:`🧪 statusline (B)`,elsewhere:null},pane:{setting:`experimentalPane`,label:`🧪 tmux pane (C)`,elsewhere:`a tmux pane below`}},T_=Object.keys(w_),E_={by:`request`},D_=e=>`drawing.${e}`,O_={subscribers:0,fps:0,shown:!0},k_=(e,t)=>`feeds.${e}.${t}`;function A_(e){return Object.fromEntries(T_.map(t=>[t,e(t)]))}const j_=A_(()=>O_);function M_(e){return typeof e==`string`&&Object.hasOwn(w_,e)?e:null}const N_=(e,t,n=[])=>({label:e,place:t,previews:n}),P_=(e,t)=>({spec:v_(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e}}}),F_={spec:d_(),domain:`bool`,parse:cg},I_=e=>({spec:f_(e),domain:e,parse:t=>lg(t,e)});function L_(e,t,n,r={}){return{kind:`session`,...P_(e,r.optionDomain),floor:t,control:n,themeDefault:r.themeDefault??!1}}function R_(e,t){return{kind:`session`,...F_,floor:e,control:t,themeDefault:!1}}function z_(e,t,n){return{kind:`session`,...I_(e),floor:t,control:n,themeDefault:!1}}function B_(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const V_=e=>({kind:`text`,spec:e}),H_={required:!1,json:{enum:[...eg]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${eg.join(`, `)}`,line:K(e.source,[...t.split(`.`),n])});return}return Xg(e,t,r,n,eg)}},U_={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Jg(e,t,r,n);return Ih(i)?i:Yg(e,t,r)}},W_={required:!1,json:{anyOf:[{enum:[...Kh]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Ih(i)?i:Xg(e,t,r,n,Kh)}},G_=/^[^\r\n]*\S[^\r\n]*$/u,K_=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),q_={required:!1,json:{type:`string`,pattern:G_.source,not:{pattern:K_.source}},parse:(e,t,n,r)=>{let i=Jg(e,t,r,n);if(i===void 0||G_.test(i)&&!K_.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:K(e.source,[...t.split(`.`),n])})}},J_=Object.fromEntries(T_.map(e=>[w_[e].setting,R_(!1,N_(w_[e].label,`toggles`))])),Y_={palette:B_(`theme`,U_,{themes:`themes`},N_(`🎨 theme`,`look`)),preset:B_(`preset`,u_(),{from:`presets`},N_(`▦`,`door`,[`layout`,`presetDelete`])),style:B_(`style`,u_(),{from:`styles`},N_(`◐`,`gear`,[`palette`]),{themeDefault:!0}),effect:B_(`effect`,W_,{from:Kh},N_(`✨`,`look`)),endcaps:L_(Zh,`powerline`,N_(`✦`,`look`),{optionDomain:`endcaps`}),variation:L_(ng,`accent`,N_(`🎼`,`gear`,[`layout`]),{optionDomain:`variations`,themeDefault:!0}),shade:L_(rg,`middle`,N_(`🔆`,`gear`,[`layout`]),{optionDomain:`shades`,themeDefault:!0}),transitions:R_(!1,N_(`fade in/out`,`look`)),autoWrap:R_(!0,N_(`wrap`,`layout`)),padding:z_({...sg,step:1},1,N_(`padding`,`layout`)),updateNotice:R_(!0,N_(`update notice`,`config`)),...J_,colorCompatibility:{kind:`config`,...P_(eg,`colorCompatibilities`),spec:H_,floor:`truecolor`},default_empty_value:V_(u_()),default_separator:V_(u_()),menuGlyph:V_(q_)},X_=Object.entries(Y_),Z_=X_.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Q_=X_.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),$_=X_.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),ev=X_.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function tv(e){return Y_[e]}const nv=e=>tv(e).floor;function rv(e){let t=Y_[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const iv=e=>`${e}.effective`,av=e=>{let t=Y_[e];return t.kind===`selection`?t.sessionKey:e},ov=Object.fromEntries(Q_.map(e=>{let t=av(e);return[t,{configKey:e,sessionKey:t,effectiveVar:iv(t),...Y_[e].control}]})),sv=Object.keys(ov),cv=Object.values(ov),lv=Z_.filter(e=>Y_[e].kind===`config`).map(e=>({configKey:e,effectiveVar:iv(e)})),uv=new Set(lv.map(e=>e.configKey)),dv=new Map([...cv,...lv].map(e=>[e.configKey,e.effectiveVar])),fv=new Map(cv.map(e=>[e.sessionKey,e.effectiveVar]));function pv(e){return Object.fromEntries(sv.map(t=>[t,e(t)]))}const mv=new Map(sv.map(e=>[ov[e].sessionKey,e])),hv=[[0,31],[127,159],[8234,8238],[8294,8303]];function gv(e){return hv.some(([t,n])=>e>=t&&e<=n)}function _v(e){let t=``;for(let n of e)t+=gv(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function vv(e,t){let n=_v(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const yv=`\x1B[38;2;255;255;255m`,bv=`\x1B[48;2;200;40;40m`,xv=`\x1B[0m`;function Sv(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const Cv={fg:Sv(yv),bg:Sv(bv)},wv={fg:Sv(`\x1B[38;2;0;0;0m`),bg:Sv(`\x1B[48;2;220;160;40m`)},Tv=new Su({"strip.separator":`default`,"strip.rail":`default`});function Ev(e){return Tv.resolve(e)}const Dv={kind:`still`},Ov=Symbol(`bar`);function kv(e){return e.name!==Uh}function Av(e,t){return n=>iu.map(iu.all(t.map(({t,effect:r})=>fu.run(fu.play(e-t),r(n)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const jv=bl;function Mv(e,t){let n=new ic(t,jv.foregroundColor,jv.ansiColors,jv.palette);return t=>e({...t,theme:n})}function Nv(e,t){return n=>$f(()=>e(n),...t)(n)}function Pv(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const Fv=4096;var Iv=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Uh,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(({passage:e})=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:Ov,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision&&u.source.width===n.source.width?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h=[],g={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m,leaves:h},_=(e,n,{ground:r})=>{let i=sm.transitions[e]({z:Pv(`${this.key}@${n}`)*Fv});return{name:e,since:t,transition:{effect:Mv(i.effect,r),done:e=>i.done(e)}}},v=({since:e,transition:n})=>n.done(t-e),y=(e,t,n)=>({drawing:t,passage:f===null?null:n===void 0||n.passage?.name===`dissolve`?_(`fade`,e,t):n.passage!==null&&!v(n.passage)?n.passage:null}),b=(e,t)=>{if(t===void 0||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return v(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:_(`dissolve`,e,r)}},ee=(e,r)=>{if(p.has(e))throw Error(`placement "${e}" was reached twice in one frame`);let i=f?.get(e),{drawing:a,deeper:o}=n.returned(e,r),s=a===null?b(e,i):y(e,a,i);return s===void 0?r:(p.set(e,s),s.passage!==null&&(s.passage.name===`fade`?m:h).push({placement:e,t:t-s.passage.since}),a===null?[...s.drawing.own,...o]:r)},x=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},S=(e,t)=>{let n=c.get(e)??new Map;c.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=s.get(e)?.get(t.scope),a=i?.name===t.name,o=Pv(t.scope===Ov?e:`${e}@${t.scope}`),l=a?i.effect:sm.loops[t.name]({z:o*Fv});return g[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:l}),l},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:x(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},ne=e=>{let n=new Map;for(let{owner:t,placement:r}of e){let e=n.get(r.id);e===void 0?n.set(r.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=p.get(e)?.passage??null;return r===null?[]:[{t:t-r.since,effect:$f(r.transition.effect,...n)}]})};return{placed:d===`off`?(e,t)=>t:ee,row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?te(t):[{...i,owners:void 0}]).filter(kv),r=ne(t);if(n.length===0&&r.length===0)return Dv;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:e=>new qf(e,Av(i.t,[...n.map(e=>{let t=S(a,e);return{t:e.t,effect:e.owners===void 0?t:Nv(t,e.owners)}}),...r]),{t:i.t,key:a,theme:jv})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=g}}}},Lv=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new Iv(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function Rv(e,t){let n=Is(t.colorSystem),r=[...Vu(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:Tv,colorSystem:n.colorSystem,onStyleError:e=>{throw e}})];return{text:Nf(r,n),moves:Number.isFinite(W.nextChange(r))}}const zv=new Map;function Bv(e){let t=zv.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>`cap`in t?t:{...t,glyph:e});return{seam:n,divider:n}},{seam:r,caps:i}=jf.plain,a=new $d({glyph:n(r.glyph),ascii:r.ascii},i);return zv.set(e,a),a}function Vv(e,t){return e===`plain`&&t!==void 0?Bv(t):jf[e]}const Hv=new Map;function Uv(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=Hv.get(t);if(n!==void 0)return n;let r=Vv(e.endcaps,e.separator),i=e=>new G(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=e=>new G(Rv(new Ed(e,r),{colorSystem:null}).text.replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return Hv.set(t,s),s}function Wv(e){return Uv(e).chrome}function Gv(e){return Uv(e).seam}const Kv=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function qv(e){return[...new Set(e.match(Kv)??[])].join(``)}function Jv(e){let t=Vv(e.endcaps,e.separator),n=e=>new G(`x`,{end:``,style:new H({bgcolor:e})});return qv(Rv(new Ed([n(`#101010`),n(`#202020`),n(`#202020`)],t),{colorSystem:null}).text)}function Yv(e,t,n=Dv){if(e.length===0)return{text:``,moves:!1};let r=Vv(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new hm([...e],{joiner:r}):new Ed([...e],r),s=Rv(n.kind===`still`?o:n.wrap(o),a);if(!s.text.endsWith(`
55
+ `)}function Kg(e,t,n,r){let i=n[r];return typeof i==`string`?i:(e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),r])}),null)}function qg(e,t,n,r){let i=n.default;if(i!==void 0){if(!(r===`string`&&typeof i==`string`||r===`number`&&typeof i==`number`||r===`boolean`&&typeof i==`boolean`)){e.issues.push({path:`${t}.default`,message:`default must be a ${r}, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),`default`])});return}return i}}function Jg(e,t,n,r){let i=n[r];if(i!==void 0){if(typeof i!=`string`){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be a string, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),r])});return}return i}}function Yg(e,t,n){let r=Jg(e,t,n,`palette`);if(r!==void 0){if(!e.allowedPalettes.has(r)){e.issues.push({path:`${t}.palette`,message:`Unknown palette "${r}"${Dh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[...t.split(`.`),`palette`])});return}return r}}function Xg(e,t,n,r,i){let a=n[r];if(a!==void 0){if(typeof a!=`string`||!i.includes(a)){e.issues.push({path:`${t}.${r}`,message:`${t}.${r} must be one of: ${i.join(`, `)}; got ${q(a)}`,line:K(e.source,[...t.split(`.`),r])});return}return a}}function Zg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Qg(e){return e===null?`null`:Array.isArray(e)?`array`:typeof e}function q(e){return typeof e==`string`?JSON.stringify(e):e===void 0?`undefined`:String(e)}function $g(e,t,n,r){return Zg(r)?(r_(e,n,r,t.noun,new Set(Object.keys(t.fields)),e_(e,t.removed??{},n,r)),t_(e,t.fields,n,r)):(e.issues.push({path:n,message:`${n} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null)}function e_(e,t,n,r){let i=Object.entries(t).filter(([e])=>r[e]!==void 0);for(let[t,r]of i)i_(e,`${n}.${t}`,`${n}.${t} was removed: ${r}`);return new Set(i.map(([e])=>`${n}.${e}`))}function t_(e,t,n,r){let i=t,a={},o=!0;for(let[t,s]of Object.entries(i)){let i=s.parse(e,n,t,r);i===void 0?s.required&&(o=!1):a[t]=i}return o?a:null}const n_=new Set;function r_(e,t,n,r,i,a=n_){for(let o of Object.keys(n))!i.has(o)&&!a.has(`${t}.${o}`)&&e.issues.push({path:`${t}.${o}`,message:`Unknown ${r} "${o}". Expected one of: ${[...i].join(`, `)}`,line:K(e.source,[...t.split(`.`),o])})}function i_(e,t,n){return e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))}),null}function a_(e,t,n,r){if(!Zg(r))return e.issues.push({path:n,message:`${t.noun} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null;let i=t.arms,a=Object.keys(i),o=Object.keys(r).filter(e=>e in i),s=Object.keys(r).filter(e=>!(e in i));for(let r of s)e.issues.push({path:`${n}.${r}`,message:`Unknown ${t.noun} key "${r}". Expected exactly one of: ${a.join(`, `)}`,line:K(e.source,[...n.split(`.`),r])});if(o.length===0)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)}`,line:K(e.source,n.split(`.`))}),null;if(o.length>1)return e.issues.push({path:n,message:`${t.noun} must declare exactly one of: ${a.join(`, `)} (found: ${o.join(`, `)})`,line:K(e.source,n.split(`.`))}),null;let c=o[0];return i[c].parse(e,`${n}.${c}`,r[c])}function o_(e,t,n,r){if(!Zg(r))return e.issues.push({path:n,message:`${n} must be an object, got ${Qg(r)}`,line:K(e.source,n.split(`.`))}),null;let i=r[t.tag];if(typeof i!=`string`)return e.issues.push({path:`${n}.${t.tag}`,message:`${n}.${t.tag} must be a string, got ${Qg(i)}`,line:K(e.source,n.split(`.`))}),null;let a=t.arms;if(!(i in a))return e.issues.push({path:`${n}.${t.tag}`,message:`Unknown ${t.noun} "${i}". Expected one of: ${Object.keys(a).join(`, `)}`,line:K(e.source,[...n.split(`.`),t.tag])}),null;let o=a[i],s=e.issues.length,c=o.parse(e,n,r),l=new Set(e.issues.slice(s).map(e=>e.path));return r_(e,n,r,`${i} ${t.memberNoun} key`,o.keys,l),c}function s_(e,t,n){return{json:x_(y_(n),e,t),keys:new Set([e,...Object.keys(n)])}}function c_(e){return(...t)=>e()(...t)}function l_(e,...t){return(n,r,i)=>{let a=e(n,r,i);if(a===null)return null;for(let e of t){if(e.ok(a))continue;let{field:t,message:i}=e.issue(a),o=t===``?r:`${r}.${t}`;return n.issues.push({path:o,message:i,line:K(n.source,o.split(`.`))}),null}return a}}function u_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Jg(e,t,r,n)}}function d_(){return{required:!1,json:{type:`boolean`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`boolean`){e.issues.push({path:`${t}.${n}`,message:`${n} must be a boolean, got ${Qg(i)}`,line:K(e.source,[n])});return}return i}}}}function f_(e){let{min:t,max:n}=e;return{required:!1,json:{type:`integer`,minimum:t,maximum:n},parse:(e,r,i,a)=>{let o=a[i];if(o!==void 0){if(typeof o!=`number`||!Number.isInteger(o)||o<t||o>n){e.issues.push({path:`${r}.${i}`,message:`${i} must be an integer between ${t} and ${n}, got ${q(o)}`,line:K(e.source,[i])});return}return o}}}}function p_(e={}){let{min:t}=e;return{required:!1,json:{type:`number`,...t!==void 0&&{minimum:t}},parse:(e,n,r,i)=>{let a=i[r];if(a!==void 0){if(typeof a!=`number`||!Number.isFinite(a)||t!==void 0&&a<t){let i=t===void 0?`a finite number`:`a finite number >= ${t}`;e.issues.push({path:`${n}.${r}`,message:`${r} must be ${i}, got ${q(a)}`,line:K(e.source,[r])});return}return a}}}}function m_(){return{required:!1,json:{type:`string`},parse:(e,t,n,r)=>Yg(e,t,r)}}function h_(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>Kg(e,t,r,n)??void 0}}function g_(e,t){return u(t)?null:`${e} must be an absolute path (\`~\` and relative paths are not expanded), got ${JSON.stringify(t)}`}function __(){return{required:!0,json:{type:`string`,pattern:`^/`},parse:(e,t,n,r)=>{let i=Kg(e,t,r,n);if(i===null)return;let a=g_(`${t}.${n}`,i);return a===null?i:i_(e,`${t}.${n}`,a)??void 0}}}function v_(e){return{required:!1,json:{enum:[...e]},parse:(t,n,r,i)=>Xg(t,n,i,r,e)}}function y_(e,t={closed:!0}){let n=e,r={},i=[];for(let[e,t]of Object.entries(n))r[e]=t.json,t.required&&i.push(e);return{type:`object`,properties:r,...i.length>0&&{required:i},...t.closed&&{additionalProperties:!1}}}function b_(e){return y_(e.fields)}function x_(e,t,n){let r=e,i={[t]:{const:n},...r.properties},a=[t,...r.required??[]];return{...r,properties:i,required:a}}function S_(e){let t=e.arms;return{anyOf:Object.values(t).map(e=>e.json)}}function C_(e){let t=e.arms;return{anyOf:Object.entries(t).map(([e,t])=>({type:`object`,properties:{[e]:t.json},required:[e],additionalProperties:!1}))}}const w_={band:{setting:`experimentalBand`,label:`🧪 band (A)`,elsewhere:`the band above the prompt`},statusline:{setting:`experimentalStatusline`,label:`🧪 statusline (B)`,elsewhere:null},pane:{setting:`experimentalPane`,label:`🧪 tmux pane (C)`,elsewhere:`a tmux pane below`},tmuxStatus:{setting:`experimentalTmuxStatus`,label:`🧪 tmux status line (C)`,elsewhere:`the tmux status line`}},T_=Object.keys(w_),E_={by:`request`},D_=e=>`drawing.${e}`,O_={subscribers:0,fps:0,shown:!0},k_=(e,t)=>`feeds.${e}.${t}`;function A_(e){return Object.fromEntries(T_.map(t=>[t,e(t)]))}const j_=A_(()=>O_);function M_(e){return typeof e==`string`&&Object.hasOwn(w_,e)?e:null}const N_=(e,t,n=[])=>({label:e,place:t,previews:n}),P_=(e,t)=>({spec:v_(e),domain:{from:e},parse:t=>e.includes(t)?t:null,...t!==void 0&&{optionDomain:{name:t,members:e}}}),F_={spec:d_(),domain:`bool`,parse:cg},I_=e=>({spec:f_(e),domain:e,parse:t=>lg(t,e)});function L_(e,t,n,r={}){return{kind:`session`,...P_(e,r.optionDomain),floor:t,control:n,themeDefault:r.themeDefault??!1}}function R_(e,t){return{kind:`session`,...F_,floor:e,control:t,themeDefault:!1}}function z_(e,t,n){return{kind:`session`,...I_(e),floor:t,control:n,themeDefault:!1}}function B_(e,t,n,r,i={}){return{kind:`selection`,sessionKey:e,spec:t,domain:n,control:r,themeDefault:i.themeDefault??!1}}const V_=e=>({kind:`text`,spec:e}),H_={required:!1,json:{enum:[...eg]},parse:(e,t,n,r)=>{if(r[n]===`auto`){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: "auto" is not supported — the render daemon runs detached, so terminal detection would read the daemon's environment, not your terminal's. Pick an explicit depth: ${eg.join(`, `)}`,line:K(e.source,[...t.split(`.`),n])});return}return Xg(e,t,r,n,eg)}},U_={required:!1,json:{type:`string`},parse:(e,t,n,r)=>{let i=Jg(e,t,r,n);return Ih(i)?i:Yg(e,t,r)}},W_={required:!1,json:{anyOf:[{enum:[...Kh]},{type:`string`,pattern:`\\{\\{`}]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&Ih(i)?i:Xg(e,t,r,n,Kh)}},G_=/^[^\r\n]*\S[^\r\n]*$/u,K_=RegExp(`^(?:✖|✕)[\\uFE0E\\uFE0F]?$`,`u`),q_={required:!1,json:{type:`string`,pattern:G_.source,not:{pattern:K_.source}},parse:(e,t,n,r)=>{let i=Jg(e,t,r,n);if(i===void 0||G_.test(i)&&!K_.test(i))return i;e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: must be one line of visible text other than a close glyph ("✖", "✕") — the settings menu needs a glyph to click`,line:K(e.source,[...t.split(`.`),n])})}},J_=Object.fromEntries(T_.map(e=>[w_[e].setting,R_(!1,N_(w_[e].label,`toggles`))])),Y_={palette:B_(`theme`,U_,{themes:`themes`},N_(`🎨 theme`,`look`)),preset:B_(`preset`,u_(),{from:`presets`},N_(`▦`,`door`,[`layout`,`presetDelete`])),style:B_(`style`,u_(),{from:`styles`},N_(`◐`,`gear`,[`palette`]),{themeDefault:!0}),effect:B_(`effect`,W_,{from:Kh},N_(`✨`,`look`)),endcaps:L_(Zh,`powerline`,N_(`✦`,`look`),{optionDomain:`endcaps`}),variation:L_(ng,`accent`,N_(`🎼`,`gear`,[`layout`]),{optionDomain:`variations`,themeDefault:!0}),shade:L_(rg,`middle`,N_(`🔆`,`gear`,[`layout`]),{optionDomain:`shades`,themeDefault:!0}),transitions:R_(!1,N_(`fade in/out`,`look`)),autoWrap:R_(!0,N_(`wrap`,`layout`)),padding:z_({...sg,step:1},1,N_(`padding`,`layout`)),updateNotice:R_(!0,N_(`update notice`,`config`)),...J_,colorCompatibility:{kind:`config`,...P_(eg,`colorCompatibilities`),spec:H_,floor:`truecolor`},default_empty_value:V_(u_()),default_separator:V_(u_()),menuGlyph:V_(q_)},X_=Object.entries(Y_),Z_=X_.filter(([,e])=>e.kind===`session`||e.kind===`config`).map(([e])=>e),Q_=X_.filter(([,e])=>e.kind===`session`||e.kind===`selection`).map(([e])=>e),$_=X_.filter(([,e])=>(e.kind===`session`||e.kind===`selection`)&&e.themeDefault).map(([e])=>e),ev=X_.flatMap(([,e])=>`optionDomain`in e&&e.optionDomain!==void 0?[e.optionDomain]:[]);function tv(e){return Y_[e]}const nv=e=>tv(e).floor;function rv(e){let t=Y_[e];if(t.kind===`text`)return`string`;let{domain:n}=t;return n===`bool`?`boolean`:typeof n==`object`&&`min`in n?`number`:`string`}const iv=e=>`${e}.effective`,av=e=>{let t=Y_[e];return t.kind===`selection`?t.sessionKey:e},ov=Object.fromEntries(Q_.map(e=>{let t=av(e);return[t,{configKey:e,sessionKey:t,effectiveVar:iv(t),...Y_[e].control}]})),sv=Object.keys(ov),cv=Object.values(ov),lv=Z_.filter(e=>Y_[e].kind===`config`).map(e=>({configKey:e,effectiveVar:iv(e)})),uv=new Set(lv.map(e=>e.configKey)),dv=new Map([...cv,...lv].map(e=>[e.configKey,e.effectiveVar])),fv=new Map(cv.map(e=>[e.sessionKey,e.effectiveVar]));function pv(e){return Object.fromEntries(sv.map(t=>[t,e(t)]))}const mv=new Map(sv.map(e=>[ov[e].sessionKey,e])),hv=[[0,31],[127,159],[8234,8238],[8294,8303]];function gv(e){return hv.some(([t,n])=>e>=t&&e<=n)}function _v(e){let t=``;for(let n of e)t+=gv(n.codePointAt(0)??0)?` `:n;return t.replace(/\s+/g,` `).trim()}function vv(e,t){let n=_v(e),r=``,i=0;for(let e of n){if(i===t)return r.replace(/.$/u,`…`);r+=e,i++}return r}const yv=`\x1B[38;2;255;255;255m`,bv=`\x1B[48;2;200;40;40m`,xv=`\x1B[0m`;function Sv(e){let t=/;2;(\d+);(\d+);(\d+)m$/.exec(e);if(t===null)throw Error(`diagnostic-style: not a 24-bit SGR: ${e}`);return`#`+t.slice(1,4).map(e=>Number(e).toString(16).padStart(2,`0`)).join(``)}const Cv={fg:Sv(yv),bg:Sv(bv)},wv={fg:Sv(`\x1B[38;2;0;0;0m`),bg:Sv(`\x1B[48;2;220;160;40m`)},Tv=new Su({"strip.separator":`default`,"strip.rail":`default`});function Ev(e){return Tv.resolve(e)}const Dv={kind:`still`},Ov=Symbol(`bar`);function kv(e){return e.name!==Uh}function Av(e,t){return n=>iu.map(iu.all(t.map(({t,effect:r})=>fu.run(fu.play(e-t),r(n)))),e=>(t,n)=>e.reduce((e,t)=>t(e,n),t))}const jv=bl;function Mv(e,t){let n=new ic(t,jv.foregroundColor,jv.ansiColors,jv.palette);return t=>e({...t,theme:n})}function Nv(e,t){return n=>$f(()=>e(n),...t)(n)}function Pv(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t/4294967296}const Fv=4096;var Iv=class{inForce=null;placements=new Map;made=new Map;drawn=null;frame={effect:Uh,t:0,made:0,reused:0,own:[],basis:`off`,revision:0,fades:[],leaves:[]};constructor(e){this.key=e}lastFrame(){return this.frame}get heldCount(){let e=[...this.drawn?.placements.values()??[]].filter(({passage:e})=>e!==null).length;return[...this.made.values()].reduce((e,t)=>e+t.size,e)}motion(e,t,n){let r=this.inForce?.name===e?this.inForce:{name:e,since:t},i={scope:Ov,name:e,t:t-r.since},a=this.placements,o=new Map,s=this.made,c=new Map,l=[],u=this.drawn,d=n.transitions?u!==null&&u.source.config===n.source.config&&u.source.preset===n.source.preset&&u.source.revision===n.source.revision&&u.source.width===n.source.width?`compared`:`fresh`:`off`,f=d===`compared`?u.placements:null,p=new Map,m=[],h=[],g={effect:e,t:i.t,made:0,reused:0,own:l,basis:d,revision:n.source.revision,fades:m,leaves:h},_=(e,n,{ground:r})=>{let i=sm.transitions[e]({z:Pv(`${this.key}@${n}`)*Fv});return{name:e,since:t,transition:{effect:Mv(i.effect,r),done:e=>i.done(e)}}},v=({since:e,transition:n})=>n.done(t-e),y=(e,t,n)=>({drawing:t,passage:f===null?null:n===void 0||n.passage?.name===`dissolve`?_(`fade`,e,t):n.passage!==null&&!v(n.passage)?n.passage:null}),b=(e,t)=>{if(t===void 0||t.drawing.own.length===0)return;if(t.passage?.name===`dissolve`)return v(t.passage)?void 0:t;let r={...t.drawing,own:t.drawing.own.map(n.hold)};return{drawing:r,passage:_(`dissolve`,e,r)}},ee=(e,r)=>{if(p.has(e))throw Error(`placement "${e}" was reached twice in one frame`);let i=f?.get(e),{drawing:a,deeper:o}=n.returned(e,r),s=a===null?b(e,i):y(e,a,i);return s===void 0?r:(p.set(e,s),s.passage!==null&&(s.passage.name===`fade`?m:h).push({placement:e,t:t-s.passage.since}),a===null?[...s.drawing.own,...o]:r)},x=(e,n)=>{let r=o.get(e)??a.get(e),i=r?.name===n?r:{name:n,since:t},s=t-i.since;return o.has(e)||(o.set(e,i),l.push({placement:e,effect:n,t:s})),{scope:e,name:n,t:s}},S=(e,t)=>{let n=c.get(e)??new Map;c.set(e,n);let r=n.get(t.scope);if(r!==void 0)return r.effect;let i=s.get(e)?.get(t.scope),a=i?.name===t.name,o=Pv(t.scope===Ov?e:`${e}@${t.scope}`),l=a?i.effect:sm.loops[t.name]({z:o*Fv});return g[a?`reused`:`made`]++,n.set(t.scope,{name:t.name,effect:l}),l},te=e=>{let t=new Map;for(let{owner:n,placement:r}of e){let e=r.effect===`bar`?i:x(r.id,r.effect),a=t.get(e.scope);a===void 0?t.set(e.scope,{...e,owners:[n]}):a.owners.push(n)}return[...t.values()]},ne=e=>{let n=new Map;for(let{owner:t,placement:r}of e){let e=n.get(r.id);e===void 0?n.set(r.id,[t]):e.push(t)}return[...n].flatMap(([e,n])=>{let r=p.get(e)?.passage??null;return r===null?[]:[{t:t-r.since,effect:$f(r.transition.effect,...n)}]})};return{placed:d===`off`?(e,t)=>t:ee,row:(e,t)=>{let n=(t.some(e=>e.placement.effect!==`bar`)?te(t):[{...i,owners:void 0}]).filter(kv),r=ne(t);if(n.length===0&&r.length===0)return Dv;let a=`${this.key}#${e}`;return{kind:`moving`,wrap:e=>new qf(e,Av(i.t,[...n.map(e=>{let t=S(a,e);return{t:e.t,effect:e.owners===void 0?t:Nv(t,e.owners)}}),...r]),{t:i.t,key:a,theme:jv})}},drawn:()=>{this.inForce=r,this.placements=o,this.made=c,this.drawn=d===`off`?null:{source:n.source,placements:p},this.frame=g}}}},Lv=class{sessions=new Map;constructor(e=256){this.maxSessions=e}of(e){let t=this.sessions.get(e)??new Iv(e);this.sessions.delete(e),this.sessions.set(e,t);for(let e of this.sessions.keys()){if(this.sessions.size<=this.maxSessions)break;this.sessions.delete(e)}return t}getStats(){let e=0;for(let t of this.sessions.values())e+=t.heldCount;return{sessions:this.sessions.size,effects:e}}};function Rv(e,t){let n=Is(t.colorSystem),r=[...Vu(e,{maxWidth:t.width??80,isTerminal:!1,asciiOnly:!1,theme:Tv,colorSystem:n.colorSystem,onStyleError:e=>{throw e}})];return{text:Nf(r,n),moves:Number.isFinite(W.nextChange(r))}}const zv=new Map;function Bv(e){let t=zv.get(e);if(t!==void 0)return t;let n=t=>{let n=t.seam.map(t=>`cap`in t?t:{...t,glyph:e});return{seam:n,divider:n}},{seam:r,caps:i}=jf.plain,a=new $d({glyph:n(r.glyph),ascii:r.ascii},i);return zv.set(e,a),a}function Vv(e,t){return e===`plain`&&t!==void 0?Bv(t):jf[e]}const Hv=new Map;function Uv(e){let t=JSON.stringify([e.endcaps,e.separator??null]),n=Hv.get(t);if(n!==void 0)return n;let r=Vv(e.endcaps,e.separator),i=e=>new G(`x`,{end:``,overflow:`ignore`,style:new H({bgcolor:e})}),a=e=>new G(Rv(new Ed(e,r),{colorSystem:null}).text.replace(/\n$/,``)).cellLength,o=a([i(`#101010`)]),s={chrome:o-1,seam:a([i(`#101010`),i(`#202020`)])-o-1};return Hv.set(t,s),s}function Wv(e){return Uv(e).chrome}function Gv(e){return Uv(e).seam}const Kv=/[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/gu;function qv(e){return[...new Set(e.match(Kv)??[])].join(``)}function Jv(e){let t=Vv(e.endcaps,e.separator),n=e=>new G(`x`,{end:``,style:new H({bgcolor:e})});return qv(Rv(new Ed([n(`#101010`),n(`#202020`),n(`#202020`)],t),{colorSystem:null}).text)}function Yv(e,t,n=Dv){if(e.length===0)return{text:``,moves:!1};let r=Vv(t.endcaps,t.separator),i=t.wrap&&Number.isFinite(t.width),a={colorSystem:t.colorCompatibility,...i?{width:t.width}:{}},o=i?new hm([...e],{joiner:r}):new Ed([...e],r),s=Rv(n.kind===`still`?o:n.wrap(o),a);if(!s.text.endsWith(`
56
56
  `))throw Error(`drawStripCells: rich-js strip output did not end its last line`);return{text:s.text.slice(0,-1),moves:s.moves}}function Xv(e,t){return Yv(e,t).text}function Zv(e){return Math.min(20,e??20)}const Qv={heading:`ERROR`,glyph:`⚠`,colors:Cv},$v={heading:`WARNING`,glyph:`⚠`,colors:wv},ey={heading:`UPDATE`,glyph:`⬆`,colors:wv},ty={heading:`LANES`,glyph:`🧪`,colors:wv};function ny(e,t){return{text:_v(e),link:t}}function ry(e,t,n){let[r,...i]=[iy(e,Qv,vr),t,iy(n,$v,yr)].flat();return r===void 0?null:{channels:[r,...i]}}function iy(e,t,n){let r=Vr([{verb:n,args:[e]}]),[i,...a]=e.split(/\r\n|\r|\n/).map(e=>ny(e,r)).filter(e=>e.text!==``).map(e=>[e]);return i===void 0?[]:[{severity:t,message:e,lines:[i,...a]}]}function ay(e){return e.channels.map(e=>`${e.severity.heading}\n${e.message}\n`).join(`
57
57
  `)}function oy(e,t,n,r){if(t===null)return e;let i=ly(r),a=cy(t,i),o=n.failedConfigFile!==null||a.length>r.rowCap,s=a.slice(0,r.rowCap-Number(o)),c=o?[dy(t,n,a.length-s.length,i)]:[],l=[...s,...c].join(`
58
58
  `);return e?`${l}\n${e}`:l}function sy(e,t){return cy(e,ly(t)).join(`
@@ -73,7 +73,7 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
73
73
  `,1)[0]??``}function MD(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function ND(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const PD={github:`gh`,gitlab:`glab`};function FD(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const ID=/^[A-Za-z]:[\\/]/;function LD(e){let t=e.trim();if(ID.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 RD(e){return LD(e)?.host||null}function zD(e){let t=RD(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const BD=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function VD(e){let t=kD(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?HD(t.value):[]}}function HD(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 UD(e){return e.urls.find(e=>JD(e)!==null)??e.urls[0]??null}function WD(e){return e.find(e=>e.name===`origin`)??e[0]??null}function GD(e){let t=WD(e);return t?UD(t):null}function KD(e){let t=WD(e);return t?t.urls.find(e=>zD(e)!==null)??UD(t):null}function qD(e){let t=(LD(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function JD(e){let t=LD(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 YD(e){let t=GD(e);return t===null?null:JD(t)}function XD(e,t,n,r){return t.ok?r(t.stdout):FD(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??jD(t.stderr)].filter(Boolean).join(`, `)}`)}function ZD(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function QD(e){let t=`detached`,n=F,r=F,i=F,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)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function $D(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!ZD(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=OD(`gh pr view`,ED,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function eO(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!ZD(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=OD(`glab mr view`,DD,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function tO(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var nO=class{isGitRepo(e){return xD(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)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}async findGitRoot(e){let t=SD(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=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=MD(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=MD(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=MD(s,YD)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return ND(kD(`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=ND(kD(`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)?I(`git log -1: unparseable timestamp "${n.value}"`):P(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`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
76
- `).length:0)}async getRemotesAsync(e){let t=tO(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 VD(await this.execGitAsync(BD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=GD(e);return(n===null?null:qD(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=KD(t.value);return n===null?F:P(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=zD(t);return n===`github`?XD(`gh pr view`,await this.execForgeAsync(PD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,$D):n===`gitlab`?XD(`glab mr view`,await this.execForgeAsync(PD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,eO):F}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=kD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(QD(t.value)):t}};const rO=(e,t)=>D(t);var iO=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??rO}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()}},aO=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 oO={showSha:!0,showStashCount:!0};function sO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function cO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function lO(e,t){return e.head!==t.head||e.index!==t.index}function uO(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 dO=class extends nO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new aO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new nO,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 iO({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}|${sO(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(P(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=cO(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}`,uO(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 F;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}`,uO(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,{...oO});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,{...oO}),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=cO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),lO(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 fO=/\r\n|\r|\n/g,pO=e=>P(e.replace(fO,` `).trim());function mO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(fO,` `))}}const hO=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}},gO=e=>e.getTime()/1e3,_O=e=>new Date(e*1e3);function vO(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 yO(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 bO=`session.id`;function xO(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?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function SO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function CO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}const wO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],TO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],EO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],DO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function OO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wO[e.getMonth()]],[`Monday`,e=>EO[e.getDay()]],[`Jan`,e=>TO[e.getMonth()]],[`Mon`,e=>DO[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 kO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function AO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kO[t];try{return RO(r,e)}catch{return zO(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 jO(e){try{return b(e)}catch{return e}}function MO(e){try{return ee(e).isDirectory()}catch{return!1}}function NO(e){let t=jO(e);return MO(t)?{dir:t,name:null,leaf:!0}:gb(t)}const PO=e=>`${e.dir}\0${e.name??``}`;var FO=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:NO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=NO(e);if(t.watcher!==null&&PO(n)===PO(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}},IO=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 LO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function RO(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`?Cb(e):t===`number`?wb(e):Tb(e)}function zO(e){return e===`number`?0:e===`boolean`?!1:``}var BO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new FO;ttlMgr=new IO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new aO;abort=new AbortController;drawn=bb.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=bb.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 _O(e)};engine=gD({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 dO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Sb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(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,xO(t,n.cwd,this.abort.signal),vO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,SO(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,pO,t.default,n);case`regex`:return this.scalarPublisher(e,mO(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=CO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?F:P(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()===``?F:o,c=CO(s,hO,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(_D(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>OO(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 Db(t)?new Eb(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=kO[t.field],r=t.varDefault===void 0?zO(n):RO(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,AO(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(bO);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(bO):``;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=LO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,RO(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,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return P(r.evaluate(_D(this.store)).map(e=>e.plain).join(``))}catch(e){return Db(e)?F:I(`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,bb.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,bb.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,RO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,zO(t))}}defaultFor(e){try{return RO(this.defaultEmptyValue,e)}catch{return zO(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 VO(e,t){let n=Y_[e],r=rv(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 HO=Object.fromEntries([...dv].map(([e,t])=>[t,VO(e,t)])),UO={subscribers:`number`,fps:`number`,shown:`boolean`},WO=Object.keys(UO),GO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bO]:{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:``},...HO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(T_.flatMap(e=>WO.map(t=>[k_(e,t),{kind:`input`,path:k_(e,t),type:UO[t],default:O_[t]}]))),[D_(`by`)]:{kind:`input`,path:D_(`by`),default:E_.by},[D_(`fps`)]:{kind:`input`,path:D_(`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:``}},KO=`ne .tmux.pane ""`;function qO(e,t,n){let r=new Set,i=e=>{for(let t of ob(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 gg(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(bO);for(let t of Object.values(e.actions)){r.add(bO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?fv.get(t.set):void 0,n=`persist`in t?dv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function JO(e,t,n){let r=mb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of qO(e,t,n.helpers)){if(pb(a,r))continue;let e=GO[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 YO(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const XO=`groups.`,ZO=`menus.`,QO=`edit.`,X=`candybar.`,$O=[XO,ZO,QO,X];function ek(e){return $O.some(t=>e.startsWith(t))}function tk(e){let t=YO(e);return $O.find(e=>t.startsWith(YO(e)))}function nk(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 rk(e){return e}function ik(e,t,n){return n===void 0?ZO+YO(e)+`.`+YO(t):ak(n)}function ak(e){return ZO+YO(e)}function ok(e,t){return e+`.`+t}function sk(e){return e+`.page`}const ck=[`closeOnPick`,`paged`,`key`,`distribution`],lk=e=>ck.includes(e),uk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${km.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function dk(e){for(let t of Object.keys(e))if(!lk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${uk}`);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&&!Am(r))throw Error(`{{ menu }} option "distribution" must be one of: ${km.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Mm(r)}}const fk=e=>`from`in e?e.from:e.themes;function pk(e,t,n){return e===`bool`?cg(t)!==null:`min`in e?lg(t,e)!==null:Gy(fk(e),n).members.includes(t)}function mk(e,t){if(e===`bool`)return og.join(` or `);if(!(`min`in e)){let n=fk(e),{members:r}=Gy(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 hk(e){return{label:e.label,domain:gk(e.domain)}}function gk(e){return e===`theme`?{themes:Hy}:e===`bool`||`min`in e?e:{from:e}}function _k(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:[...og]}},variables:{}};if(`from`in o)return vk(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 vk(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 vk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=ok(n,t),s=`${t}.open`,c=sk(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,qr),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const yk=Object.fromEntries(Object.entries(Y_).map(([e,t])=>[e,t.spec]));function bk(e){return Y_[e].domain}function xk(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 Sk(e){return xk(`${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 Ck(e){return xk(`${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 wk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Ih(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 Tk={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."},Ek={noun:`globals key`,fields:yk,removed:Tk},Dk={preset:Sk(`a preset`),menuGlyph:Ck(`a preset`)},Ok={noun:`preset globals key`,fields:{...yk,...Dk},removed:Tk};function kk(e){return zk(e)&&!(e in Dk)}const Ak=`is decided later than any rule could be settled`,jk={noun:`editGlobals key`,removed:Tk,fields:{...yk,preset:Sk(`the editGlobals fragment`),menuGlyph:Ck(`the editGlobals fragment`),palette:wk(yk.palette,`the editGlobals fragment`,Ak),style:wk(yk.style,`the editGlobals fragment`,Ak),effect:wk(yk.effect,`the editGlobals fragment`,Ak)}},Mk={noun:`theme default key`,fields:{...Object.fromEntries($_.map(e=>[e,yk[e]])),style:wk(yk.style,`a theme's default`,`is the look that theme wears by name`)}};function Nk(e,t){if(!Zg(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Qg(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${Dh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=$g(e,Mk,t,i);a!==null&&(n[r]=a)}return n}function Pk(e,t,n){return n===void 0?{}:$g(e,Ek,t,n)??{}}function Fk(e,t,n){return $g(e,Ok,t,n)??{}}function Ik(){return b_(Ok)}function Lk(e,t,n){return $g(e,jk,t,n)??{}}const Rk=new Set(Object.keys(yk));function zk(e){return Rk.has(e)}function Bk(e){return Object.hasOwn(Tk,e)?Tk[e]:void 0}function Vk(){return[...Rk]}const Hk=new Map(Object.entries(Y_).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Uk(e){let t=new Map;for(let[n,r]of Hk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Wk=/^segments\.([^.]+)\.palette$/,Gk=/^presets\.(.+)\.root$/,Kk=/^presets\.(.+)\.globals\.([^.]+)$/,qk=/^themeDefaults\.(.+)\.([^.]+)$/;function Jk(e){return`presets.${e}.root`}function Yk(e,t){return`themeDefaults.${e}.${t}`}const Xk=e=>$_.includes(e);function Zk(e,t){return`presets.${e}.globals.${t}`}function Qk(e){if(zk(e))return{scope:`globals`,field:e};let t=Wk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Kk.exec(e);if(n&&kk(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=qk.exec(e);if(r&&Xk(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Gk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function $k(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 eA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],tA=[...eA,`other`],nA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},rA=bS({fromString:e=>e}),iA=`edit.mode`,aA=`edit.configure`,oA=`edit.toggle`,sA=`edit.unconfigure`,cA=[oA,sA],lA=`arrange`,uA=`${QO}draft.`;function dA(e,t){return`${e}:${t}`}const fA={variable:iA,key:iA,member:lA},pA=$r(fA);function mA(e){try{return rA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function hA(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`&&mA(e))return!0;return!1}function gA(e,t){if(nk(e,t,QO,`edit mode`),!hA(t))return;let{variables:n,actions:r}=_A();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function _A(){return{variables:{[iA]:ii(iA,qr),[aA]:ii(aA,qr)},actions:{[oA]:ai(iA,lA),[sA]:{set:aA,to:qr}}}}const vA=`open`;function yA(e,t,n,r){let i={variable:e,key:e,member:vA};return r.variables[e]=ii(e,qr),r.actions[e]=ai(e,vA),r.segments[e]={template:ti(e,`(?)`,`✕`),...bA(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 bA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const xA=`none`;function SA(e){return Nc(e,`background`)}var CA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function wA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=TA(n,i),l=c!==xA,u=l?c===void 0?o:EA(a,c,`bg`):SA(a);e.bg=u;let d=TA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:eh(a,e,t))(u):void 0:EA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function TA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function EA(e,t,n){try{return Nc(e,t)}catch(e){throw e instanceof Mc?new CA(t,n,e.message):e}}const DA=`🔧`,OA={help:[`-h`,`--help`],version:[`-V`,`--version`]},kA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],AA=Object.fromEntries(kA.map(e=>[e.member,e.label])),jA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},MA=Object.keys(jA),NA=pv(e=>ov[e].place),PA=e=>Object.hasOwn(jA,e),FA=e=>PA(e)?FA(NA[jA[e].beside]):e,IA=e=>PA(e)?`${IA(NA[jA[e].beside])} › ${jA[e].trigger}`:e===`door`?`first line`:AA[e],LA=e=>IA(NA[e]),RA=e=>`${w_[e].label} is off — turn it on in the settings menu's ${LA(w_[e].setting)}, or set globals.${w_[e].setting}: true`,zA=[...new Set(Object.values(w_).map(e=>LA(e.setting)))].join(` or `),BA=[`✚ inserts`,`✖ removes`,`${DA} configures`,`↺ resets layout`],VA={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`]},HA=`
76
+ `).length:0)}async getRemotesAsync(e){let t=tO(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 VD(await this.execGitAsync(BD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=GD(e);return(n===null?null:qD(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=KD(t.value);return n===null?F:P(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=zD(t);return n===`github`?XD(`gh pr view`,await this.execForgeAsync(PD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,$D):n===`gitlab`?XD(`glab mr view`,await this.execForgeAsync(PD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,eO):F}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=kD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(QD(t.value)):t}};const rO=(e,t)=>D(t);var iO=class{slots=new Map;maxWatchers;counters;logger;closed=!1;constructor(e={}){this.maxWatchers=e.maxWatchers??128,this.counters=e.counters,this.logger=e.logger??rO}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()}},aO=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 oO={showSha:!0,showStashCount:!0};function sO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function cO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function lO(e,t){return e.head!==t.head||e.index!==t.index}function uO(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 dO=class extends nO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new aO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new nO,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 iO({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}|${sO(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(P(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=cO(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}`,uO(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 F;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}`,uO(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,{...oO});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,{...oO}),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=cO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),lO(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 fO=/\r\n|\r|\n/g,pO=e=>P(e.replace(fO,` `).trim());function mO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(fO,` `))}}const hO=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}},gO=e=>e.getTime()/1e3,_O=e=>new Date(e*1e3);function vO(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 yO(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 bO=`session.id`;function xO(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?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function SO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function CO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}const wO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],TO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],EO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],DO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function OO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>wO[e.getMonth()]],[`Monday`,e=>EO[e.getDay()]],[`Jan`,e=>TO[e.getMonth()]],[`Mon`,e=>DO[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 kO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function AO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=kO[t];try{return RO(r,e)}catch{return zO(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 jO(e){try{return b(e)}catch{return e}}function MO(e){try{return ee(e).isDirectory()}catch{return!1}}function NO(e){let t=jO(e);return MO(t)?{dir:t,name:null,leaf:!0}:gb(t)}const PO=e=>`${e.dir}\0${e.name??``}`;var FO=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:NO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=NO(e);if(t.watcher!==null&&PO(n)===PO(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}},IO=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 LO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function RO(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`?Cb(e):t===`number`?wb(e):Tb(e)}function zO(e){return e===`number`?0:e===`boolean`?!1:``}var BO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new FO;ttlMgr=new IO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new aO;abort=new AbortController;drawn=bb.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=bb.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 _O(e)};engine=gD({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 dO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Sb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(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,xO(t,n.cwd,this.abort.signal),vO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,SO(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,pO,t.default,n);case`regex`:return this.scalarPublisher(e,mO(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=CO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?F:P(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()===``?F:o,c=CO(s,hO,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(_D(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>OO(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 Db(t)?new Eb(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=kO[t.field],r=t.varDefault===void 0?zO(n):RO(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,AO(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(bO);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(bO):``;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=LO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,RO(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,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return P(r.evaluate(_D(this.store)).map(e=>e.plain).join(``))}catch(e){return Db(e)?F:I(`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,bb.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,bb.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,RO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,zO(t))}}defaultFor(e){try{return RO(this.defaultEmptyValue,e)}catch{return zO(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 VO(e,t){let n=Y_[e],r=rv(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 HO=Object.fromEntries([...dv].map(([e,t])=>[t,VO(e,t)])),UO={subscribers:`number`,fps:`number`,shown:`boolean`},WO=Object.keys(UO),GO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[bO]:{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:``},...HO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(T_.flatMap(e=>WO.map(t=>[k_(e,t),{kind:`input`,path:k_(e,t),type:UO[t],default:O_[t]}]))),[D_(`by`)]:{kind:`input`,path:D_(`by`),default:E_.by},[D_(`fps`)]:{kind:`input`,path:D_(`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:``}},KO=`ne .tmux.pane ""`;function qO(e,t,n){let r=new Set,i=e=>{for(let t of ob(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 gg(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(bO);for(let t of Object.values(e.actions)){r.add(bO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?fv.get(t.set):void 0,n=`persist`in t?dv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function JO(e,t,n){let r=mb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of qO(e,t,n.helpers)){if(pb(a,r))continue;let e=GO[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 YO(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const XO=`groups.`,ZO=`menus.`,QO=`edit.`,X=`candybar.`,$O=[XO,ZO,QO,X];function ek(e){return $O.some(t=>e.startsWith(t))}function tk(e){let t=YO(e);return $O.find(e=>t.startsWith(YO(e)))}function nk(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 rk(e){return e}function ik(e,t,n){return n===void 0?ZO+YO(e)+`.`+YO(t):ak(n)}function ak(e){return ZO+YO(e)}function ok(e,t){return e+`.`+t}function sk(e){return e+`.page`}const ck=[`closeOnPick`,`paged`,`key`,`distribution`],lk=e=>ck.includes(e),uk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${km.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function dk(e){for(let t of Object.keys(e))if(!lk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${uk}`);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&&!Am(r))throw Error(`{{ menu }} option "distribution" must be one of: ${km.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Mm(r)}}const fk=e=>`from`in e?e.from:e.themes;function pk(e,t,n){return e===`bool`?cg(t)!==null:`min`in e?lg(t,e)!==null:Gy(fk(e),n).members.includes(t)}function mk(e,t){if(e===`bool`)return og.join(` or `);if(!(`min`in e)){let n=fk(e),{members:r}=Gy(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 hk(e){return{label:e.label,domain:gk(e.domain)}}function gk(e){return e===`theme`?{themes:Hy}:e===`bool`||`min`in e?e:{from:e}}function _k(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:[...og]}},variables:{}};if(`from`in o)return vk(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 vk(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 vk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=ok(n,t),s=`${t}.open`,c=sk(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,qr),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const yk=Object.fromEntries(Object.entries(Y_).map(([e,t])=>[e,t.spec]));function bk(e){return Y_[e].domain}function xk(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 Sk(e){return xk(`${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 Ck(e){return xk(`${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 wk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Ih(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 Tk={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."},Ek={noun:`globals key`,fields:yk,removed:Tk},Dk={preset:Sk(`a preset`),menuGlyph:Ck(`a preset`)},Ok={noun:`preset globals key`,fields:{...yk,...Dk},removed:Tk};function kk(e){return zk(e)&&!(e in Dk)}const Ak=`is decided later than any rule could be settled`,jk={noun:`editGlobals key`,removed:Tk,fields:{...yk,preset:Sk(`the editGlobals fragment`),menuGlyph:Ck(`the editGlobals fragment`),palette:wk(yk.palette,`the editGlobals fragment`,Ak),style:wk(yk.style,`the editGlobals fragment`,Ak),effect:wk(yk.effect,`the editGlobals fragment`,Ak)}},Mk={noun:`theme default key`,fields:{...Object.fromEntries($_.map(e=>[e,yk[e]])),style:wk(yk.style,`a theme's default`,`is the look that theme wears by name`)}};function Nk(e,t){if(!Zg(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${Qg(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${Dh(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=$g(e,Mk,t,i);a!==null&&(n[r]=a)}return n}function Pk(e,t,n){return n===void 0?{}:$g(e,Ek,t,n)??{}}function Fk(e,t,n){return $g(e,Ok,t,n)??{}}function Ik(){return b_(Ok)}function Lk(e,t,n){return $g(e,jk,t,n)??{}}const Rk=new Set(Object.keys(yk));function zk(e){return Rk.has(e)}function Bk(e){return Object.hasOwn(Tk,e)?Tk[e]:void 0}function Vk(){return[...Rk]}const Hk=new Map(Object.entries(Y_).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Uk(e){let t=new Map;for(let[n,r]of Hk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Wk=/^segments\.([^.]+)\.palette$/,Gk=/^presets\.(.+)\.root$/,Kk=/^presets\.(.+)\.globals\.([^.]+)$/,qk=/^themeDefaults\.(.+)\.([^.]+)$/;function Jk(e){return`presets.${e}.root`}function Yk(e,t){return`themeDefaults.${e}.${t}`}const Xk=e=>$_.includes(e);function Zk(e,t){return`presets.${e}.globals.${t}`}function Qk(e){if(zk(e))return{scope:`globals`,field:e};let t=Wk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=Kk.exec(e);if(n&&kk(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=qk.exec(e);if(r&&Xk(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Gk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function $k(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 eA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],tA=[...eA,`other`],nA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},rA=bS({fromString:e=>e}),iA=`edit.mode`,aA=`edit.configure`,oA=`edit.toggle`,sA=`edit.unconfigure`,cA=[oA,sA],lA=`arrange`,uA=`${QO}draft.`;function dA(e,t){return`${e}:${t}`}const fA={variable:iA,key:iA,member:lA},pA=$r(fA);function mA(e){try{return rA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function hA(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`&&mA(e))return!0;return!1}function gA(e,t){if(nk(e,t,QO,`edit mode`),!hA(t))return;let{variables:n,actions:r}=_A();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function _A(){return{variables:{[iA]:ii(iA,qr),[aA]:ii(aA,qr)},actions:{[oA]:ai(iA,lA),[sA]:{set:aA,to:qr}}}}const vA=`open`;function yA(e,t,n,r){let i={variable:e,key:e,member:vA};return r.variables[e]=ii(e,qr),r.actions[e]=ai(e,vA),r.segments[e]={template:ti(e,`(?)`,`✕`),...bA(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 bA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const xA=`none`;function SA(e){return Nc(e,`background`)}var CA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function wA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=TA(n,i),l=c!==xA,u=l?c===void 0?o:EA(a,c,`bg`):SA(a);e.bg=u;let d=TA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:eh(a,e,t))(u):void 0:EA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function TA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function EA(e,t,n){try{return Nc(e,t)}catch(e){throw e instanceof Mc?new CA(t,n,e.message):e}}const DA=`🔧`,OA={help:[`-h`,`--help`],version:[`-V`,`--version`]},kA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],AA=Object.fromEntries(kA.map(e=>[e.member,e.label])),jA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},MA=Object.keys(jA),NA=pv(e=>ov[e].place),PA=e=>Object.hasOwn(jA,e),FA=e=>PA(e)?FA(NA[jA[e].beside]):e,IA=e=>PA(e)?`${IA(NA[jA[e].beside])} › ${jA[e].trigger}`:e===`door`?`first line`:AA[e],LA=e=>IA(NA[e]),RA=e=>`${w_[e].label} is off — turn it on in the settings menu's ${LA(w_[e].setting)}, or set globals.${w_[e].setting}: true`,zA=[...new Set(Object.values(w_).map(e=>LA(e.setting)))].join(` or `),BA=[`✚ inserts`,`✖ removes`,`${DA} configures`,`↺ resets layout`],VA={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`]},HA=`
77
77
  cc-candybar - Beautiful powerline statusline for Claude Code
78
78
 
79
79
  Usage: cc-candybar [options]
@@ -136,8 +136,9 @@ Subcommands:
136
136
  click — one JSON message per stdout line. Reads
137
137
  Claude Code's statusline JSON from stdin (one object
138
138
  a line) and sends it as the session's data
139
- (--config rides with it). LANE is band, statusline
140
- or pane: the experimental lane this stream serves,
139
+ (--config rides with it). LANE is one of
140
+ ${T_.join(`, `)}:
141
+ the experimental lane this stream serves,
141
142
  which streams only while its toggle in the settings
142
143
  menu's ${zA} is on.
143
144
  bar-pane PANE Draw the bar of the Claude Code session in tmux
@@ -173,7 +174,7 @@ Config tooling:
173
174
  running daemon; none spawn one.)
174
175
 
175
176
  `,UA=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,WA={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function GA(e){let t=e[WA.socket]??``,n=e[WA.pane]??``;if(t===``||n===``)return null;let r=e[WA.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const KA=[`moves`,`can-move`,`still`];function qA(e,t,n){return t<n+60?{kind:`unseen`,over:Math.max(0,Math.floor(t-n))}:{kind:`seen`,seconds:e.filter(e=>e>=n&&e<n+60).length}}const JA=e=>e.kind===`seen`&&e.seconds>=45,YA=e=>e.kind===`unseen`?[1,e.over]:[JA(e)?2:0,e.seconds],XA=(e,t)=>{let[n,r]=[YA(e),YA(t)];return n[0]-r[0]||n[1]-r[1]},ZA=e=>e.reduce((e,t)=>XA(t.redraws,e.redraws)<0?t:e);function QA(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const $A=[`carried`,`missing`,`unanswered`];function ej(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:QA(e)===`no`?`unanswered`:`missing`}function tj(e){return{path:e.transcript_path,answered:QA(e)===`yes`}}const nj=[...KA,`failed`,`drawing`],rj=[`statusline`,`frames`],ij=e=>e?.kind===`frames`?`frames`:`statusline`;var aj=class{seen=new Map;see(e,t,n,r){let i=ij(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);if(o!==void 0&&o.order>r)return;let s=Math.floor(n),c=new Set([...o?.redrawn??[],s].filter(e=>e>s-60));this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r,since:o?.since??n,redrawn:c}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value)}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r,since:i,redrawn:a})=>({...n,sessionId:t,ago:e-r,since:e-i,redrawn:[...a].map(t=>Math.floor(e)-t)}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const oj={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},sj=e=>oj[e];function cj(e){return sj(e).glyphs.kind===`bundled`}function lj(e){return sj(e).glyphs.kind===`configured`}const uj=e=>sj(e).label,dj=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function fj(e,t){let n=t.codePointAt(0);return dj.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&hj(e,t)===!0)}const pj=Object.keys(oj);function mj(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function hj(e,t){let n=mj(e),r=mj(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function gj(e){for(let t of pj){let n=sj(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function _j(e){let t=pj.find(t=>sj(t).term===e);return t===void 0?null:{name:t,version:null}}function vj(e){let t=gj(e.termtype)??_j(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function yj(e){let t=e.TERM_PROGRAM,n=pj.find(e=>sj(e).program===t),r=n===void 0?_j(e.TERM):{name:n,version:sj(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function bj(e){switch(e.kind){case`known`:return uj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function xj(e){switch(e.kind){case`known`:return uj(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Sj({name:e,version:t}){let n=sj(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=hj(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const Cj=pj.filter(e=>sj(e).links!==null).map(uj).join(`, `);function wj(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!Na(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!Na(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function Tj(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const Ej=[`managed`,`project`],Dj=e=>!Ej.includes(e.scope),Oj={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:Aa(t.projectDir)}),user:e=>({scope:`user`,path:e})},kj=[`drawn`,`boxes`],Aj=1024*1024,jj=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function Mj(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function Nj(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const Pj=WA.truecolor;function Fj(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const Ij={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>Fj(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=Tj(t.sources,Pj);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${Pj} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,Pj],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Oj[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${Pj} to "1" there`}:o(s)})},Lj={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>Fj(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},Rj={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${jj(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's red strip names), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${jj(e.value.of)} measured`}},zj={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},Bj={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
176
- `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Nj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${zj[e]}`)])}}},Vj="re-run `cc-candybar install`";function Hj(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${Vj}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Vj}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Vj}`)}const Uj={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${Vj}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Vj}`};case`lost`:return Nj([...Hj(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function Wj({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function Gj(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <band|statusline|pane>\``:e.checkout===null?Vj:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Kj(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${Gj(e,`native`)}`];let{bundle:i,source:a}=Wj(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${Gj(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${Gj(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const qj=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},Jj={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${qj(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:Nj([...new Set(i.flatMap(e=>Kj(n,r,e)))])}};function Yj({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function Xj(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Zj={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?Xj(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return Nj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=Yj(e.value,n),u=Nj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges RSS, which counts pages macOS has reclaimed`]:[],...o.kind===`measured`&&Ln(o.charge.bytes,s)?[`the daemon holds ${Vn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},Qj=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function $j(e,t){let n=bj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Sj(e.terminal):{kind:`unknown`}}function eM({identified:e,tmuxClient:t},n){let r=xj(e),i=$j(e,n),a=bj(e)===null?Qj:`${Qj}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${Cj}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const tM={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return Nj(eM(t,n))}}},nM=e=>e.filter(e=>e.role===`statusline`),rM={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{if(e.kind===`failed`)return{ok:!1,reason:e.reason};let i=[t,...n],[a,...o]=i.flatMap(({sources:e,bars:t})=>{let[n,...r]=nM(t).filter(e=>e.frame===`moves`||e.frame===`can-move`);if(n===void 0)return[];let i=ZA([n,...r]);return[{redraws:i.redraws,verdict:iM(e,i)}]}).sort((e,t)=>XA(e.redraws,t.redraws));if(a===void 0){let e=i.flatMap(e=>e.bars),t=nM(e);return t.some(e=>e.frame===`still`)?{ok:!0}:{ok:!1,reason:`${t.length>0?t.some(e=>e.frame===`drawing`)?`the bar's latest render has not finished`:`the bar's recent renders failed`:e.length>0?"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline":r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:qj(r)}, so whether it moves is unknown — run the doctor again once the bar has redrawn`}}let[s,...c]=[a,...o].flatMap(({verdict:e})=>e.ok?[]:[e]);if(s===void 0)return a.verdict;let l=[...new Set(c.map(e=>e.reason))].filter(e=>e!==s.reason);return l.length===0?s:{...s,more:l}}};function iM(e,t){let n=t.frame===`moves`?`the bar moves (an effect, a fade, or an animated segment)`:`the bar can start moving (a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`,r=wj(e);if(r.kind===`present`&&r.refreshInterval!==1){let{from:e,refreshInterval:t}=r,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return Dj(e)?{ok:!1,reason:`${n}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${n}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}let{redraws:i}=t;if(i.kind===`unseen`)return{ok:!1,reason:`${n}, and this daemon has watched Claude Code redraw it for only ${i.over} of the 60 seconds its redraw rate is judged over, so whether it is redrawn every second is unknown — run the doctor again once the bar has been on screen for a minute`};if(JA(i))return{ok:!0,note:`Claude Code redrew the bar in ${i.seconds} of the last 60 seconds`};let a=`${n}, but Claude Code redrew it in only ${i.seconds} of the last 60 seconds`,o=`a statusLine from --settings, MDM or server-managed settings, which the doctor cannot read, runs the bar; set "refreshInterval": 1 beside its command there`;switch(r.kind){case`unread`:return{ok:!1,reason:`${a}, and Claude Code's settings could not be read: ${r.reason}`};case`absent`:return{ok:!1,reason:`${a}, and no settings file Claude Code reads here sets a statusLine (read: ${r.read.join(`, `)||`none`}) — ${o}`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${r.from.path} sets statusLine to ${JSON.stringify(r.value)}, not a statusLine object — ${r.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:return{ok:!1,reason:`${a}, though ${r.from.path} sets statusLine.refreshInterval to 1 — set within the last minute, it shows once Claude Code has redrawn the bar for one (restart Claude Code if it does not); otherwise ${o}`}}}const aM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function oM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return xj(e);case`bundling`:case`unread`:case`configured`:return[uj(e.name),e.version].filter(e=>e!==null).join(` `)}}function sM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return bj(e);case`bundling`:case`unread`:return uj(e.name);case`configured`:{let t=uj(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function cM(e){let t=sM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${aM(e.glyphs)}`}}const lM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=cM(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=oM(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${aM(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=oj[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:hj(i.version,e);if(t===!0)return{ok:!0};let n=uj(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${aM(n)} — set a Nerd Font as its font`)}}}};function uM(e){return e.join(`, `)}function dM(e){return`or set missingData: "ignore" on ${uM(e)}`}function fM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${uM(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${uM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${dM(t)}`]:[`${uM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${dM(t)}`]}function pM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${uM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${uM(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${uM(n)}: ${qj(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${uM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${uM(n)}`]:[]}function mM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${uM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${dM(t)}`];case`failed`:return[`${uM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const hM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>Nj([...fM(e.pullRequests),...pM(e.rateLimits,t),...mM(e.memento)])};function gM({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${Aj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const _M=[Bj,Jj,Zj,Uj,tM,Ij,Lj,Rj,rM,lM,hM,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${qj(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:Nj(e.value.flatMap(gM))}],vM=_M.filter(e=>e.takesMark);function yM(e){return _M.map(t=>({check:t,verdict:t.probe(e)}))}function bM(e){return _M.find(t=>t.name===e)}const xM=/^[^\s"=\\]+$/,SM=e=>xM.test(e)?e:JSON.stringify(e),CM=`${X}doctor.`;function wM(e){let t=`${CM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function TM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?bj(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function EM(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function DM(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=Wj(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}function OM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${Xj(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${Yj(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Hn(i.charge)}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function kM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function AM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>jM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed redrawn=failed chains=${SM(i)}`;let a=nM(r.flatMap(e=>e.bars)),o=e=>a.filter(t=>t.frame===e).length,s=a.map(({redraws:e})=>e.kind===`seen`?`${e.seconds}`:`unseen(${e.over})`);return`frames=${nj.map(o).join(`/`)} redrawn=${s.join(`,`)||`-`} chains=${SM(i)}`}function jM(e){let t=wj(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function MM(e){let t=Tj(e,Pj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${SM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function NM(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function PM(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=cM(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function FM(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function IM(e){return e.flatMap(({check:e,verdict:t})=>{let n=wM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:ag},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:FM(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?ag:ig},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const LM={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function RM(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(LM).map(([t,n])=>[`${e}${t}`,n]))}}const zM=`armed`,BM=`disarmed`,VM=`.armed`,HM=e=>e.endsWith(VM);function UM(e,t,n){let r=`${e}${VM}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${zM}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:zM},[a]:{set:r,to:BM},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:BM}},disarm:a}}const WM=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function GM(e){return typeof e==`string`&&WM.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function KM(e){let t=GM(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const qM=[`/compact`,`/model`],JM=`/clear`;function YM(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=UM(`${e}clear`,{arm:JM,confirm:`${JM} ✓ confirm`},[n]);return{template:qM.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${KO} }}`,actions:{...Object.fromEntries(qM.map(e=>[t(e),{slash:KM(e)}])),...r.actions,[n]:{slash:KM(JM)}},variables:r.variables,disarm:r.disarm}}const XM=Array.from({length:10},(e,t)=>(t+1)*1e5),ZM=XM[0],QM=XM[XM.length-1];function $M(e){let t;try{t=Da(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=ZM&&n<=QM?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${ZM}–${QM} tokens)`)}function eN(e,t){let n=Math.min(t??QM,QM),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:XM.filter(e=>e<r).at(-1)??0,higher:XM.find(e=>e>r&&e<=n)??0}}function tN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${KO} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:KM(`/autocompact auto`)},...Object.fromEntries(XM.map(t=>[`${e}${t}`,{slash:KM(`/autocompact ${t}`)}]))}}}const nN=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,rN=`${X}menu`,iN=`open`,aN=`${X}edit`,oN=`${X}toolbar`,sN=RM(X),cN=`${X}commands`,lN=YM(`${cN}.`),uN=`${X}autocompact`,dN=tN(`${uN}.`,nN),fN=e=>({kind:`segment`,name:e}),pN=`${X}tab`,mN=e=>`${pN}.${e}`,hN=e=>`${mN(e)}.toggle`,gN=e=>({variable:pN,key:pN,member:e}),_N=`${X}save`,vN=`${X}preset.save`,yN=`${X}preset.delete`,bN=e=>`${X}${e}`,xN=e=>`${X}apply.${e}`,SN=e=>`${X}reset.${e}`,CN=`${X}themeDefault.save`,wN=`${X}themeDefault.differs`,TN=`${X}themeDefault.theme`,EN={when:`{{ .${wN} }}`,template:`{{ action "${CN}" (printf "⤓ default for %s" .${TN}) }} {{ swatch "${xN(`theme`)}" .${TN} }}`},DN=`${X}resetAll`,ON=`${rN}.toggle`,kN={variable:rN,key:rN,member:iN},AN=`${X}undo`,jN=`${X}back`,MN=`${jN}.step`,NN=`${X}navigation.back`,PN=jN,FN={template:`{{ if gt .${NN} 0 }}{{ action "${jN}" "◁" }}{{ else }}{{ fg (${UA}) "◁" }}{{ end }}`},IN=`${X}redo`,LN=`${X}doctor`,RN=`${LN}.run`,zN=e=>`${LN}.fix.${e}`,BN=(e,t)=>`${LN}.mark.${e}.${t}`,VN=e=>`${LN}.${e}`,HN={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},UN=ak(`${X}pickers`),WN=e=>`${X}${e}`,GN=e=>`${WN(e)}.toggle`,KN=e=>PA(e)?ak(`${X}${e}Pickers`):UN,qN=e=>{let t=KN(NA[jA[e].beside]);return{variable:t,key:t,member:e}},JN={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${yN}" (printf "🚮 delete %s" .${ov.preset.effectiveVar}) }}`}},YN=(e,t)=>`${X}list.${e}.${t}`,XN=e=>`${X}resettable.${e}`,ZN=e=>e.length===0?`false`:`(or ${e.map(e=>`.${XN(e)}`).join(` `)})`,QN=T_.map(e=>[w_[e].setting,e]),$N={variables:{},actions:{},segments:{}},eP=Object.fromEntries(QN.map(([e,t])=>[e,yA(`${X}help.${e}`,VA[t],[],$N)])),tP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],nP=e=>{let t=t=>`.${k_(e,t)}`,n=tP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${ov[w_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},rP=`{{ if eq .${D_(`by`)} "feed" }} {{ printf "%2d" (int .${D_(`fps`)}) }} fps{{ end }}`,iP=Object.fromEntries(QN.map(([e,t])=>[e,nP(t)])),aP=Object.keys(ov).map(e=>{let t=ov[e],n=bk(t.configKey),r=_k({label:t.label,domain:n},t.sessionKey,t.effectiveVar,xN(e),KN(NA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>JN[e])}}),oP=e=>aP.filter(t=>NA[t.name]===e),sP=e=>aP.filter(t=>FA(NA[t.name])===e),cP=e=>MA.filter(t=>jA[t].beside===e),lP=e=>oP(e).flatMap(e=>[xP(e),...[eP[e.name]].filter(e=>e!==void 0),...cP(e.name).map(e=>Qr(WN(e),qN(e),{kind:`container`,direction:`horizontal`,children:lP(e)},`drop`))]);new Set(aP.flatMap(e=>[e.sessionKey,e.configKey]));const uP=UM(DN,{arm:`⟲`,confirm:`⟲ reset all?`},aP.map(e=>SN(e.name))),dP=[`unsaved`,`history.undo`,`history.redo`],fP=e=>`${X}${e}`,pP=fP(`unsaved`),mP=(e,t)=>({body:t,shown:`(gt .${fP(e)} 0)`}),hP=[mP(`unsaved`,`{{ action "${_N}" (printf "💾 save %d" .${pP}) }}`),mP(`history.undo`,`{{ action "${AN}" "↶" }}`),mP(`history.redo`,`{{ action "${IN}" "↷" }}`),{body:uP.template,shown:`(or ${ZN(aP.map(e=>e.name))} ${uP.armed})`}],gP={when:`{{ or ${hP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+hP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},_P=[{step:uP,place:`door`},{step:lN,place:`session`}],vP=e=>e.map(e=>e.step.disarm),yP=vP(_P),bP=vP(_P.filter(e=>e.place!==`door`));function xP(e){let t=bN(e.name);return e.control.kind===`inline`?fN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>fN(YN(e.name,n)))},`drop`)}function SP(e){return e===rN}function CP(e){let t=fN(rN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[CP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function wP(e){return TP(e)>0?e:CP(e)}function TP(e){let t=0;for(let n of gg(e))n.kind===`segment`&&SP(n.name)&&(t+=1);return t}function EP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&SP(e.name)||e.opens!==void 0&&EP(e.opens.body,!0):e.children.some(e=>EP(e,n))}const DP={session:{direction:`vertical`,content:[fN(oN),{kind:`container`,direction:`horizontal`,children:[fN(cN),fN(uN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[fN(CN)]},layout:{direction:`horizontal`,content:[fN(vN),fN(aN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[fN(LN),..._M.map(e=>fN(VN(e.name)))],after:[]}},OP=e=>({kind:`container`,direction:DP[e].direction,children:[...DP[e].content,...lP(e),...DP[e].after]});function kP(e){return e.kind===`segment`?SP(e.name)?Qr(e.name,kN,jP,`above`):e:NP(e)}function AP(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[fN(PN),...lP(`door`),fN(_N)]},{kind:`container`,direction:`horizontal`,children:kA.map(({member:e})=>Qr(mN(e),gN(e),OP(e),`drop`))}]}}const jP=AP();function MP(e){let t=new Map;for(let e of gg(jP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${rN}.fold.${YO(t)}`;return e.actions[i]={set:t,to:r.default},i})}function NP(e){return{...e,children:e.children.map(e=>kP(e))}}function PP(e){let t={variables:{[rN]:ii(rN,qr)},actions:{[ON]:ai(rN,iN),[RN]:{doctor:`run`},[aN]:{do:[...cA]},...sN.actions,...lN.actions,...dN.actions,[_N]:{save:!0},[AN]:{undo:!0},[MN]:{back:!0},[jN]:{do:[MN,...yP]},[IN]:{redo:!0},[vN]:{preset:`save`},[CN]:{themeDefault:`save`},[yN]:{preset:`delete`,name:`{{ .${ov.preset.effectiveVar} }}`}},segments:{[rN]:{template:`{{ $door := ${ni(rN,ri(e),ri(`✖`))} }}{{ if ${ei(kN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+rP},[oN]:{template:sN.template},[cN]:{template:lN.template,when:lN.when},[uN]:{template:dN.template,bg:dN.bg,when:dN.when},[PN]:FN,[_N]:gP,[CN]:EN,[vN]:{template:`{{ action "${vN}" "+ preset" }}`},[LN]:{template:`{{ action "${RN}" "🩺 doctor" }}`},[aN]:{template:`{{ action "${aN}" "✎ arrange" "✎ done" }}`}}};t.variables[wN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[TN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[NN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of dP)t.variables[fP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[pN]=ii(pN,`session`);for(let{member:e,label:n}of kA){t.actions[hN(e)]=ai(pN,e),t.actions[mN(e)]={do:[hN(e),...bP]};let r=ZN(sP(e).map(e=>e.name)),i=`(ternary ${ri(` •`)} "" ${r})`,a=e=>`(print ${ri(e)} ${i})`;t.segments[mN(e)]={template:`{{ ${ni(mN(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,lN.variables,uP.variables),IP(t),FP(t),t.actions[rN]={do:[ON,...yP,...MP(t)]},t}function FP(e){for(let t of _M){let n=wM(t.name),r=zN(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?kj:[];for(let n of i)e.actions[BN(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${BN(t.name,e)}" "${HN[e]}" }}`).join(``);e.segments[VN(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${ig}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function IP(e){for(let t of aP){Object.assign(e.actions,t.control.actions);let n=SN(t.name);e.actions[n]={reset:t.configKey},e.variables[XN(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${XN(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[bN(t.name)]={template:`${t.control.template}${iP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[YN(t.name,r)]=n})}Object.assign(e.actions,uP.actions),Object.assign(e.variables,$N.variables),Object.assign(e.actions,$N.actions),Object.assign(e.segments,$N.segments);for(let t of MA){let n=qN(t);e.actions[GN(t)]=ai(n.key,n.member),e.segments[WN(t)]={template:`{{ action "${GN(t)}" ${ri(jA[t].trigger)} }}`}}}function LP(e){let{variables:t,actions:n}=_A();Object.assign(e.variables,t),Object.assign(e.actions,n)}function RP(e){let t=PP(e.globals.menuGlyph??`🍫`);LP(t);let n={...e.presets},r=[];for(let t of Fy(e.presets)){let{node:i}=Ry(e,t),a=kP(wP(i));r.push(a),n[t]={...Ly(e.presets,t),root:a}}let i=JO(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const zP=`${QO}live`,BP=[`☐ live`,`☑ live`],VP=`${QO}done`,HP=`${QO}cancel`,UP=`${QO}rewind`,WP=`${QO}changes`,GP=`(gt .${WP} 0)`,KP=`(or ${GP} (gt .${pP} 0))`,qP={variable:zP,key:zP,member:`open`};function JP(e){return`${QO}configuring.p${e}`}function YP(e){return`and ${ei(fA)} (not ${ei(qP)}) (ne .${JP(e)} "true")`}function XP(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${aA} "${Zr(e)}")`).join(` `)} false }}`}}function ZP(e,t,n){return`{{ if ${YP(e)} }}${t}{{ else }}${n}{{ end }}`}const QP=`{{ and ${ei(fA)} .preset.customized }}`,$P=ek;function eF(e){return new Map([...Uy(e),...nF(e)])}const tF=`${QO}addable`;function nF(e){return new Map([[tF,{members:Object.keys(e.segments).filter(e=>!$P(e)),library:{groups:tA.map(e=>({id:e,label:nA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function rF(e,t,n){return n.segments[e]={template:t,when:pA,bg:xA},{kind:`segment`,name:e}}function iF(e,t,n){let r=`${QO}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${$m}`}) (action "${r}" "✖") }}`}function aF(e){return`{{ if ${ei(fA)} }}${e}{{ end }}`}function oF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(fA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function sF(e){return e.flatMap(e=>[...gg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function cF(e,t,n){return`${uA}${e}.${t}.${n}`}function lF(e,t,n,r){let i=fg(n),a=`${QO}${e.presetIdent}`,o=dA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=ak(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:qr},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:aA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=cF(e.presetIdent,i,r),l=`${uA}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Fg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=_k(hk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${DA}" }}`,ref:{variable:aA,key:aA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const uF=`${QO}label:`;function dF(e){if(e.startsWith(uF)){let t=e.slice(uF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function fF(e,t,n,r){let{artifacts:i}=n,a=fg(e),o=`${uF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Ag.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,oF([r.ref],`{{ ${YP(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Ag.map(e=>[e,r.drafts[e]]))}}function pF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${QO}${i}.insert.${t}`,s=`${QO}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:tF,anchor:n,relation:r};let c=rk(o),l=ik(s,o,void 0),u=sk(l),d=ok(l,c);return a.variables[l]=ii(l,qr),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${$m}`}) $m }}{{ end }}`}}function mF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!$P(e.name)),i=e=>mF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=hg(o,i);if($P(o.name)){n.push(s);continue}let c=fg(o),l=a===r?[pF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=pF(t,u,c,`after`),f=iF(t,u,c),p=t.segments[o.name],m=lF(t,u,o,jg(p)),h=aF(f),g=aF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>rF(e.host,e.template,t.artifacts)),{...fF(o,p,t,m),lead:h,trail:g},{...s,when:ZP(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},rF(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:oF(sF(n),ZP(t.presetIdent,`true`,e.when))}}}function hF(e,t,n,r,i,a,o){let s=`${QO}${t}.resetLayout`,c=`${QO}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:QP},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},gF(e,o)]}}function gF(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),gF(n,t)]}:{...e,children:[...e.children,t]}}function _F(e,t,n,r,i,a){let{node:o}=Ry(e,t),s={presetIdent:YO(t),rootKey:Jk(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=mF(o,s);return n.variables[JP(s.presetIdent)]=XP(s.configured),hF(c,s.presetIdent,s.rootKey,n,r,i,a)}function vF(e){let t={variables:{},actions:{},segments:{}},n=yA(`${QO}help`,BA,[fA],t);t.variables[zP]=ii(zP,qr),t.actions[zP]=ai(zP,qP.member),t.segments[zP]={template:ti(zP,...BP),when:pA};let r={kind:`segment`,name:zP},i=n;t.variables[WP]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[VP]={do:[_N,...cA]},t.segments[VP]={template:`{{ if ${KP} }}{{ action "${VP}" "✓ save" }}{{ else }}{{ action "${VP}" "✓ done" }}{{ end }}`,when:pA},t.actions[UP]={rewind:!0},t.actions[HP]={do:[UP,...cA]},t.segments[HP]={template:`{{ action "${HP}" "↩ cancel" }}`,when:`{{ and ${ei(fA)} ${GP} }}`};let a=[{kind:`segment`,name:VP},{kind:`segment`,name:HP}],o={...e.presets},s=[];for(let n of Fy(e.presets)){let c=_F(e,n,t,a,r,i);s.push(c),o[n]={...Ly(e.presets,n),root:c}}let c=JO(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function yF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function bF(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function xF(e,t,n){let r=mg(e,new Set(n.map(pg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const SF=/^-?\d+$/;function CF(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function wF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!SF.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function TF(e,t,n){return r=>r?SF.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function EF(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!SF.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function DF(e){return e===`config`?`set-config`:`set-state`}function OF(e,t,n){return t.kind===`int`?wF(`menu page "${e}"`):t.kind===`range`?TF(t.min,t.max,`${n} stepper "${e}"`):CF(t.allowed,`${n} "${e}"`,DF(n))}function kF(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:EF(e,n,t)}))}function AF(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of kF(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,OF(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function jF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};AF(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=AF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const MF=jF({},`config`,zF);function NF(e,t){return MF.register(e,t)}function PF(e){return MF.gateFor(e)}function FF(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Gy(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[yF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[yF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Gy(e.insertSegmentFrom,t).members.map(t=>yF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function IF(e,t){let n=Uk(e).get(t);return n===void 0?null:String(n)}function LF(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?Qk(n.persist):null;e?.scope===`preset-root`&&t.add(Jk(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function RF(e){let t=eF(e);return[...LF(e),...Object.values(e.actions).flatMap(e=>FF(e,t))]}function zF(e){return kF(RF(e),`config`)}function BF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:UF(t.segments,VF(t.segments,e.segments??{})),root:jy(e.root??wy,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:UF(t.presets,HF(t.presets,e.presets??{})),themeDefaults:UF(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function VF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function HF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function UF(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function WF(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Sg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):qF(e,`${t}.cache`,n.cache)}function GF(e){return{required:!0,json:JF(),parse:(t,n,r,i)=>WF(t,n,i,e)??void 0}}const KF={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&XF(n)?{ttl:n}:i_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return i_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=g_(`cache.watch_file`,n);return r===null?{watch_file:n}:i_(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:i_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:i_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:i_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function qF(e,t,n){return a_(e,KF,t,n)}function JF(){return C_(KF)}const YF=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function XF(e){return YF.test(e)}function ZF(e,t,n){if(n===void 0)return{};if(!Zg(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Qg(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=o_(e,CI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function QF(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Qg(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function $F(){return{required:!0,json:{enum:[...wg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!wg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${wg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function eI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return qg(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const tI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:i_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?nI(e,t,n):i_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:i_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function nI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return i_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:i_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function rI(){return{required:!1,json:C_(tI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:a_(e,tI,`${t}.parse`,r.parse)??void 0)}}function iI(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Zg(r.parse)&&`json`in r.parse?aI(e,t,r.default):Jg(e,t,r,`default`)}}function aI(e,t,n){if(n!==void 0)return oI(n)?n:i_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function oI(e){return e!==null&&sI(e)}function sI(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(sI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(sI)}default:return!1}}const cI={value:QF(),default:u_()},lI={path:h_(),type:v_([`string`,`number`,`boolean`]),default:eI()},uI={name:h_(),default:u_()},dI={path:__(),readMode:v_([`whole`,`first-line`]),parse:rI(),cache:GF(`file`),default:iI()},fI={command:h_(),parse:rI(),cache:GF(`shell`),default:iI()};function pI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const mI={template:h_(),default:u_()},hI=pI(`a template variable recomputes whenever a variable it reads changes`),gI={layout:h_(),default:u_()},_I=pI(`a time variable reads the instant its render is drawn at`),vI={field:$F(),default:u_()},yI=pI(`a git variable is refreshed by the daemon's own watch on the repository`),bI={key:h_(),default:u_()},xI=`kind`;function SI(e,t,n={}){return{...s_(xI,e,t),parse:(r,i,a)=>{e_(r,n,i,a);let o=t_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const CI={tag:xI,noun:`source kind`,memberNoun:`variable`,arms:{literal:SI(`literal`,cI),input:SI(`input`,lI),env:SI(`env`,uI),file:SI(`file`,dI),shell:SI(`shell`,fI),template:SI(`template`,mI,hI),time:SI(`time`,gI,_I),git:SI(`git`,vI,yI),state:SI(`state`,bI)}};function wI(){return S_(CI)}function TI(){return{type:`object`,additionalProperties:wI()}}const EI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function DI(e){let t=EI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const OI=/^[A-Za-z_][A-Za-z0-9_]*$/,kI={pattern:OI.source},AI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},jI={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...kI}}}]},default:AI}},MI=[`label`,`domain`,`default`],NI=[`min`,`max`,`step`,`atLeast`];function PI(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function FI(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return PI(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return PI(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?PI(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(Zg(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!NI.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:PI(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return PI(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function II(e,t,n){if(!Zg(n))return PI(e,t,`${t} must be { label, domain, default }, got ${Qg(n)}`);for(let r of Object.keys(n))MI.includes(r)||PI(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${MI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||PI(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=FI(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!LI(n.default)||!Pg(o,n.default)?PI(e,`${t}.default`,`default must be ${Rg(o)}, got ${q(n.default)}`):o}function LI(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const RI={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Og}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function zI(e){return Ag.includes(e)}function BI(){return{required:!1,json:{type:`object`,propertyNames:{...kI,not:{enum:[...Ag]}},additionalProperties:jI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zg(i))return PI(e,a,`${a} must be an object of name → { label, domain, default }, got ${Qg(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!OI.test(t)){PI(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(zI(t)){PI(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${RI[t]}`);continue}let r=II(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const VI=$O.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function HI(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${VI})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!ek(i)?i:PI(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${$O.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function UI(){return{required:!1,json:{type:`object`,propertyNames:kI,additionalProperties:AI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zg(i))return PI(e,a,`a placement's "settings" must be an object of setting name → value, got ${Qg(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))LI(n)?o[t]=n:PI(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Qg(n)}`);return o}}}function WI(e){return new Set(Object.keys(e.segments).filter(e=>!ek(e)))}function GI(e,t,n){if(t===void 0)return{};if(!Zg(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Qg(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=$g(e,n.has(i)?ZI:XI,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function KI(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?i_(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${DI(t.slice(9))}`)??void 0:Kg(e,t,r,n)??void 0}}function qI(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function JI(){return{required:!1,json:TI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return ZF(e,`${t}.${n}`,i)}}}const YI={template:KI(),description:u_(),group:v_(eA),width:qI(),justify:v_(zg),truncate:v_(Bg),bg:u_(),fg:u_(),when:u_(),palette:m_(),vars:JI(),settings:BI(),missingData:v_(Tg)},XI={noun:`segment key`,fields:YI},ZI={noun:`segment key`,fields:{...YI,template:u_()}},QI=`#/definitions/LayoutNode`,$I={kind:`container`,direction:`vertical`,children:[]};function eL(e){return{required:!0,json:{const:e},parse:()=>e}}function tL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function nL(){return{required:!0,json:{enum:[...ug]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ug.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${ug.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function rL(e){return{required:!0,json:{type:`array`,items:{$ref:QI}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Qg(a)}`,line:K(t.source,[`root`])}),[])}}}const iL={noun:`layout-node key`,fields:{kind:eL(`segment`),name:tL(),when:u_(),id:HI(),settings:UI()}},aL=()=>v_(km),oL={noun:`layout-node key`,fields:{kind:eL(`container`),direction:nL(),children:rL(c_(()=>dL)),when:u_(),distribution:aL()}};function sL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const cL={noun:`layout-node key`,fields:{seg:sL(),when:u_(),id:HI(),settings:UI()}},lL={noun:`layout-node key`,fields:{h:rL(c_(()=>dL)),when:u_(),distribution:aL()}},uL={noun:`layout-node key`,fields:{v:rL(c_(()=>dL)),when:u_(),distribution:aL()}},dL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),$I):{kind:`segment`,name:n};if(!Zg(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Qg(n)}`,line:K(e.source,[`root`])}),$I;if(n.kind===`container`)return $g(e,oL,t,n)??$I;if(n.kind===`segment`)return $g(e,iL,t,n)??$I;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
177
+ `).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Nj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${zj[e]}`)])}}},Vj="re-run `cc-candybar install`";function Hj(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${Vj}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Vj}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Vj}`)}const Uj={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${Vj}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Vj}`};case`lost`:return Nj([...Hj(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function Wj({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function Gj(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${T_.join(`|`)}>\``:e.checkout===null?Vj:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Kj(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${Gj(e,`native`)}`];let{bundle:i,source:a}=Wj(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${Gj(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${Gj(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const qj=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},Jj={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${qj(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:Nj([...new Set(i.flatMap(e=>Kj(n,r,e)))])}};function Yj({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function Xj(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const Zj={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?Xj(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return Nj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=Yj(e.value,n),u=Nj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges RSS, which counts pages macOS has reclaimed`]:[],...o.kind===`measured`&&Ln(o.charge.bytes,s)?[`the daemon holds ${Vn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},Qj=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function $j(e,t){let n=bj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Sj(e.terminal):{kind:`unknown`}}function eM({identified:e,tmuxClient:t},n){let r=xj(e),i=$j(e,n),a=bj(e)===null?Qj:`${Qj}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${Cj}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const tM={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return Nj(eM(t,n))}}},nM=e=>e.filter(e=>e.role===`statusline`),rM={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{if(e.kind===`failed`)return{ok:!1,reason:e.reason};let i=[t,...n],[a,...o]=i.flatMap(({sources:e,bars:t})=>{let[n,...r]=nM(t).filter(e=>e.frame===`moves`||e.frame===`can-move`);if(n===void 0)return[];let i=ZA([n,...r]);return[{redraws:i.redraws,verdict:iM(e,i)}]}).sort((e,t)=>XA(e.redraws,t.redraws));if(a===void 0){let e=i.flatMap(e=>e.bars),t=nM(e);return t.some(e=>e.frame===`still`)?{ok:!0}:{ok:!1,reason:`${t.length>0?t.some(e=>e.frame===`drawing`)?`the bar's latest render has not finished`:`the bar's recent renders failed`:e.length>0?"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline":r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:qj(r)}, so whether it moves is unknown — run the doctor again once the bar has redrawn`}}let[s,...c]=[a,...o].flatMap(({verdict:e})=>e.ok?[]:[e]);if(s===void 0)return a.verdict;let l=[...new Set(c.map(e=>e.reason))].filter(e=>e!==s.reason);return l.length===0?s:{...s,more:l}}};function iM(e,t){let n=t.frame===`moves`?`the bar moves (an effect, a fade, or an animated segment)`:`the bar can start moving (a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`,r=wj(e);if(r.kind===`present`&&r.refreshInterval!==1){let{from:e,refreshInterval:t}=r,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return Dj(e)?{ok:!1,reason:`${n}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${n}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}let{redraws:i}=t;if(i.kind===`unseen`)return{ok:!1,reason:`${n}, and this daemon has watched Claude Code redraw it for only ${i.over} of the 60 seconds its redraw rate is judged over, so whether it is redrawn every second is unknown — run the doctor again once the bar has been on screen for a minute`};if(JA(i))return{ok:!0,note:`Claude Code redrew the bar in ${i.seconds} of the last 60 seconds`};let a=`${n}, but Claude Code redrew it in only ${i.seconds} of the last 60 seconds`,o=`a statusLine from --settings, MDM or server-managed settings, which the doctor cannot read, runs the bar; set "refreshInterval": 1 beside its command there`;switch(r.kind){case`unread`:return{ok:!1,reason:`${a}, and Claude Code's settings could not be read: ${r.reason}`};case`absent`:return{ok:!1,reason:`${a}, and no settings file Claude Code reads here sets a statusLine (read: ${r.read.join(`, `)||`none`}) — ${o}`};case`not-an-object`:return{ok:!1,reason:`${a}, and ${r.from.path} sets statusLine to ${JSON.stringify(r.value)}, not a statusLine object — ${r.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:return{ok:!1,reason:`${a}, though ${r.from.path} sets statusLine.refreshInterval to 1 — set within the last minute, it shows once Claude Code has redrawn the bar for one (restart Claude Code if it does not); otherwise ${o}`}}}const aM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function oM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return xj(e);case`bundling`:case`unread`:case`configured`:return[uj(e.name),e.version].filter(e=>e!==null).join(` `)}}function sM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return bj(e);case`bundling`:case`unread`:return uj(e.name);case`configured`:{let t=uj(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function cM(e){let t=sM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${aM(e.glyphs)}`}}const lM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=cM(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=oM(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${aM(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=oj[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:hj(i.version,e);if(t===!0)return{ok:!0};let n=uj(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${aM(n)} — set a Nerd Font as its font`)}}}};function uM(e){return e.join(`, `)}function dM(e){return`or set missingData: "ignore" on ${uM(e)}`}function fM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${uM(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${uM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${dM(t)}`]:[`${uM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${dM(t)}`]}function pM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${uM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${uM(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${uM(n)}: ${qj(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${uM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${uM(n)}`]:[]}function mM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${uM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${dM(t)}`];case`failed`:return[`${uM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const hM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>Nj([...fM(e.pullRequests),...pM(e.rateLimits,t),...mM(e.memento)])};function gM({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${Aj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const _M=[Bj,Jj,Zj,Uj,tM,Ij,Lj,Rj,rM,lM,hM,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${qj(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:Nj(e.value.flatMap(gM))}],vM=_M.filter(e=>e.takesMark);function yM(e){return _M.map(t=>({check:t,verdict:t.probe(e)}))}function bM(e){return _M.find(t=>t.name===e)}const xM=/^[^\s"=\\]+$/,SM=e=>xM.test(e)?e:JSON.stringify(e),CM=`${X}doctor.`;function wM(e){let t=`${CM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function TM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?bj(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function EM(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function DM(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=Wj(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}function OM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${Xj(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${Yj(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Hn(i.charge)}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function kM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function AM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>jM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed redrawn=failed chains=${SM(i)}`;let a=nM(r.flatMap(e=>e.bars)),o=e=>a.filter(t=>t.frame===e).length,s=a.map(({redraws:e})=>e.kind===`seen`?`${e.seconds}`:`unseen(${e.over})`);return`frames=${nj.map(o).join(`/`)} redrawn=${s.join(`,`)||`-`} chains=${SM(i)}`}function jM(e){let t=wj(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function MM(e){let t=Tj(e,Pj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${SM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function NM(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function PM(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=cM(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function FM(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function IM(e){return e.flatMap(({check:e,verdict:t})=>{let n=wM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:ag},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:FM(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?ag:ig},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const LM={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function RM(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(LM).map(([t,n])=>[`${e}${t}`,n]))}}const zM=`armed`,BM=`disarmed`,VM=`.armed`,HM=e=>e.endsWith(VM);function UM(e,t,n){let r=`${e}${VM}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${zM}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:zM},[a]:{set:r,to:BM},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:BM}},disarm:a}}const WM=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function GM(e){return typeof e==`string`&&WM.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function KM(e){let t=GM(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const qM=[`/compact`,`/model`],JM=`/clear`;function YM(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=UM(`${e}clear`,{arm:JM,confirm:`${JM} ✓ confirm`},[n]);return{template:qM.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${KO} }}`,actions:{...Object.fromEntries(qM.map(e=>[t(e),{slash:KM(e)}])),...r.actions,[n]:{slash:KM(JM)}},variables:r.variables,disarm:r.disarm}}const XM=Array.from({length:10},(e,t)=>(t+1)*1e5),ZM=XM[0],QM=XM[XM.length-1];function $M(e){let t;try{t=Da(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=ZM&&n<=QM?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${ZM}–${QM} tokens)`)}function eN(e,t){let n=Math.min(t??QM,QM),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:XM.filter(e=>e<r).at(-1)??0,higher:XM.find(e=>e>r&&e<=n)??0}}function tN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${KO} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:KM(`/autocompact auto`)},...Object.fromEntries(XM.map(t=>[`${e}${t}`,{slash:KM(`/autocompact ${t}`)}]))}}}const nN=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,rN=`${X}menu`,iN=`open`,aN=`${X}edit`,oN=`${X}toolbar`,sN=RM(X),cN=`${X}commands`,lN=YM(`${cN}.`),uN=`${X}autocompact`,dN=tN(`${uN}.`,nN),fN=e=>({kind:`segment`,name:e}),pN=`${X}tab`,mN=e=>`${pN}.${e}`,hN=e=>`${mN(e)}.toggle`,gN=e=>({variable:pN,key:pN,member:e}),_N=`${X}save`,vN=`${X}preset.save`,yN=`${X}preset.delete`,bN=e=>`${X}${e}`,xN=e=>`${X}apply.${e}`,SN=e=>`${X}reset.${e}`,CN=`${X}themeDefault.save`,wN=`${X}themeDefault.differs`,TN=`${X}themeDefault.theme`,EN={when:`{{ .${wN} }}`,template:`{{ action "${CN}" (printf "⤓ default for %s" .${TN}) }} {{ swatch "${xN(`theme`)}" .${TN} }}`},DN=`${X}resetAll`,ON=`${rN}.toggle`,kN={variable:rN,key:rN,member:iN},AN=`${X}undo`,jN=`${X}back`,MN=`${jN}.step`,NN=`${X}navigation.back`,PN=jN,FN={template:`{{ if gt .${NN} 0 }}{{ action "${jN}" "◁" }}{{ else }}{{ fg (${UA}) "◁" }}{{ end }}`},IN=`${X}redo`,LN=`${X}doctor`,RN=`${LN}.run`,zN=e=>`${LN}.fix.${e}`,BN=(e,t)=>`${LN}.mark.${e}.${t}`,VN=e=>`${LN}.${e}`,HN={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},UN=ak(`${X}pickers`),WN=e=>`${X}${e}`,GN=e=>`${WN(e)}.toggle`,KN=e=>PA(e)?ak(`${X}${e}Pickers`):UN,qN=e=>{let t=KN(NA[jA[e].beside]);return{variable:t,key:t,member:e}},JN={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${yN}" (printf "🚮 delete %s" .${ov.preset.effectiveVar}) }}`}},YN=(e,t)=>`${X}list.${e}.${t}`,XN=e=>`${X}resettable.${e}`,ZN=e=>e.length===0?`false`:`(or ${e.map(e=>`.${XN(e)}`).join(` `)})`,QN=T_.map(e=>[w_[e].setting,e]),$N={variables:{},actions:{},segments:{}},eP=Object.fromEntries(QN.map(([e,t])=>[e,yA(`${X}help.${e}`,VA[t],[],$N)])),tP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],nP=e=>{let t=t=>`.${k_(e,t)}`,n=tP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${ov[w_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},rP=`{{ if eq .${D_(`by`)} "feed" }} {{ printf "%2d" (int .${D_(`fps`)}) }} fps{{ end }}`,iP=Object.fromEntries(QN.map(([e,t])=>[e,nP(t)])),aP=Object.keys(ov).map(e=>{let t=ov[e],n=bk(t.configKey),r=_k({label:t.label,domain:n},t.sessionKey,t.effectiveVar,xN(e),KN(NA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>JN[e])}}),oP=e=>aP.filter(t=>NA[t.name]===e),sP=e=>aP.filter(t=>FA(NA[t.name])===e),cP=e=>MA.filter(t=>jA[t].beside===e),lP=e=>oP(e).flatMap(e=>[xP(e),...[eP[e.name]].filter(e=>e!==void 0),...cP(e.name).map(e=>Qr(WN(e),qN(e),{kind:`container`,direction:`horizontal`,children:lP(e)},`drop`))]);new Set(aP.flatMap(e=>[e.sessionKey,e.configKey]));const uP=UM(DN,{arm:`⟲`,confirm:`⟲ reset all?`},aP.map(e=>SN(e.name))),dP=[`unsaved`,`history.undo`,`history.redo`],fP=e=>`${X}${e}`,pP=fP(`unsaved`),mP=(e,t)=>({body:t,shown:`(gt .${fP(e)} 0)`}),hP=[mP(`unsaved`,`{{ action "${_N}" (printf "💾 save %d" .${pP}) }}`),mP(`history.undo`,`{{ action "${AN}" "↶" }}`),mP(`history.redo`,`{{ action "${IN}" "↷" }}`),{body:uP.template,shown:`(or ${ZN(aP.map(e=>e.name))} ${uP.armed})`}],gP={when:`{{ or ${hP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+hP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},_P=[{step:uP,place:`door`},{step:lN,place:`session`}],vP=e=>e.map(e=>e.step.disarm),yP=vP(_P),bP=vP(_P.filter(e=>e.place!==`door`));function xP(e){let t=bN(e.name);return e.control.kind===`inline`?fN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>fN(YN(e.name,n)))},`drop`)}function SP(e){return e===rN}function CP(e){let t=fN(rN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[CP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function wP(e){return TP(e)>0?e:CP(e)}function TP(e){let t=0;for(let n of gg(e))n.kind===`segment`&&SP(n.name)&&(t+=1);return t}function EP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&SP(e.name)||e.opens!==void 0&&EP(e.opens.body,!0):e.children.some(e=>EP(e,n))}const DP={session:{direction:`vertical`,content:[fN(oN),{kind:`container`,direction:`horizontal`,children:[fN(cN),fN(uN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[fN(CN)]},layout:{direction:`horizontal`,content:[fN(vN),fN(aN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[fN(LN),..._M.map(e=>fN(VN(e.name)))],after:[]}},OP=e=>({kind:`container`,direction:DP[e].direction,children:[...DP[e].content,...lP(e),...DP[e].after]});function kP(e){return e.kind===`segment`?SP(e.name)?Qr(e.name,kN,jP,`above`):e:NP(e)}function AP(){return{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[fN(PN),...lP(`door`),fN(_N)]},{kind:`container`,direction:`horizontal`,children:kA.map(({member:e})=>Qr(mN(e),gN(e),OP(e),`drop`))}]}}const jP=AP();function MP(e){let t=new Map;for(let e of gg(jP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${rN}.fold.${YO(t)}`;return e.actions[i]={set:t,to:r.default},i})}function NP(e){return{...e,children:e.children.map(e=>kP(e))}}function PP(e){let t={variables:{[rN]:ii(rN,qr)},actions:{[ON]:ai(rN,iN),[RN]:{doctor:`run`},[aN]:{do:[...cA]},...sN.actions,...lN.actions,...dN.actions,[_N]:{save:!0},[AN]:{undo:!0},[MN]:{back:!0},[jN]:{do:[MN,...yP]},[IN]:{redo:!0},[vN]:{preset:`save`},[CN]:{themeDefault:`save`},[yN]:{preset:`delete`,name:`{{ .${ov.preset.effectiveVar} }}`}},segments:{[rN]:{template:`{{ $door := ${ni(rN,ri(e),ri(`✖`))} }}{{ if ${ei(kN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+rP},[oN]:{template:sN.template},[cN]:{template:lN.template,when:lN.when},[uN]:{template:dN.template,bg:dN.bg,when:dN.when},[PN]:FN,[_N]:gP,[CN]:EN,[vN]:{template:`{{ action "${vN}" "+ preset" }}`},[LN]:{template:`{{ action "${RN}" "🩺 doctor" }}`},[aN]:{template:`{{ action "${aN}" "✎ arrange" "✎ done" }}`}}};t.variables[wN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[TN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[NN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of dP)t.variables[fP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[pN]=ii(pN,`session`);for(let{member:e,label:n}of kA){t.actions[hN(e)]=ai(pN,e),t.actions[mN(e)]={do:[hN(e),...bP]};let r=ZN(sP(e).map(e=>e.name)),i=`(ternary ${ri(` •`)} "" ${r})`,a=e=>`(print ${ri(e)} ${i})`;t.segments[mN(e)]={template:`{{ ${ni(mN(e),a(n),a(`▾ ${n}`))} }}`}}return Object.assign(t.variables,lN.variables,uP.variables),IP(t),FP(t),t.actions[rN]={do:[ON,...yP,...MP(t)]},t}function FP(e){for(let t of _M){let n=wM(t.name),r=zN(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?kj:[];for(let n of i)e.actions[BN(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${BN(t.name,e)}" "${HN[e]}" }}`).join(``);e.segments[VN(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${ig}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function IP(e){for(let t of aP){Object.assign(e.actions,t.control.actions);let n=SN(t.name);e.actions[n]={reset:t.configKey},e.variables[XN(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${XN(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[bN(t.name)]={template:`${t.control.template}${iP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[YN(t.name,r)]=n})}Object.assign(e.actions,uP.actions),Object.assign(e.variables,$N.variables),Object.assign(e.actions,$N.actions),Object.assign(e.segments,$N.segments);for(let t of MA){let n=qN(t);e.actions[GN(t)]=ai(n.key,n.member),e.segments[WN(t)]={template:`{{ action "${GN(t)}" ${ri(jA[t].trigger)} }}`}}}function LP(e){let{variables:t,actions:n}=_A();Object.assign(e.variables,t),Object.assign(e.actions,n)}function RP(e){let t=PP(e.globals.menuGlyph??`🍫`);LP(t);let n={...e.presets},r=[];for(let t of Fy(e.presets)){let{node:i}=Ry(e,t),a=kP(wP(i));r.push(a),n[t]={...Ly(e.presets,t),root:a}}let i=JO(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const zP=`${QO}live`,BP=[`☐ live`,`☑ live`],VP=`${QO}done`,HP=`${QO}cancel`,UP=`${QO}rewind`,WP=`${QO}changes`,GP=`(gt .${WP} 0)`,KP=`(or ${GP} (gt .${pP} 0))`,qP={variable:zP,key:zP,member:`open`};function JP(e){return`${QO}configuring.p${e}`}function YP(e){return`and ${ei(fA)} (not ${ei(qP)}) (ne .${JP(e)} "true")`}function XP(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${aA} "${Zr(e)}")`).join(` `)} false }}`}}function ZP(e,t,n){return`{{ if ${YP(e)} }}${t}{{ else }}${n}{{ end }}`}const QP=`{{ and ${ei(fA)} .preset.customized }}`,$P=ek;function eF(e){return new Map([...Uy(e),...nF(e)])}const tF=`${QO}addable`;function nF(e){return new Map([[tF,{members:Object.keys(e.segments).filter(e=>!$P(e)),library:{groups:tA.map(e=>({id:e,label:nA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function rF(e,t,n){return n.segments[e]={template:t,when:pA,bg:xA},{kind:`segment`,name:e}}function iF(e,t,n){let r=`${QO}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${$m}`}) (action "${r}" "✖") }}`}function aF(e){return`{{ if ${ei(fA)} }}${e}{{ end }}`}function oF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(fA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function sF(e){return e.flatMap(e=>[...gg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function cF(e,t,n){return`${uA}${e}.${t}.${n}`}function lF(e,t,n,r){let i=fg(n),a=`${QO}${e.presetIdent}`,o=dA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=ak(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:qr},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:aA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=cF(e.presetIdent,i,r),l=`${uA}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Fg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=_k(hk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${DA}" }}`,ref:{variable:aA,key:aA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const uF=`${QO}label:`;function dF(e){if(e.startsWith(uF)){let t=e.slice(uF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function fF(e,t,n,r){let{artifacts:i}=n,a=fg(e),o=`${uF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Ag.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,oF([r.ref],`{{ ${YP(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Ag.map(e=>[e,r.drafts[e]]))}}function pF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${QO}${i}.insert.${t}`,s=`${QO}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:tF,anchor:n,relation:r};let c=rk(o),l=ik(s,o,void 0),u=sk(l),d=ok(l,c);return a.variables[l]=ii(l,qr),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${$m}`}) $m }}{{ end }}`}}function mF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!$P(e.name)),i=e=>mF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=hg(o,i);if($P(o.name)){n.push(s);continue}let c=fg(o),l=a===r?[pF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=pF(t,u,c,`after`),f=iF(t,u,c),p=t.segments[o.name],m=lF(t,u,o,jg(p)),h=aF(f),g=aF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>rF(e.host,e.template,t.artifacts)),{...fF(o,p,t,m),lead:h,trail:g},{...s,when:ZP(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},rF(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:oF(sF(n),ZP(t.presetIdent,`true`,e.when))}}}function hF(e,t,n,r,i,a,o){let s=`${QO}${t}.resetLayout`,c=`${QO}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:QP},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},gF(e,o)]}}function gF(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),gF(n,t)]}:{...e,children:[...e.children,t]}}function _F(e,t,n,r,i,a){let{node:o}=Ry(e,t),s={presetIdent:YO(t),rootKey:Jk(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=mF(o,s);return n.variables[JP(s.presetIdent)]=XP(s.configured),hF(c,s.presetIdent,s.rootKey,n,r,i,a)}function vF(e){let t={variables:{},actions:{},segments:{}},n=yA(`${QO}help`,BA,[fA],t);t.variables[zP]=ii(zP,qr),t.actions[zP]=ai(zP,qP.member),t.segments[zP]={template:ti(zP,...BP),when:pA};let r={kind:`segment`,name:zP},i=n;t.variables[WP]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[VP]={do:[_N,...cA]},t.segments[VP]={template:`{{ if ${KP} }}{{ action "${VP}" "✓ save" }}{{ else }}{{ action "${VP}" "✓ done" }}{{ end }}`,when:pA},t.actions[UP]={rewind:!0},t.actions[HP]={do:[UP,...cA]},t.segments[HP]={template:`{{ action "${HP}" "↩ cancel" }}`,when:`{{ and ${ei(fA)} ${GP} }}`};let a=[{kind:`segment`,name:VP},{kind:`segment`,name:HP}],o={...e.presets},s=[];for(let n of Fy(e.presets)){let c=_F(e,n,t,a,r,i);s.push(c),o[n]={...Ly(e.presets,n),root:c}}let c=JO(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function yF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function bF(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function xF(e,t,n){let r=mg(e,new Set(n.map(pg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const SF=/^-?\d+$/;function CF(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function wF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!SF.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function TF(e,t,n){return r=>r?SF.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function EF(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!SF.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function DF(e){return e===`config`?`set-config`:`set-state`}function OF(e,t,n){return t.kind===`int`?wF(`menu page "${e}"`):t.kind===`range`?TF(t.min,t.max,`${n} stepper "${e}"`):CF(t.allowed,`${n} "${e}"`,DF(n))}function kF(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:EF(e,n,t)}))}function AF(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of kF(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,OF(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function jF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};AF(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=AF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const MF=jF({},`config`,zF);function NF(e,t){return MF.register(e,t)}function PF(e){return MF.gateFor(e)}function FF(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Gy(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[yF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[yF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Gy(e.insertSegmentFrom,t).members.map(t=>yF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function IF(e,t){let n=Uk(e).get(t);return n===void 0?null:String(n)}function LF(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?Qk(n.persist):null;e?.scope===`preset-root`&&t.add(Jk(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function RF(e){let t=eF(e);return[...LF(e),...Object.values(e.actions).flatMap(e=>FF(e,t))]}function zF(e){return kF(RF(e),`config`)}function BF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:UF(t.segments,VF(t.segments,e.segments??{})),root:jy(e.root??wy,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:UF(t.presets,HF(t.presets,e.presets??{})),themeDefaults:UF(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function VF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function HF(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function UF(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function WF(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${Sg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):qF(e,`${t}.cache`,n.cache)}function GF(e){return{required:!0,json:JF(),parse:(t,n,r,i)=>WF(t,n,i,e)??void 0}}const KF={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&XF(n)?{ttl:n}:i_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return i_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=g_(`cache.watch_file`,n);return r===null?{watch_file:n}:i_(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:i_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:i_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:i_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function qF(e,t,n){return a_(e,KF,t,n)}function JF(){return C_(KF)}const YF=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function XF(e){return YF.test(e)}function ZF(e,t,n){if(n===void 0)return{};if(!Zg(n))return e.issues.push({path:t,message:`${t} must be an object, got ${Qg(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=o_(e,CI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function QF(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${Qg(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function $F(){return{required:!0,json:{enum:[...wg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!wg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${wg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function eI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return qg(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const tI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:i_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?nI(e,t,n):i_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:i_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function nI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return i_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:i_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function rI(){return{required:!1,json:C_(tI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:a_(e,tI,`${t}.parse`,r.parse)??void 0)}}function iI(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>Zg(r.parse)&&`json`in r.parse?aI(e,t,r.default):Jg(e,t,r,`default`)}}function aI(e,t,n){if(n!==void 0)return oI(n)?n:i_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function oI(e){return e!==null&&sI(e)}function sI(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(sI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(sI)}default:return!1}}const cI={value:QF(),default:u_()},lI={path:h_(),type:v_([`string`,`number`,`boolean`]),default:eI()},uI={name:h_(),default:u_()},dI={path:__(),readMode:v_([`whole`,`first-line`]),parse:rI(),cache:GF(`file`),default:iI()},fI={command:h_(),parse:rI(),cache:GF(`shell`),default:iI()};function pI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const mI={template:h_(),default:u_()},hI=pI(`a template variable recomputes whenever a variable it reads changes`),gI={layout:h_(),default:u_()},_I=pI(`a time variable reads the instant its render is drawn at`),vI={field:$F(),default:u_()},yI=pI(`a git variable is refreshed by the daemon's own watch on the repository`),bI={key:h_(),default:u_()},xI=`kind`;function SI(e,t,n={}){return{...s_(xI,e,t),parse:(r,i,a)=>{e_(r,n,i,a);let o=t_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const CI={tag:xI,noun:`source kind`,memberNoun:`variable`,arms:{literal:SI(`literal`,cI),input:SI(`input`,lI),env:SI(`env`,uI),file:SI(`file`,dI),shell:SI(`shell`,fI),template:SI(`template`,mI,hI),time:SI(`time`,gI,_I),git:SI(`git`,vI,yI),state:SI(`state`,bI)}};function wI(){return S_(CI)}function TI(){return{type:`object`,additionalProperties:wI()}}const EI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function DI(e){let t=EI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const OI=/^[A-Za-z_][A-Za-z0-9_]*$/,kI={pattern:OI.source},AI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},jI={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...kI}}}]},default:AI}},MI=[`label`,`domain`,`default`],NI=[`min`,`max`,`step`,`atLeast`];function PI(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function FI(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return PI(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return PI(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?PI(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(Zg(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!NI.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:PI(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return PI(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function II(e,t,n){if(!Zg(n))return PI(e,t,`${t} must be { label, domain, default }, got ${Qg(n)}`);for(let r of Object.keys(n))MI.includes(r)||PI(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${MI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||PI(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=FI(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!LI(n.default)||!Pg(o,n.default)?PI(e,`${t}.default`,`default must be ${Rg(o)}, got ${q(n.default)}`):o}function LI(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const RI={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Og}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function zI(e){return Ag.includes(e)}function BI(){return{required:!1,json:{type:`object`,propertyNames:{...kI,not:{enum:[...Ag]}},additionalProperties:jI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zg(i))return PI(e,a,`${a} must be an object of name → { label, domain, default }, got ${Qg(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!OI.test(t)){PI(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(zI(t)){PI(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${RI[t]}`);continue}let r=II(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const VI=$O.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function HI(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${VI})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!ek(i)?i:PI(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${$O.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function UI(){return{required:!1,json:{type:`object`,propertyNames:kI,additionalProperties:AI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!Zg(i))return PI(e,a,`a placement's "settings" must be an object of setting name → value, got ${Qg(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))LI(n)?o[t]=n:PI(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${Qg(n)}`);return o}}}function WI(e){return new Set(Object.keys(e.segments).filter(e=>!ek(e)))}function GI(e,t,n){if(t===void 0)return{};if(!Zg(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${Qg(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=$g(e,n.has(i)?ZI:XI,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function KI(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?i_(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${DI(t.slice(9))}`)??void 0:Kg(e,t,r,n)??void 0}}function qI(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function JI(){return{required:!1,json:TI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return ZF(e,`${t}.${n}`,i)}}}const YI={template:KI(),description:u_(),group:v_(eA),width:qI(),justify:v_(zg),truncate:v_(Bg),bg:u_(),fg:u_(),when:u_(),palette:m_(),vars:JI(),settings:BI(),missingData:v_(Tg)},XI={noun:`segment key`,fields:YI},ZI={noun:`segment key`,fields:{...YI,template:u_()}},QI=`#/definitions/LayoutNode`,$I={kind:`container`,direction:`vertical`,children:[]};function eL(e){return{required:!0,json:{const:e},parse:()=>e}}function tL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function nL(){return{required:!0,json:{enum:[...ug]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&ug.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${ug.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function rL(e){return{required:!0,json:{type:`array`,items:{$ref:QI}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${Qg(a)}`,line:K(t.source,[`root`])}),[])}}}const iL={noun:`layout-node key`,fields:{kind:eL(`segment`),name:tL(),when:u_(),id:HI(),settings:UI()}},aL=()=>v_(km),oL={noun:`layout-node key`,fields:{kind:eL(`container`),direction:nL(),children:rL(c_(()=>dL)),when:u_(),distribution:aL()}};function sL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const cL={noun:`layout-node key`,fields:{seg:sL(),when:u_(),id:HI(),settings:UI()}},lL={noun:`layout-node key`,fields:{h:rL(c_(()=>dL)),when:u_(),distribution:aL()}},uL={noun:`layout-node key`,fields:{v:rL(c_(()=>dL)),when:u_(),distribution:aL()}},dL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),$I):{kind:`segment`,name:n};if(!Zg(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${Qg(n)}`,line:K(e.source,[`root`])}),$I;if(n.kind===`container`)return $g(e,oL,t,n)??$I;if(n.kind===`segment`)return $g(e,iL,t,n)??$I;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
177
178
  Old: { kind: "cells", segments: ["seg1", "seg2"] }
178
179
  New: { h: ["seg1", "seg2"] }`,line:K(e.source,[`root`])}),$I;if(n.kind===`group`){let r=$g(e,vL,t,n);return r===null?$I:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),bL(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:K(e.source,[`root`])}),$I}if(a){let r=$g(e,cL,t,n);return r===null?$I:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=$g(e,lL,t,n);return r===null?$I:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=$g(e,uL,t,n);return r===null?$I:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:K(e.source,[`root`])}),$I};function fL(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Sy.source},additionalProperties:{$ref:QI}},parse:(e,t,n,r)=>{let i=r[n];if(!Zg(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${Qg(i)}`,line:K(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!Sy.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:K(e.source,[...t.split(`.`),n,r])});continue}a[r]=dL(e,`${t}.${n}.${r}`,o)}return a}}}const pL={noun:`root key`,fields:{rows:fL(),when:u_(),distribution:aL()}};function mL(e,t,n){return Zg(n)&&`rows`in n?$g(e,pL,t,n)??{rows:{}}:dL(e,t,n)}function hL(){return{required:!0,json:{type:`string`,pattern:Sy.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Sy.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${qr}", got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}function gL(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}}function _L(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=Kg(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:K(e.source,[...t.split(`.`),n])});return}return i}}}}const vL={noun:`layout-node key`,fields:{kind:eL(`group`),name:hL(),label:_L(),open:d_(),direction:v_(ug),key:gL(),bg:u_(),fg:u_(),when:u_(),distribution:aL(),children:rL(c_(()=>dL))}};function yL(e){return e.key??`groups.`+e.name}function bL(e){let t=XO+e.name;return Qr(t,{variable:t,key:yL(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function xL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function SL(e,t){nk(e,t,XO,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&xL(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&yL(t)===yL(r)&&xL(e,t.path,`group "${t.name}" shares key "${yL(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=yL(t);if(i.has(n)||i.set(n,qr),t.open===!0){let r=i.get(n);r!==`closed`&&xL(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=XO+e.name,r=yL(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ii(r,i.get(r)),o[t]=ai(r,e.name),s[t]={template:ti(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const CL=`menu`,wL=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,TL=e=>e.kind===`call`&&e.name===`dict`,EL=e=>e.kind===`literal`&&typeof e.value!=`object`,DL=e=>Yr(``,e,2)===void 0;function OL(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&TL(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(TL))return t(`whose options (dict …) is not its last argument — ${wL}`);if(i!==void 0&&a===void 0&&!EL(i)&&DL(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Yr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${wL}`);let c=a===void 0?{}:dw(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=dk(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=tk(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${ak(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function kL(e){let t=bS({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===CL).map(OL)}catch{return`parse-failed`}}function AL(e){let t=bS({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(CL)}catch{return!1}}function jL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function ML(e,t){nk(e,t,ZO,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))AL(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:K(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&AL(i)&&jL(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of gg(ky(t.root)))typeof n.when==`string`&&AL(n.when)&&jL(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!AL(r))continue;let n=kL(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:NL(r.apply);n!==void 0&&jL(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function NL(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(rk(e)===`closed`)return`whose apply action is named "${qr}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function PL(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Fy(e.presets)){let a=new Map,s=new Map;for(let c of gg(Ry(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,kL(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=fg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||NL(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=rk(i),f=ik(u,i,l.key),p=sk(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=ok(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=ai(f,d),n[f]=ii(f,qr),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const FL=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function IL(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function LL(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function RL(e,t){if(t===void 0)return{};if(!Zg(t))return Z(e,`actions`,`actions must be an object, got ${Qg(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=zL(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function zL(e,t,n){if(!Zg(n))return Z(e,t,`${t} must be an action object, got ${Qg(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=FL.filter(e=>e in n);return r.length===1?BL[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${FL.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const BL={set:(e,t,n)=>bR(e,t,n,`set`,gR),persist:(e,t,n)=>bR(e,t,n,`persist`,_R),copy:VL(`copy`),open:VL(`open`),reset:HL,undo:WL(`undo`),redo:WL(`redo`),back:WL(`back`),rewind:WL(`rewind`),save:WL(`save`),preset:GL,themeDefault:KL,doctor:JL,ceiling:YL,slash:XL,do:ZL};function VL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=Kg(t,n,r,e);return i===null?null:{[e]:i}}}function HL(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=QL(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const UL={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function WL(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${UL[e]}), got ${q(r[e])}`),null)}}function GL(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${q(r)}`),null;if(r===`save`)return{preset:`save`};let a=Kg(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function KL(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${q(n.themeDefault)}`),null)}const qL={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function JL(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(qL,r),a=i?qL[r]:[...new Set(Object.values(qL).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(qL).map(e=>`"${e}"`).join(`, `)}, got ${q(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?vM:_M;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${q(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return kj.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${kj.map(e=>`"${e}"`).join(` or `)}, got ${q(c)}`),null)}function YL(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Z(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${q(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Z(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${q(a)}`),null):{ceiling:`set`,to:a}}function XL(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=GM(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}function ZL(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${q(r)}`),null):{do:r}}function QL(e,t,n,r,i,a){let o=Kg(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const $L={set:`the SessionState key to write`,persist:`the config globals field to write`};function eR(e,t,n,r){let i=$L[r],a=QL(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function tR(e){return e===`set`?`set-state`:`set-config`}const nR={to:xR(`set`)},rR={to:xR(`persist`)},iR={from:SR(`set`)},aR={from:SR(`persist`)},oR={min:DR(),max:DR(),by:DR()},sR={int:wR()},cR={cycle:CR(`set`)},lR={cycle:CR(`persist`)},uR={removeSegment:TR(`removeSegment`)},dR={insertSegment:TR(`insertSegment`),anchor:TR(`anchor`),relation:ER()},fR={insertSegmentFrom:SR(`persist`),anchor:TR(`anchor`),relation:ER()},pR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},mR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function hR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>t_(e,t,n,r),c=y_(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?l_(s,...n):s}}const gR=[hR(`set`,nR),hR(`set`,iR),hR(`set`,oR,[pR,mR]),hR(`set`,sR),hR(`set`,cR)],_R=[hR(`persist`,rR),hR(`persist`,aR),hR(`persist`,oR,[pR,mR]),hR(`persist`,lR),hR(`persist`,uR),hR(`persist`,dR,[],[`insertSegment`]),hR(`persist`,fR,[],[`insertSegmentFrom`])];function vR(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function yR(e){let t=vR(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function bR(e,t,n,r,i){let a=eR(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${yR(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function xR(e){let t=tR(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>QL(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function SR(e){let t=tR(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${q(o)}`)}}}function CR(e){let t=tR(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${Qg(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function wR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${q(r[n])}`);return}return!0}}}function TR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=Kg(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function ER(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${q(i)}`);return}return i}}}function DR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${q(i)}`);return}return i}}}function OR(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const kR={noun:`style key`,fields:{hueShift:p_(),chromaScale:p_({min:0}),lightnessScale:p_(),lightnessShift:p_()}};function AR(e,t){if(!Zg(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${Qg(t)}`,line:K(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:K(e.source,[`styles`,r])});continue}if($h(r)){e.issues.push({path:`styles.${r}`,message:OR(`styles.${r}`,r,`globals.endcaps`),line:K(e.source,[`styles`,r])});continue}let t=$g(e,kR,`styles.${r}`,i);t!==null&&(n[r]={...xc,...t})}return n}const jR={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:mL(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Ik(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Fk(e,`${t}.${n}`,r[n])}}};function MR(e,t){if(!Zg(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${Qg(t)}`,line:K(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:K(e.source,[`presets`,r])});continue}let t=$g(e,jR,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function NR(e,t){if(t===void 0)return{};if(!Zg(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${Qg(t)}`,line:K(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${q(i)}`,line:K(e.source,[`helpers`,r])});continue}n[r]=i}return n}const PR=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function FR(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function IR(e){let t=PR.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${FR(t)}`}function LR(e){let t=PR.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${FR(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}function RR(e,t){let n=new Map;for(let e of Object.keys(t)){let t=YO(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:K(e.source,[`presets`])})}function zR(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Ih(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:$h(i)?OR(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:K(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:K(e.source,[`globals`,`preset`])}),RR(e,t.presets);let i=mb(t);for(let t of i.names)t!==`settings`&&!t.startsWith(HR)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:K(e.source,[`variables`,t])});let a=(t,n,r)=>{TP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${rN}" ${TP(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),EP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${rN}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r}),o(t)&&e.issues.push({path:n,message:`${n} sets "distribution" on a container inside a bar cell — everything inside a cell wears that cell's hue and shade, so it would place nothing. Set it on the row whose children are the cells (the horizontal container) or on the root, which places the rows.`,line:r});let i=new Map;for(let e of gg(t)){if(e.kind!==`segment`)continue;let t=fg(e);i.set(t,[...i.get(t)??[],e])}for(let[t,a]of i){if(a.length<2)continue;let o=a[1].name,s=mg(o,new Set(i.keys()));e.issues.push({path:n,message:`${n} has ${a.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t=!1){return e.kind===`segment`?!1:t&&e.distribution!==void 0||e.children.some(n=>o(n,t||dg[e.direction]===`cell`))}let s=(n,r)=>{for(let[a,o]of Ay(n,r)){let n=K(e.source,o.split(`.`));if(a.when!==void 0&&(ez(e,`${o}.when`,a.when,i,{line:n}),$R(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(SP(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${rN}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${rN}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${DI(a.name)}`,line:n}),XR(e,t,a,o,n)}}};n.root!==void 0&&s(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&s(t.root,`presets.${e}.root`);let c=new Map([[`root`,Oy(t.root)]]);for(let e of Fy(t.presets)){let{node:n,path:r}=Ry(t,e);c.set(r,n)}for(let[t,n]of c)a(n,t,K(e.source,t.split(`.`)));sz(e,t,i,()=>!0)}const BR=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function VR(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=K(e.source,[`actions`,n,r]);if(!Fy(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Fy(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${DI(i)}`,line:c})},p=new Set(pg(Ry(t,a).node)),m=(r,i)=>{!EI.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${DI(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const HR=`settings.`;function UR(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>HR+e)])}}function WR(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:K(e.source,[`segments`,t,`settings`,n])})},a=qR(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Ng(n,KR(n)))i(e,`the defaults do not stand together: ${t}`)}function GR(e){return qR(e).length>0||Ng(e,KR(e)).length>0}function KR(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function qR(e){let t=t=>Mg(JR(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||Mg(JR(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${YR(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function JR(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function YR(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&Mg(n)!==void 0).map(([e])=>e)}function XR(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=jg(a),s=`${r}: placement "${fg(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:Pg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Dh(a):``}, but it must be ${Rg(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>Pg(o[e],t))||GR(o)))for(let{message:t}of Ng(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function ZR(e,t,n,r,i){n.kind===`template`&&ez(e,`${t}.template`,n.template,r,{segCtx:i}),Cg(n)&&`key`in n.cache&&ez(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function QR(e,t,n,r,i){if(!(!Cg(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:K(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function $R(e,t,n,r){try{rA.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function ez(e,t,n,r,i){for(let[a,o]of ob(n,r.helpers)){if(pb(a,r))continue;if(a.startsWith(HR)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??K(e.source,t.split(`.`))});continue}if(o!==null){tz(e,o,`Template references unknown variable ".${a}"${LR(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&pb(n,r)?` (segment-local vars are namespaced — write ".${n}")`:LR(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??K(e.source,t.split(`.`))})}}function tz(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:K(e.source,[`helpers`,t])})}function nz(e,t,n,r,i){let a=n.set,o=bk(ov[r].configKey),s=`${a} takes ${mk(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:K(e.source,[`actions`,t,`min`])});return}let c=az(n,i);if(c===iz){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:K(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!pk(o,e.value,i));if(l.length!==0){if(a===ov.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>$h(e.value)))){let r=ov.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:OR(`actions.${t}.to`,n.to,`set: "${r}", to`),line:K(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:K(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=rz?r.join(`, `):`${r.slice(0,rz).join(`, `)} and ${r.length-rz} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:K(e.source,[`actions`,t,n])})}}}const rz=3,iz=Symbol(`any integer`);function az(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?Gy(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:iz}function oz(e,t){return Object.entries(e).filter(([e])=>t(e))}function sz(e,t,n,r){let i=eF(t),a=Wy(i);for(let[n,o]of oz(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${qy(r,i)}`,line:K(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;uv.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:K(e.source,[`actions`,n,`set`])});let s=mv.get(o.set);s!==void 0&&nz(e,n,o,s,i)}for(let[n,i]of oz(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&LL(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:K(e.source,[`actions`,n,`do`])})});for(let[n,i]of oz(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=Qk(r);if(o===null){let t=Bk(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${Vk().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:K(e.source,[`actions`,n,a])});continue}let s=BR.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){VR(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Fy(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Fy(t.presets).join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Dh(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${DI(o.segment)}`,line:K(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:K(e.source,[`actions`,n,a])})}}for(let[i,a]of oz(t.variables,r)){ZR(e,`variables.${i}`,a,n);let t=IR(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:K(e.source,[`variables`,i])})}for(let[i,a]of oz(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))ZR(e,`segments.${i}.vars.${t}`,r,n,i);let r=jg(a);WR(e,i,r);let o=UR(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){ez(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of ub(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){tz(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:K(e.source,[`segments`,i,n])})}}}}for(let[i,a]of oz(t.variables,r))QR(e,`variables.${i}`,a,n);for(let[i,a]of oz(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))QR(e,`segments.${i}.vars.${t}`,r,n,i)}function cz(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=lz(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:K(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function lz(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of ob(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Cg(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function uz(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function dz(e,t){return s.resolve(e,uz(t))}function fz(e,t){return typeof t==`string`&&t!==``?dz(e,t):void 0}function pz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const mz=new Set([`data`,`segments`,`helpers`,`actions`]),hz=`plugin.json5`,gz=/^[a-z][a-z0-9_]*$/;function _z(e){let t=s.basename(s.dirname(e));return gz.test(t)?t:void 0}const vz=`plugins.`;function yz(e){return`${vz}${e}.data`}function bz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:xz(e)}}}function xz(e){return e instanceof Vg?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function Sz(e,t){return e.map(e=>dz(s.dirname(t),e))}function Cz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=_z(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${hz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${hz} and list that`;return o(t,a===void 0?e.config:Ez(Tz(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${gz}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=Tz(e.config,a),u=bz(()=>{let i=p.readFileSync(n,`utf-8`),o=BF(Mz(n,a,{source:i,json:ui.default.parse(i)},t),l);return r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,Ez(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function wz(e){let t=`${vz}${e}.`;return e=>e.startsWith(t)}function Tz(e,t){let n=wz(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function Ez(e,t,n){return{...e,variables:{...e.variables,[yz(t)]:{kind:`dropped`,reason:pz(n),definition:n.path}}}}function Dz(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Oz(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Dz)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:pz(e)}));return t=>{let i=Dz(t);if(i===void 0)return[];let a=e.config.variables[yz(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function kz(e,t){let n=Fy(e.presets).flatMap(t=>[...gg(Ry(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,Az(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Dz(t),r=n===void 0?void 0:e.variables[yz(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>ub(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...fb(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${yz(Dz(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function Az(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,jz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function jz(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function Mz(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Vg(e,a)};if(!Zg(r))return a.push({path:``,message:`a plugin definition must be an object, got ${Qg(r)}`}),o();for(let e of Object.keys(r))mz.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...mz].join(`, `)}`});let s=Rz(r.data,e,i,a);if(Zg(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(Ah()),groups:[]},l=ZF(c,`data`,{[yz(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!Zg(t)||!Zg(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=Zg(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:Pz(t,Iz(t,GI(c,r.segments,new Set))),helpers:Pz(t,NR(c,r.helpers)),actions:Pz(t,Lz(t,RL(c,r.actions)))};for(let[e,t]of Nz(u))try{rA.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*Nz(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function Pz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${vz}${e}.${t}`,n]))}function Fz(e,t){return`${vz}${e}.${t}`}function Iz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,n.kind===`state`?{...n,key:Fz(e,n.key)}:n]))}]))}function Lz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Fz(e,n.set)}:n]))}function Rz(e,t,n,r){if(typeof e==`string`&&e!==``)return dz(s.dirname(t),e);if(Zg(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(Zg(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function zz(e){let t=[...[...(process.env.XDG_DATA_DIRS||Hz()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),Bz(),...e===null?[]:[s.join(e,Vz)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function Bz(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const Vz=s.join(`.cc-candybar`,`plugins`);function Hz(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function Uz(e){let t=zz(e),n=new Map,r=[],i=[];for(let e of t){let t=Wz(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,hz));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${hz}: move this file to ${s.join(e,`<name>`,hz)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function Wz(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||Gz(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function Gz(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function Kz(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const qz=[`json5`,`json`];function Jz(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?qz.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...qz.map(e=>s.join(r,`.cc-candybar.${e}`)),...qz.map(e=>`${Yz()}.${e}`)])]}function Yz(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function Xz(e,t,n){let r=[],i=new Map;for(let a of Jz(e,t,n)){let e=Kz(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:Zz(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function Zz(e){let t=Yz();return e.find(e=>qz.some(n=>e===`${t}.${n}`))??`${t}.${qz[0]}`}function Qz(e,t,n){let r=Xz(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function $z(e){return eB(e).join(`
179
180
  `)||null}function eB(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function tB(e,t){let n=Jz(e,t).filter(e=>Kz(e)===`present`),r=new Map;for(let e of n){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),i=s.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function nB(e,t,n,r){return e===null?{...fB,config:BF(fB.raw,t)}:iB(e,p.readFileSync(e,`utf-8`),t,n,r)}const rB={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function iB(e,t,n,r,i){let a=hB(e,t,i,(t,a)=>{let o=Cz(Sz(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>uB(t,n,r,e,i)),s=Oz(o,r.beneath.dropped);return{inherited:new Set([...WI(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=kz(BF(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(pz)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const aB=new WeakMap;function oB(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,cB(e)])]),a=aB.get(n)??new Map;aB.set(n,a);let o=JSON.stringify([t.projectDir,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=Cz(e,t,{config:n,rendering:new Map},(e,t,n)=>uB(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function sB(e,t,n){return Cz(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>uB(e,t,n,`<plugin install>`,void 0)).dropped}function cB(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function lB(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:CD(r.cwd)},s=Uz(o.projectDir),c=oB(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=iB(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(pz));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:pB(nB(null,u,rB),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:pB(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),pB(e,e.path,a);throw n.entered(v.path),e}}function uB(e,t,n,r,i){if(n){pB(dB(e),r,i);return}let a=wz(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(sz(s,e,mb(e),a),cz(s,e,a),o.length>0)throw new Vg(r,o)}function dB(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const fB={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function pB({config:e,raw:t,source:n},r=`<config>`,i=new Set(Ah())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(zR(o,e,t),cz(o,e),a.length>0)throw new Vg(r,a);let s=PL(e,a);if(a.length>0)throw new Vg(r,a);return vF(RP(s))}function mB(e,t,n=new Set(Ah()),r=gB){return hB(e,t,n,()=>({inherited:r,layer:null})).raw}function hB(e,t,n,r){let i=_B(e,t),a=Wg(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Ah()),groups:[]};if(!Zg(i))throw new Vg(e,[{path:``,message:`Config root must be an object, got ${Qg(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:bB({...c,issues:[]},i.plugins)??[],Zg(i.segments)?Object.keys(i.segments):[]),d=vB(c,i,l);if(s.length>0)throw new Vg(e,s,o);return{raw:d,warnings:o,layer:u}}const gB=new Set;function _B(e,t){try{return ui.default.parse(t)}catch(t){let n=t;throw new Vg(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function vB(e,t,n){for(let n of Object.keys(t))yB.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...yB].join(`, `)}`,line:K(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=Pk(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=ZF(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=GI(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
@@ -181,8 +182,8 @@ Config tooling:
181
182
  With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
182
183
  Single-row example: root: { h: ["seg1", "seg2"] }`,line:K(e.source,[`layout`])}),t.root!==void 0&&(r.root=mL(e,`root`,t.root)),t.actions!==void 0&&(r.actions=RL(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:K(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=AR(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Nk(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=MR(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Lk(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=NR(e,t.helpers)),t.plugins!==void 0&&(r.plugins=bB(e,t.plugins)),SL(e,r),ML(e,r),gA(e,r),nk(e,r,X,`the global settings menu`),r}const yB=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function bB(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${Qg(t)}`,line:K(e.source,[`plugins`])})}const xB={},SB=YM(`commands.`),CB=tN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),wB=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,TB=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${wB}) (basename .project_dir) (ne (${wB}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,EB=`{{ ${UA} }}`,DB={min:0,max:100,step:5},OB={warnAt:{label:`warning at %`,domain:DB,default:50},errorAt:{label:`error at %`,domain:{...DB,atLeast:`warnAt`},default:80}};function kB(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:DB,default:80}}}const AB={globals:{palette:`tokyo-night`},variables:{...SB.variables,...GO,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? 󰅃 󰅃 󰄿 󰶼`},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:TB},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:EB,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:RM(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:SB.template,when:SB.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:kB(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:kB(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:OB,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:OB,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${$m} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:CB.template,bg:CB.bg,when:CB.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...RM(``).actions,...SB.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...CB.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:xB,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${$m} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${UA}) 2 (readableOn (color "accent") (bgOf) ${$m})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${$m}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:nN(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},jB=new Set([AB.globals.palette,...Object.keys(AB.themeDefaults),...Object.values(AB.segments).map(e=>e.palette)].filter(e=>e!==void 0)),MB=BF(mB(`<default>`,JSON.stringify(AB),jB),AB),NB=Fy(MB.presets);function PB(e){return NB.includes(e)}const FB=Object.freeze({});function IB(e,t){return e.kind===`decided`?t[e.name]??FB:FB}function LB(e,t){return{...e,...Object.fromEntries($_.map(n=>[n,e[n]??t[n]]))}}const RB=e=>A_(t=>e[w_[t].setting]);function zB(e,t,n,r){let i=tv(e);return kh(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function BB(e,t,n){let r=Iy(t(`preset`),e.globals.preset,e.presets),i=zy(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=by(a.palette,t(`theme`),i.palette),s=LB(i,IB(o,e.themeDefaults));return{...Object.fromEntries(Z_.map(e=>[e,zB(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Hh(a.style,t(`style`),s.style,e.styles),effect:Xh(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function VB(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?ig:ag;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const HB=Object.entries(ov),UB=new Set(cv.map(e=>e.sessionKey)),WB=()=>!1;function GB(e,t){return BB(e,e=>UB.has(e)?t(e):null,WB)}const KB=[`preset`,`theme`];function qB(e,t,n){let r=new Set(KB.slice(0,n).map(e=>ov[e].sessionKey));return BB(e,e=>r.has(e)?t(e):null,WB)}function JB(e,t){let n=Array.from({length:KB.length+1},(n,r)=>qB(e,t,r));return e=>{let t=KB.indexOf(e);return n[t===-1?KB.length:t]}}function YB(e,t,n,r){return e.flatMap(([e,i])=>{let a=VB(t,e);return a===null||a===VB(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function XB(e,t,n){return VB(GB(e,t),n)}function ZB(e,t){let n=GB(e,t);return YB(HB,n,JB(e,t),t=>QB(e,n.preset,t.configKey))}function QB(e,t,n){return n in(Ly(e.presets,t).globals??{})?Zk(t,n):n}function $B(e,t,n){let r=Iy(t(ov.preset.sessionKey),e.globals.preset,e.presets),i=Qk(n);return{key:i?.scope===`globals`?QB(e,r,i.field):n,globals:zy(e,r)}}function eV(e,t){let{preset:n}=GB(e,t);return rV(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ig(a,s);return c===void 0||Fg(c)===Fg(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function tV(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Fy(e.presets).flatMap(n=>{let i=rV(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return Ng(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:Ig(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const nV=new WeakMap;function rV(e,t){let n=nV.get(e)??new Map;nV.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...gg(Ry(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=jg(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function iV(e,t){let n=GB(e,t);return{from:n.preset,globals:Ly(e.presets,n.preset).globals??{},picks:YB(HB.filter(([e])=>e!==`preset`),n,JB(e,t),e=>e.configKey),placements:eV(e,t)}}function aV(e,t){return BB({...e,globals:{palette:t},presets:{}},()=>null,WB)}function oV(e,t){let n=GB(e,t),r=VB(n,`theme`);if(r===null)return{kind:`rule`};let i=aV(e,r),a=zy(e,n.preset),o=Object.fromEntries($_.map(e=>[e,VB(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:$_.some(e=>o[e]!==VB(i,e))}}function sV(e){return{sessionKeys:cv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...kk(e)?NB.map(t=>Zk(t,e)):[],...Xk(e)?Ah().map(t=>Yk(t,e)):[]]}}function cV(e){return new Set(cv.map(e=>e.configKey).filter(t=>sV(t).fileKeys.some(t=>dV(e,uV(t)))))}function lV(e,t,n){let r=ZB(e,n),i=new Set(r.map(e=>e.configKey)),a=pv(e=>i.has(ov[e].configKey)||t.has(ov[e].configKey)),o=oV(e,n);return{unsaved:r.length+eV(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function uV(e){let t=Qk(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return $k(t)}function dV(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&dV(e[n],r)}const fV=Ah(),pV=new Set(fV),mV=new Set(Zh),hV=e=>e?pV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${fV.join(`, `)})`}:{ok:!1,reason:`theme name is required`},gV=e=>e?mV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${Zh.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},_V=new Set([`1`,`true`]),vV=new Set([`0`,`false`]),yV={endcaps:gV,theme:hV,"toolbar-expanded":e=>_V.has(e)?{ok:!0,value:`1`}:vV.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},bV=jF(yV,`state`,DV);function xV(e,t){return bV.register(e,t)}function SV(e){return bV.gateFor(e)}function CV(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:Gy(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function wV(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(yV,e.key))}function TV(e,t,n){let r=mv.get(n);if(r!==void 0)return XB(e,t,r);for(let[,t]of Dg(e))if(t.key===n)return t.default??null;return null}function EV(e){let t=eF(e);return wV(Object.values(e.actions).flatMap(e=>CV(e,t)))}function DV(e){return kF(EV(e))}const OV=`update.dismissed`,kV=`updateNotice`,AV=ov.updateNotice.sessionKey;function jV(e){return e.kind===`source`?e.newer.digest:La(e.newer)}const MV=e=>`${e.version} [${Ke(e.digest)}]`;function NV(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:MV(e.newer),running:MV(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:La(e.newer),running:La(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${za}@${La(e.newer)}`,`install`]}}}}const PV={kind:`idle`},FV={kind:`running`};function IV(e,t,n){if(e===null)return[];let r=jV(e);if(!n.enabled||n.dismissed===r)return[];let i=NV(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
183
184
  `),c=Vr([{verb:yr,args:[s]}]),l=t.kind===`running`?ny(`[${i.busy}]`,c):ny(`[${i.act}]`,Vr([{verb:Mr,args:[n.sessionId]}]));return[{severity:ey,message:s,lines:[[ny(a,c),l,ny(`[dismiss]`,Vr([{verb:pr,args:[n.sessionId,OV,r]}])),ny(`[disable]`,Vr([{verb:br,args:[n.sessionId,kV,`false`]},{verb:pr,args:[n.sessionId,AV,`false`]}]))],...o.map(e=>[ny(e,c)])]}]}function LV(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function RV(e){switch(e.kind){case`current`:return[`info`,`build: current ${MV(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${MV(e.source)}, running ${MV(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function zV(e){switch(e.kind){case`current`:return[`info`,`release: current ${La(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${La(e.latest)}, running ${La(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${La(e.installed)}, latest ${La(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function BV(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const VV=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function HV(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=VV(e.stderr)??e.error??VV(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function UV(){let e=[NF(kV,[`false`]),xV(AV,[`false`]),xV(OV,[])];return()=>e.forEach(e=>e())}function WV(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=PV,d=null,f=BV(s),p=BV(s),m=()=>LV(c,l);function h(){let e=m(),t=e===null?null:jV(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:xV(OV,[t])})}function g(){c=Qe(t,Ye),f(RV(c)),h()}async function _(){l=Va(qe,await Ba(za,a,i)),p(zV(l)),h()}return{arm(){UV(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>IV(m(),u,e),act(){let e=m();if(e===null)throw new J(`apply-update: nothing newer is known to apply`);let t=NV(e);if(u.kind===`running`)throw new J(`apply-update: already ${t.busy}`);u=FV,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),lt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=PV,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=HV(n);u={kind:`failed`,identity:jV(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function GV(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function KV(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function qV(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:GV(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=GV(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!KV(t,n)){a(`info`,`binary ${n.kind===`absent`?`gone`:`changed`} (${e}); shutting down`),c&&clearInterval(c),i();return}}};return{arm(){for(let{path:e,stamp:t}of o)t.kind===`failed`&&a(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);c=setInterval(l,n),c.unref()},checkNow:l}}const JV=`${bv}${yv}`;function YV(e){return`${JV}⚠ cc-candybar: ${XV(e)}${xv}\n`}function XV(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${vv(e.message,60)}`;case`render_failed`:return`render failed: ${vv(e.message,60)}`;case`switched_off`:return`switched off: ${vv(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${vv(e.message,60)}`}}function ZV(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
184
- `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:YV(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const QV=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function $V(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?QV[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const eH={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},tH=Object.keys(eH);function nH(e,t){let n=$V(t.color),r=$V(t.bgcolor),i={};for(let e of tH){if(t[e]!==!0)continue;let n=eH[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const rH=new H;function iH(e){return{ok:!0,band:new Gf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(nH(t.slice(r,i.start),rH)),n.push(nH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(nH(t.slice(r),rH)),n})}}function aH(e){let t=ZV(pn(e)).output;try{return iH(t)}catch(e){return iH(`${bv}${yv}⚠ cc-candybar ${_v(e instanceof Error?e.message:String(e))}${xv}\n`)}}const oH={band:e=>JSON.stringify(aH(e)),statusline:(e,t)=>t,pane:(e,t)=>t};var sH=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const cH={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var lH=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await sH.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await sH.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(cH).length} models`),this.executionCache=cH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(cH).length} models`),cH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const uH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function dH(e){if(typeof e==`string`)return uH.exec(e)?.[1]}function fH(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function pH(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function mH(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=fH(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?dH(pH(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function hH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function gH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function _H(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=TH(i,t,s.value);let c=SH(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function vH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(bH(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=pH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||yH.test(r)?`claude-code`:`prompt`}const yH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function bH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function xH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=vH(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:mH(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function SH(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function CH(e){let t=SH(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return xH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function wH(e){let t=[];for(let n of e.split(`
185
- `)){let e=CH(n);e&&t.push(e)}return t}function TH(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function EH(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function DH(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=TH(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>wH(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var OH=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function kH(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const AH=new Map,jH={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},MH={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function NH(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function PH(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function FH(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const IH={entries:0,cost:0,breakdown:FH(),days:new Map};async function LH(e,t){let n=NH(new Date(PH())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await lH.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=NH(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...jH};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function RH(e){let t=0,n=0,r=FH(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...jH};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:MH,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function zH(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var BH=class{sessions=new Map;flight=new OH;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new OH;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:MH,i=t?.cost?.total_cost_usd??null;return P({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=NH(_O(n)),i=hH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return I(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...jH},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??AH:AH;c||=a.has(r);let l=a.get(r)??jH;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?P({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):F}async observeSpeed(e,t,n){if(!e)return F;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=kH(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),P({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return F;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,P(a);if(!t)return a?P(a):F;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),P(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await _H(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of EH(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await DH(e,r,IH,LH);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of EH(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...RH(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=PH(),i=await gH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await zH(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},VH=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await DH(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of EH(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function HH(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var UH=class{fold;constructor(e={}){this.fold=new VH(void 0,HH,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return I(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),F):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),P({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const WH={messageCount:0,nonPrompts:0,recent:[]},GH=new Set([`turn`,`interrupt`,`claude-code`]);function KH(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!GH.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function qH(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var JH=class{fold;constructor(e={}){this.fold=new VH(WH,KH,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:qH(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const YH={command:null,todos:[],pending:[],done:[]};function XH(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function ZH(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function QH(e,t){if(t.isSidechain)return e;let n=ZH(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=XH(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function $H(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>XH(e,t.name),[]),done:e.done}}var eU=class{fold;constructor(e={}){this.fold=new VH(YH,QH,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`activity (${e}): ${n.reason}`):P($H(n.value))}};function tU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function nU(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function rU(e,t,n,r){return nU(ut(tU(e,t,n,r)),n)}async function iU(e,t,n){return nU(await lt(tU(e,t,n)),n)}const aU=e=>`${e.socket}\n${e.pane}`;var oU=class{names=new Map;asking=new OH;constructor(e=Date.now){this.now=e}getSessionName(e){let t=aU(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await iU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?P(r):F:I(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const sU=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var cU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=sU(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=sU(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function lU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const uU=s.join(`lib`,`ceiling_config.py`),dU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function fU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function pU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return I(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return P(n)}function mU(e,t){if(!p.existsSync(e))return F;let n;try{n=fU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return I(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return F;let i=pU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return F;let a=[uU,dU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?P(r.installPath):I(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function hU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function gU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function _U(e){let t;try{t=JSON.parse(e)}catch{return I(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?P({ceiling:i,session:r}):I(`memento read: unexpected answer: ${e.trim()}`)}async function vU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
185
+ `,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:YV(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const QV=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function $V(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?QV[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const eH={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},tH=Object.keys(eH);function nH(e,t){let n=$V(t.color),r=$V(t.bgcolor),i={};for(let e of tH){if(t[e]!==!0)continue;let n=eH[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const rH=new H;function iH(e){return{ok:!0,band:new Gf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(nH(t.slice(r,i.start),rH)),n.push(nH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(nH(t.slice(r),rH)),n})}}function aH(e){let t=ZV(pn(e)).output;try{return iH(t)}catch(e){return iH(`${bv}${yv}⚠ cc-candybar ${_v(e instanceof Error?e.message:String(e))}${xv}\n`)}}function oH(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const sH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function cH(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:sH[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const lH={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},uH=Object.keys(lH);function dH(e){return e.replaceAll(`#`,`##`)}function fH(e){let t=uH.filter(t=>e[t]===!0).map(e=>{let t=lH[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${cH(e.color)}`,`bg=${cH(e.bgcolor)}`,...t].join(`,`)}]`}const pH=new H;function mH(e){let t={},n=(e,n)=>{let r=fH(n)+dH(e);if(n.link===void 0)return r;let i=oH(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new Gf().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),pH)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),pH)),r.join(``)}),links:t}}function hH(e){let t=ZV(pn(e)).output;try{return mH(t)}catch(e){return mH(`${bv}${yv}⚠ cc-candybar ${_v(e instanceof Error?e.message:String(e))}${xv}\n`)}}const gH={band:e=>JSON.stringify(aH(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:hH(e)})};var _H=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const vH={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var yH=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await _H.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await _H.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(vH).length} models`),this.executionCache=vH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(vH).length} models`),vH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const bH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function xH(e){if(typeof e==`string`)return bH.exec(e)?.[1]}function SH(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function CH(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function wH(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=SH(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?xH(CH(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function TH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function EH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function DH(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=FH(i,t,s.value);let c=MH(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function OH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(AH(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=CH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||kH.test(r)?`claude-code`:`prompt`}const kH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function AH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function jH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=OH(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:wH(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function MH(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function NH(e){let t=MH(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return jH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function PH(e){let t=[];for(let n of e.split(`
186
+ `)){let e=NH(n);e&&t.push(e)}return t}function FH(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function IH(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function LH(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=FH(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>PH(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var RH=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function zH(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const BH=new Map,VH={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},HH={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function UH(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function WH(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function GH(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const KH={entries:0,cost:0,breakdown:GH(),days:new Map};async function qH(e,t){let n=UH(new Date(WH())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await yH.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=UH(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...VH};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function JH(e){let t=0,n=0,r=GH(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...VH};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:HH,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function YH(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var XH=class{sessions=new Map;flight=new RH;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new RH;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:HH,i=t?.cost?.total_cost_usd??null;return P({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=UH(_O(n)),i=TH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return I(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...VH},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??BH:BH;c||=a.has(r);let l=a.get(r)??VH;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?P({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):F}async observeSpeed(e,t,n){if(!e)return F;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=zH(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),P({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return F;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,P(a);if(!t)return a?P(a):F;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),P(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await DH(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of IH(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await LH(e,r,KH,qH);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of IH(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...JH(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=WH(),i=await EH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await YH(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},ZH=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await LH(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of IH(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function QH(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var $H=class{fold;constructor(e={}){this.fold=new ZH(void 0,QH,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return I(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),F):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),P({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const eU={messageCount:0,nonPrompts:0,recent:[]},tU=new Set([`turn`,`interrupt`,`claude-code`]);function nU(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!tU.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function rU(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var iU=class{fold;constructor(e={}){this.fold=new ZH(eU,nU,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return F;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:rU(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const aU={command:null,todos:[],pending:[],done:[]};function oU(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function sU(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function cU(e,t){if(t.isSidechain)return e;let n=sU(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=oU(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function lU(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>oU(e,t.name),[]),done:e.done}}var uU=class{fold;constructor(e={}){this.fold=new ZH(aU,cU,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?I(`activity (${e}): ${n.reason}`):P(lU(n.value))}};function dU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function fU(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function pU(e,t,n,r){return fU(ut(dU(e,t,n,r)),n)}async function mU(e,t,n,r){return fU(await lt(dU(e,t,n,r)),n)}const hU=e=>`${e.socket}\n${e.pane}`;var gU=class{names=new Map;asking=new RH;constructor(e=Date.now){this.now=e}getSessionName(e){let t=hU(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await mU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?P(r):F:I(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const _U=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var vU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=_U(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=_U(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function yU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const bU=s.join(`lib`,`ceiling_config.py`),xU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function SU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function CU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return I(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return P(n)}function wU(e,t){if(!p.existsSync(e))return F;let n;try{n=SU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return I(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return F;let i=CU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return F;let a=[bU,xU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?P(r.installPath):I(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function TU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function EU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function DU(e){let t;try{t=JSON.parse(e)}catch{return I(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?P({ceiling:i,session:r}):I(`memento read: unexpected answer: ${e.trim()}`)}async function OU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
186
187
  import json, math, sys
187
188
  sys.path.insert(0, sys.argv[1])
188
189
  from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
@@ -191,18 +192,18 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
191
192
  layer = ceiling_in(directory / CONFIG_NAME)
192
193
  print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
193
194
  "session": layer.text if layer else None}))
194
- `,s.join(e,`lib`),t.sessionId,t.cwd],env:hU(t),timeoutMs:3e3,category:`memento.read`});return n.ok?_U(n.stdout):I(gU(n))}function yU(e,t,n){let r=ut({bin:s.join(e,dU),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:hU(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(gU(r))}function bU(e,t){return mU(Ca(e),t)}function xU(){return{locate:e=>bU(e.claudeConfigDir,e.projectDir),read:vU,move:yU}}function SU(e){return{gitProvider:new dO({watchers:e.watchers,logger:e.logger}),usageStore:new BH({logger:e.logger}),contextProvider:new UH({logger:e.logger}),metricsProvider:new JH({logger:e.logger}),activityProvider:new eU({logger:e.logger}),tmuxService:new oU,mementoProvider:new cU(xU()),autoCompact:$M,log:e.logger}}const CU=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function wU(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function TU(e){let t=await EU(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function EU(e){for(let t of[65536,1048576]){let n=await _a(e,t);if(n.kind!==`ok`)return n;let r=DU(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function DU(e,t){let n=e.toString(`utf8`).split(`
195
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!CU.test(t))continue;let r=wU(t);if(r!=null)return r}return null}function OU(e,t,n){return Me({dir:e.project_dir,env:n===void 0?[]:[[ya,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function kU(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function AU(e){return{...Object.fromEntries(Z_.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:PB(e.preset)}}}const jU={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function MU(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const NU=10*1e3;function PU(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function FU(e,t){if(!(t<60))return e*3600/t}function IU(e,t,n,r){let i=r-t;if(i<50||i>NU)return;let a=n-e;if(!(a<=0))return a*1e3/i}function LU(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=IU(t.input,t.atMs,n.input,n.atMs),i=IU(t.output,t.atMs,n.output,n.atMs),a=IU(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function RU(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>NU)continue;let o=IU(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function zU(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function BU(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>zU(C.hostname())),i=n(`user`,()=>C.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function VU(e,t){let n=[],r=t=>ob(t,e.helpers).keys(),i=zy(e,t);for(let e of Fh){let t=i[e];if(Ih(t))for(let e of r(t))n.push(e)}for(let i of gg(Ry(e,t).node)){if(i.when)for(let e of r(i.when))n.push(e);i.kind===`segment`&&n.push(...HU(e,i.name))}return WU(e,n)}function HU(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(t=>t?[...ob(t,e.helpers).keys()]:[]):[]}function UU(e,t,n){return WU(e,[...HU(e,t),...n.flatMap(t=>[...ob(t,e.helpers).keys()])])}function WU(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[...t],i=new Set,a=t=>ob(t,e.helpers).keys(),o=new Set;for(;r.length>0;){let e=r.pop();for(let t of KU(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function GU(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=VU(e,n);return t.set(n,i),i}}function KU(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function qU(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function JU(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(jU).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function YU(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>qU(i,e),u=_O(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[p,m,h,g,_,v,y,b,ee,x,S]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,JU(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(F):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>TU(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(lU({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(Sa(xa(o.claudeConfigDir)))))]),te=[],ne=e=>{if(e.kind===`failed`){te.push(e.reason);return}return e.kind===`ok`?e.value:void 0},C=rW(p,u);te.push(...C.failures);let re=BU(o);te.push(...re.failures);let ie=ne(m),ae=ne(h),w=ne(g),T=ne(_),oe=ne(v),E=ne(y),se=ne(b),ce=QU(x);x.kind===`failed`&&te.push(`memento: ${x.reason}`);let le=XU(S,w?.maxTokens);S.kind===`failed`&&te.push(`autocompact: ${S.reason}`);for(let e of te)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?PU(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?PU(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?FU(me,he):void 0,_e=ne(ee),ve=_e===void 0?void 0:LU(_e),ye=_e===void 0?void 0:RU(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=nW(process.env.HOME??process.env.USERPROFILE),Se=e.workspace?{...e.workspace,current_dir:nW(e.workspace.current_dir)??``,project_dir:nW(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>nW(e)??e)}:e.workspace,Ce=ie===void 0?void 0:tW({cost:ie.session.cost,tokens:ie.session.tokens}),we=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},Te=T===void 0?void 0:tW({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ee=oe===void 0?void 0:$U(oe);return{...e,...Se!==void 0&&{workspace:Se},...xe!==void 0&&{home:xe},...C.git!==void 0&&{git:C.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...AU(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},feeds:n.feeds(e.session_id),...c,...s!==null&&{configPath:s},resumeCommand:OU(Se,e.session_id,o.claudeConfigDir),...Ce!==void 0&&{session:Ce},...we!==void 0&&{today:we},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...Te!==void 0&&{metrics:Te},...Ee!==void 0&&{activity:Ee},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function XU(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return eN(e.value,t)}}const ZU=e=>e.trim().split(`
196
- `).at(-1).trim();function QU(e){switch(e.kind){case`absent`:return;case`failed`:return{error:ZU(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function $U(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=eW(e.running),i=eW(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function eW(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function tW(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function nW(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function rW(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=n.upstream===void 0?void 0:i(`tracking`,wD(n.upstream,n.aheadBehind)),p=i(`repoName`,n.repoName),m=i(`repoUrl`,n.repoUrl),h=n.pullRequest===void 0?void 0:TD(n.pullRequest,n.head),g={};switch(h?.kind){case`ok`:g={prNumber:h.value.number,prState:h.value.state,prUrl:h.value.url};break;case`failed`:r.push(`git.pr: ${h.reason}`),g={prError:h.reason};break;case`earlier`:g={prEarlier:h.value.state};break;case`absent`:case void 0:break}return{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{tracking:f},...p!==void 0&&{repoName:p},...m!==void 0&&{repoUrl:m},...g},failures:r}}function iW(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const aW={kind:`hidden`},oW={kind:`shown`};function sW(e,t){try{return iW(e,t)?oW:aW}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function cW(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function lW(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function uW({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function dW({text:e,placement:t,lead:n,trail:r}){return{text:fW(e),placement:t,...n!==void 0&&{lead:fW(n)},...r!==void 0&&{trail:fW(r)}}}function fW(e){let t=e.blankCopy(e.plain);t.style=Ev(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Ev(i).clearMetaAndLinks(),n,r);return t}function pW(e){let t=uW(e);if(t.length===1)return e.text;let n=cW(t);return n.style=e.text.style,n}function mW(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=cW(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:cW([d,...c],a)},...l.length>0&&{trail:cW([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(lW(u,n,p),[{text:u,...f}])}const hW=RegExp(`\\x1b\\[[0-9;]*m|${id.source}`,`g`);function gW(e){return Math.max(0,...e.split(`
197
- `).map(e=>L(e.replace(hW,``))))}function _W(e,t){let n=()=>e.map(e=>({owner:pW(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=Xv(e.map(pW),t).split(`
198
- `);if(i.length>1)return n();let a=Math.max(0,t.width-gW(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];lW(c,c.cellLength+a,n)}),n()}function vW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=yW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Ev(a.style)};if(e.style.link){i();let r=yW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function yW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>bW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function bW(e,t){let n=e.copy();return n.style=t,n}function xW(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function SW(e,t){let{look:n}=xW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function CW(e,t){let{layout:n}=xW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function wW(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function TW(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,EW(e,t,o,n,r,i));return i}function EW(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Gy(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=dv.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Gy(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Gy(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:kW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:kW(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:IL(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:kW(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function DW(e){return e.kind===`do`?DW(e.head):e}function OW(e){switch(DW(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function kW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function AW(e,t){return e.has(t)?Cb(e.read(t)):``}function jW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function MW(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function NW(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Ev(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Ev(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function PW(e,t){return Math.max(e.members.indexOf(AW(t,e.stateVar)),0)}function FW(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=AW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=AW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=AW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(PW(e,r)+1)%e.members.length];return{effects:[{verb:pr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:mr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:hr,args:[jW(e.text,_D(r))]}],active:!1};case`open`:return{effects:[{verb:gr,args:[jW(e.target,_D(r))]}],active:!1};case`persist-literal`:{let t=AW(r,e.stateVar);return{effects:[{verb:br,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=AW(r,e.stateVar);return{effects:[{verb:br,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(PW(e,r)+1)%e.members.length];return{effects:[{verb:br,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:xr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Er,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Or,args:[i]}],active:!1};case`redo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`back`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:jr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Sr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Tr,args:[i,jW(e.name,_D(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Nr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Pr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Fr,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Lr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:Rr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Dr,args:[i,e.key,yF(e.op)]}],active:!1};case`do`:{let a=FW(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>FW(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Dr,args:[i,e.key,yF(r)]}],active:!1}}}}function IW(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,PW(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function LW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=xW(n,`action "${e}"`).store,{display:a,boundValue:o}=IW(e,DW(r),t,i),s=AW(i,`session.id`),{effects:c,active:l}=FW(r,a.plain,o,i,s);return NW(a,Vr(c),l)}function RW(e){return{action:{fn:(t,...n)=>LW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function zW(e,t){return MW(`✕`,Vr([{verb:pr,args:[AW(e,`session.id`),t,qr]}]),!1)}function BW(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(eh(e,t,n))})}function VW({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function HW(e,t,n){return new H({color:B.fromRgba(Hc(Wm(e,`warning`),t,$m,n))})}function UW(e,t,n){return H.combine([BW(e,t,n),HW(e,t,n)])}function WW(e,t,n){return BW(e.palette,xh(e.palette,e.disclosure,[t],n),n)}function GW(e){let t=B.fromRgba(Wm(e,`background`)),n=G.fromFragments(_m.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Wm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const KW=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},qW=e=>new H({bold:e});function JW(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>KW(a,H.combine([WW(e,{...n,distribution:t},i),qW(o)]));let o=BW(e.palette,a,i);return(e,t,i,a)=>YW(i,H.combine([o,qW(a)]),r(t,n))}const YW=(e,t,n)=>KW(G.fromFragments([KW(e,t),KW(` `,t),GW(n)]));function XW(e,t){return t===void 0?(e,t,n)=>KW(n):(n,r,i)=>YW(i,void 0,t(r,e))}function ZW(e,t,n,r,i){let a=BW(e.palette,i,r);return(e,r,i,o)=>KW(G.fromFragments([KW(o?`[`:` `,a),GW(n(r,t)),KW(o?`]`:` `,a)]))}function QW(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>$W(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function $W(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function eG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function tG(e){return{current:null,drawnAt:e}}function nG(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function rG(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function iG(e){return new G(e).cellLength}function aG(e){let{width:t,chromeCols:n,padding:r}=xW(e,`a row fit`);return Math.max(1,t-n-2*r)}function oG(e){let{padding:t,seamCols:n}=xW(e,`a row fit`);return Math.max(1,aG(e)-(iG(`✕`)+2*t+n))}function sG(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function cG(e,t,n){let r=iG(`←`)+1+iG(`→`)+1,i=sG(e,t,n);return(i.length>1?sG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function lG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function uG(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function dG(e,t,n){let r=e.compiled.get(t),i=r&&DW(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function fG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=xW(a,`picker`).store,d=AW(u,`session.id`),f=`stateVar`in t?AW(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?oG(a):aG(a):1/0,h=(r.kind===`led`?0:iG(`✕`)+1)+c.reduce((e,t)=>e+iG(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?cG(_.map(e=>e.cellLength),m,h):QW(g.entries,g.groups,i),y=parseInt(AW(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>Vr([{verb:pr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:pr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Vr([...FW(l,e,e,u,d).effects,...C]),ie=(e,n)=>NW(e,re(t.options[n])),ae=r.kind===`led`?[]:[MW(`✕`,Vr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>MW(e,Vr([...FW(l,r,r,u,d).effects,{verb:pr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(MW(`←`,te(x-1),!1));let w=x<v.length-1?[MW(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[lG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[lG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(lG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>iG(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:_v(a),s=` `.repeat(n-iG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(lG([ie(p(r,eG(c,m)),r)],i))}}return se}function pG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{dD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=uG(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=dG(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=rG(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=fG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,JW(u,Mm(void 0),SW(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),HW(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function mG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function hG(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function gG(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=xW(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=AW(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return lG([],!0);let d=AW(o,t.stateVar),f=mG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Vr(FW(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=NW(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):NW(XW(SW(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Vr(FW(n.compiled.get(a),p(0),void 0,o,c).effects)),b=hG(e=>v(e).cellLength,u,iG(`◀`)+1+y.cellLength+1+iG(`▶`),oG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return lG([...ee(-1).reverse(),MW(`◀`,h(-1),!1),y,MW(`▶`,h(1),!1),...ee(1)],!0)}function _G(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(dD(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&OW(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=dG(e,n,`carousel`),l=rG(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return gG(n,c,e,JW(l,Mm(void 0),SW(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function vG(e,t,n){let r=dG(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function yG(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function bG(e,t,n,r){let i=vG(e,t,n),a=r??AW(xW(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,SW(e,`{{ ${n} }}`))}function xG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(dD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return GW(bG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=vG(e,r,`swatches`),o=uG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=rG(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=fG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,ZW(s,SW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),HW(s.palette,s.bg,c),u===0?[]:(()=>{let t=mG(l,AW(xW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[yG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const SG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function CG(e,t,n,r){let i=fh(e,n,r),a=(t,n)=>({text:t,colour:n,ink:eh(e,n,r)});return[[Dm(t).map((n,i)=>{let a=Gm(e,n);return{text:SG[i%SG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Wm(e,`warning`)),a(`error`,Wm(e,`error`))]]]}function wG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:VW({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function TG(e,t,n,r,i){let a=CG(e,t,n,r).map(e=>wG(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
199
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function EG(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(dD(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=SW(e,`{{ themePreview }}`);return TG(r===void 0?a:bG(e,r,`themePreview`),o,{...rG(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),oG(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const DG=e=>e.slice(e.lastIndexOf(`.`)+1),OG=(e,t)=>{let n=new G(DG(e));return n.truncate(t,{marker:`…`}),n.plain};function kG(e,t){let n=e.map(e=>e.map(({name:e})=>iG(DG(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function AG(e,t,n,r){let i=kG(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${OG(s,i)} `,{style:VW(Th(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
200
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function jG(e,t){return{layoutPreview:{fn:()=>AG(CW(e,`{{ layoutPreview }}`),SW(e,`{{ layoutPreview }}`).decor,t.drawnAt(),oG(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function MG(e,t,n,r){let i=rG(r.activeSegment,`{{ menu }}`),a=r.action,o=ik(i.placementId,e,n.key),s=sk(o),c=rk(e),l=xW(a,`menu`).store,u=AW(l,o)===c,d=AW(l,`session.id`),f=u?qr:c,p=MW(Xr(`{{ menu "${e}" }}`,t,2,+!!u),Vr([{verb:pr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=fh(i.palette,i.disclosure,t).plane,l=dG(a,e,`menu`);return fG(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,qr],[s,`0`]],onPick:n.closeOnPick},n.paged,a,JW(i,n.distribution,SW(a,`{{ menu }}`),l.paletteOf,t,c),HW(i.palette,c,t))})():[]),p}const NG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function PG(e,t){let n=t[t.length-1],r=NG(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:dk(r??{})}}function FG(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=PG(t,n);return MG(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function IG(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=LG(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function LG(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function RG(e){let t={fn:(()=>{let t=rG(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>rG(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=rG(e,`{{ keptOn }}`),i=Nc(r,t),a=Nc(r,n),o=ws(Wc(i,z.TRUECOLOR),Wc(a,z.TRUECOLOR)),s=Math.min($m,Math.max(o,3));return(Uc(i,e.drawnAt(),(e,t)=>ws(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=YE(()=>rG(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...zG(s)];return IG({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function zG(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function BG(e){let t=[],n=[];for(let r of e){if(!r.contains(`
195
+ `,s.join(e,`lib`),t.sessionId,t.cwd],env:TU(t),timeoutMs:3e3,category:`memento.read`});return n.ok?DU(n.stdout):I(EU(n))}function kU(e,t,n){let r=ut({bin:s.join(e,xU),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:TU(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(EU(r))}function AU(e,t){return wU(Ca(e),t)}function jU(){return{locate:e=>AU(e.claudeConfigDir,e.projectDir),read:OU,move:kU}}function MU(e){return{gitProvider:new dO({watchers:e.watchers,logger:e.logger}),usageStore:new XH({logger:e.logger}),contextProvider:new $H({logger:e.logger}),metricsProvider:new iU({logger:e.logger}),activityProvider:new uU({logger:e.logger}),tmuxService:new gU,mementoProvider:new vU(jU()),autoCompact:$M,log:e.logger}}const NU=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function PU(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function FU(e){let t=await IU(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function IU(e){for(let t of[65536,1048576]){let n=await _a(e,t);if(n.kind!==`ok`)return n;let r=LU(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function LU(e,t){let n=e.toString(`utf8`).split(`
196
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!NU.test(t))continue;let r=PU(t);if(r!=null)return r}return null}function RU(e,t,n){return Me({dir:e.project_dir,env:n===void 0?[]:[[ya,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function zU(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function BU(e){return{...Object.fromEntries(Z_.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:PB(e.preset)}}}const VU={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function HU(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const UU=10*1e3;function WU(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function GU(e,t){if(!(t<60))return e*3600/t}function KU(e,t,n,r){let i=r-t;if(i<50||i>UU)return;let a=n-e;if(!(a<=0))return a*1e3/i}function qU(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=KU(t.input,t.atMs,n.input,n.atMs),i=KU(t.output,t.atMs,n.output,n.atMs),a=KU(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function JU(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>UU)continue;let o=KU(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function YU(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function XU(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>YU(C.hostname())),i=n(`user`,()=>C.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function ZU(e,t){let n=[],r=t=>ob(t,e.helpers).keys(),i=zy(e,t);for(let e of Fh){let t=i[e];if(Ih(t))for(let e of r(t))n.push(e)}for(let i of gg(Ry(e,t).node)){if(i.when)for(let e of r(i.when))n.push(e);i.kind===`segment`&&n.push(...QU(e,i.name))}return eW(e,n)}function QU(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(t=>t?[...ob(t,e.helpers).keys()]:[]):[]}function $U(e,t,n){return eW(e,[...QU(e,t),...n.flatMap(t=>[...ob(t,e.helpers).keys()])])}function eW(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[...t],i=new Set,a=t=>ob(t,e.helpers).keys(),o=new Set;for(;r.length>0;){let e=r.pop();for(let t of nW(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function tW(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=ZU(e,n);return t.set(n,i),i}}function nW(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function rW(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function iW(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(VU).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function aW(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>rW(i,e),u=_O(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>I(`${e}: ${String(t)}`)):Promise.resolve(F),[p,m,h,g,_,v,y,b,ee,x,S]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(r??e.workspace?.current_dir,iW(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(F):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>FU(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(yU({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(Sa(xa(o.claudeConfigDir)))))]),te=[],ne=e=>{if(e.kind===`failed`){te.push(e.reason);return}return e.kind===`ok`?e.value:void 0},C=pW(p,u);te.push(...C.failures);let re=XU(o);te.push(...re.failures);let ie=ne(m),ae=ne(h),w=ne(g),T=ne(_),oe=ne(v),E=ne(y),se=ne(b),ce=cW(x);x.kind===`failed`&&te.push(`memento: ${x.reason}`);let le=oW(S,w?.maxTokens);S.kind===`failed`&&te.push(`autocompact: ${S.reason}`);for(let e of te)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?WU(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?WU(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?GU(me,he):void 0,_e=ne(ee),ve=_e===void 0?void 0:qU(_e),ye=_e===void 0?void 0:JU(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=fW(process.env.HOME??process.env.USERPROFILE),Se=e.workspace?{...e.workspace,current_dir:fW(e.workspace.current_dir)??``,project_dir:fW(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>fW(e)??e)}:e.workspace,Ce=ie===void 0?void 0:dW({cost:ie.session.cost,tokens:ie.session.tokens}),we=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},Te=T===void 0?void 0:dW({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ee=oe===void 0?void 0:lW(oe);return{...e,...Se!==void 0&&{workspace:Se},...xe!==void 0&&{home:xe},...C.git!==void 0&&{git:C.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...BU(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},feeds:n.feeds(e.session_id),...c,...s!==null&&{configPath:s},resumeCommand:RU(Se,e.session_id,o.claudeConfigDir),...Ce!==void 0&&{session:Ce},...we!==void 0&&{today:we},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...Te!==void 0&&{metrics:Te},...Ee!==void 0&&{activity:Ee},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function oW(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return eN(e.value,t)}}const sW=e=>e.trim().split(`
197
+ `).at(-1).trim();function cW(e){switch(e.kind){case`absent`:return;case`failed`:return{error:sW(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function lW(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=uW(e.running),i=uW(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function uW(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function dW(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function fW(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function pW(e,t){if(e.kind===`absent`)return{failures:[]};if(e.kind===`failed`)return{failures:[e.reason]};let n=e.value,r=[],i=(e,t)=>{if(!(t===void 0||t.kind===`absent`)){if(t.kind===`failed`){r.push(`git.${e}: ${t.reason}`);return}return t.value}},a=i(`aheadBehind`,n.aheadBehind),o=i(`sha`,n.sha),s=i(`operation`,n.operation),c=i(`timeSinceCommit`,n.committedAt),l=c===void 0?void 0:Math.floor((t-c)/1e3),u=i(`stash`,n.stashCount),d=i(`upstream`,n.upstream),f=n.upstream===void 0?void 0:i(`tracking`,wD(n.upstream,n.aheadBehind)),p=i(`repoName`,n.repoName),m=i(`repoUrl`,n.repoUrl),h=n.pullRequest===void 0?void 0:TD(n.pullRequest,n.head),g={};switch(h?.kind){case`ok`:g={prNumber:h.value.number,prState:h.value.state,prUrl:h.value.url};break;case`failed`:r.push(`git.pr: ${h.reason}`),g={prError:h.reason};break;case`earlier`:g={prEarlier:h.value.state};break;case`absent`:case void 0:break}return{git:{branch:n.branch,status:n.status,...a!==void 0&&{ahead:a.ahead,behind:a.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...o!==void 0&&{sha:o},...s!==void 0&&{operation:s},...l!==void 0&&{timeSinceCommit:l},...u!==void 0&&{stash:u},...d!==void 0&&{upstream:d},...f!==void 0&&{tracking:f},...p!==void 0&&{repoName:p},...m!==void 0&&{repoUrl:m},...g},failures:r}}function mW(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const hW={kind:`hidden`},gW={kind:`shown`};function _W(e,t){try{return mW(e,t)?gW:hW}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function vW(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function yW(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function bW({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function xW({text:e,placement:t,lead:n,trail:r}){return{text:SW(e),placement:t,...n!==void 0&&{lead:SW(n)},...r!==void 0&&{trail:SW(r)}}}function SW(e){let t=e.blankCopy(e.plain);t.style=Ev(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Ev(i).clearMetaAndLinks(),n,r);return t}function CW(e){let t=bW(e);if(t.length===1)return e.text;let n=vW(t);return n.style=e.text.style,n}function wW(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=vW(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:vW([d,...c],a)},...l.length>0&&{trail:vW([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(yW(u,n,p),[{text:u,...f}])}const TW=RegExp(`\\x1b\\[[0-9;]*m|${id.source}`,`g`);function EW(e){return Math.max(0,...e.split(`
198
+ `).map(e=>L(e.replace(TW,``))))}function DW(e,t){let n=()=>e.map(e=>({owner:CW(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=Xv(e.map(CW),t).split(`
199
+ `);if(i.length>1)return n();let a=Math.max(0,t.width-EW(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];yW(c,c.cellLength+a,n)}),n()}function OW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=kW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Ev(a.style)};if(e.style.link){i();let r=kW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function kW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>AW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function AW(e,t){let n=e.copy();return n.style=t,n}function jW(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function MW(e,t){let{look:n}=jW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function NW(e,t){let{layout:n}=jW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function PW(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function FW(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,IW(e,t,o,n,r,i));return i}function IW(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=Gy(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=dv.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=Gy(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=Gy(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:zW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:zW(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:IL(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:zW(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function LW(e){return e.kind===`do`?LW(e.head):e}function RW(e){switch(LW(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function zW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function BW(e,t){return e.has(t)?Cb(e.read(t)):``}function VW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function HW(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function UW(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Ev(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Ev(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function WW(e,t){return Math.max(e.members.indexOf(BW(t,e.stateVar)),0)}function GW(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=BW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=BW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=BW(r,e.stateVar);return{effects:[{verb:pr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(WW(e,r)+1)%e.members.length];return{effects:[{verb:pr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:mr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:hr,args:[VW(e.text,_D(r))]}],active:!1};case`open`:return{effects:[{verb:gr,args:[VW(e.target,_D(r))]}],active:!1};case`persist-literal`:{let t=BW(r,e.stateVar);return{effects:[{verb:br,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=BW(r,e.stateVar);return{effects:[{verb:br,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(WW(e,r)+1)%e.members.length];return{effects:[{verb:br,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:xr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Er,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:Or,args:[i]}],active:!1};case`redo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`back`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:jr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Sr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Tr,args:[i,VW(e.name,_D(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Nr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Pr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Fr,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Lr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:Rr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Dr,args:[i,e.key,yF(e.op)]}],active:!1};case`do`:{let a=GW(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>GW(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Dr,args:[i,e.key,yF(r)]}],active:!1}}}}function KW(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,WW(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function qW(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=jW(n,`action "${e}"`).store,{display:a,boundValue:o}=KW(e,LW(r),t,i),s=BW(i,`session.id`),{effects:c,active:l}=GW(r,a.plain,o,i,s);return UW(a,Vr(c),l)}function JW(e){return{action:{fn:(t,...n)=>qW(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function YW(e,t){return HW(`✕`,Vr([{verb:pr,args:[BW(e,`session.id`),t,qr]}]),!1)}function XW(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(eh(e,t,n))})}function ZW({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function QW(e,t,n){return new H({color:B.fromRgba(Hc(Wm(e,`warning`),t,$m,n))})}function $W(e,t,n){return H.combine([XW(e,t,n),QW(e,t,n)])}function eG(e,t,n){return XW(e.palette,xh(e.palette,e.disclosure,[t],n),n)}function tG(e){let t=B.fromRgba(Wm(e,`background`)),n=G.fromFragments(_m.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Wm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const nG=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},rG=e=>new H({bold:e});function iG(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>nG(a,H.combine([eG(e,{...n,distribution:t},i),rG(o)]));let o=XW(e.palette,a,i);return(e,t,i,a)=>aG(i,H.combine([o,rG(a)]),r(t,n))}const aG=(e,t,n)=>nG(G.fromFragments([nG(e,t),nG(` `,t),tG(n)]));function oG(e,t){return t===void 0?(e,t,n)=>nG(n):(n,r,i)=>aG(i,void 0,t(r,e))}function sG(e,t,n,r,i){let a=XW(e.palette,i,r);return(e,r,i,o)=>nG(G.fromFragments([nG(o?`[`:` `,a),tG(n(r,t)),nG(o?`]`:` `,a)]))}function cG(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>lG(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function lG(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function uG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function dG(e){return{current:null,drawnAt:e}}function fG(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function pG(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function mG(e){return new G(e).cellLength}function hG(e){let{width:t,chromeCols:n,padding:r}=jW(e,`a row fit`);return Math.max(1,t-n-2*r)}function gG(e){let{padding:t,seamCols:n}=jW(e,`a row fit`);return Math.max(1,hG(e)-(mG(`✕`)+2*t+n))}function _G(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function vG(e,t,n){let r=mG(`←`)+1+mG(`→`)+1,i=_G(e,t,n);return(i.length>1?_G(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function yG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function bG(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function xG(e,t,n){let r=e.compiled.get(t),i=r&&LW(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function SG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=jW(a,`picker`).store,d=BW(u,`session.id`),f=`stateVar`in t?BW(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?gG(a):hG(a):1/0,h=(r.kind===`led`?0:mG(`✕`)+1)+c.reduce((e,t)=>e+mG(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?vG(_.map(e=>e.cellLength),m,h):cG(g.entries,g.groups,i),y=parseInt(BW(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>Vr([{verb:pr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:pr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Vr([...GW(l,e,e,u,d).effects,...C]),ie=(e,n)=>UW(e,re(t.options[n])),ae=r.kind===`led`?[]:[HW(`✕`,Vr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>HW(e,Vr([...GW(l,r,r,u,d).effects,{verb:pr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(HW(`←`,te(x-1),!1));let w=x<v.length-1?[HW(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[yG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[yG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(yG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>mG(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:_v(a),s=` `.repeat(n-mG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(yG([ie(p(r,uG(c,m)),r)],i))}}return se}function CG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{dD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=bG(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=xG(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=pG(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=SG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,iG(u,Mm(void 0),MW(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),QW(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function wG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function TG(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function EG(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=jW(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=BW(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return yG([],!0);let d=BW(o,t.stateVar),f=wG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Vr(GW(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=UW(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):UW(oG(MW(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Vr(GW(n.compiled.get(a),p(0),void 0,o,c).effects)),b=TG(e=>v(e).cellLength,u,mG(`◀`)+1+y.cellLength+1+mG(`▶`),gG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return yG([...ee(-1).reverse(),HW(`◀`,h(-1),!1),y,HW(`▶`,h(1),!1),...ee(1)],!0)}function DG(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(dD(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&RW(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=xG(e,n,`carousel`),l=pG(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return EG(n,c,e,iG(l,Mm(void 0),MW(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function OG(e,t,n){let r=xG(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function kG(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function AG(e,t,n,r){let i=OG(e,t,n),a=r??BW(jW(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,MW(e,`{{ ${n} }}`))}function jG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(dD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return tG(AG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=OG(e,r,`swatches`),o=bG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=pG(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=SG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,sG(s,MW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),QW(s.palette,s.bg,c),u===0?[]:(()=>{let t=wG(l,BW(jW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[kG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const MG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function NG(e,t,n,r){let i=fh(e,n,r),a=(t,n)=>({text:t,colour:n,ink:eh(e,n,r)});return[[Dm(t).map((n,i)=>{let a=Gm(e,n);return{text:MG[i%MG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Wm(e,`warning`)),a(`error`,Wm(e,`error`))]]]}function PG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:ZW({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function FG(e,t,n,r,i){let a=NG(e,t,n,r).map(e=>PG(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
200
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function IG(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(dD(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=MW(e,`{{ themePreview }}`);return FG(r===void 0?a:AG(e,r,`themePreview`),o,{...pG(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),gG(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const LG=e=>e.slice(e.lastIndexOf(`.`)+1),RG=(e,t)=>{let n=new G(LG(e));return n.truncate(t,{marker:`…`}),n.plain};function zG(e,t){let n=e.map(e=>e.map(({name:e})=>mG(LG(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function BG(e,t,n,r){let i=zG(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${RG(s,i)} `,{style:ZW(Th(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
201
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function VG(e,t){return{layoutPreview:{fn:()=>BG(NW(e,`{{ layoutPreview }}`),MW(e,`{{ layoutPreview }}`).decor,t.drawnAt(),gG(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function HG(e,t,n,r){let i=pG(r.activeSegment,`{{ menu }}`),a=r.action,o=ik(i.placementId,e,n.key),s=sk(o),c=rk(e),l=jW(a,`menu`).store,u=BW(l,o)===c,d=BW(l,`session.id`),f=u?qr:c,p=HW(Xr(`{{ menu "${e}" }}`,t,2,+!!u),Vr([{verb:pr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=fh(i.palette,i.disclosure,t).plane,l=xG(a,e,`menu`);return SG(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,qr],[s,`0`]],onPick:n.closeOnPick},n.paged,a,iG(i,n.distribution,MW(a,`{{ menu }}`),l.paletteOf,t,c),QW(i.palette,c,t))})():[]),p}const UG=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function WG(e,t){let n=t[t.length-1],r=UG(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:dk(r??{})}}function GG(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=WG(t,n);return HG(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function KG(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=qG(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function qG(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function JG(e){let t={fn:(()=>{let t=pG(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>pG(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=pG(e,`{{ keptOn }}`),i=Nc(r,t),a=Nc(r,n),o=ws(Wc(i,z.TRUECOLOR),Wc(a,z.TRUECOLOR)),s=Math.min($m,Math.max(o,3));return(Uc(i,e.drawnAt(),(e,t)=>ws(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=YE(()=>pG(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...YG(s)];return KG({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function YG(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function XG(e){let t=[],n=[];for(let r of e){if(!r.contains(`
201
202
  `)){n.push(r);continue}let e=r.split(`
202
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function VG(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 HG(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 UG(e){return{...e,cells:e.cells.map(dW)}}function WG(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,...GG(e,r)]}function GG(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 KG(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:WG(e.direction,e.children.map((t,i)=>n(t,[...r,qG(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function qG(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:dg[e.direction]}}const JG={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Mm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,_g(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),WG(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,qG(e,r))))}},YG={drop:e=>e.place,above:()=>`above`},XG={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},ZG={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:fg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,vg(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,QG(e,t))};function QG(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=yD(t.scope,e.settings);if(t.gate.kind===`failed`)return $G(e,a,t,t.gate.message);try{if(!iW(i.when,a))return[];let n=my(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:SA(n)},s=e.opens!==void 0&&iW(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:YG[g.placement](e)})),v=BG(vW(l,m)).map((e,t)=>({cells:mW(e,{...h,lead:t===0?vW(u,m):[],trail:t===0?vW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:mW(vW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>mW(vW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?XG[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(uW(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(uW)),[...re,...C]}catch(n){return $G(e,a,t,n.message??String(n))}}function $G(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:mW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:SA(n.palette)},lead:eK(e.lead,e,t,n),trail:eK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function eK(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 tK={container:JG,segment:ZG};function nK(e){return tK[e]}function rK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yO(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 iK(e,t){switch(xg(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 aK(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:rK(n.cache),parse:iK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:rK(n.cache),parse:iK(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 oK(e,t){let n=nx.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 sK(e,t,n){let{compiled:r,loadWarnings:i}=lK(e,t,n.cwd,cK);return{...r,loadWarnings:i}}const cK=(e,t)=>pK(t);function lK(e,t,n,r){let i=uK(e),a=dK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:fK(e,t,n)}}function uK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of fv)n in t&&r.set(e,n);for(let[t,n]of Dg(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function dK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function fK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{aK(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{aK(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function pK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>xW(n,`now`).registry.now(),i=()=>xW(n,`drawnAt`).registry.drawnAt(),a=tG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Fy(e.presets),l=eF(e),u=gD({extraFuncs:{...RW(n),...pG(n,a),..._G(n,a),...EG(n,a),...xG(n,a,r),...jG(n,a),...FG(o),...RG(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=oK(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=TW(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=jg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Lg(t,e,a,t=>String(xW(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 nK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=Ry(e,t);b.set(t,y(n,r))}let ee=new Map(Fh.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 Fh){let r=t[n];if(!Ih(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:mK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function mK(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 hK(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 gK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Gh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Wh[e]}}function _K(e,t){return e.kind===`decided`?e.name:Wh[t]}function vK(e){return yK(e).filter(e=>!e.name.startsWith(QO)).map(e=>e.id)}function yK(e){return e.kind===`container`?e.children.flatMap(yK):[e,...e.opens===void 0?[]:yK(e.opens.body)]}function bK(...e){return xK(...e).text}function xK(e,t,n,r,i,a,o,s,c=BB(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(tg(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Wv(o),padding:o.padding,seamCols:Gv(o),look:void 0,layout:void 0};l.u(wW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Em[c.variation],shade:wm[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(_K(_,`palette`),_K(v,`style`),_K(y,`effect`)));let S=_D(n),te=Rh(_,e=>{let n=hK(t,`palette`,e);return yy(gK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=Rh(v,n=>Vh(gK(`style`,hK(t,`style`,n),S,p),e.styles)),C=Rh(y,e=>Yh(gK(`effect`,hK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=gy(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Iv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:HG,hold:UG});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}=Th(i,a,c),f=nG(t.activeSegment,e.name,e.id,i,d,l,u),p=wA(f,c,o.bg,o.fg,n),h=()=>fh(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 BW(i,h().state,c)},get band(){return BW(i,h().plane,c)},get close(){return UW(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?sW(e.when,S):aW,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${vK(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,Ch(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,wh(n)),closeDisclosure:e=>zW(n,e),placed:ae.placed};return nK(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 "${Ny}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=sW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(dF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return iW(t.segments[e.name].when,yD(S,e.settings))}catch{return!0}};h.layout=()=>KG(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=dF(e);return r===void 0?[]:[{name:r,address:t,palette:my(n.theme,ie)}]}));let ce=VG(oe(E,!0,Sh(ee))).map(({line:e,row:t})=>{let n=_W(e.cells,o);return Yv(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||yK(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(`
203
- `),motion:le}}catch(e){l.e=e}finally{l.d()}}function*SK(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*CK(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 Fy(e.presets)){for(let n of gg(Ry(e,t).node))n.when!==void 0&&(yield n.when);let n=zy(e,t);for(let e of Fh){let t=n[e];Ih(t)&&(yield t)}}for(let[,t]of SK(e))t.kind===`template`&&(yield t.template),Cg(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 wK(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function TK(e,t){let n=new Set,r=new Set,i=new Set;for(let e of CK(t)){for(let r of ob(e,t.helpers).keys())n.add(r);for(let{name:n}of ub(e,t.helpers))r.add(n);for(let n of db(e,t.helpers))i.add(n)}for(let[,e]of SK(t))if(Cg(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 Fy(t.presets))for(let n of gg(Ry(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>wK(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!ek(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(SK(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 EK=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,MK(e,t,n,`initial value`),this.cell=bb.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){MK(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}},DK=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,bb.computed)(()=>{let e=n();return MK(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}},OK=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=bb.observable.box(jK(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=jK(e);AK(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function kK(e){return JSON.stringify(e)}function AK(e,t){return kK(e)===kK(t)}function jK(e){return e.kind===`ok`?{kind:`ok`,value:xb(e.value)}:e}function MK(e,t,n,r){let i=Sb(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var NK=class{nodes=bb.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new EK(e,t,n))}defineDocument(e,t){this.declare(e,new OK(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new DK(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,bb.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,bb.runInAction)(()=>n.set(t))}runInAction(e){(0,bb.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 kK(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,bb.runInAction)(()=>{for(let t of this.nodes.values())t instanceof DK&&(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,bb.runInAction)(()=>this.nodes.set(e,t))}};function PK(e){return Math.floor(e/4)}function FK(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=_z(e),r=t===void 0?void 0:n.variables[yz(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 IK(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function LK(e,t,n){return e+`\0`+t+`\0`+(n??``)}function RK(e,t){return new Set(Fy(e.presets).filter(n=>Ry(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[...Jz(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=gb(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}=gb(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 BK(e){return e.filter(Boolean).join(`
204
- `)||null}function VK(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=lB(t.layers,MB,{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??MB,l=a.find(e=>e.path===t.home)?.raw??{},u=new NK,d=new BO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=lK(o,d,e,r.compile??cK),n.push(...f.loadWarnings),SV(o),PF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:GU(o),lastRenderCellsBySegment:new Map,authoredRoots:RK(c,l),fileHeldSettings:cV(l),unused:[...new Map(a.flatMap(e=>TK(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 HK(e,t,n,r){let i=Xz(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[tB(e,t),$z(i)],s,c=null;try{s=VK(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Vg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:BK(o),state:null,error:e instanceof Vg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:BK(o),state:s,error:null}}function UK(e,t,n){return VK(e,{layers:[],home:``,projectDir:t},[],n)}var WK=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)??pK(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=LK(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=HK(e,t,n,this.deps);a.state!==null&&this.log(`info`,FK(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??UK(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`,IK(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=HK(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,FK(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 GK=16384;var KK=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<GK){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%GK}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},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,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 qK(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 JK={load:()=>({}),save:()=>{},flush:()=>{}};var YK=class{sessions;storage;head=0;atom=(0,bb.createAtom)(`SessionState`);constructor(e=JK,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,bb.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,bb.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,bb.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 XK(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 ZK=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 XK(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 QK=new Set([`1`,`true`]),$K=new Set([`0`,`false`,``]);function eq(e,t){let n=Tq(e),r=n.scope===`segment-palette`?`string`:rv(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(QK.has(t))return`true`;if($K.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function tq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function nq(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 rq(e){return/^\s*$/.test(e)?null:_i(e)}function iq(e,t){return e!==null&&yi(e,t)!==void 0}function aq(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(aq),...i}}return e}function oq(e){if(!Ty(e))return aq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,aq(t)])),...n}}const sq=AB,cq=sq.segments,lq=sq.presets,uq=sq.root;function dq(e,t,n,r){if(!iq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function fq(e,t){let n=$k(t);return t.scope===`segment-palette`&&dq(e,[`segments`,t.segment],cq[t.segment],n.join(`.`)),n}function pq(e){return _i(Di(e))}function mq(){return Object.entries(uq.rows).map(([e,t])=>{let n=aq(t);return{path:[`root`],fragment:pq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function hq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function gq(e,t){if(t===void 0)return null;let n=oq(t);return{path:e,fragment:pq(n),unit:{path:e,value:n}}}function _q(e,t){let n=[`presets`,t],r=[...n,`root`],i=lq[t];dq(e,n,i,r.join(`.`));let a=hq(e,r)??gq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function vq(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 yq(e,t){return[...mq(),hq(e,[`root`]),_q(e,t)].filter(e=>e!==null).reduce(vq,new Map)}function bq(e,t,n){for(let{node:r,...i}of yq(e,t).values())if(Xi(r,n))return i;throw new J(`${xq(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 xq(e,t){return _q(e,t)?.path??[`root`]}function Sq(e,t){return t.scope===`preset-root`?xq(e,t.preset):$k(t)}function Cq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function wq(e){let t=Qk(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Tq(e){let t=wq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Eq(e,t,n,r,i){i(t,n,Lq(t,r)),nq(t.path,r,e.logger),e.record(t.path,n,r)}function Dq(e,t,n){let r=Aq(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 Oq=()=>{};function kq(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 Aq(e,t,n){let r=jq(e,t);if(r===null)return[];let i=new Set(Fq(Pq(r),Pq(n)));return Fq(Nq(e,r),Nq(e,n)).filter(e=>!i.has(e))}function jq(e,t){try{return Mq(e,t)}catch(e){if(e instanceof Vg)return null;throw e}}function Mq(e,t){return lB(t===null?e.above:[e.path,...e.above],MB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Nq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Pq(e){return e.layers.at(-1)?.config??e.base}function Fq(e,t,n=``){return!Iq(e)||!Iq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Fq(e[r],t[r],n===``?r:`${n}.${r}`))}function Iq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Lq(e,t){try{return Mq(e,t)}catch(e){throw e instanceof Vg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function Rq(e,t){let n=Tq(t),r=rq(tq(e)??``),i=r===null?void 0:yi(r,$k(n));return i!==void 0&&`value`in i?i.value:void 0}function zq(e,t,n){Bq(e,t,n,[])}function Bq(e,t,n,r){let i=tq(t.path),a=n.reduce((e,[t,n])=>Vi(e,fq(rq(e),Tq(t)),eq(t,n),Ti),i??``);Eq(e,t,i,kq(t,()=>Vq(a,t.path,r,e=>e)),Dq)}function Vq(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=bq(rq(s),n,i),l=ea(Cq(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 Hq(e,t,n){let r=rq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of yq(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(_q(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 Uq(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!PB(t[1])?2:0)}function Wq(e,t,n){let r=n.map(wq),i=tq(t.path);if(i===null)return;let a=r.reduce((e,t)=>Uq(e,Sq(rq(e),t)),i);a!==i&&Eq(e,t,i,a,Oq)}function Gq(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function Kq(e,t){let n=new Set([...NB,...Gq(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(YO));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(YO(e)))}function qq(e,t,n,r,i,a){let o=tq(t.path),s=rq(o??``),c=Kq(s,t),l=[`presets`,c],u=kq(t,()=>_q(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=Zk(c,e);return[fq(s,Tq(n)),eq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Eq(e,t,o,kq(t,()=>Vq(p,t.path,a.map(e=>({...e,preset:c})),Hq)),Dq),c}function Jq(e,t,n,r){let i=tq(t.path);Eq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),Dq)}function Yq(e,t,n){if(PB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=tq(t.path),a=rq(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`]);Eq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>Uq(e,t),i),Oq)}function Xq(e,t,n,r){let i=wq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=tq(t.path),o=r.op===`remove`?r.target:r.anchor,s=kq(t,()=>bq(rq(a??``),i.preset,o)),c=Cq(a??``,s),{after:l,placed:u}=Zq(c,s.path,r,()=>{let e=Lq(t,c).config;return Fy(e.presets).map(t=>Ry(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 Eq(e,t,a,l,Dq),u}function Zq(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=xF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const Qq={load:()=>({}),save:()=>{}},$q=new Set(cv.map(e=>e.sessionKey)),eJ=e=>$q.has(e)||e.startsWith(uA),tJ=8*1024*1024,nJ={past:[],future:[]},rJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var iJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=Qq){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)??nJ;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)??nJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(rJ(n));r.set(rJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:qK(this.sessionState,e=>eJ(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:fJ(i,n),o=r.get(e),s=o===void 0?a:gJ(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`,mJ(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(rJ)),a=n.net.filter(e=>!i.has(rJ(e))),o=sJ(_J(hJ(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(yJ).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=sJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...lJ(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(rJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:_J(n,t),future:_J(i,t),...a!==void 0&&{savepoint:{at:_J([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(rJ(e))),below:_J(a.below,t)}}}),new J(`${r}: ${o.map(yJ).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):tq(t.file)}write(e,t,n){t.kind===`file`?nq(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||aJ(n)>tJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,oJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${tJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function aJ(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 oJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...lJ(n,1,[])}:{past:e,future:t.slice(1),...lJ(n,0,[])}}function sJ(e){return e.slice(-50)}const cJ=e=>e===fA.member;function lJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:uJ(e.net,n),below:e.below}}}function uJ(e,t){let n=new Map(e.map(e=>[rJ(e),e]));for(let e of t){let t=n.get(rJ(e));n.set(rJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const dJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function fJ(e,t){let n=[...e.past,t],r=sJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...lJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...pJ(e.future,a),...i.below]},n.length-r.length,t)}}function pJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function mJ(e,t){return{past:e.past.slice(0,-1),future:sJ([...e.future,t]),...lJ(e.savepoint,0,dJ(t))}}function hJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...pJ(r,t.at-i.length),...t.below]}function gJ(e,t){if(cJ(t.after)&&!cJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!cJ(t.after)&&cJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function _J(e,t){return e.map(e=>e.filter(e=>!t.has(rJ(e)))).filter(e=>e.length>0)}function vJ(e){return e.map(yJ).join(`, `)}function yJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function bJ(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 xJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(bJ))}function SJ(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(bJ)&&xJ(t.below)}function CJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return xJ(t.past)&&xJ(t.future)&&(t.savepoint===void 0||SJ(t.savepoint))}function wJ(e,t){let n=e=>e.kind===`file`||eJ(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 TJ(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(CJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,wJ(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 EJ=e=>!eJ(e)&&!HM(e)&&e!==`update.dismissed`;var DJ=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:qK(e,EJ,(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,bb.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 OJ=`click.error`;function kJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,OJ,JSON.stringify(i))}function AJ(e,t,n){let r=jJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,OJ,JSON.stringify({...r,answered:!0}))}function jJ(e,t){let n=e.get(t,OJ);return n===null?null:NJ(n)}function MJ(e,t,n,r){let i=jJ(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 NJ(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 PJ(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 FJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function IJ(e){let t=e=>({kind:`failed`,reason:e});if(!FJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!FJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!kj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${kj.join(` or `)}`)}return{kind:`ok`,value:e}}function LJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const RJ=e=>PJ(e,`doctor-marks.json`,{},IJ),zJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},BJ=(e,t)=>e.includes(t)?e:[...e,t],VJ=e=>PJ(e,`doctor-clicked-terminals.json`,[],zJ);var HJ=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const UJ=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},WJ=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),GJ=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=WJ(e,t);return r===void 0?n:r.projectDir},KJ=(e,t)=>WJ(e,t).map(({role:t,frame:n,since:r,redrawn:i,projectDir:a,claudeConfigDir:o})=>({role:t,frame:n,projectDir:a,claudeConfigDir:o,redraws:qA(i,r,e.kind===`recent`?Math.min(...i):0)}));function qJ(e){let t=new Map;for(let n of e.split(`
205
- `)){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*JJ(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 YJ={pullRequests:e=>JU(e).showPullRequest===!0,rateLimits:e=>qU(e,`block`)||qU(e,`weekly`),memento:e=>qU(e,`memento`)};function XJ(e,t){let n=new Map;for(let r of gg(Ry(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=>Eg(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,UU(e,t,n.get(t))])),a=e=>r.filter(t=>YJ[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`),memento:a(`memento`)}}
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 ZG(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 QG(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 $G(e){return{...e,cells:e.cells.map(xW)}}function eK(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,...tK(e,r)]}function tK(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 nK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:eK(e.direction,e.children.map((t,i)=>n(t,[...r,rK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function rK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:dg[e.direction]}}const iK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Mm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,_g(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),eK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,rK(e,r))))}},aK={drop:e=>e.place,above:()=>`above`},oK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},sK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:fg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,vg(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,cK(e,t))};function cK(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=yD(t.scope,e.settings);if(t.gate.kind===`failed`)return lK(e,a,t,t.gate.message);try{if(!mW(i.when,a))return[];let n=my(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:SA(n)},s=e.opens!==void 0&&mW(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:aK[g.placement](e)})),v=XG(OW(l,m)).map((e,t)=>({cells:wW(e,{...h,lead:t===0?OW(u,m):[],trail:t===0?OW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:wW(OW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>wW(OW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?oK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(bW(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(bW)),[...re,...C]}catch(n){return lK(e,a,t,n.message??String(n))}}function lK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:wW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:SA(n.palette)},lead:uK(e.lead,e,t,n),trail:uK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function uK(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 dK={container:iK,segment:sK};function fK(e){return dK[e]}function pK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:yO(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 mK(e,t){switch(xg(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 hK(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:pK(n.cache),parse:mK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:pK(n.cache),parse:mK(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 gK(e,t){let n=nx.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 _K(e,t,n){let{compiled:r,loadWarnings:i}=yK(e,t,n.cwd,vK);return{...r,loadWarnings:i}}const vK=(e,t)=>CK(t);function yK(e,t,n,r){let i=bK(e),a=xK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:SK(e,t,n)}}function bK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of fv)n in t&&r.set(e,n);for(let[t,n]of Dg(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function xK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function SK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{hK(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{hK(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function CK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>jW(n,`now`).registry.now(),i=()=>jW(n,`drawnAt`).registry.drawnAt(),a=dG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Fy(e.presets),l=eF(e),u=gD({extraFuncs:{...JW(n),...CG(n,a),...DG(n,a),...IG(n,a),...jG(n,a,r),...VG(n,a),...GG(o),...JG(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=gK(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=FW(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=jg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Lg(t,e,a,t=>String(jW(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 fK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=Ry(e,t);b.set(t,y(n,r))}let ee=new Map(Fh.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 Fh){let r=t[n];if(!Ih(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:wK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function wK(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 TK(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 EK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Gh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Wh[e]}}function DK(e,t){return e.kind===`decided`?e.name:Wh[t]}function OK(e){return kK(e).filter(e=>!e.name.startsWith(QO)).map(e=>e.id)}function kK(e){return e.kind===`container`?e.children.flatMap(kK):[e,...e.opens===void 0?[]:kK(e.opens.body)]}function AK(...e){return jK(...e).text}function jK(e,t,n,r,i,a,o,s,c=BB(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(tg(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Wv(o),padding:o.padding,seamCols:Gv(o),look:void 0,layout:void 0};l.u(PW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Em[c.variation],shade:wm[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(DK(_,`palette`),DK(v,`style`),DK(y,`effect`)));let S=_D(n),te=Rh(_,e=>{let n=TK(t,`palette`,e);return yy(EK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=Rh(v,n=>Vh(EK(`style`,TK(t,`style`,n),S,p),e.styles)),C=Rh(y,e=>Yh(EK(`effect`,TK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=gy(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Iv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:QG,hold:$G});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}=Th(i,a,c),f=fG(t.activeSegment,e.name,e.id,i,d,l,u),p=wA(f,c,o.bg,o.fg,n),h=()=>fh(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 XW(i,h().state,c)},get band(){return XW(i,h().plane,c)},get close(){return $W(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?_W(e.when,S):hW,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${OK(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,Ch(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,wh(n)),closeDisclosure:e=>YW(n,e),placed:ae.placed};return fK(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 "${Ny}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=_W(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(dF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return mW(t.segments[e.name].when,yD(S,e.settings))}catch{return!0}};h.layout=()=>nK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=dF(e);return r===void 0?[]:[{name:r,address:t,palette:my(n.theme,ie)}]}));let ce=ZG(oe(E,!0,Sh(ee))).map(({line:e,row:t})=>{let n=DW(e.cells,o);return Yv(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||kK(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
+ `),motion:le}}catch(e){l.e=e}finally{l.d()}}function*MK(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*NK(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 Fy(e.presets)){for(let n of gg(Ry(e,t).node))n.when!==void 0&&(yield n.when);let n=zy(e,t);for(let e of Fh){let t=n[e];Ih(t)&&(yield t)}}for(let[,t]of MK(e))t.kind===`template`&&(yield t.template),Cg(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 PK(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function FK(e,t){let n=new Set,r=new Set,i=new Set;for(let e of NK(t)){for(let r of ob(e,t.helpers).keys())n.add(r);for(let{name:n}of ub(e,t.helpers))r.add(n);for(let n of db(e,t.helpers))i.add(n)}for(let[,e]of MK(t))if(Cg(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 Fy(t.presets))for(let n of gg(Ry(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>PK(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!ek(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map(MK(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 IK=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,HK(e,t,n,`initial value`),this.cell=bb.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){HK(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}},LK=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,bb.computed)(()=>{let e=n();return HK(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}},RK=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=bb.observable.box(VK(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=VK(e);BK(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function zK(e){return JSON.stringify(e)}function BK(e,t){return zK(e)===zK(t)}function VK(e){return e.kind===`ok`?{kind:`ok`,value:xb(e.value)}:e}function HK(e,t,n,r){let i=Sb(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var UK=class{nodes=bb.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new IK(e,t,n))}defineDocument(e,t){this.declare(e,new RK(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new LK(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,bb.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,bb.runInAction)(()=>n.set(t))}runInAction(e){(0,bb.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 zK(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,bb.runInAction)(()=>{for(let t of this.nodes.values())t instanceof LK&&(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,bb.runInAction)(()=>this.nodes.set(e,t))}};function WK(e){return Math.floor(e/4)}function GK(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=_z(e),r=t===void 0?void 0:n.variables[yz(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 KK(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function qK(e,t,n){return e+`\0`+t+`\0`+(n??``)}function JK(e,t){return new Set(Fy(e.presets).filter(n=>Ry(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function YK(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...Jz(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=gb(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}=gb(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 XK(e){return e.filter(Boolean).join(`
205
+ `)||null}function ZK(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=lB(t.layers,MB,{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??MB,l=a.find(e=>e.path===t.home)?.raw??{},u=new UK,d=new BO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=yK(o,d,e,r.compile??vK),n.push(...f.loadWarnings),SV(o),PF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:tW(o),lastRenderCellsBySegment:new Map,authoredRoots:JK(c,l),fileHeldSettings:cV(l),unused:[...new Map(a.flatMap(e=>FK(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 QK(e,t,n,r){let i=Xz(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[tB(e,t),$z(i)],s,c=null;try{s=ZK(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Vg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:XK(o),state:null,error:e instanceof Vg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:XK(o),state:s,error:null}}function $K(e,t,n){return ZK(e,{layers:[],home:``,projectDir:t},[],n)}var eq=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)??CK(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=qK(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=QK(e,t,n,this.deps);a.state!==null&&this.log(`info`,GK(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??$K(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`,KK(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=QK(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,GK(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=YK(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 tq=16384;var nq=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<tq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%tq}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 rq(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 iq={load:()=>({}),save:()=>{},flush:()=>{}};var aq=class{sessions;storage;head=0;atom=(0,bb.createAtom)(`SessionState`);constructor(e=iq,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,bb.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,bb.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,bb.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 oq(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 sq=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 oq(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 cq=new Set([`1`,`true`]),lq=new Set([`0`,`false`,``]);function uq(e,t){let n=Fq(e),r=n.scope===`segment-palette`?`string`:rv(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(cq.has(t))return`true`;if(lq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function dq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function fq(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 pq(e){return/^\s*$/.test(e)?null:_i(e)}function mq(e,t){return e!==null&&yi(e,t)!==void 0}function hq(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(hq),...i}}return e}function gq(e){if(!Ty(e))return hq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,hq(t)])),...n}}const _q=AB,vq=_q.segments,yq=_q.presets,bq=_q.root;function xq(e,t,n,r){if(!mq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function Sq(e,t){let n=$k(t);return t.scope===`segment-palette`&&xq(e,[`segments`,t.segment],vq[t.segment],n.join(`.`)),n}function Cq(e){return _i(Di(e))}function wq(){return Object.entries(bq.rows).map(([e,t])=>{let n=hq(t);return{path:[`root`],fragment:Cq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Tq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Eq(e,t){if(t===void 0)return null;let n=gq(t);return{path:e,fragment:Cq(n),unit:{path:e,value:n}}}function Dq(e,t){let n=[`presets`,t],r=[...n,`root`],i=yq[t];xq(e,n,i,r.join(`.`));let a=Tq(e,r)??Eq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Oq(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 kq(e,t){return[...wq(),Tq(e,[`root`]),Dq(e,t)].filter(e=>e!==null).reduce(Oq,new Map)}function Aq(e,t,n){for(let{node:r,...i}of kq(e,t).values())if(Xi(r,n))return i;throw new J(`${jq(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 jq(e,t){return Dq(e,t)?.path??[`root`]}function Mq(e,t){return t.scope===`preset-root`?jq(e,t.preset):$k(t)}function Nq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Pq(e){let t=Qk(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Fq(e){let t=Pq(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function Iq(e,t,n,r,i){i(t,n,qq(t,r)),fq(t.path,r,e.logger),e.record(t.path,n,r)}function Lq(e,t,n){let r=Bq(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 Rq=()=>{};function zq(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 Bq(e,t,n){let r=Vq(e,t);if(r===null)return[];let i=new Set(Gq(Wq(r),Wq(n)));return Gq(Uq(e,r),Uq(e,n)).filter(e=>!i.has(e))}function Vq(e,t){try{return Hq(e,t)}catch(e){if(e instanceof Vg)return null;throw e}}function Hq(e,t){return lB(t===null?e.above:[e.path,...e.above],MB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Uq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function Wq(e){return e.layers.at(-1)?.config??e.base}function Gq(e,t,n=``){return!Kq(e)||!Kq(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>Gq(e[r],t[r],n===``?r:`${n}.${r}`))}function Kq(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qq(e,t){try{return Hq(e,t)}catch(e){throw e instanceof Vg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function Jq(e,t){let n=Fq(t),r=pq(dq(e)??``),i=r===null?void 0:yi(r,$k(n));return i!==void 0&&`value`in i?i.value:void 0}function Yq(e,t,n){Xq(e,t,n,[])}function Xq(e,t,n,r){let i=dq(t.path),a=n.reduce((e,[t,n])=>Vi(e,Sq(pq(e),Fq(t)),uq(t,n),Ti),i??``);Iq(e,t,i,zq(t,()=>Zq(a,t.path,r,e=>e)),Lq)}function Zq(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Aq(pq(s),n,i),l=ea(Nq(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 Qq(e,t,n){let r=pq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of kq(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(Dq(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 $q(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!PB(t[1])?2:0)}function eJ(e,t,n){let r=n.map(Pq),i=dq(t.path);if(i===null)return;let a=r.reduce((e,t)=>$q(e,Mq(pq(e),t)),i);a!==i&&Iq(e,t,i,a,Rq)}function tJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function nJ(e,t){let n=new Set([...NB,...tJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(YO));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(YO(e)))}function rJ(e,t,n,r,i,a){let o=dq(t.path),s=pq(o??``),c=nJ(s,t),l=[`presets`,c],u=zq(t,()=>Dq(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=Zk(c,e);return[Sq(s,Fq(n)),uq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Iq(e,t,o,zq(t,()=>Zq(p,t.path,a.map(e=>({...e,preset:c})),Qq)),Lq),c}function iJ(e,t,n,r){let i=dq(t.path);Iq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),Lq)}function aJ(e,t,n){if(PB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=dq(t.path),a=pq(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`]);Iq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>$q(e,t),i),Rq)}function oJ(e,t,n,r){let i=Pq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=dq(t.path),o=r.op===`remove`?r.target:r.anchor,s=zq(t,()=>Aq(pq(a??``),i.preset,o)),c=Nq(a??``,s),{after:l,placed:u}=sJ(c,s.path,r,()=>{let e=qq(t,c).config;return Fy(e.presets).map(t=>Ry(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 Iq(e,t,a,l,Lq),u}function sJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=xF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const cJ={load:()=>({}),save:()=>{}},lJ=new Set(cv.map(e=>e.sessionKey)),uJ=e=>lJ.has(e)||e.startsWith(uA),dJ=8*1024*1024,fJ={past:[],future:[]},pJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var mJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=cJ){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)??fJ;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)??fJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(pJ(n));r.set(pJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:rq(this.sessionState,e=>uJ(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:SJ(i,n),o=r.get(e),s=o===void 0?a:EJ(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`,wJ(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(pJ)),a=n.net.filter(e=>!i.has(pJ(e))),o=_J(DJ(TJ(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(kJ).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=_J(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...yJ(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(pJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:DJ(n,t),future:DJ(i,t),...a!==void 0&&{savepoint:{at:DJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(pJ(e))),below:DJ(a.below,t)}}}),new J(`${r}: ${o.map(kJ).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):dq(t.file)}write(e,t,n){t.kind===`file`?fq(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||hJ(n)>dJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,gJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${dJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function hJ(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 gJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...yJ(n,1,[])}:{past:e,future:t.slice(1),...yJ(n,0,[])}}function _J(e){return e.slice(-50)}const vJ=e=>e===fA.member;function yJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:bJ(e.net,n),below:e.below}}}function bJ(e,t){let n=new Map(e.map(e=>[pJ(e),e]));for(let e of t){let t=n.get(pJ(e));n.set(pJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const xJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function SJ(e,t){let n=[...e.past,t],r=_J(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...yJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...CJ(e.future,a),...i.below]},n.length-r.length,t)}}function CJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function wJ(e,t){return{past:e.past.slice(0,-1),future:_J([...e.future,t]),...yJ(e.savepoint,0,xJ(t))}}function TJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...CJ(r,t.at-i.length),...t.below]}function EJ(e,t){if(vJ(t.after)&&!vJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!vJ(t.after)&&vJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function DJ(e,t){return e.map(e=>e.filter(e=>!t.has(pJ(e)))).filter(e=>e.length>0)}function OJ(e){return e.map(kJ).join(`, `)}function kJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function AJ(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 jJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(AJ))}function MJ(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(AJ)&&jJ(t.below)}function NJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return jJ(t.past)&&jJ(t.future)&&(t.savepoint===void 0||MJ(t.savepoint))}function PJ(e,t){let n=e=>e.kind===`file`||uJ(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 FJ(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(NJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,PJ(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 IJ=e=>!uJ(e)&&!HM(e)&&e!==`update.dismissed`;var LJ=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:rq(e,IJ,(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,bb.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 RJ=`click.error`;function zJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,RJ,JSON.stringify(i))}function BJ(e,t,n){let r=VJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,RJ,JSON.stringify({...r,answered:!0}))}function VJ(e,t){let n=e.get(t,RJ);return n===null?null:UJ(n)}function HJ(e,t,n,r){let i=VJ(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 UJ(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 WJ(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 GJ=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function KJ(e){let t=e=>({kind:`failed`,reason:e});if(!GJ(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!GJ(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!kj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${kj.join(` or `)}`)}return{kind:`ok`,value:e}}function qJ(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const JJ=e=>WJ(e,`doctor-marks.json`,{},KJ),YJ=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},XJ=(e,t)=>e.includes(t)?e:[...e,t],ZJ=e=>WJ(e,`doctor-clicked-terminals.json`,[],YJ);var QJ=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const $J=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},eY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),tY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=eY(e,t);return r===void 0?n:r.projectDir},nY=(e,t)=>eY(e,t).map(({role:t,frame:n,since:r,redrawn:i,projectDir:a,claudeConfigDir:o})=>({role:t,frame:n,projectDir:a,claudeConfigDir:o,redraws:qA(i,r,e.kind===`recent`?Math.min(...i):0)}));function rY(e){let t=new Map;for(let n of e.split(`
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*iY(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 aY={pullRequests:e=>iW(e).showPullRequest===!0,rateLimits:e=>rW(e,`block`)||rW(e,`weekly`),memento:e=>rW(e,`memento`)};function oY(e,t){let n=new Map;for(let r of gg(Ry(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=>Eg(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,$U(e,t,n.get(t))])),a=e=>r.filter(t=>aY[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`),memento:a(`memento`)}}
206
207
  /*!
207
208
  * Copyright (c) Squirrel Chat et al., All rights reserved.
208
209
  * SPDX-License-Identifier: BSD-3-Clause
@@ -230,9 +231,9 @@ print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
230
231
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
231
232
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
232
233
  */
233
- function ZJ(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function QJ(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
234
+ function sY(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function cY(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
234
235
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
235
- `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=ZJ(t.toml,t.ptr),i=QJ(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
236
+ `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=sY(t.toml,t.ptr),i=cY(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
236
237
  /*!
237
238
  * Copyright (c) Squirrel Chat et al., All rights reserved.
238
239
  * SPDX-License-Identifier: BSD-3-Clause
@@ -260,7 +261,7 @@ function ZJ(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
260
261
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
261
262
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
262
263
  */
263
- function $J(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
264
+ function lY(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
264
265
  `:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
265
266
  /*!
266
267
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -289,7 +290,7 @@ function $J(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
289
290
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
290
291
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
291
292
  */
292
- let eY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var tY=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(eY);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
293
+ let uY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var dY=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(uY);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
293
294
  /*!
294
295
  * Copyright (c) Squirrel Chat et al., All rights reserved.
295
296
  * SPDX-License-Identifier: BSD-3-Clause
@@ -317,7 +318,7 @@ let eY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
317
318
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
318
319
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
319
320
  */
320
- function nY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function rY(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function iY(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?hY(e):mY(e);return e.d++,t}return r===34||r===39?$J(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?aY(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?cY(e,r,t):e.s.charCodeAt(e.p+2)===58?lY(e,r,t):aY(e,e.p,r,0,t)}function aY(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||rY(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return oY(e,t,16,i);if(a===98)return oY(e,t,2,i);if(a===111)return oY(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else nY(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!rY(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:nY(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):sY(e,c,10,t)}function oY(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!rY(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):nY(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),sY(e,o,n,t)}function sY(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function cY(e,t,n){let r=e.p++,i;if(!nY(t)||!nY(e.s.charCodeAt(e.p++))||!nY(e.s.charCodeAt(e.p++))||!nY(e.s.charCodeAt(e.p++)))return aY(e,e.p=r,t,0,n);if(e.p+=5,nY(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!nY(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return uY(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;nY(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return uY(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return uY(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return uY(e,e.s.slice(r,e.p),2,i,r)}function lY(e,t,n){let r=e.p;if(!nY(t)||!nY(e.s.charCodeAt(++e.p)))return aY(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;nY(e.s.charCodeAt(++e.p)););return uY(e,e.s.slice(r,e.p),4,!1,r)}function uY(e,t,n,r,i,a){if(e.ld){let a=new tY(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
321
+ function fY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function pY(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function mY(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?TY(e):wY(e);return e.d++,t}return r===34||r===39?lY(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?hY(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?vY(e,r,t):e.s.charCodeAt(e.p+2)===58?yY(e,r,t):hY(e,e.p,r,0,t)}function hY(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||pY(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return gY(e,t,16,i);if(a===98)return gY(e,t,2,i);if(a===111)return gY(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else fY(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!pY(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:fY(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):_Y(e,c,10,t)}function gY(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!pY(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):fY(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),_Y(e,o,n,t)}function _Y(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function vY(e,t,n){let r=e.p++,i;if(!fY(t)||!fY(e.s.charCodeAt(e.p++))||!fY(e.s.charCodeAt(e.p++))||!fY(e.s.charCodeAt(e.p++)))return hY(e,e.p=r,t,0,n);if(e.p+=5,fY(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!fY(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return bY(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;fY(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return bY(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return bY(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return bY(e,e.s.slice(r,e.p),2,i,r)}function yY(e,t,n){let r=e.p;if(!fY(t)||!fY(e.s.charCodeAt(++e.p)))return hY(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;fY(e.s.charCodeAt(++e.p)););return bY(e,e.s.slice(r,e.p),4,!1,r)}function bY(e,t,n,r,i,a){if(e.ld){let a=new dY(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
321
322
  /*!
322
323
  * Copyright (c) Squirrel Chat et al., All rights reserved.
323
324
  * SPDX-License-Identifier: BSD-3-Clause
@@ -345,7 +346,7 @@ function nY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
345
346
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
346
347
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
347
348
  */
348
- function dY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function fY(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;dY(e)}}
349
+ function xY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function SY(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;xY(e)}}
349
350
  /*!
350
351
  * Copyright (c) Squirrel Chat et al., All rights reserved.
351
352
  * SPDX-License-Identifier: BSD-3-Clause
@@ -373,7 +374,7 @@ function dY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
373
374
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
374
375
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
375
376
  */
376
- function pY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push($J(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function mY(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(fY(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=pY(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),fY(e,!0,!0);let l=iY(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),fY(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function hY(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(fY(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(iY(e,93)),fY(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
377
+ function CY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(lY(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function wY(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(SY(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=CY(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),SY(e,!0,!0);let l=mY(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),SY(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function TY(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(SY(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(mY(e,93)),SY(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
377
378
  /*!
378
379
  * Copyright (c) Squirrel Chat et al., All rights reserved.
379
380
  * SPDX-License-Identifier: BSD-3-Clause
@@ -401,7 +402,7 @@ function pY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
401
402
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
402
403
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
403
404
  */
404
- function gY(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function _Y(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function vY(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,fY(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=pY(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=gY(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(_Y(n,u,a),o=!0)}else{a=n.p;let e=gY(n,pY(n),s,c,0);!e&&!o&&_Y(n,e,a),fY(n,!0,!0);let t=iY(n,void 0);e&&!o&&(e[1][e[0]]=t)}fY(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),fY(n)}return r}``.isWellFormed;
405
+ function EY(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function DY(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function OY(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,SY(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=CY(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=EY(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(DY(n,u,a),o=!0)}else{a=n.p;let e=EY(n,CY(n),s,c,0);!e&&!o&&DY(n,e,a),SY(n,!0,!0);let t=mY(n,void 0);e&&!o&&(e[1][e[0]]=t)}SY(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),SY(n)}return r}``.isWellFormed;
405
406
  /*!
406
407
  * Copyright (c) Squirrel Chat et al., All rights reserved.
407
408
  * SPDX-License-Identifier: BSD-3-Clause
@@ -429,7 +430,7 @@ function gY(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
429
430
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
430
431
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
431
432
  */
432
- const yY=e=>e.codePointAt(0).toString(16).toUpperCase(),bY=String.raw`
433
+ const kY=e=>e.codePointAt(0).toString(16).toUpperCase(),AY=String.raw`
433
434
  ObjC.import("AppKit");
434
435
  ObjC.import("CoreText");
435
436
  function lacksOf(font, points) {
@@ -476,45 +477,49 @@ function run(argv) {
476
477
  : iterm(argv[1], points),
477
478
  );
478
479
  }
479
- `;function xY(e){let t=ut({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,bY,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new HJ(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const SY=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),CY=e=>[...e].map(yY).join(`,`);function wY(e,t){let n=xY([`font`,e.kind,e.name,CY(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:SY(r)}}}function TY(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!fj(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const EY=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function DY(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>TY(e,n));if(t!==null)return r[0];let i=r.find(e=>!EY(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function OY(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=xY([`iterm`,r??``,CY(n)]);return i.kind===`failed`?i:DY(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:SY(e.lacks)})),r,e)}function kY(e,t){let n=e.split(`
480
- `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const AY=e=>e.replace(/[\\:,=-]/g,`\\$&`);function jY(e,t){let n=ut({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
481
- `,`:family=${AY(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new HJ(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return kY(n.stdout,t)}function MY(e,t){return process.platform===`darwin`?wY(e,t):jY(e.name,t)}function NY(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function PY(e){return e===`darwin`?`Menlo`:`monospace`}const FY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function IY(e){let t=FY(e.font)?e.font:{},n=FY(t.normal)?t.normal:{},r=(FY(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function LY(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=vY(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=IY(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=LY(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function RY(e,t){let n=C.homedir(),r=NY(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:LY(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??PY(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=MY({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const zY={iterm2:OY,alacritty:(e,t,n)=>RY(t,n)};function BY(e,t,n){return zY[e.name](e.version,t,n)}function VY(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const HY=e=>PJ(e,`doctor-post-mortems-read.json`,{through:null},VY);function UY(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const WY={realpath:e=>UY(()=>p.realpathSync(e)),checkoutOf:Je,digest:e=>UY(()=>Ge(e)),nativeShipped:Wa(process.platform,process.arch)};function GY(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const KY=e=>({marks:RJ(e),clicked:VJ(e),postMortemsRead:HY(e)}),qY=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function JY(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const YY=/^(sshd|mosh-server)\b/;function XY(e,t){let n=qJ(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of JJ(n,t))if(YY.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function ZY(e){let t=ut({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new HJ(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return XY(t.stdout,e)}const QY=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function $Y(e,t){let n=[];for(let r of e.split(`
482
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function eX(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=QY.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function tX(){let e=ut({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:$Y(e.stdout,eX)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function nX(e){let t=rU(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new HJ(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:JY(t.stdout)}function rX(e){return{probeTmux:nX,remoteLogin:ZY,fontInUse:BY,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ka(process.platform),install:WY,daemons:tX,forge:cX,memento:bU,transcript:aX}}function iX(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
480
+ `;function jY(e){let t=ut({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,AY,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new QJ(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const MY=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),NY=e=>[...e].map(kY).join(`,`);function PY(e,t){let n=jY([`font`,e.kind,e.name,NY(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:MY(r)}}}function FY(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!fj(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const IY=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function LY(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>FY(e,n));if(t!==null)return r[0];let i=r.find(e=>!IY(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function RY(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=jY([`iterm`,r??``,NY(n)]);return i.kind===`failed`?i:LY(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:MY(e.lacks)})),r,e)}function zY(e,t){let n=e.split(`
481
+ `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const BY=e=>e.replace(/[\\:,=-]/g,`\\$&`);function VY(e,t){let n=ut({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
482
+ `,`:family=${BY(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new QJ(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return zY(n.stdout,t)}function HY(e,t){return process.platform===`darwin`?PY(e,t):VY(e.name,t)}function UY(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function WY(e){return e===`darwin`?`Menlo`:`monospace`}const GY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function KY(e){let t=GY(e.font)?e.font:{},n=GY(t.normal)?t.normal:{},r=(GY(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function qY(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=OY(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=KY(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=qY(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function JY(e,t){let n=C.homedir(),r=UY(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:qY(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??WY(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=HY({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const YY={iterm2:RY,alacritty:(e,t,n)=>JY(t,n)};function XY(e,t,n){return YY[e.name](e.version,t,n)}function ZY(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const QY=e=>WJ(e,`doctor-post-mortems-read.json`,{through:null},ZY);function $Y(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const eX={realpath:e=>$Y(()=>p.realpathSync(e)),checkoutOf:Je,digest:e=>$Y(()=>Ge(e)),nativeShipped:Wa(process.platform,process.arch)};function tX(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const nX=e=>({marks:JJ(e),clicked:ZJ(e),postMortemsRead:QY(e)}),rX=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function iX(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const aX=/^(sshd|mosh-server)\b/;function oX(e,t){let n=rY(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of iY(n,t))if(aX.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function sX(e){let t=ut({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new QJ(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return oX(t.stdout,e)}const cX=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function lX(e,t){let n=[];for(let r of e.split(`
483
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function uX(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=cX.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function dX(){let e=ut({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:lX(e.stdout,uX)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function fX(e){let t=pU(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new QJ(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:iX(t.stdout)}function pX(e){return{probeTmux:fX,remoteLogin:sX,fontInUse:XY,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ka(process.platform),install:eX,daemons:dX,forge:vX,memento:AU,transcript:hX}}function mX(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
483
484
  `)+1,i=n.lastIndexOf(`
484
485
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
485
- `)){let t=SH(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function aX(e){let t=va(e,Aj+1);return t.kind===`ok`?P(iX(t.value.buf,t.value.fromStart)):t}function oX(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 sX={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function cX(e){if(SD(e)===void 0)return{kind:`ok`,value:null};let t=VD(ut({bin:`git`,args:[...BD],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=KD(t.value);if(n===null)return{kind:`ok`,value:null};let r=zD(n);if(r===null)return{kind:`ok`,value:null};let i=PD[r],a=sX[r],o=a.loginHost(RD(n)),s=ut({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return lX(i,o,a.nonZero,s)}function lX(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):FD(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:jD(r.stderr)}):{kind:`failed`,reason:AD(e,r)}}function uX(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
486
- `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const dX=e=>UY(()=>ja(e));function fX(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:dX(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 pX(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function mX(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:yj(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:vj(t),tmuxClient:t}}}}function hX(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(cj(s))return{kind:`bundling`,name:s,version:c};if(!lj(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 gX(e){return{kind:`arrived`,handler:e,bar:qe}}function _X(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function vX(e,t,n,r,i){return{pullRequests:_X(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:_X(t.rateLimits,()=>i),memento:_X(t.memento,()=>({located:e.memento(r,n.projectDir),claudeConfigDir:r}))}}function yX(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 bX(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=BB(d.config,r,()=>!1),p=pX(e,t.tmux),m=mX(p,t.terminalEnv),h=[...new Set([...Jv(f),...qv(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:hX(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:uX(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:vX(e,XJ(d.config,f.preset),n,xa(t.claudeConfigDir),a),transcripts:oX(e,o),claudeSettings:fX({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Sa(xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function xX(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:dX(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 SX={connectMs:200,budgetMs:500};async function CX(e){let n=e.includes(`--json`),r=await wX();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${ln(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
487
- `);let i=TX(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(NX(r.value))}function wX(){return nn({kind:`stats`},SX,e=>`stats`in e?e.stats:void 0)}function TX(e,t=EX){let n=KK.referenceSnapshot(),r=DX(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=kX(e.version,e.sourceDigest??null),a=kX(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 EX=Object.keys(KK.referenceSnapshot());function DX(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!OX(e))return[];if(!OX(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(...DX(e[i],t[i],a)):r.push(a)}return r}function OX(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kX(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function AX(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function jX(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function MX(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 NX(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${kX(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${MX(e.uptimeSec)}`),t.push(` rss ${AX(e.rssBytes)}`),t.push(` heapUsed ${AX(e.heapUsedBytes)}`),t.push(` heapTotal ${AX(e.heapTotalBytes)}`),t.push(` external ${AX(e.externalBytes)}`),t.push(` arrayBuffers ${AX(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 ${jX(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 ${jX(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 ${AX(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${AX(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 ${AX(e.renderCache.accountedBytes)} / ${AX(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(`
486
+ `)){let t=MH(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function hX(e){let t=va(e,Aj+1);return t.kind===`ok`?P(mX(t.value.buf,t.value.fromStart)):t}function gX(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 _X={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function vX(e){if(SD(e)===void 0)return{kind:`ok`,value:null};let t=VD(ut({bin:`git`,args:[...BD],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=KD(t.value);if(n===null)return{kind:`ok`,value:null};let r=zD(n);if(r===null)return{kind:`ok`,value:null};let i=PD[r],a=_X[r],o=a.loginHost(RD(n)),s=ut({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return yX(i,o,a.nonZero,s)}function yX(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):FD(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:jD(r.stderr)}):{kind:`failed`,reason:AD(e,r)}}function bX(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
487
+ `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const xX=e=>$Y(()=>ja(e));function SX(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:xX(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 CX(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function wX(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:yj(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:vj(t),tmuxClient:t}}}}function TX(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(cj(s))return{kind:`bundling`,name:s,version:c};if(!lj(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 EX(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 DX(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function OX(e,t,n,r,i){return{pullRequests:DX(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:DX(t.rateLimits,()=>i),memento:DX(t.memento,()=>({located:e.memento(r,n.projectDir),claudeConfigDir:r}))}}function kX(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 AX(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=BB(d.config,r,()=>!1),p=CX(e,t.tmux),m=wX(p,t.terminalEnv),h=[...new Set([...Jv(f),...qv(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:TX(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:bX(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:OX(e,oY(d.config,f.preset),n,xa(t.claudeConfigDir),a),transcripts:gX(e,o),claudeSettings:SX({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Sa(xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function jX(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:xX(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 MX={connectMs:200,budgetMs:500};async function NX(e){let n=e.includes(`--json`),r=await PX();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=FX(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(UX(r.value))}function PX(){return nn({kind:`stats`},MX,e=>`stats`in e?e.stats:void 0)}function FX(e,t=IX){let n=nq.referenceSnapshot(),r=LX(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=zX(e.version,e.sourceDigest??null),a=zX(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 IX=Object.keys(nq.referenceSnapshot());function LX(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!RX(e))return[];if(!RX(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(...LX(e[i],t[i],a)):r.push(a)}return r}function RX(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zX(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function BX(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function VX(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function HX(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 UX(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${zX(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${HX(e.uptimeSec)}`),t.push(` rss ${BX(e.rssBytes)}`),t.push(` heapUsed ${BX(e.heapUsedBytes)}`),t.push(` heapTotal ${BX(e.heapTotalBytes)}`),t.push(` external ${BX(e.externalBytes)}`),t.push(` arrayBuffers ${BX(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 ${VX(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 ${VX(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 ${BX(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${BX(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 ${BX(e.renderCache.accountedBytes)} / ${BX(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
489
  `)+`
489
- `}const PX=e=>({kind:`ok`,value:e}),FX=e=>({kind:`failed`,reason:e});var IX=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const LX=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function RX(e){return LX.test(e)?e:null}function zX(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return PX(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return PX({app:n,missing:FX(`its script could not be read (${r.reason})`)});let i=to(r.value);return PX({app:n,missing:i===null?FX("its script is not one `cc-candybar install` wrote"):PX([i.node,i.script].filter(t=>!e.exists(t)))})}async function BX(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 VX(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(`${dr}://${Ir}/${n}`);return(r===null?await BX(e,n):null)??{kind:`lost`,unopened:r,opener:zX(e)}}function HX(e,t,n){let r=ut({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?PX(r.stdout):FX(r.stderr.trim()||r.error||r.reason)}const UX=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${dr}://probe"));u.isNil() ? "" : u.path.js`;async function WX(){let e=await wX();if(e.kind!==`ok`)return FX(ln(e).split(`
490
- `).join(` — `));let t=TX(e.value,[`handlerProbes`]);if(t!==null)return FX(t);let{version:n,handlerProbes:r}=e.value;return PX({version:n,arrivals:r})}function GX(){return{platform:process.platform,sockets:{own:vt(),handler:yt()},now:Date.now,nonce:ne,daemon:WX,open:e=>{let t=HX(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=HX(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,UX]);if(e.kind===`failed`)return e;let t=e.value.trim();return PX(t===``?null:t)},script:e=>HX(`doctor.osadecompile`,`/usr/bin/osadecompile`,[no(e)]),exists:p.existsSync}}const KX=/^─{20,}/,qX=/^❯(\s|$)/,JX=/›\s*stashed$/;function YX(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>KX.test(e)?[t]:[]).at(-2);return n===void 0||!qX.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function XX(e){if(e.inMode)return{kind:`in-mode`};let t=YX(e);return t===null?{kind:`no-prompt`}:JX.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function ZX(e){return/^❯\s*\S/u.test(YX(e)?.prompt??``)}const QX=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function $X(e){return e.screen.some(e=>QX.test(e))}const eZ={"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 tZ(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 nZ(e,t,n){let r=tZ(t);if(r.kind===`refused`)return r;let i=r.hint,a=XX(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:eZ[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function rZ(e,t,n,r){let i=rU(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function iZ(e){let t=rZ(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(`
491
- `);return{inMode:n!==`0`,screen:r}}function aZ(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function oZ(e,t){let n=rZ(e,`claude-input.type`,aZ(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function sZ(){return{read:iZ,type:oZ}}function cZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function lZ(e){return uZ(()=>decodeURIComponent(e))}function uZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function dZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const fZ=(e,t)=>dZ(lZ(e),t),pZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,lZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},mZ=(e,t)=>dZ(lZ(e),t),hZ=(e,t)=>dZ(lZ(e),t),gZ=(e,t)=>{let n=cZ(lZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},_Z=(e,t)=>{let[n=``,...r]=uZ(()=>Br(e)),i=cZ(n),a=SV(jZ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}xZ(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},vZ=/^-?\d+$/;function yZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const bZ=(e,t)=>{let[n=``,r=``,i=``]=uZ(()=>Br(e)),a=cZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!vZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=jZ(t,a),c=SV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&vZ.test(u)?SZ(l,parseInt(u,10)):CZ(`step-state`,r,l,TV(s,e=>t.sessionState.get(a,e),r)),f=yZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);xZ(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function xZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(uA));if(i.length===0)return;let a=tV(jZ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function SZ(e,t){return Math.max(e.min,Math.min(e.max,t))}function CZ(e,t,n,r){if(r===null)return n.min;if(!vZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return SZ(n,parseInt(r,10))}const wZ=`render-origin`;function TZ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function EZ(e){return JSON.stringify(e)}function DZ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function OZ(e,t){let n=kZ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function kZ(e,t){let n=e.sessionState.get(t,wZ);return n===null?null:TZ(DZ(n),e.sessionState,t)}function AZ(e,t,n){let r=kZ(e,t);if(r===null)return;let{path:i}=MZ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function jZ(e,t){return e.configFor(OZ(e,t))}function MZ(e){return Qz(e.projectDir,e.cwd,e.configFile??void 0)}function NZ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const PZ=(e,t)=>{let[n=``,r=``,i=``]=uZ(()=>Br(e)),a=cZ(n),o=OZ(t,a),s=t.configFor(o),c=PF(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=MZ(o),d=$B(s,e=>t.sessionState.get(a,e),r);zq(NZ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},FZ=(e,t)=>{let[n=``,r=``,i=``]=uZ(()=>Br(e)),a=cZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!vZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=OZ(t,a),c=t.configFor(s),l=PF(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=MZ(s),f=$B(c,e=>t.sessionState.get(a,e),r),p=Rq(d.path,f.key),m=typeof p==`number`?SZ(u,p):CZ(`step-config`,r,u,IF(f.globals,r)),h=yZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);zq(NZ(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},IZ=(e,t)=>{let[n=``]=uZ(()=>Br(e)),r=cZ(n),i=OZ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=ZB(a,o),c=eV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=SV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});RZ(`save`,l,c);let d=MZ(i);Bq(NZ(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(LZ)].join(` `)} → ${d.path} (session=${r})`)},LZ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Fg(e.value)}`;function RZ(e,t,n){for(let r of n){let n=t.validate(r.key,Fg(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const zZ=(e,t)=>{let[n=``]=uZ(()=>Br(e)),r=cZ(n),i=OZ(t,r),a=t.configFor(i),o=iV(a,e=>t.sessionState.get(r,e)),s=SV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});RZ(`save-preset`,s,o.placements);let l=MZ(i),u=qq(NZ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...cv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,ov.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(LZ)].join(` `)} → ${l.path} (session=${r})`)},BZ=(e,t)=>{let[n=``]=uZ(()=>Br(e)),r=cZ(n),i=OZ(t,r),a=oV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=MZ(i);Jq(NZ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(ZB(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=$_.map(e=>ov[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${$_.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},VZ=(e,t)=>{let[n=``,r=``]=uZ(()=>Br(e)),i=cZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=OZ(t,i),o=MZ(a);Yq(NZ(t,i),o,r),t.reloadConfig(a);let s=ov.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},HZ=(e,t)=>{let[n=``,...r]=uZ(()=>Br(e)),i=cZ(n),a=OZ(t,i),o=PF(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=MZ(a),l=r.map(sV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);Wq(NZ(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function UZ(e,t){let n=(e,t)=>[...gg(Ry(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Fy(t.presets).flatMap(e=>n(t,e).map(t=>dA(YO(e),fg(t)))));return Fy(e.presets).flatMap(t=>n(e,t).map(e=>({member:dA(YO(t),fg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function WZ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[aA]:[]])}const GZ=(e,t)=>{let[n=``,r=``,i=``]=uZ(()=>Br(e)),a=cZ(n),o=OZ(t,a),s=t.configFor(o),c=PF(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=bF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=MZ(o),f=Xq(NZ(t,a),d,r,u);t.reloadConfig(o);let p=WZ(UZ(s,t.configFor(o)),t.sessionState.get(a,aA)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},KZ=(e,t)=>{let[n=``]=uZ(()=>Br(e)),r=cZ(n);t.journal.commit();let i=t.history.undo(r);AZ(t,r,i),t.dlog(`info`,`undo: restored ${vJ(i)} (session=${r})`)},qZ=(e,t)=>{let n=cZ(lZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,SV(jZ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},JZ=(e,t)=>{let n=cZ(lZ(e));t.journal.commit();let r=t.history.rewind(n);AZ(t,n,r),t.dlog(`info`,`rewind: put back ${vJ(r)||`nothing`} as edit mode found it (session=${n})`)},YZ=(e,t)=>{let[n=``]=uZ(()=>Br(e)),r=cZ(n);t.journal.commit();let i=t.history.redo(r);AZ(t,r,i),t.dlog(`info`,`redo: re-applied ${vJ(i)} (session=${r})`)},XZ=(e,t)=>{cZ(lZ(e)),t.applyUpdate()},ZZ=`client-hints`;function QZ(e,t){let n=e.sessionState.get(t,ZZ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function $Z(e,t,n){let r=yM(n);e.sessionState.setBatch(t,IM(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${PM(n.nerdFont,n.marks)} ${TM(n.terminal,n.clicked)} ${EM(n.terminal,n.width)} ${DM(n.install)} ${OM(n.daemon)} ${kM(n.data)} ${NM(n.transcripts)} ${AM(n.frames,n.claudeSettings)} ${MM(n.claudeSettings.origin.sources)} (session=${t})`)}function eQ(e,t){let n={kind:`clicked`,sessionId:t},r=e.clients.ofSession(t,gO(new Date)),i;try{i=bX(e.doctor,QZ(e,t),OZ(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:KJ(n,r)},yX(t,r),qY(e.doctorStores))}catch(e){throw e instanceof HJ?new J(e.message):e}return{...i,urlHandler:gX(e.clientVersion),install:GY(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:tQ(e,i)}}function tQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?bj(t.identified):null;if(r===null)return n;try{return e.doctorStores.clicked.update(e=>BJ(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const nQ=(e,t)=>{let n=cZ(lZ(e));$Z(t,n,eQ(t,n))},rQ=(e,t)=>{let n=RX(lZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);t.probes.arrive({nonce:n,handler:t.clientVersion}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${t.clientVersion??`unreported`}`)},iQ=(e,t)=>{let[n=``,r=``]=uZ(()=>Br(e)),i=cZ(n),a=bM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=eQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=xX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Mj(s.fix)} (session=${i})`),$Z(t,i,c.value)},aQ=(e,t)=>{let[n=``,r=``,i=``]=uZ(()=>Br(e)),a=cZ(n),o=bM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!kj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${kj.join(` or `)}`);let s=eQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>LJ(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),$Z(t,a,{...s,marks:u})},oQ=(e,t)=>{let[n=``,...r]=uZ(()=>Br(e)),i=cZ(n),a=OZ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=IL(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=lU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},QZ(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},sQ=(e,t)=>{let[n=``,r=``]=uZ(()=>Br(e)),i=cZ(n),a=Object.values(t.configFor(OZ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=nZ(t.claudeInput,QZ(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},cQ=`config-override`,lQ=new Map([[hr,fZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=cZ(uZ(()=>decodeURIComponent(e.slice(0,n)))),i=uZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,cQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,cQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[gr,pZ],[pr,_Z],[mr,bZ],[br,PZ],[xr,FZ],[Er,HZ],[Sr,IZ],[Cr,zZ],[wr,BZ],[Tr,VZ],[Dr,GZ],[Or,KZ],[kr,YZ],[Ar,qZ],[jr,JZ],[vr,mZ],[yr,hZ],[_r,gZ],[Mr,XZ],[Nr,nQ],[Pr,iQ],[Fr,aQ],[Ir,rQ],[Lr,oQ],[Rr,sQ]]),uQ=new Set([pr,mr,br,xr,Er,Sr,Cr,wr,Tr,Dr,Or,kr,Ar,jr,_r,Mr,Nr,Pr,Fr,Lr,Rr]),dQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Wr(Hr(e))){if(!i&&uQ.has(a)){let e=Br(o);e.length>0&&e[0]&&(i=e[0])}let e=lQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&kJ(t.sessionState,i,n.join(`
492
- `),gO(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function fQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const pQ=new Map([...lQ,[fr,dQ]].map(([e,t])=>[e,fQ(t)]));Object.freeze([...pQ.keys()]);const mQ=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),hQ=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],gQ=[[`workspace.added_dirs`,`string-list`]];function _Q(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of hQ){let i=bQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=vQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of gQ){let i=bQ(n,e),a=i===void 0?r:yQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))mQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function vQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function yQ(e){return Array.isArray(e)&&e.every(e=>vQ(e)===`string`)?`string-list`:vQ(e)}function bQ(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function xQ(e,t){switch(e){case`vars`:return{what:e,vars:SQ(t)};case`segments`:return{what:e,segments:DQ(t)};case`config`:return{what:e,config:jQ(t)}}}function SQ(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=TQ(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=CQ(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:wQ(r.lastUpdatedMs())})}return o}function CQ(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function wQ(e){return e===null?null:Math.max(0,Date.now()-e)}function TQ(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,EQ(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,EQ(i));return t}function EQ(e){return e.kind}function DQ(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=kQ(n),o=OQ(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:AQ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function OQ(e){let t=new Map;for(let n of Fy(e.presets))for(let r of gg(Ry(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=fg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function kQ(e){let t=[],n=new Set;for(let r of gg(Oy(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function AQ(e,t,n){let r=new Set;for(let i of ob(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function jQ(e){return e===null?null:e.config}const MQ=[`vars`,`segments`,`config`];function NQ(e){return typeof e==`string`&&MQ.includes(e)}function PQ(e){return Math.max(1,e-2)}const FQ={moving:1e3/30,still:1e3},IQ=1e3;function LQ(e){return T_.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function RQ(e,t){e.push(t);let n=e.findIndex(e=>e>t-IQ);e.splice(0,n)}const zQ=e=>({resp:e,bytes:JSON.stringify(e)}),BQ=(e,t)=>w_[t].elsewhere===null?e.statusline:e.bar,VQ=e=>Math.round(1e3/e);var HQ=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return j_;let n=this.deps.now()-IQ,r=this.shown(t);return A_(e=>{let i=t.rates.get(e);if(i===void 0)return O_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:VQ(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=VQ(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:zQ(t.resp),statusline:zQ(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||BQ(i,t).bytes!==BQ(r,t).bytes)&&RQ(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=BQ(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:RA(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function UQ(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const WQ=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,GQ=`#{session_id} #{client_control_mode}`;function KQ(e){let t=new Set;for(let n of e.split(`
493
- `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function qQ(e,t){let n=new Set;for(let r of e.split(`
494
- `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}var JQ=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${w(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:qQ(t.stdout,KQ(n.stdout))}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!YQ(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}n.size>0&&this.deps.onChange(n)}};function YQ(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const XQ=`CC_CANDYBAR_CONFIG`;function ZQ(e,t){return fz(t,e[XQ])}const $=e=>({arity:e,keep:!0}),QQ=e=>({arity:e,keep:!1}),$Q={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":QQ(`none`),"--background":QQ(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":QQ(`optional`),"-c":QQ(`none`),"--continue":QQ(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":QQ(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":QQ(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":QQ(`none`),"--forward-subagent-text":$(`none`),"--from-pr":QQ(`optional`),"-h":QQ(`none`),"--help":QQ(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":QQ(`none`),"--print":QQ(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":QQ(`optional`),"--resume":QQ(`optional`),"--safe-mode":$(`none`),"--session-id":QQ(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":QQ(`optional`),"--tmux":QQ(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":QQ(`none`),"--version":QQ(`none`),"-w":QQ(`optional`),"--worktree":QQ(`optional`)},e$={resume:`--resume`,fresh:`--session-id`};function t$(e){return[e$[e.kind],e.sessionId]}const n$=e=>e.startsWith(`-`)&&e!==`-`;function r$(e,t){let n=o$(t);return n===null?{dir:e??t,args:[]}:e!==null&&i$(e,n.top)?{dir:e,args:[]}:{dir:e===null||o$(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const i$=(e,t)=>e===t||e.startsWith(t+s.sep);function a$(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!n$(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=$Q[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!n$(e)):o.arity===`variadic`?s$(n.slice(r),e=>!n$(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function o$(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function s$(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const c$=`candybar-band@cc-candybar`,l$=s.join(`bin`,`cc-candybar-native`),u$=`@cc-candybar-bar-pane`,d$=KM(`/reload-plugins`),f$=e=>({kind:`done`,said:e});function p$(e){let t=tZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const m$={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${w_.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,l$);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${c$} from ${r}`,finished:h$(e,r,n)}},off:()=>f$(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=p$(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${w_.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:v$(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>f$(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=p$(e),i=n.barPanes(r);return i.length>0?f$(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):f$(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=tZ(e.hints.tmux);if(r.kind===`refused`)return f$(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return f$(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}}};async function h$(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,c$],r);let i=nZ(n.claudeInput,e.hints.tmux,d$);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${c$} from ${t} and typed /reload-plugins into ${i.pane}`}const g$=new Set([ya,XQ,...Mt]);function _$(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function v$(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${w_.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=C$(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${w_.statusline.label} off and on again`);let s=y$(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=a$(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=_$(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>g$.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...t$(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=b$(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(r$(null,i.cwd),_))}let y=m(r$(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${x$[g.kind](e.sessionId)}, and its statusline follows lane B`}function y$(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function b$(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const x$={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},S$={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function C$(e){let t=XX(e);return t.kind===`ready`?$X(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:ZX(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:S$[t.kind]}const w$={switches:Object.fromEntries(T_.map(e=>[e,!1])),revision:0};var T$=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??w$;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of T_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),kJ(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=m$[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function E$(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function D$(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function O$(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function k$(e,t,n){let r=E$(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const A$=2e3;function j$(e,t,n){let r=rU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function M$(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function N$(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const P$=`#{pane_id} #{${u$}}`;function F$(e,t){return e.split(`
495
- `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const I$=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function L$(e,t,n){for(let r of JJ(qJ(e),t)){if(r.command.split(` `).some(e=>I$.test(e)))return!0;if(r.pid===n)return!1}return!1}const R$=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
496
- `);async function z$(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=M$(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,R$,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function B$(e,t){return M$(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function V$(e){let t=await iU(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await B$(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function H$(e){let{panePid:t,cwd:n,foreground:r}=await V$(e),i=await B$(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await z$(r),o=qJ(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:L$(i,r,t)}}function U$(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function W$(e){return{claudeInput:sZ(),barPanes:e=>F$(j$(e,[`list-panes`,`-a`,`-F`,P$]),e.pane),openBarPane:(e,t,n)=>{let r=j$(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return j$(e,[`set-option`,`-p`,`-t`,r,u$,e.pane]),r},closePane:(e,t)=>void j$(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void M$(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:U$(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:Kz,paneClaude:H$,paneDir:async(e,t)=>{let n=Date.now()+A$;for(;;){let r=await V$(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${A$/1e3} s`);await ge(100)}},launcherNode:e=>k$(e,e=>D$(e,p.constants.X_OK),O$),onPath:(e,t)=>{let n=E$(e,t,e=>D$(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?N$(r.stdout):null;return i===null?(M$(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void j$(e,aZ(e.pane,`cc-candybar-lane`,[]),t)}}function G$(e,t){return T_.filter(n=>e[n]&&w_[n].elsewhere!==null&&t.has(n))}function K$(e,t){let n=`the bar is drawn in ${t.map(e=>w_[e].elsewhere).join(` and `)}`,r=Vr([{verb:Er,args:[e,...t.map(e=>w_[e].setting)]}]);return{channels:[{severity:ty,message:n,lines:[[ny(n,Vr([{verb:hr,args:[n]}])),ny(`[⟲ draw it here]`,r)]]}]}}const q$={order:-1/0,text:null,failure:null};var J$=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??q$;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??q$;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function Y$(e,t){for(let n of Object.entries(t))e.push(n)}const X$={ok:`info`,"bad-request":`warn`,threw:`error`};function Z$(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function Q$(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...Z$(t)];return{level:X$[t.kind],line:`render${r.map(([e,t])=>` ${e}=${SM(t)}`).join(``)}`}}const $$=new KK,e1=new IX,t1=new aj,n1=i(import.meta.url),r1=KY(gt());st($$.launchStats);const i1=new iO({counters:$$,logger:M}),a1=SU({watchers:i1,logger:M}),{gitProvider:o1,usageStore:s1,mementoProvider:c1}=a1,l1=new YK,u1=new iJ(l1,M),d1=new DJ,f1=new Lv,p1=new T$({edge:W$(e=>m1.following(e)),host:{bundle:n1,node:[t.execPath,...t.execArgv],socket:vt(),preload:$a(n1)},state:l1,log:M,now:()=>gO(new Date),defer:e=>void pe(e)}),m1=new HQ({render:(e,t)=>e0(e,t),watch:(e,t)=>(0,bb.reaction)(()=>l1.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>n0(e),shown:e=>h1.shown(e.hints.tmux),watching:()=>h1.follow(),periods:FQ,now:()=>performance.now(),log:M}),h1=new JQ({listPanes:e=>iU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,WQ]),listClients:e=>iU({socket:e},`frames.visibility`,[`list-clients`,`-F`,GQ]),sockets:()=>new Set(m1.watched().flatMap(({req:e})=>g1(e))),onChange:e=>m1.wakeWhere(t=>g1(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function g1({hints:{tmux:e}}){return e==null?[]:[e.socket]}const _1=new J$(At()),v1=new WK({gitService:o1,sessionState:l1,watchers:i1,log:M},{budgetBytes:()=>(j1(),PK(w1)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),y1=60*1e3,b1=qV({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:y1,stat:p.statSync,exit:()=>I1(0),log:M}),x1=WV({entryUrl:import.meta.url,intervalMs:y1,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>b1.checkNow(),log:M});let S1=null,C1=null,w1=0;function T1(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),I1(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),I1(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),I1(0)});try{M1(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),I1(1);return}S1=Oo(t.pid);let e=Ro(Bo(S1));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),I1(1);return}C1=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),l1.useStorage(new ZK(wt(),500,M)),u1.useStorage(TJ(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),I1(0)}}),E1(E.createServer({allowHalfOpen:!1},e=>{L1(e)}),vt(),!1)}function E1(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),I1(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}D1(e,n)}),e.listen(n,()=>O1(n))}function D1(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),I1(1);return}}E1(e,n,!0)}function O1(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),I1(0);return}N1(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(w1)}MB`),tr();let r=_1.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),b1.arm(),x1.arm(),j1().arm(),k1(e,n.identity)}function k1(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>I1(e),log:M}).arm()}let A1=null;function j1(){if(A1===null)throw Error(`daemon: limits not yet established`);return A1}function M1(e){w1=Pn(e),A1=Bn(Kn($$.startedAt.getTime(),e=>I1(e),{limitBytes:w1}))}function N1(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:S1});n!==null&&M(`warn`,`lease write failed: ${n}`)}let P1=0,F1=!1;function I1(e){if(!F1){F1=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{o1.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{s1.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{i1.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{l1.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),C1!==null&&zo(C1,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function L1(e){P1++,$$.inFlight=P1;let t=!1,n=!0,r=()=>{n&&(n=!1,P1=Math.max(0,P1-1),$$.inFlight=P1)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>I1(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,$$.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,R1)},200),s=$t(e=>{G1(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(H1(e),null,R1)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,R1)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=UQ(e),c=m1.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(oH[i](e,t))),refused:t=>e.end(Zt(t))});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const R1=()=>{},z1=e=>({resp:e,exitAfterFlush:null,delivered:R1}),B1=e=>({kind:`reply`,...e}),V1={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},H1=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),U1=(e,t)=>B1(z1({ok:!1,error:t,code:e,daemonV:3}));function W1(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return U1(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return U1(`VERSION_MISMATCH`,`this client's subscribe names no lane (${T_.join(`, `)}): it predates the lane toggles — update it`);let t=M_(e.lane);return t===null?U1(`BAD_REQUEST`,`subscribe needs a lane, one of ${T_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function G1(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?U1(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?W1(e):typeof e.kind!=`string`||!Object.hasOwn(V1,e.kind)?U1(`BAD_REQUEST`,`unknown kind`):B1(await K1(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:R1})}async function K1(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:R1};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return z1(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:m1.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return z1({ok:!0,stats:$$.snapshot({gitCache:o1.getStats(),usageCache:s1.getStats(),transcriptReads:ua(),renderCache:v1.stats,effectCache:f1.getStats(),sessionState:{sessions:l1.size(),observers:l1.observers(),revision:l1.latestRevision()},frameFeeds:m1.getStats(),watchersActive:i1.size(),nextRestartReason:j1().describeNextRestart(),handlerProbes:e1.list(),clients:t1.list(gO(new Date)),bundle:n1,daemon:j1().serving(),doctorStores:qY(r1)})});if(e.kind===`render`){let n=new Date,r=gO(n),i=n.getTime(),a=[],o=++$$.requestsTotal,s=r0(e),c=(e,t)=>t1.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:tj(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),m1.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await l0(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?R1:()=>AJ(l1,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:H1(e),delivered:R1})):i0(s.problems);l.outcome.kind!==`ok`&&$$.requestsErrored++,Y$(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=Q$(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return z1($1(e.verb,e.value,Xt(e.clientVersion)));if(e.kind===`debug`){if(!NQ(e.what))return z1({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${MQ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=v1.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?Z1(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??nv(`colorCompatibility`)):X1};return z1({ok:!0,debug:xQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function q1(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:fz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const J1={sessionState:l1,dlog:M,applyUpdate:()=>x1.act(),doctor:rX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];v1.reload(...t);let n=v1.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:r1,probes:e1,clients:t1,bundle:n1,serving:()=>j1().serving(),memento:c1,claudeInput:sZ(),history:u1,navigation:d1,configFor:e=>v1.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>v1.reload(e.projectDir,e.cwd,e.configFile??void 0)};J1.reloadConfig;const Y1={endcaps:nv(`endcaps`),colorCompatibility:nv(`colorCompatibility`),wrap:nv(`autoWrap`),padding:nv(`padding`),width:1/0},X1=new Map;function Z1(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Xv(i,{...Y1,colorCompatibility:t}));return n}const Q1={...a1,history:e=>u1.depth(e),feeds:e=>m1.feedsOf(e)};function $1(e,t,n){let r=pQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...J1,clientVersion:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}async function e0(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await a0(e,gO(n),r,{by:`feed`,fps:t}),s=_1.linkFor(e.hookData.session_id,s0(i)),c=e.hookData.session_id,l=o0(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:u0(c,i,s,l,G$(o,m1.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=Q$(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=H1(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function t0(e,t){return BB(t.config,t=>l1.get(e,t),e=>t.authoredRoots.has(e))}function n0(e){try{var t=na();let n=e.hookData.session_id,r=TZ(e.requested,l1,n);return RB(t0(n,t.u(v1.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function r0(e){let{report:t}=_Q(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=q1(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:ej(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const i0=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:R1});async function a0(e,t,n,r){try{var i=na();Y$(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);Y$(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=TZ(e.requested,l1,a),{entry:u,state:d}=i.u(v1.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=PQ(f??120),m=Zv(o.termRows);Y$(n,{width:String(p)});let h=t=>l1.get(e.hookData.session_id,t),g=t0(a,d),_=RB(g);Y$(n,{lanes:T_.filter(e=>_[e]).join(`,`)||`-`}),p1.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:QA(e.hookData)},_,u1.revision(a));let v=await YU(e.hookData,t,{...Q1,navigation:e=>d1.depth(e,l1,SV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...lV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});Y$(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:MU(v.git),feeds:LQ(v.feeds)});let y=[],b=kU(g,p),ee=f1.of(a),x=xK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=MJ(l1,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
497
- `),re=x1.notice({sessionId:a,dismissed:l1.get(a,OV),enabled:g.updateNotice}),ie=u.lastError===null?null:u.failedFile,ae=[...u.lastWarning===null?[]:[{kind:`load`,message:u.lastWarning}],...y],w=ry(C,re,ae.map(e=>e.message).join(`
498
- `)),T=o1.getStats(),oe=s1.getStats(),E=ee.lastFrame(),se=E.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ce=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,le=ae.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return Y$(n,{git:`${T.size}/${T.hits}h/${T.misses}m`,usage:`${oe.size}/${oe.hits}h/${oe.misses}m`,effect:E.effect,effectT:E.t.toFixed(3),effectRows:`${E.made}made/${E.reused}reused`,effectOwn:se,fadeBasis:E.basis,stateRev:String(E.revision),fades:ce(E.fades),leaves:ce(E.leaves),motion:x.motion,err:C?`Y`:`N`,clickError:S.kind===`none`?`-`:S.kind,upd:String(re.length),warn:le}),{drawn:{body:x.text,diagnostics:w,failedConfigFile:ie,geometry:{width:p,rowCap:m,colorCompatibility:g.colorCompatibility}},motion:x.motion,clickShown:te,lanes:_}}catch(e){i.e=e}finally{i.d()}}function o0(e,t){return oy(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
499
- `}function s0(e){return e.diagnostics===null?null:ay(e.diagnostics)}function c0(e){let t=e.hookData.session_id,{client:n,...r}=e.hints,i=JSON.stringify(r);l1.get(t,`client-hints`)!==i&&l1.set(t,ZZ,i);let a=EZ(e.requested);l1.get(t,`render-origin`)!==a&&l1.set(t,wZ,a)}async function l0(e,t,n,r){c0(e);let{drawn:i,motion:a,clickShown:o,lanes:s}=await a0(e,n,r,E_),{link:c,failure:l}=_1.sync(e.hookData.session_id,t,s0(i));Y$(r,{dumpFailed:l===null?`-`:JSON.stringify(l)});let u=o0(i,c),d=e.hookData.session_id,f=G$(s,m1.following(d)),p=u0(d,i,c,u,f),m=ij(e.hints.client??null)===`statusline`;return Y$(r,{handoff:(m?f:[]).join(`,`)||`-`}),{answer:m?p:u,motion:a,clickShown:o}}function u0(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:o0({...t,body:sy(K$(e,[a,...o]),t.geometry)},n)}const d0={connectMs:200,budgetMs:500};async function f0(e,n){let r=n.includes(`--json`),i=await p0(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${ln(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
500
- `);return}t.stdout.write(m0(i.value))}function p0(e){return nn({kind:`debug`,what:e},d0,e=>`debug`in e?e.debug:void 0)}function m0(e){switch(e.what){case`vars`:return h0(e.vars);case`segments`:return g0(e.segments);case`config`:return _0(e.config);default:return e}}function h0(e){if(e.length===0)return`no variables (DSL not active)
501
- `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${y0(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${v0(a.value)}${e}${o}`)}return t.join(`
490
+ `}const WX=e=>({kind:`ok`,value:e}),GX=e=>({kind:`failed`,reason:e});var KX=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const qX=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function JX(e){return qX.test(e)?e:null}function YX(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return WX(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return WX({app:n,missing:GX(`its script could not be read (${r.reason})`)});let i=to(r.value);return WX({app:n,missing:i===null?GX("its script is not one `cc-candybar install` wrote"):WX([i.node,i.script].filter(t=>!e.exists(t)))})}async function XX(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 ZX(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(`${dr}://${Ir}/${n}`);return(r===null?await XX(e,n):null)??{kind:`lost`,unopened:r,opener:YX(e)}}function QX(e,t,n){let r=ut({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?WX(r.stdout):GX(r.stderr.trim()||r.error||r.reason)}const $X=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${dr}://probe"));u.isNil() ? "" : u.path.js`;async function eZ(){let e=await PX();if(e.kind!==`ok`)return GX(ln(e).split(`
491
+ `).join(` — `));let t=FX(e.value,[`handlerProbes`]);if(t!==null)return GX(t);let{version:n,handlerProbes:r}=e.value;return WX({version:n,arrivals:r})}function tZ(){return{platform:process.platform,sockets:{own:vt(),handler:yt()},now:Date.now,nonce:ne,daemon:eZ,open:e=>{let t=QX(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=QX(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,$X]);if(e.kind===`failed`)return e;let t=e.value.trim();return WX(t===``?null:t)},script:e=>QX(`doctor.osadecompile`,`/usr/bin/osadecompile`,[no(e)]),exists:p.existsSync}}const nZ=/^─{20,}/,rZ=/^❯(\s|$)/,iZ=/›\s*stashed$/;function aZ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>nZ.test(e)?[t]:[]).at(-2);return n===void 0||!rZ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function oZ(e){if(e.inMode)return{kind:`in-mode`};let t=aZ(e);return t===null?{kind:`no-prompt`}:iZ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function sZ(e){return/^❯\s*\S/u.test(aZ(e)?.prompt??``)}const cZ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function lZ(e){return e.screen.some(e=>cZ.test(e))}const uZ={"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 dZ(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 fZ(e,t,n){let r=dZ(t);if(r.kind===`refused`)return r;let i=r.hint,a=oZ(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:uZ[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function pZ(e,t,n,r){let i=pU(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function mZ(e){let t=pZ(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(`
492
+ `);return{inMode:n!==`0`,screen:r}}function hZ(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function gZ(e,t){let n=pZ(e,`claude-input.type`,hZ(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function _Z(){return{read:mZ,type:gZ}}function vZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function yZ(e){return bZ(()=>decodeURIComponent(e))}function bZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function xZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const SZ=(e,t)=>xZ(yZ(e),t),CZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,yZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},wZ=(e,t)=>xZ(yZ(e),t),TZ=(e,t)=>xZ(yZ(e),t),EZ=(e,t)=>{let n=vZ(yZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},DZ=(e,t)=>{let[n=``,...r]=bZ(()=>Br(e)),i=vZ(n),a=SV(VZ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}jZ(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},OZ=/^-?\d+$/;function kZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const AZ=(e,t)=>{let[n=``,r=``,i=``]=bZ(()=>Br(e)),a=vZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!OZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=VZ(t,a),c=SV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&OZ.test(u)?MZ(l,parseInt(u,10)):NZ(`step-state`,r,l,TV(s,e=>t.sessionState.get(a,e),r)),f=kZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);jZ(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function jZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(uA));if(i.length===0)return;let a=tV(VZ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function MZ(e,t){return Math.max(e.min,Math.min(e.max,t))}function NZ(e,t,n,r){if(r===null)return n.min;if(!OZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return MZ(n,parseInt(r,10))}const PZ=`render-origin`;function FZ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function IZ(e){return JSON.stringify(e)}function LZ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function RZ(e,t){let n=zZ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function zZ(e,t){let n=e.sessionState.get(t,PZ);return n===null?null:FZ(LZ(n),e.sessionState,t)}function BZ(e,t,n){let r=zZ(e,t);if(r===null)return;let{path:i}=HZ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function VZ(e,t){return e.configFor(RZ(e,t))}function HZ(e){return Qz(e.projectDir,e.cwd,e.configFile??void 0)}function UZ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const WZ=(e,t)=>{let[n=``,r=``,i=``]=bZ(()=>Br(e)),a=vZ(n),o=RZ(t,a),s=t.configFor(o),c=PF(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=HZ(o),d=$B(s,e=>t.sessionState.get(a,e),r);Yq(UZ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},GZ=(e,t)=>{let[n=``,r=``,i=``]=bZ(()=>Br(e)),a=vZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!OZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=RZ(t,a),c=t.configFor(s),l=PF(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=HZ(s),f=$B(c,e=>t.sessionState.get(a,e),r),p=Jq(d.path,f.key),m=typeof p==`number`?MZ(u,p):NZ(`step-config`,r,u,IF(f.globals,r)),h=kZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);Yq(UZ(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},KZ=(e,t)=>{let[n=``]=bZ(()=>Br(e)),r=vZ(n),i=RZ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=ZB(a,o),c=eV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=SV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});JZ(`save`,l,c);let d=HZ(i);Xq(UZ(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(qZ)].join(` `)} → ${d.path} (session=${r})`)},qZ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Fg(e.value)}`;function JZ(e,t,n){for(let r of n){let n=t.validate(r.key,Fg(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const YZ=(e,t)=>{let[n=``]=bZ(()=>Br(e)),r=vZ(n),i=RZ(t,r),a=t.configFor(i),o=iV(a,e=>t.sessionState.get(r,e)),s=SV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});JZ(`save-preset`,s,o.placements);let l=HZ(i),u=rJ(UZ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...cv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,ov.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(qZ)].join(` `)} → ${l.path} (session=${r})`)},XZ=(e,t)=>{let[n=``]=bZ(()=>Br(e)),r=vZ(n),i=RZ(t,r),a=oV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=HZ(i);iJ(UZ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(ZB(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=$_.map(e=>ov[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${$_.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},ZZ=(e,t)=>{let[n=``,r=``]=bZ(()=>Br(e)),i=vZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=RZ(t,i),o=HZ(a);aJ(UZ(t,i),o,r),t.reloadConfig(a);let s=ov.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},QZ=(e,t)=>{let[n=``,...r]=bZ(()=>Br(e)),i=vZ(n),a=RZ(t,i),o=PF(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=HZ(a),l=r.map(sV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);eJ(UZ(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function $Z(e,t){let n=(e,t)=>[...gg(Ry(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Fy(t.presets).flatMap(e=>n(t,e).map(t=>dA(YO(e),fg(t)))));return Fy(e.presets).flatMap(t=>n(e,t).map(e=>({member:dA(YO(t),fg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function eQ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[aA]:[]])}const tQ=(e,t)=>{let[n=``,r=``,i=``]=bZ(()=>Br(e)),a=vZ(n),o=RZ(t,a),s=t.configFor(o),c=PF(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=bF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=HZ(o),f=oJ(UZ(t,a),d,r,u);t.reloadConfig(o);let p=eQ($Z(s,t.configFor(o)),t.sessionState.get(a,aA)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},nQ=(e,t)=>{let[n=``]=bZ(()=>Br(e)),r=vZ(n);t.journal.commit();let i=t.history.undo(r);BZ(t,r,i),t.dlog(`info`,`undo: restored ${OJ(i)} (session=${r})`)},rQ=(e,t)=>{let n=vZ(yZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,SV(VZ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},iQ=(e,t)=>{let n=vZ(yZ(e));t.journal.commit();let r=t.history.rewind(n);BZ(t,n,r),t.dlog(`info`,`rewind: put back ${OJ(r)||`nothing`} as edit mode found it (session=${n})`)},aQ=(e,t)=>{let[n=``]=bZ(()=>Br(e)),r=vZ(n);t.journal.commit();let i=t.history.redo(r);BZ(t,r,i),t.dlog(`info`,`redo: re-applied ${OJ(i)} (session=${r})`)},oQ=(e,t)=>{vZ(yZ(e)),t.applyUpdate()},sQ=`client-hints`;function cQ(e,t){let n=e.sessionState.get(t,sQ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function lQ(e,t,n){let r=yM(n);e.sessionState.setBatch(t,IM(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${PM(n.nerdFont,n.marks)} ${TM(n.terminal,n.clicked)} ${EM(n.terminal,n.width)} ${DM(n.install)} ${OM(n.daemon)} ${kM(n.data)} ${NM(n.transcripts)} ${AM(n.frames,n.claudeSettings)} ${MM(n.claudeSettings.origin.sources)} (session=${t})`)}function uQ(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,gO(new Date)),i;try{i=AX(e.doctor,cQ(e,t),RZ(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:nY(n,r)},kX(t,r),rX(e.doctorStores))}catch(e){throw e instanceof QJ?new J(e.message):e}return{...i,urlHandler:EX(e.arrival),install:tX(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:dQ(e,i)}}function dQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?bj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>XJ(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const fQ=(e,t)=>{let n=vZ(yZ(e));lQ(t,n,uQ(t,n))},pQ=(e,t)=>{let n=JX(yZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new J(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},mQ=(e,t)=>{let[n=``,r=``]=bZ(()=>Br(e)),i=vZ(n),a=bM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=uQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=jX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Mj(s.fix)} (session=${i})`),lQ(t,i,c.value)},hQ=(e,t)=>{let[n=``,r=``,i=``]=bZ(()=>Br(e)),a=vZ(n),o=bM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!kj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${kj.join(` or `)}`);let s=uQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>qJ(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),lQ(t,a,{...s,marks:u})},gQ=(e,t)=>{let[n=``,...r]=bZ(()=>Br(e)),i=vZ(n),a=RZ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=IL(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=yU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},cQ(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},_Q=(e,t)=>{let[n=``,r=``]=bZ(()=>Br(e)),i=vZ(n),a=Object.values(t.configFor(RZ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=fZ(t.claudeInput,cQ(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},vQ=`config-override`,yQ=new Map([[hr,SZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=vZ(bZ(()=>decodeURIComponent(e.slice(0,n)))),i=bZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,vQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,vQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[gr,CZ],[pr,DZ],[mr,AZ],[br,WZ],[xr,GZ],[Er,QZ],[Sr,KZ],[Cr,YZ],[wr,XZ],[Tr,ZZ],[Dr,tQ],[Or,nQ],[kr,aQ],[Ar,rQ],[jr,iQ],[vr,wZ],[yr,TZ],[_r,EZ],[Mr,oQ],[Nr,fQ],[Pr,mQ],[Fr,hQ],[Ir,pQ],[Lr,gQ],[Rr,_Q]]),bQ=new Set([pr,mr,br,xr,Er,Sr,Cr,wr,Tr,Dr,Or,kr,Ar,jr,_r,Mr,Nr,Pr,Fr,Lr,Rr]),xQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Wr(Hr(e))){if(!i&&bQ.has(a)){let e=Br(o);e.length>0&&e[0]&&(i=e[0])}let e=yQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&zJ(t.sessionState,i,n.join(`
493
+ `),gO(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function SQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const CQ=new Map([...yQ,[fr,xQ]].map(([e,t])=>[e,SQ(t)]));Object.freeze([...CQ.keys()]);const wQ=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),TQ=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],EQ=[[`workspace.added_dirs`,`string-list`]];function DQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of TQ){let i=AQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=OQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of EQ){let i=AQ(n,e),a=i===void 0?r:kQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))wQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function OQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function kQ(e){return Array.isArray(e)&&e.every(e=>OQ(e)===`string`)?`string-list`:OQ(e)}function AQ(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function jQ(e,t){switch(e){case`vars`:return{what:e,vars:MQ(t)};case`segments`:return{what:e,segments:LQ(t)};case`config`:return{what:e,config:VQ(t)}}}function MQ(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=FQ(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=NQ(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:PQ(r.lastUpdatedMs())})}return o}function NQ(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function PQ(e){return e===null?null:Math.max(0,Date.now()-e)}function FQ(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,IQ(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,IQ(i));return t}function IQ(e){return e.kind}function LQ(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=zQ(n),o=RQ(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:BQ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function RQ(e){let t=new Map;for(let n of Fy(e.presets))for(let r of gg(Ry(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=fg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function zQ(e){let t=[],n=new Set;for(let r of gg(Oy(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function BQ(e,t,n){let r=new Set;for(let i of ob(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function VQ(e){return e===null?null:e.config}const HQ=[`vars`,`segments`,`config`];function UQ(e){return typeof e==`string`&&HQ.includes(e)}function WQ(e){return Math.max(1,e-2)}const GQ={moving:1e3/30,still:1e3},KQ=1e3;function qQ(e){return T_.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function JQ(e,t){e.push(t);let n=e.findIndex(e=>e>t-KQ);e.splice(0,n)}const YQ=e=>({resp:e,bytes:JSON.stringify(e)}),XQ=(e,t)=>w_[t].elsewhere===null?e.statusline:e.bar,ZQ=e=>Math.round(1e3/e);var QQ=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return j_;let n=this.deps.now()-KQ,r=this.shown(t);return A_(e=>{let i=t.rates.get(e);if(i===void 0)return O_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:ZQ(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=ZQ(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:YQ(t.resp),statusline:YQ(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||XQ(i,t).bytes!==XQ(r,t).bytes)&&JQ(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=XQ(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:RA(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function $Q(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const e$=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,t$=`#{session_id} #{client_control_mode} #{pane_id}`;function n$(e){let t=new Set;for(let n of e.split(`
494
+ `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function r$(e,t){let n=new Set;for(let r of e.split(`
495
+ `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function i$(e,t){let n=new Map;for(let t of e.split(`
496
+ `)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
497
+ `)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var a$=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${w(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:r$(t.stdout,n$(n.stdout)),status:i$(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!o$(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function o$(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const s$=`@cc-candybar-status-prior`,c$=`@cc-candybar-status-wrote`,l$=`@cc-candybar-binding-prior`,u$=[`-T`,`root`,`MouseDown1Status`],d$=Array.from({length:5},(e,t)=>t),f$=e=>`@cc-candybar-row-${e}`,p$=e=>`#[fill=terminal]#{${f$(e)}}`,m$=e=>`status-format[${e}]`;function h$(e){return e===0?`off`:e===1?`on`:String(e)}function g$(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function _$(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function v$(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function y$(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function b$(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function x$(e){return e.map(e=>e.map(b$).join(` `)).join(` ; `)}const S$=`ccb:separator`;function C$(e){return y$(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,S$],e]))}function w$(e,t){let n=e.split(`${S$}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const T$=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],E$=e=>[`show-options`,`-g`,`-q`,`-v`,e],D$=e=>[[`show-options`,`-t`,e],T$(e,`status`),...d$.map(t=>T$(e,m$(t)))];function O$(e){let[t=``,n=``,...r]=e,i=t.split(`
498
+ `).map(e=>e.split(` `)[0]??``),a={};for(let e of d$)i.includes(m$(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function k$(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,m$(Number(t)),v$(n)])]}const A$=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...D$(e),...d$.map(e=>E$(m$(e))),T$(e,s$),T$(e,c$)];function j$(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:g$(t)}catch(e){return{kind:`theirs`,why:`${s$} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function M$(e,t,n){let[r=``,...i]=t,a=O$(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return j$(s,c,n);let l=g$(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,p$(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,s$,JSON.stringify(f)],...k$(e,d)]}}const N$=e=>[...D$(e),T$(e,c$)];function P$(e,t,n){let r=O$(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(_$(r.formats,t.wrote))a.push(...k$(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,m$(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,v$(t.status)]):o.push(`status`)),a.push(...d$.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,f$(t)]),[`set-option`,`-q`,`-u`,`-t`,e,s$],[`set-option`,`-q`,`-u`,`-t`,e,c$]),{commands:a,kept:o}}const F$=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,I$=[[`list-keys`,`-T`,`root`]];function L$(e){let t=F$.exec(e);return t===null?null:{line:t[0],command:t[1]}}const R$=`cc-candybar://tmux-status-click/`,z$=e=>`${R$}${zr([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,B$=e=>e?.command.includes(R$)??!1;function V$(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,l$]};return B$(L$(t))?{steps:[e===null?{command:[`unbind-key`,...u$]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var H$=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),this.deps.defer(()=>{this.held.get(e)===a&&(a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=hH(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)}))})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[e,t]of this.servers){for(let[n,r]of[...t.layouts]){t.layouts.delete(n);let i=this.askSync(e,N$(n));if(i===null)continue;let a=P$(n,r.prior,i);this.writeSync(e,a.commands),this.saidRestored(e,n,a.kept)}let n=t.binding;if(t.binding={kind:`none`},n.kind===`ours`||n.kind===`adopted`){let t=this.askSync(e,I$);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let[t,n,r,...i]=Br(e);if(t===void 0||n===void 0||r===void 0||i.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let a=[...this.held.values()].find(e=>e.socket===t&&e.pane===`%${n}`)?.frame?.links[r];return a===void 0?{kind:`refused`,reason:`pane %${n}'s status line draws no link ${r} now`}:{kind:`link`,url:a}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${s$}}\t#{${c$}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
499
+ `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=j$(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[E$(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${l$} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,A$(n));if(r===null||this.closed)return null;let i=M$(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,f$(r),e])}),i!==n.status){let e=h$(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,c$,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,x$(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,N$(n));if(i===null)return;let a=P$(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,I$);if(r===null||this.closed)return;let i=L$(r[0]??``);if(n.kind===`none`&&B$(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&B$(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...u$,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${b$(`${this.deps.handler} ${z$(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,I$);if(r===null)return;let i=V$(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=V$(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,C$(t));return n.kind===`ok`?w$(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,C$(t)));return n.kind===`ok`?w$(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,y$(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,y$(t),n)))}};const U$=`CC_CANDYBAR_CONFIG`;function W$(e,t){return fz(t,e[U$])}const $=e=>({arity:e,keep:!0}),G$=e=>({arity:e,keep:!1}),K$={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":G$(`none`),"--background":G$(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":G$(`optional`),"-c":G$(`none`),"--continue":G$(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":G$(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":G$(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":G$(`none`),"--forward-subagent-text":$(`none`),"--from-pr":G$(`optional`),"-h":G$(`none`),"--help":G$(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":G$(`none`),"--print":G$(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":G$(`optional`),"--resume":G$(`optional`),"--safe-mode":$(`none`),"--session-id":G$(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":G$(`optional`),"--tmux":G$(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":G$(`none`),"--version":G$(`none`),"-w":G$(`optional`),"--worktree":G$(`optional`)},q$={resume:`--resume`,fresh:`--session-id`};function J$(e){return[q$[e.kind],e.sessionId]}const Y$=e=>e.startsWith(`-`)&&e!==`-`;function X$(e,t){let n=$$(t);return n===null?{dir:e??t,args:[]}:e!==null&&Z$(e,n.top)?{dir:e,args:[]}:{dir:e===null||$$(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const Z$=(e,t)=>e===t||e.startsWith(t+s.sep);function Q$(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!Y$(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=K$[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!Y$(e)):o.arity===`variadic`?e1(n.slice(r),e=>!Y$(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function $$(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function e1(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const t1=`candybar-band@cc-candybar`,n1=s.join(`bin`,`cc-candybar-native`),r1=`@cc-candybar-bar-pane`,i1=KM(`/reload-plugins`),a1=e=>({kind:`done`,said:e});function o1(e){let t=dZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const s1={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${w_.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,n1);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${t1} from ${r}`,finished:c1(e,r,n)}},off:()=>a1(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=o1(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${w_.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:d1(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>a1(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=o1(e),i=n.barPanes(r);return i.length>0?a1(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):a1(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=dZ(e.hints.tmux);if(r.kind===`refused`)return a1(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return a1(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>a1(`the daemon draws ${o1(e).pane}'s bar in its status line`),off:()=>a1(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function c1(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,t1],r);let i=fZ(n.claudeInput,e.hints.tmux,i1);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${t1} from ${t} and typed /reload-plugins into ${i.pane}`}const l1=new Set([ya,U$,...Mt]);function u1(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function d1(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${w_.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=g1(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${w_.statusline.label} off and on again`);let s=f1(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=Q$(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=u1(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>l1.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...J$(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=p1(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(X$(null,i.cwd),_))}let y=m(X$(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${m1[g.kind](e.sessionId)}, and its statusline follows lane B`}function f1(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function p1(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const m1={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},h1={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function g1(e){let t=oZ(e);return t.kind===`ready`?lZ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:sZ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:h1[t.kind]}const _1={switches:Object.fromEntries(T_.map(e=>[e,!1])),revision:0};var v1=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??_1;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of T_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),zJ(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=s1[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function y1(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function b1(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function x1(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function S1(e,t,n){let r=y1(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const C1=2e3;function w1(e,t,n){let r=pU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function T1(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function E1(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const D1=`#{pane_id} #{${r1}}`;function O1(e,t){return e.split(`
500
+ `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const k1=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function A1(e,t,n){for(let r of iY(rY(e),t)){if(r.command.split(` `).some(e=>k1.test(e)))return!0;if(r.pid===n)return!1}return!1}const j1=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
501
+ `);async function M1(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=T1(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,j1,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function N1(e,t){return T1(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function P1(e){let t=await mU(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await N1(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function F1(e){let{panePid:t,cwd:n,foreground:r}=await P1(e),i=await N1(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await M1(r),o=rY(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:A1(i,r,t)}}function I1(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function L1(e){return{claudeInput:_Z(),barPanes:e=>O1(w1(e,[`list-panes`,`-a`,`-F`,D1]),e.pane),openBarPane:(e,t,n)=>{let r=w1(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return w1(e,[`set-option`,`-p`,`-t`,r,r1,e.pane]),r},closePane:(e,t)=>void w1(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void T1(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:I1(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:Kz,paneClaude:F1,paneDir:async(e,t)=>{let n=Date.now()+C1;for(;;){let r=await P1(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${C1/1e3} s`);await ge(100)}},launcherNode:e=>S1(e,e=>b1(e,p.constants.X_OK),x1),onPath:(e,t)=>{let n=y1(e,t,e=>b1(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?E1(r.stdout):null;return i===null?(T1(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void w1(e,hZ(e.pane,`cc-candybar-lane`,[]),t)}}function R1(e,t){return T_.filter(n=>e[n]&&w_[n].elsewhere!==null&&t.has(n))}function z1(e,t){let n=`the bar is drawn in ${t.map(e=>w_[e].elsewhere).join(` and `)}`,r=Vr([{verb:Er,args:[e,...t.map(e=>w_[e].setting)]}]);return{channels:[{severity:ty,message:n,lines:[[ny(n,Vr([{verb:hr,args:[n]}])),ny(`[⟲ draw it here]`,r)]]}]}}const B1={order:-1/0,text:null,failure:null};var V1=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??B1;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??B1;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function H1(e,t){for(let n of Object.entries(t))e.push(n)}const U1={ok:`info`,"bad-request":`warn`,threw:`error`};function W1(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function G1(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...W1(t)];return{level:U1[t.kind],line:`render${r.map(([e,t])=>` ${e}=${SM(t)}`).join(``)}`}}const K1=new nq,q1=new KX,J1=new aj,Y1=i(import.meta.url),X1=nX(gt());st(K1.launchStats);const Z1=new iO({counters:K1,logger:M}),Q1=MU({watchers:Z1,logger:M}),{gitProvider:$1,usageStore:e0,mementoProvider:t0}=Q1,n0=new aq,r0=new mJ(n0,M),i0=new LJ,a0=new Lv,o0=[t.execPath,...t.execArgv],s0=new v1({edge:L1(e=>l0.following(e)),host:{bundle:Y1,node:o0,socket:vt(),preload:$a(Y1)},state:n0,log:M,now:()=>gO(new Date),defer:e=>void pe(e)}),c0=new H$({edge:{run:(e,t,n)=>mU({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>pU({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>l0.subscribe(e,t),sessionInPane:(e,t)=>l0.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${je(vt())}`,...[...o0,Y1].map(je),`url-handle`].join(` `),owner:vt(),defer:e=>void pe(e),log:M}),l0=new QQ({render:(e,t)=>X0(e,t),watch:(e,t)=>(0,bb.reaction)(()=>n0.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>Q0(e),shown:e=>u0.shown(e.hints.tmux),watching:()=>u0.follow(),periods:GQ,now:()=>performance.now(),log:M}),u0=new a$({listPanes:e=>mU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,e$]),listClients:e=>mU({socket:e},`frames.visibility`,[`list-clients`,`-F`,t$]),sockets:()=>new Set(l0.watched().flatMap(({req:e})=>d0(e))),onAnswer:(e,t)=>c0.answered(e,t),onChange:e=>l0.wakeWhere(t=>d0(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function d0({hints:{tmux:e}}){return e==null?[]:[e.socket]}const f0=new V1(At()),p0=new eq({gitService:$1,sessionState:n0,watchers:Z1,log:M},{budgetBytes:()=>(E0(),WK(y0)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),m0=60*1e3,h0=qV({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:m0,stat:p.statSync,exit:()=>j0(0),log:M}),g0=WV({entryUrl:import.meta.url,intervalMs:m0,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>h0.checkNow(),log:M});let _0=null,v0=null,y0=0;function b0(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),j0(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),j0(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),j0(0)});try{D0(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),j0(1);return}_0=Oo(t.pid);let e=Ro(Bo(_0));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),j0(1);return}v0=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),n0.useStorage(new sq(wt(),500,M)),r0.useStorage(FJ(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),j0(0)}}),x0(E.createServer({allowHalfOpen:!1},e=>{M0(e)}),vt(),!1)}function x0(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),j0(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}S0(e,n)}),e.listen(n,()=>C0(n))}function S0(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),j0(1);return}}x0(e,n,!0)}function C0(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),j0(0);return}O0(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(y0)}MB`),tr();let r=f0.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),h0.arm(),g0.arm(),E0().arm(),w0(e,n.identity)}function w0(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>j0(e),log:M}).arm()}let T0=null;function E0(){if(T0===null)throw Error(`daemon: limits not yet established`);return T0}function D0(e){y0=Pn(e),T0=Bn(Kn(K1.startedAt.getTime(),e=>j0(e),{limitBytes:y0}))}function O0(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:_0});n!==null&&M(`warn`,`lease write failed: ${n}`)}let k0=0,A0=!1;function j0(e){if(!A0){A0=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{c0.restoreAll(),$1.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{e0.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{Z1.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{n0.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),v0!==null&&zo(v0,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function M0(e){k0++,K1.inFlight=k0;let t=!1,n=!0,r=()=>{n&&(n=!1,k0=Math.max(0,k0-1),K1.inFlight=k0)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>j0(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,K1.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,N0)},200),s=$t(e=>{B0(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(L0(e),null,N0)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,N0)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=$Q(e),c=l0.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(gH[i](e,t))),refused:t=>e.end(Zt(t)),drawing:()=>!0});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const N0=()=>{},P0=e=>({resp:e,exitAfterFlush:null,delivered:N0}),F0=e=>({kind:`reply`,...e}),I0={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},L0=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),R0=(e,t)=>F0(P0({ok:!1,error:t,code:e,daemonV:3}));function z0(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return R0(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return R0(`VERSION_MISMATCH`,`this client's subscribe names no lane (${T_.join(`, `)}): it predates the lane toggles — update it`);let t=M_(e.lane);return t===null?R0(`BAD_REQUEST`,`subscribe needs a lane, one of ${T_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function B0(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?R0(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?z0(e):typeof e.kind!=`string`||!Object.hasOwn(I0,e.kind)?R0(`BAD_REQUEST`,`unknown kind`):F0(await V0(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:N0})}async function V0(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:N0};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return P0(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:l0.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return P0({ok:!0,stats:K1.snapshot({gitCache:$1.getStats(),usageCache:e0.getStats(),transcriptReads:ua(),renderCache:p0.stats,effectCache:a0.getStats(),sessionState:{sessions:n0.size(),observers:n0.observers(),revision:n0.latestRevision()},frameFeeds:l0.getStats(),tmuxStatus:c0.stats(),watchersActive:Z1.size(),nextRestartReason:E0().describeNextRestart(),handlerProbes:q1.list(),clients:J1.list(gO(new Date)),bundle:Y1,daemon:E0().serving(),doctorStores:rX(X1)})});if(e.kind===`render`){let n=new Date,r=gO(n),i=n.getTime(),a=[],o=++K1.requestsTotal,s=$0(e),c=(e,t)=>J1.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:tj(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),l0.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await a2(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?N0:()=>BJ(n0,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:L0(e),delivered:N0})):e2(s.problems);l.outcome.kind!==`ok`&&K1.requestsErrored++,H1(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=G1(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return P0(J0(e.verb,e.value,{via:`link`,handler:Xt(e.clientVersion)}));if(e.kind===`debug`){if(!UQ(e.what))return P0({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${HQ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=p0.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?K0(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??nv(`colorCompatibility`)):G0};return P0({ok:!0,debug:jQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function H0(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:fz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const U0={sessionState:n0,dlog:M,applyUpdate:()=>g0.act(),doctor:pX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];p0.reload(...t);let n=p0.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:X1,probes:q1,clients:J1,bundle:Y1,serving:()=>E0().serving(),memento:t0,claudeInput:_Z(),history:r0,navigation:i0,configFor:e=>p0.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>p0.reload(e.projectDir,e.cwd,e.configFile??void 0)};U0.reloadConfig;const W0={endcaps:nv(`endcaps`),colorCompatibility:nv(`colorCompatibility`),wrap:nv(`autoWrap`),padding:nv(`padding`),width:1/0},G0=new Map;function K0(e,t){let n=new Map;for(let[r,i]of e)n.set(r,Xv(i,{...W0,colorCompatibility:t}));return n}const q0={...Q1,history:e=>r0.depth(e),feeds:e=>l0.feedsOf(e)};function J0(e,t,n){if(e===`tmux-status-click`)return Y0(t);let r=CQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...U0,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function Y0(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=c0.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=fo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):J0(e.verb,e.value,{via:`tmux-status`})}let i=ut({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}async function X0(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await t2(e,gO(n),r,{by:`feed`,fps:t}),s=f0.linkFor(e.hookData.session_id,r2(i)),c=e.hookData.session_id,l=n2(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:o2(c,i,s,l,R1(o,l0.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=G1(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=L0(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function Z0(e,t){return BB(t.config,t=>n0.get(e,t),e=>t.authoredRoots.has(e))}function Q0(e){try{var t=na();let n=e.hookData.session_id,r=FZ(e.requested,n0,n);return RB(Z0(n,t.u(p0.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function $0(e){let{report:t}=DQ(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=H0(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:ej(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const e2=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:N0});async function t2(e,t,n,r){try{var i=na();H1(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);H1(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=FZ(e.requested,n0,a),{entry:u,state:d}=i.u(p0.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=WQ(f??120),m=Zv(o.termRows);H1(n,{width:String(p)});let h=t=>n0.get(e.hookData.session_id,t),g=Z0(a,d),_=RB(g);H1(n,{lanes:T_.filter(e=>_[e]).join(`,`)||`-`}),s0.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:QA(e.hookData)},_,r0.revision(a)),c0.observe(a,o.tmux,_.tmuxStatus);let v=await aW(e.hookData,t,{...q0,navigation:e=>i0.depth(e,n0,SV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...lV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});H1(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:HU(v.git),feeds:qQ(v.feeds)});let y=[],b=zU(g,p),ee=a0.of(a),x=jK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=HJ(n0,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
502
+ `),re=g0.notice({sessionId:a,dismissed:n0.get(a,OV),enabled:g.updateNotice}),ie=u.lastError===null?null:u.failedFile,ae=[...u.lastWarning===null?[]:[{kind:`load`,message:u.lastWarning}],...y],w=ry(C,re,ae.map(e=>e.message).join(`
503
+ `)),T=$1.getStats(),oe=e0.getStats(),E=ee.lastFrame(),se=E.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ce=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,le=ae.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return H1(n,{git:`${T.size}/${T.hits}h/${T.misses}m`,usage:`${oe.size}/${oe.hits}h/${oe.misses}m`,effect:E.effect,effectT:E.t.toFixed(3),effectRows:`${E.made}made/${E.reused}reused`,effectOwn:se,fadeBasis:E.basis,stateRev:String(E.revision),fades:ce(E.fades),leaves:ce(E.leaves),motion:x.motion,err:C?`Y`:`N`,clickError:S.kind===`none`?`-`:S.kind,upd:String(re.length),warn:le}),{drawn:{body:x.text,diagnostics:w,failedConfigFile:ie,geometry:{width:p,rowCap:m,colorCompatibility:g.colorCompatibility}},motion:x.motion,clickShown:te,lanes:_}}catch(e){i.e=e}finally{i.d()}}function n2(e,t){return oy(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
504
+ `}function r2(e){return e.diagnostics===null?null:ay(e.diagnostics)}function i2(e){let t=e.hookData.session_id,{client:n,...r}=e.hints,i=JSON.stringify(r);n0.get(t,`client-hints`)!==i&&n0.set(t,sQ,i);let a=IZ(e.requested);n0.get(t,`render-origin`)!==a&&n0.set(t,PZ,a)}async function a2(e,t,n,r){i2(e);let{drawn:i,motion:a,clickShown:o,lanes:s}=await t2(e,n,r,E_),{link:c,failure:l}=f0.sync(e.hookData.session_id,t,r2(i));H1(r,{dumpFailed:l===null?`-`:JSON.stringify(l)});let u=n2(i,c),d=e.hookData.session_id,f=R1(s,l0.following(d)),p=o2(d,i,c,u,f),m=ij(e.hints.client??null)===`statusline`;return H1(r,{handoff:(m?f:[]).join(`,`)||`-`}),{answer:m?p:u,motion:a,clickShown:o}}function o2(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:n2({...t,body:sy(z1(e,[a,...o]),t.geometry)},n)}const s2={connectMs:200,budgetMs:500};async function c2(e,n){let r=n.includes(`--json`),i=await l2(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${ln(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
505
+ `);return}t.stdout.write(u2(i.value))}function l2(e){return nn({kind:`debug`,what:e},s2,e=>`debug`in e?e.debug:void 0)}function u2(e){switch(e.what){case`vars`:return d2(e.vars);case`segments`:return f2(e.segments);case`config`:return p2(e.config);default:return e}}function d2(e){if(e.length===0)return`no variables (DSL not active)
506
+ `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${h2(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${m2(a.value)}${e}${o}`)}return t.join(`
502
507
  `)+`
503
- `}function g0(e){if(e.length===0)return`no segments (DSL not active)
508
+ `}function f2(e){if(e.length===0)return`no segments (DSL not active)
504
509
  `;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
505
510
  `)+`
506
- `}function _0(e){return e===null?`config: DSL not active
511
+ `}function p2(e){return e===null?`config: DSL not active
507
512
  `:JSON.stringify(e,null,2)+`
508
- `}function v0(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function y0(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function b0(){let e=S0();return e===null?null:p.readFileSync(e,`utf-8`)}function x0(){let e;try{e=b0()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function S0(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const C0=5e3;function w0(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:eN(4e5,1e6),...AU(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:pv(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:OU(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function T0(e,t){let n=Xz(e,e),r=$z(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function E0(e,n=t.cwd()){let r=[],i=fz(n,e)??null,a=i===null?T0(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=tB(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await k0(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Vg&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Vg||e instanceof Error?e.message:String(e),warnings:r})}}async function D0(e,t,n){let r=lB(e,MB,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new NK,o=new BO(a,i.globals.default_empty_value??``,void 0,new YK);try{let s=sK(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(C0);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${C0} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function O0({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:bK(t,n,r,i,w0(a,e.at(-1)??null,s),s,kU(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}}},a),failures:c,advisories:l}}async function k0(e,t,n){let r=await D0(e,t,n),{config:i}=r,a=gO(new Date);try{let e=UV();try{SV(i),PF(i)}finally{e()}let t=Iy(null,i.globals.preset,i.presets),o=(e,t)=>{let n=BB(i,t=>t===`preset`?e:null,()=>t),o;try{o=O0(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Fy(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
513
+ `}function m2(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function h2(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function g2(){let e=v2();return e===null?null:p.readFileSync(e,`utf-8`)}function _2(){let e;try{e=g2()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function v2(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const y2=5e3;function b2(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:eN(4e5,1e6),...BU(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:pv(()=>!0),themeDefault:{differs:!0,theme:`<theme>`},resumeCommand:RU(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function x2(e,t){let n=Xz(e,e),r=$z(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function S2(e,n=t.cwd()){let r=[],i=fz(n,e)??null,a=i===null?x2(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=tB(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await T2(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Vg&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Vg||e instanceof Error?e.message:String(e),warnings:r})}}async function C2(e,t,n){let r=lB(e,MB,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new UK,o=new BO(a,i.globals.default_empty_value??``,void 0,new aq);try{let s=_K(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(y2);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${y2} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function w2({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:AK(t,n,r,i,b2(a,e.at(-1)??null,s),s,zU(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}}},a),failures:c,advisories:l}}async function T2(e,t,n){let r=await C2(e,t,n),{config:i}=r,a=gO(new Date);try{let e=UV();try{SV(i),PF(i)}finally{e()}let t=Iy(null,i.globals.preset,i.presets),o=(e,t)=>{let n=BB(i,t=>t===`preset`?e:null,()=>t),o;try{o=w2(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Fy(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
509
514
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
510
- `));return d}finally{r.registry.dispose()}}function A0(e){return e.map(e=>`warning: ${e}\n`).join(``)}function j0(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:A0(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:A0(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const M0=`--render`,N0=`Usage: cc-candybar check [${M0}] [config-file]\n`;function P0(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==M0);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${N0}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${N0}`}:{kind:`run`,target:n[0],render:t.includes(M0)}}async function F0(e){let n=P0(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:j0(await E0(n.target??ZQ(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const I0=/^[a-z][a-z0-9+.-]*:\/\//i,L0=/^[^@\s/]+@[^:\s/]+:/,R0=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function z0(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function B0(e,t,n){let r=dz(t,e);if(n(r))return{kind:`path`,dir:r};if(I0.test(e)||L0.test(e))return{kind:`git`,url:e,shown:z0(e)};let i=R0.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function V0(e,t){let n=s.join(e,Vz),r=Wz(n);if(`error`in r)throw Error(`${t}: could not list ${Vz}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${Vz}/<name>/${hz}`);return r.folders.map(e=>s.join(n,e,hz))}function H0(e,t,n){let r=(n,...r)=>{let i=ut({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
511
- `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${Vz}/`)}function U0(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return H0(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function W0(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function G0(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,hz),s.join(t,hz));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function K0(e,t,n){let r=V0(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,hz))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=sB(a.map(e=>s.join(e,hz)),MB,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(Vz,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,Vz))}`).join(`
512
- `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:W0(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)G0(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,hz),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function q0(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=B0(n,process.cwd(),MO);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=U0(i,t=>K0(t,Bz(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function J0(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const Y0=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function X0(e,t,n){return{termCols:J0(e.COLUMNS,n.columns),termRows:J0(e.LINES,n.rows),ssh:Y0.some(t=>(e[t]??``)!==``),tmux:GA(e),configEnv:ZQ(e,t),claudeConfigDir:ba(e,t),mementoEnv:Nt(e,t),terminalEnv:Ft(e)}}function Z0(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function Q0(e){let t=TX(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=Z0(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:tn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const $0=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},e2=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`)};function t2(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function n2(e){let t=TX(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=t2(n?.postMortems,e=>Array.isArray(e)&&e.every($0)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&e2(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function r2(e,t,n){let r=TX(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=Z0(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const i2=e=>rj.includes(e.role),a2=e=>r2(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&$A.includes(e.rateLimits),`the rate-limit windows they carried`),o2=e=>r2(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),s2=e=>r2(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&typeof e.since==`number`&&Array.isArray(e.redrawn)&&e.redrawn.length>0&&e.redrawn.every(Number.isInteger)&&i2(e)&&nj.includes(e.frame),`what they drew, when, and from which project`),c2=e=>r2(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&i2(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function l2(e,t,n){let r=e.doctorStores?.[t],i=t2(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function u2(e){let t=TX(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:l2(e,`marks`,IJ),clicked:l2(e,`clicked`,zJ),postMortemsRead:l2(e,`postMortemsRead`,VY)}}async function d2(){let e=await wX();if(e.kind!==`ok`){let t={kind:`failed`,reason:ln(e).split(`
513
- `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:Q0(e.value),rateLimits:a2(e.value),transcripts:o2(e.value),frames:s2(e.value),widths:c2(e.value),serving:n2(e.value),stores:u2(e.value)}}const f2=` (fix: click the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,p2=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor`;function m2({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:f2}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${p2}\n`)}function h2(e){let t={sessionState:new YK},n=HK(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??UK(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function g2(e,t,n){return n.kind===`failed`?n:GY(e,n.value.bundle,WJ(t,n.value.clients).map(({client:e})=>e))}function _2(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:WJ(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function v2(e,t){return t.kind===`failed`?t:{kind:`ok`,value:WJ(e,t.value).map(e=>e.transcript)}}function y2(e,t){return t.kind===`failed`?t:{kind:`ok`,value:KJ(e,t.value)}}function b2(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:yX(e.sessionId,WJ(e,t.value))}async function x2(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=X0(r,i,a()),u=UJ(r.CLAUDE_CODE_SESSION_ID);s={...bX(e,l,{projectDir:GJ(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:fz(i,o)??ZQ(r,i)??null},()=>null,c.serving,_2(u,c.rateLimits,xa(l.claudeConfigDir)),v2(u,c.transcripts),u,y2(u,c.frames),b2(u,c.widths,l.termCols??null),c.stores),urlHandler:await VX(t),install:g2(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=yM(s);return{stdout:c.map(m2).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function S2(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new _e(e),{columns:r}=n;return n.destroy(),{columns:r}}async function C2(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
515
+ `));return d}finally{r.registry.dispose()}}function E2(e){return e.map(e=>`warning: ${e}\n`).join(``)}function D2(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:E2(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:E2(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const O2=`--render`,k2=`Usage: cc-candybar check [${O2}] [config-file]\n`;function A2(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==O2);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${k2}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${k2}`}:{kind:`run`,target:n[0],render:t.includes(O2)}}async function j2(e){let n=A2(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:D2(await S2(n.target??W$(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const M2=/^[a-z][a-z0-9+.-]*:\/\//i,N2=/^[^@\s/]+@[^:\s/]+:/,P2=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function F2(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function I2(e,t,n){let r=dz(t,e);if(n(r))return{kind:`path`,dir:r};if(M2.test(e)||N2.test(e))return{kind:`git`,url:e,shown:F2(e)};let i=P2.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function L2(e,t){let n=s.join(e,Vz),r=Wz(n);if(`error`in r)throw Error(`${t}: could not list ${Vz}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${Vz}/<name>/${hz}`);return r.folders.map(e=>s.join(n,e,hz))}function R2(e,t,n){let r=(n,...r)=>{let i=ut({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
516
+ `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${Vz}/`)}function z2(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return R2(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function B2(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function V2(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,hz),s.join(t,hz));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function H2(e,t,n){let r=L2(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,hz))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=sB(a.map(e=>s.join(e,hz)),MB,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(Vz,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,Vz))}`).join(`
517
+ `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:B2(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)V2(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,hz),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function U2(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=I2(n,process.cwd(),MO);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=z2(i,t=>H2(t,Bz(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function W2(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const G2=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function K2(e,t,n){return{termCols:W2(e.COLUMNS,n.columns),termRows:W2(e.LINES,n.rows),ssh:G2.some(t=>(e[t]??``)!==``),tmux:GA(e),configEnv:W$(e,t),claudeConfigDir:ba(e,t),mementoEnv:Nt(e,t),terminalEnv:Ft(e)}}function q2(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function J2(e){let t=FX(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=q2(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:tn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const Y2=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},X2=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`)};function Z2(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function Q2(e){let t=FX(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=Z2(n?.postMortems,e=>Array.isArray(e)&&e.every(Y2)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&X2(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function $2(e,t,n){let r=FX(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=q2(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const e4=e=>rj.includes(e.role),t4=e=>$2(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&$A.includes(e.rateLimits),`the rate-limit windows they carried`),n4=e=>$2(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),r4=e=>$2(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&typeof e.since==`number`&&Array.isArray(e.redrawn)&&e.redrawn.length>0&&e.redrawn.every(Number.isInteger)&&e4(e)&&nj.includes(e.frame),`what they drew, when, and from which project`),i4=e=>$2(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&e4(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function a4(e,t,n){let r=e.doctorStores?.[t],i=Z2(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function o4(e){let t=FX(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:a4(e,`marks`,KJ),clicked:a4(e,`clicked`,YJ),postMortemsRead:a4(e,`postMortemsRead`,ZY)}}async function s4(){let e=await PX();if(e.kind!==`ok`){let t={kind:`failed`,reason:ln(e).split(`
518
+ `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:J2(e.value),rateLimits:t4(e.value),transcripts:n4(e.value),frames:r4(e.value),widths:i4(e.value),serving:Q2(e.value),stores:o4(e.value)}}const c4=` (fix: click the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,l4=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor`;function u4({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:c4}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${l4}\n`)}function d4(e){let t={sessionState:new aq},n=QK(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??$K(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function f4(e,t,n){return n.kind===`failed`?n:tX(e,n.value.bundle,eY(t,n.value.clients).map(({client:e})=>e))}function p4(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:eY(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function m4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:eY(e,t.value).map(e=>e.transcript)}}function h4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:nY(e,t.value)}}function g4(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:kX(e.sessionId,eY(e,t.value))}async function _4(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=K2(r,i,a()),u=$J(r.CLAUDE_CODE_SESSION_ID);s={...AX(e,l,{projectDir:tY(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:fz(i,o)??W$(r,i)??null},()=>null,c.serving,p4(u,c.rateLimits,xa(l.claudeConfigDir)),m4(u,c.transcripts),u,h4(u,c.frames),g4(u,c.widths,l.termCols??null),c.stores),urlHandler:await ZX(t),install:f4(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=yM(s);return{stdout:c.map(u4).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function v4(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new _e(e),{columns:r}=n;return n.destroy(),{columns:r}}async function y4(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
514
519
  Usage: cc-candybar doctor [config-file]
515
- `),t.exit(2));let n=t.cwd(),r=await x2(rX(h2),GX(),d2,t.env,n,S2,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function w2(e){return!e.ok&&e.code!==`RENDER_FAILED`}function T2(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=E.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Zt(c))),s.on(`data`,$t(e=>{let t=e;w2(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function E2(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function D2(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function O2(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=T2(e,t,n,e=>{s=E2(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=D2(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&qn();let e=s;s=E2(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function k2(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function A2(e,n){let{values:r,tokens:i}=T({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=M_(r.lane);c===null&&(s(`--lane needs one of ${T_.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=UQ(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{k2(p,e)&&t(),p=e},h=async e=>{let r=await mn(e,a,o,{...X0(t.env,o,t.stderr),client:Lt(`frames`,n)});r.kind!==`ok`&&(s(ln(r)),r.kind===`transient`&&qn())},g=e=>{f?.close(),f=O2(vt(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of ve({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function j2(e){let t=e.replace(/\n+$/,``).split(`
516
- `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const M2=5e3,N2=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function P2(e,t,n,r){let i=e.split(`
517
- `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?qQ(e,KQ(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function F2(e,t){let[n,r]=await Promise.all([iU(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,WQ]),iU(e,`bar-pane.tmux`,[`list-clients`,`-F`,GQ])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:P2(n.stdout,r.stdout,t,e.pane)}:r:n}function I2(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>M2)throw Error(`tmux has not answered for ${M2/1e3} s: ${t.reason}`)}}function L2(e){let{positionals:t}=(()=>{try{return T({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${N2}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(N2);return{pane:n}}async function R2(e){try{return await z2(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function z2(e){let{pane:n}=L2(e),r=GA(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await F2(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=I2(),f=async()=>{if(a.kind!==`shown`)return;let e=j2(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await iU(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:O2(vt(),e,`pane`,{frame:e=>n(ZV(pn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=I2();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await hn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${vt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(qn(),u=``),c=ln(e))}h(),await ge(500);let e=await F2(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const B2=i(import.meta.url),V2=e=>e.some(e=>t.argv.includes(e));function H2(){console.log(HA);let e=$a(B2),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${w_.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Re(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const U2={install:async e=>{await go(e,B2),t.exit(0)},"install-url-handler":async()=>{uo(B2),t.exit(0)},"url-handle":async e=>{await po(e[0])},daemon:async()=>{T1()},"daemon-stats":async e=>{await CX(e),t.exit(0)},frames:async()=>{await A2(t.argv,B2)},check:async e=>{await F0(e)},lint:async e=>{await F0(e)},plugin:async e=>{t.exit(q0(e))},schema:async()=>{x0()},doctor:async e=>{await C2(e)},"bar-pane":async e=>{t.exit(await R2(e))},...Object.fromEntries(MQ.map(e=>[e,async n=>{await f0(e,n),t.exit(0)}]))};async function W2(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(U2,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),V2(OA.help)&&(H2(),t.exit(0)),V2(OA.version)&&(console.log(`cc-candybar ${qe}`),t.exit(0)),n!==null){await U2[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
520
+ `),t.exit(2));let n=t.cwd(),r=await _4(pX(d4),tZ(),s4,t.env,n,v4,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function b4(e){return!e.ok&&e.code!==`RENDER_FAILED`}function x4(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=E.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Zt(c))),s.on(`data`,$t(e=>{let t=e;b4(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function S4(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function C4(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function w4(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=x4(e,t,n,e=>{s=S4(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=C4(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&qn();let e=s;s=S4(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function T4(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function E4(e,n){let{values:r,tokens:i}=T({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=M_(r.lane);c===null&&(s(`--lane needs one of ${T_.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=$Q(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{T4(p,e)&&t(),p=e},h=async e=>{let r=await mn(e,a,o,{...K2(t.env,o,t.stderr),client:Lt(`frames`,n)});r.kind!==`ok`&&(s(ln(r)),r.kind===`transient`&&qn())},g=e=>{f?.close(),f=w4(vt(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of ve({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function D4(e){let t=e.replace(/\n+$/,``).split(`
521
+ `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const O4=5e3,k4=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function A4(e,t,n,r){let i=e.split(`
522
+ `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?r$(e,n$(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function j4(e,t){let[n,r]=await Promise.all([mU(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,e$]),mU(e,`bar-pane.tmux`,[`list-clients`,`-F`,t$])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:A4(n.stdout,r.stdout,t,e.pane)}:r:n}function M4(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>O4)throw Error(`tmux has not answered for ${O4/1e3} s: ${t.reason}`)}}function N4(e){let{positionals:t}=(()=>{try{return T({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${k4}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(k4);return{pane:n}}async function P4(e){try{return await F4(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function F4(e){let{pane:n}=N4(e),r=GA(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await j4(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=M4(),f=async()=>{if(a.kind!==`shown`)return;let e=D4(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await mU(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:w4(vt(),e,`pane`,{frame:e=>n(ZV(pn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=M4();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await hn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${vt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(qn(),u=``),c=ln(e))}h(),await ge(500);let e=await j4(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const I4=i(import.meta.url),L4=e=>e.some(e=>t.argv.includes(e));function R4(){console.log(HA);let e=$a(I4),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${w_.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Re(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const z4={install:async e=>{await go(e,I4),t.exit(0)},"install-url-handler":async()=>{uo(I4),t.exit(0)},"url-handle":async e=>{await po(e[0])},daemon:async()=>{b0()},"daemon-stats":async e=>{await NX(e),t.exit(0)},frames:async()=>{await E4(t.argv,I4)},check:async e=>{await j2(e)},lint:async e=>{await j2(e)},plugin:async e=>{t.exit(U2(e))},schema:async()=>{_2()},doctor:async e=>{await y4(e)},"bar-pane":async e=>{t.exit(await P4(e))},...Object.fromEntries(HQ.map(e=>[e,async n=>{await c2(e,n),t.exit(0)}]))};async function B4(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(z4,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),L4(OA.help)&&(R4(),t.exit(0)),L4(OA.version)&&(console.log(`cc-candybar ${qe}`),t.exit(0)),n!==null){await z4[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
518
523
 
519
524
  cc-candybar is designed to be used as a Claude Code statusLine command.
520
525
  It reads hook data from stdin and outputs formatted statusline.
@@ -530,4 +535,4 @@ Add to ~/.claude/settings.json:
530
535
  Run with --help for more options.
531
536
 
532
537
  To test output manually:
533
- echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),H2(),t.exit(1));let i=ZV(await mn(r,t.argv.slice(1),t.cwd(),{...X0(t.env,t.cwd(),t.stderr),client:Lt(`node`,B2)}));i.debug!==null&&D(i.debug),i.kick&&qn(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}W2();export{};
538
+ echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),R4(),t.exit(1));let i=ZV(await mn(r,t.argv.slice(1),t.cwd(),{...K2(t.env,t.cwd(),t.stderr),client:Lt(`node`,I4)}));i.debug!==null&&D(i.debug),i.kick&&qn(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}B4();export{};