@promptctl/cc-candybar 1.160.0 → 1.160.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +2 -2
  2. package/package.json +5 -5
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){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()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(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 qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.160.0`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`e839d098ff514ef8fd321458c6dac850d41f33a2a8d5a249449641fdecf883aa`}function tt(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 nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.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 st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(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 ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(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),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(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:rt(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 D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.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:rt(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 ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(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 gt(e,t,n){let r=_t(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 _t(e){let t=e;for(let e=0;e<O;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 ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(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 Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){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 jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(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 Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
2
+ import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){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()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(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 qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.160.1`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`02e47226abacdb511c7bc66b0644d006eea91337dc00db167833eb5e2d8fd0b1`}function tt(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 nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.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 st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(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 ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(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),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(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:rt(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 D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.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:rt(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 ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(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 gt(e,t,n){let r=_t(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 _t(e){let t=e;for(let e=0;e<O;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 ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(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 Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){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 jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(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 Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
3
3
  `)}function k(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=It.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 Kt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function qt(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 Jt=1e4;function Yt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Jt?Jt:t}function Xt(e){return typeof e==`boolean`?e:void 0}function Zt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var A=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Qt(e){return $t(JSON.stringify(e))}function $t(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function en(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 A(`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 A(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function tn(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=en(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(Qt(t))})}function nn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Kt(n);return Rt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function rn(e,t,n){let r=null;try{r=await ln(St(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await tn(r,{v:3,...a},i);return sn(a.kind,o,n)}catch(e){return cn(e)}finally{r&&r.destroy()}}function an(e,t){return typeof e==`string`?e:t}function on(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function sn(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=an(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:on(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 cn(e){if(e instanceof A||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 ln(e,t){return new Promise((n,r)=>{let i=ue.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function un(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 dn={connectMs:50,budgetMs:150},fn={connectMs:50,budgetMs:200};function pn(e){let t=e.output;return typeof t==`string`?t:void 0}function mn(e){return sn(`render`,e,pn)}function hn(e,t,n,r){return rn(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),dn,pn)}function gn(e,t){return rn(()=>({kind:`pane-session`,socket:e,pane:t}),fn,e=>`paneSession`in e?e.paneSession:void 0)}function _n(e,t){return rn(()=>({kind:`click`,verb:e,value:t,clientVersion:Ze}),fn,pn)}let vn=null;function yn(){if(vn!==null){try{p.closeSync(vn.fd)}catch{}vn=null}}async function bn(e){let t=await p.promises.stat(e).catch(()=>null);if(vn!==null&&vn.path===e&&t!==null&&vn.id===xn(t))return{held:vn,size:t.size};yn(),await p.promises.mkdir(s.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>p.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>p.fstat(n,(n,r)=>n===null?e(r):t(n)));return vn={path:e,fd:n,id:xn(r)},{held:vn,size:r.size}}function xn(e){return`${e.dev}:${e.ino}`}function Sn(e,t){return new Promise((n,r)=>p.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function Cn(e){for(let t=2;t>=1;t--)await p.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await p.promises.rename(e,`${e}.1`).catch(()=>{})}let wn=[],Tn=0,En=0,Dn=0,j=null,On=!1;const kn=[];let An=!1,jn=!1;function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;if(jn||(jn=!0,process.on(`exit`,()=>{An=!0,Rn(!0,In)})),wn.push(n),Tn+=Buffer.byteLength(n),Tn>4194304){let e=0;for(;Tn>4194304/2&&e<wn.length-1;){let t=Buffer.byteLength(wn[e]);Tn-=t,Dn+=t,e++}wn.splice(0,e),En+=e}An?Rn(!0,In):On||Nn()}function Mn(){Rn(!1,Ln)}async function Nn(){On=!0;try{for(;wn.length>0;){let e=Pn();j={bytes:Buffer.from(e),state:{kind:`taken`}};try{await Fn(Ft(),j)}catch(t){yn(),j.state.kind!==`landed`&&Bn(e,t)}finally{j=null}}}finally{On=!1;for(let e of kn.splice(0))e()}}function Pn(){let e=(En===0?``:`${new Date().toISOString()} [warn] log: ${En} earlier line(s) dropped (${Dn} bytes): more than 4194304 bytes were waiting for the disk\n`)+wn.join(``);return wn=[],Tn=0,En=0,Dn=0,e}async function Fn(e,t){let{held:n,size:r}=await bn(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await Sn(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){yn();let e=await p.promises.stat(n.path).catch(()=>null);e!==null&&xn(e)===n.id&&await Cn(n.path)}}const In=1e3,Ln=2e3;function Rn(e,t){let n=j,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=zn(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Bn(n.bytes.toString(),t)}}if(r.length===0&&wn.length===0)return;let a=Buffer.concat([r,Buffer.from(Pn())]);try{let e=Ft();p.mkdirSync(s.dirname(e),{recursive:!0}),p.appendFileSync(e,a),i!==null&&n!==null&&xn(p.fstatSync(i.fd))===xn(p.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Bn(a.toString(),e)}}function zn(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=p.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Bn(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Vn=5e3;function Hn(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 Un=`/usr/bin/footprint`;function Wn(e,t){return e===`darwin`?[Jn(Un,[`-p`,String(t)]),Jn(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Yn(`/proc/self/smaps_rollup`),Yn(`/proc/self/status`)]:[]}function Gn(e,t){return e===`darwin`?Kn(t,e=>pt({bin:Un,args:e,timeoutMs:Vn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Kn(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}`}${Xn(r.stderr)}`};let i=qn(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 qn(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Jn(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=D({bin:e,args:[...t],timeoutMs:Vn,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}`}${Xn(n.stderr)}`}}}}function Yn(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 Xn(e){let t=e.split(`
5
5
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const Zn=`CC_CANDYBAR_RSS_LIMIT_MB`;function Qn(e){let t=e[Zn];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Zn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function $n(e){return Qn(e)*2}const er=1024*1024,tr=e=>Math.round(e/er);function nr(e){return Qn(e)*er}const rr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function ir(e,t){return e>t}function ar(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const or=.75;function sr(e,t){return e>t*or}function cr(e,t,n){let{prefix:r,suffix:i}=rr[t];return s.join(e,`${r}${n}${i}`)}function lr(e){for(let t of Object.keys(rr)){let{prefix:n,suffix:r}=rr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function ur(e){let t=e.limitBytes??1024*er,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=ar(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${pr(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${dr(s)} > limit ${tr(t)} MB (rss ${tr(a)} MB, v8 heap ${tr(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return mr(e.log,`memory report`,()=>{let t=cr(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),mr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=cr(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),mr(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of hr(e.listArtifacts()).slice(n))for(let n of Object.values(t))mr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&sr(i.charge.bytes,t)?`${dr(i.charge)} approaching limit ${tr(t)} MB (v8 heap ${tr(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:hr(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 dr(e){return e.kind===`charged`?`${e.measure} ${tr(e.bytes)} MB`:`rss ${tr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${tr(e.gap)} MB gap`} (standing in: ${e.unread})`}function fr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function pr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${tr(e.gap)}MB`:``;return`measure=${fr(e)} charge=${tr(e.bytes)}MB rss=${tr(t)}MB heap=${tr(n)}MB limit=${tr(r)}MB${i}`}function mr(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function hr(e){let t=new Map;for(let n of e){let e=s.basename(n),r=lr(e);if(r===null)continue;let{prefix:i,suffix:a}=rr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(rr);return[...t].sort(([e],[t])=>ir(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function gr(e,t,n={}){let r=xt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Gn(process.platform,process.pid),captureMemoryReport:()=>Hn(Wn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>de.writeHeapSnapshot(e),writeLogNow:Mn,listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>lr(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function _r(e={}){if(Nr()!==null)return;let n=e.spawn??Fr,r=Ar();if(r.kind===`contended`){let e=yr();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),vr(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),vr(n);return}try{vr(n)}finally{Mr()}}function vr(e){Er()&&br(e)}function yr(){try{let e=p.statSync(jt());return Date.now()-e.mtimeMs}catch{return null}}function br(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -197,7 +197,7 @@ Config tooling:
197
197
  `)){n.push(r);continue}let e=r.split(`
198
198
  `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function dX(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}`}})}const fX=e=>e.kind===`failed`?yJ:e;function pX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function mX(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:n,opened:r.length>0,ground:i},deeper:r}}function hX(e){return{...e,cells:e.cells.map(TJ)}}function gX(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,..._X(e,r)]}function _X(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 vX(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:gX(e.direction,e.children.map((t,i)=>n(t,[...r,yX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function yX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:S_[e.direction]}}const bX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ah(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,O_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),gX(e.direction,e.children.map((n,r)=>t.renderChild(n,fX(t.gate),yX(e,r))))}},xX={drop:e=>e.place,above:()=>`above`},SX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},CX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:C_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,k_(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,wX(e,t))};function wX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=Ok(t.scope,e.settings);if(t.gate.kind===`failed`)return AX(e,r,t,t.gate.message);try{let i=t.placement(e),a=pX(t.gate,i.gate());if(a.kind===`failed`)return AX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return AX(e,r,t,s.message);let c=Pb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:qj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?TX(f.variable):EX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?DX(p.segment,u):OX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:yJ,h.disclosure).map(e=>({...e,place:xX[v.placement](e)})),b=(e,t,n)=>OJ(MJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?SX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(kX(wJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(wJ)),[...ie,...re]}catch(n){return AX(e,r,t,n.message??String(n))}}const TX=e=>({kind:`waiting`,variable:e});function EX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=oS(e);if(t===void 0)throw e;return TX(t.variable)}}function DX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:uX(MJ(r,c)).map((e,t)=>({cells:OJ(e,{...l,lead:t===0?MJ(i,c):[],trail:t===0?MJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:OJ(MJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function OX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=MJ(jX(e.lead,e,t,n),l),d=MJ(jX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return OJ(MJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function kX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function AX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:OJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:qj(n.palette)},lead:jX(e.lead,e,t,n),trail:jX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function jX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=oS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const MX={container:bX,segment:CX};function NX(e){return MX[e]}var PX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?FX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const FX={kind:`hidden`},IX={palette:`theme`,style:`style`,effect:`effect`},LX=Oy.get(`colorCompatibility`),RX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function zX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function BX(e){if(e.ok)return e.value;throw e.error}const VX=e=>({read:()=>e}),HX=ph({basePalette:fh,palette:fh,decor:Dg});var UX=class{evaluated=0;memory=new PX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&HX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=Ek(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(LX);return typeof e==`string`&&d_(e)?e:`truecolor`});let i=(0,J.observable)(RX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return vX(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jI(e);return i===void 0?[]:[{name:i,address:n,palette:Pb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>f_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=mA(e);return t===void 0?fA(e)===void 0?tA(this.view.get().payload(),e):tA(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[IX[e]];if(t.kind===`decided`)return KX(t.name,null,null);let r=JX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=YX(this.source,e,i.name,r.where,e=>{t=e}),KX(n,t,null)}case`pending`:return KX(n??Qg[e],null,i.variable);case`failed`:return n=Qg[e],KX(n,$g(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!qX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??Qg[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return xJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>vY(this.source.activeSegment,()=>xJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new XX(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:RJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=oS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:zX(e)}),BX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function WX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new UX(t,n,e,r);return e.views.set(t,a),a}function GX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const KX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),qX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function JX(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 view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function YX(e,t,n,r,i){switch(t){case`palette`:return zb(n,r,i).name;case`style`:return Yg(n,e.styles).name;case`effect`:return a_(n).name}}var XX=class{where=ZX(ph({palette:fh,region:Tg}));ground=ZX(ph({colours:$X,bodyOpen:fh}));opened=ZX(ph({colours:$X,open:fh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ok(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?VX(bJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>vY(r,()=>xJ(a,i))),this.open=d===void 0?VX(yJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>vY(r,()=>xJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return nZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return rZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?VX(aZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return iZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),sZ(n,r,this.affixes.read())}};function ZX(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const QX=(e,t)=>e.hex===t.hex,$X=ph({palette:fh,drawnAt:fh,tint:QX,text:QX,bg:QX,disclosure:Og});function eZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const tZ=e=>dg(e.palette,e.disclosure,e.drawnAt);function nZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Pg(n,r,i)};return _Y(e,eZ(t,c),e=>{let t=Yj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function rZ(e,t,n,r,i,a){return _Y(e,eZ(t,n),e=>(e.bg=i?tZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function iZ(e,t,n,r,i,a,o){return _Y(e,eZ(t,n),e=>(e.bg=r?tZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const aZ={lead:[],trail:[],drops:[]};function oZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return eY(t,tZ(e).state,n)},get band(){return eY(t,tZ(e).plane,n)},get close(){return rY(t,tZ(e).state,n)},disclosure:r}}function sZ(e,t,n){return{styles:oZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?tZ(e).shortfalls:[]}}function cZ(e,t,n,r,i,a,o){let s=nZ(e,t,n,r,i,void 0,void 0,o);return sZ(s,rZ(e,t,s,a,!1,o),aZ)}function lZ(e,t,n,r,i){return oZ(nZ(e,t,n,r,i,void 0,void 0,{}))}function uZ(e,t){return{payload:()=>e,selections:()=>t}}function dZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Vk(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 fZ(e,t){switch(M_(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 pZ(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:dZ(n.cache),parse:fZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:dZ(n.cache),parse:fZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function mZ(e,t){let n=JS.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 hZ(e,t,n){let{compiled:r,loadWarnings:i}=_Z(e,t,n.cwd,gZ(n.signer),xZ);return{...r,loadWarnings:i}}const gZ=e=>(t,n)=>SZ(n,e);function _Z(e,t,n,r,i=xZ){let a=vZ(e),o=yZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:bZ(e,t,n,i)}}function vZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of ky)n in t&&r.set(e,n);for(let[t,n]of R_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...mB(e)].sort(([e],[t])=>e<t?-1:1)}}function yZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function bZ(e,t,n,r){let i=cX(e),a=mB(e),o=[];for(let[s,c]of Gx(e))if(r.has(i.get(s)))try{pZ(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const xZ=new Set([`directory`,`view`]);function SZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>FJ(i,`drawnAt`).registry.drawnAt(),o=hY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=tx(e.presets),u=bI(e),d=[e=>zY(i,o,e.now)],f=Tk({extraFuncs:{...QJ(i),...RY(i),...AY(i,o),...PY(i,o),...WY(i,o),...XY(i,o),...eX(s),...rX(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=mZ(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=zJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),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 b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=H_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>J_(t,e,a,t=>String(FJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return NX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=ix(e,t);S.set(t,x(n,r))}let te=new Map(Wg.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of gB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:TZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:sB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:Sk(d)},re=yB(ne),ie=[...S.values()].flatMap(wZ(y)).some(e=>re(m.get(e))),ae=ie?yB({...ne,clock:new Set([...ne.clock,YY])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function CZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const wZ=e=>t=>{let n=[];return vX(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function TZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const EZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function DZ(e,t,n,r,i){let a=OZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function OZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Qg[e];case`failed`:return r({kind:`rule`,slot:e,message:$g(t.where,e,`the rule failed — ${n.error}`)}),Qg[e]}}function kZ(e){return AZ(e).filter(e=>!e.name.startsWith(SA)).map(e=>e.id)}function AZ(e){return e.kind===`container`?e.children.flatMap(AZ):[e,...e.opens===void 0?[]:AZ(e.opens.body)]}function jZ(e,t,n,r,i,a,o,s,c=XH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return WX(t,n,r,uZ(l,c)),NZ(e,t,n,r,l,a,o,s,c)}function MZ(...e){return jZ(...e).text}function NZ(e,t,n,r,i,a,o,s,c){try{var l=ja();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new eb(``),g=h.clockAt(a,t_[c.animationSpeed]);l.u(pk(a,g.anim));let _=GX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:cb(v),padding:v.padding,seamCols:lb(v),preset:c.preset},i);let y=_.evaluated;l.u(RJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:wh[c.variation],shade:Sh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,mX),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=YX(t,e,DZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:oe,effect:se}=_.selections(),T=w.kind===`decided`?w:zb(C(`palette`),``,EZ),ce=oe.kind===`decided`?oe:Yg(C(`style`),e.styles),le=se.kind===`decided`?se:a_(C(`effect`)),ue=T.value,de=Ib(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Yv(c.idleSince,c.menuTimeout,a),pe=Vh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Zh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:mX,hold:hX},me);u?.clear();let ge=t=>e.segments[t],_e=e=>{for(let t of e.shortfalls)m.add(t);return e},ve=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>_e(t.evaluate(e,n))}},ye=(e,i,a)=>{let o=i.kind===`hidden`?i:pX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${kZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:de,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:ve,evaluateOnce:(e,n,i,o)=>_e(cZ(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,Mg(a,n)),renderBody:(e,t,n)=>ye(e,t,Ng(n)),closeDisclosure:e=>$J(n,e),placed:(e,t)=>te.placed(e,he.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>lZ(t.activeSegment,e,n,a,r.drawnAt())};return NX(e.kind).render(e,c)},be=t.roots.get(b);if(be===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${$b}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=dX(ye(be,bJ,jg(x))).map(({line:e,row:t})=>{let n=jJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...pb(n.map(e=>e.owner),v,he.row(t,r,n))}});he.drawn(),te.commit();let Se=xe.filter(e=>e.kind===`menu`).length,Ce=xe.some(e=>e.moves)?`moves`:Se>0||_.selections().effect.kind===`expression`||ee||AZ(be).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:xe.map(e=>e.text).join(`
199
199
  `),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*PZ(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*FZ(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 tx(e.presets)){for(let n of D_(ix(e,t).node))n.when!==void 0&&(yield n.when);let n=ax(e,t);for(let e of Wg){let t=n[e];Gg(t)&&(yield t)}}for(let[,t]of PZ(e))for(let[,e]of F_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of gx(t))yield e}function IZ(e,t){let n=uB(t),r=new Set,i=new Set,a=new Set;for(let e of FZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Lx(e,t.helpers))i.add(n);for(let n of Hx(e,t.helpers))a.add(n)}for(let[,e]of PZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of tx(t.presets))for(let n of D_(ix(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!wA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(PZ(e));return[...d(`variable`,f.keys(),e=>l(e,f.get(e))),...d(`action`,Object.keys(e.actions??{}),e=>o.has(e)),...d(`helper`,Object.keys(e.helpers??{}),e=>a.has(e)),...d(`segment`,Object.keys(e.segments??{}),e=>c.has(e))]}var LZ=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function RZ(e){return Math.floor(Math.max(e/4,e*or-67108864))}const zZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function BZ(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=aV(e),r=t===void 0?void 0:n.variables[sV(t)];return r?.kind===`file`?r.path:`none`},d=o.flatMap(e=>{let t=aV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>pV(e)(t)&&t!==sV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${e.join(` < `)||`<default>`}: projections=${[...mB(n).keys()].join(`,`)||`-`} instantSegments=${CZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}function VZ(e){let t=e=>e.join(`,`)||`-`;return`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} awaiting=${t(e.repos.awaiting)} declined=${t(e.repos.declined)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function HZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function UZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function WZ(e,t){return new Set(tx(e.presets).filter(n=>ix(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function GZ(e,t){let n=new Map,{loaded:r,dropped:i,unreached:a}=e.state.plugins,o=[...new Set([...e.state.plugins.roots,s.join(e.projectDir,RV)])];for(let t of[...tH(e.projectDir,e.cwd,e.configFile),...o,...r,...[...i,...a].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))]){let{dir:e,name:r}=Xx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of o){let{dir:t,name:r,leaf:i}=Xx(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 KZ(e){return e.filter(Boolean).join(`
200
- `)||null}function qZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vH(t.layers,VH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??VH,l=a.find(e=>e.path===t.home)?.raw??{},u=new yS,d=new aA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=_Z(o,d,e,r.compile??gZ(r.signer),ZZ),n.push(...f.loadWarnings);let t=d.view();n.push(...bZ(o,t,e,QZ)),t.dispose(),MU(o),eL(o),p=JZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Hq(o),authoredRoots:WZ(c,l),fileHeldSettings:vU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>IZ(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},sources:p}}function JZ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function YZ(e,t,n,r){let i=performance.now(),a=rH(wq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[uH(e,t),cH(a),QV(o)],l,u=null;try{l=qZ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof Q_&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:KZ(c),state:null,error:e instanceof Q_||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:KZ(c),state:l,error:null}}function XZ(e,t,n){return qZ(e,{layers:[],home:``,repo:t},[],n)}const ZZ=new Set([`directory`]),QZ=new Set([`view`]);function $Z(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new LZ;bZ(e.config,l,t,QZ);let d=()=>YH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),$q(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});WX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var eQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=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??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{};let{dir:n,name:r}=Xx(Cq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{files:[],dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??SZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=UZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,BZ(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??XZ(t,a.repos.plugins,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=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=ja();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(UZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=$Z(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return YZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}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,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,HZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,BZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let n=GZ(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}latestView(){return[...this.views.values()].at(-1)??null}};const tQ=16384;var nQ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=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,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,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:Ze,sourceDigest:et(),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},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},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,J.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,J.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,J.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,J.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;writing=!1;generation=0;constructor(e,t=500,n=Me){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.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=`${this.filePath}.writing`;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}if(t!==this.generation){await p.promises.rm(i,{force:!0});return}let c=performance.now();p.renameSync(i,this.filePath),this.saved(r,e,n,a+performance.now()-c),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.generation++,this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.renameSync(n,this.filePath),this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};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`:by(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(_t(e),{force:!0});return}gt(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:Wi(e)}function mQ(e,t){return e!==null&&Ki(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(!Gb(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=zH,vQ=_Q.segments,yQ=_Q.presets,bQ=_Q.root;function xQ(e,t,n,r){if(!mQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function SQ(e,t){let n=Cj(t);return t.scope===`segment-palette`&&xQ(e,[`segments`,t.segment],vQ[t.segment],n.join(`.`)),n}function CQ(e){return Wi(ea(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:Ki(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&&xa(a.fragment)?a:null}function OQ(e,t){let n=ba(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(Ca(r,n))return i;throw new q(`${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):Cj(t)}function NQ(e,{unit:t}){return t===null?e:ma(e,t.path,ea(t.value),Qi)}function PQ(e){let t=Sj(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 q(`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 q)||e.above.length===0?t:new q(`${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 Q_)return null;throw e}}function HQ(e,t){return vH(t===null?e.above:[e.path,...e.above],VH,{entered:()=>{},warned:()=>{}},{repo:e.repo,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 Q_?new q(`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:Ki(r,Cj(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])=>ma(e,SQ(pQ(e),FQ(t)),uQ(t,n),Qi),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=Da(NQ(s,c),c.path,i,a,ea(o));if(l===null)throw new q(`${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(!Ca(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ji(e,c):ea(s.value);if(a!==`#`)return ma(e,[...i,`rows`,a],l,Qi);if(DQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ma(e,i,l,Qi)}return e}function $Q(e,t){return ga(e,t,t[0]===`presets`&&t.length>2&&!UH(t[1])?2:0)}function e$(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 t$(e){let t=e===null?void 0:Ki(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function n$(e,t){let n=new Set([...HH,...t$(e),...t.above.flatMap(e=>Object.keys(Li.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(vA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(vA(e)))}function r$(e,t,n,r,i,a){let o=dQ(t.path),s=pQ(o??``),c=n$(s,t),l=[`presets`,c],u=zQ(t,()=>DQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ji(o??``,u.fragment):ea(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],ea(r)]]],f=i.map(([e,t])=>{let n=xj(c,e);return[SQ(s,FQ(n)),uQ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ma(e,t,n,Qi),ma(o??``,l,`{}`,Qi));return IQ(e,t,o,zQ(t,()=>ZQ(p,t.path,a.map(e=>({...e,preset:c})),QQ)),LQ),c}function i$(e,t,n,r){let i=dQ(t.path);IQ(e,t,i,ma(i??``,[`themeDefaults`,n],ea(r),Qi),LQ)}function a$(e,t,n){if(UH(n))throw new q(`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||Ki(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ki(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 o$(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}=s$(c,s.path,r,()=>{let e=qQ(t,c).config;return tx(e.presets).map(t=>ix(e,t).node)});if(l===null)throw new q(`${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 s$(e,t,n,r){switch(n.op){case`remove`:return{after:Ta(e,t,n.target),placed:null};case`insert`:{let i=VI(n.segment,n.anchor,r());return{after:Ea(e,t,i,n.anchor,n.relation),placed:i}}}}const c$={load:()=>({}),save:()=>{}},l$=new Set(Ty.map(e=>e.sessionKey)),u$=e=>l$.has(e)||e.startsWith(Fj),d$=8*1024*1024,f$={past:[],future:[]},p$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var m$=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=c$){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)??f$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??f$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(p$(n));r.set(p$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:rQ(this.sessionState,e=>u$(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:S$(i,n),o=r.get(e),s=o===void 0?a:E$(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 q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,w$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`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(p$)),a=n.net.filter(e=>!i.has(p$(e))),o=_$(D$(T$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(k$).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 q(`redo: nothing to redo`);let a=[...n,i],o=_$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...y$(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(p$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:D$(n,t),future:D$(i,t),...a!==void 0&&{savepoint:{at:D$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(p$(e))),below:D$(a.below,t)}}}),new q(`${r}: ${o.map(k$).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){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||h$(n)>d$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,g$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${d$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function h$(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 g$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...y$(n,1,[])}:{past:e,future:t.slice(1),...y$(n,0,[])}}function _$(e){return e.slice(-50)}const v$=e=>e===Lj.member;function y$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:b$(e.net,n),below:e.below}}}function b$(e,t){let n=new Map(e.map(e=>[p$(e),e]));for(let e of t){let t=n.get(p$(e));n.set(p$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const x$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function S$(e,t){let n=[...e.past,t],r=_$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...y$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...C$(e.future,a),...i.below]},n.length-r.length,t)}}function C$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function w$(e,t){return{past:e.past.slice(0,-1),future:_$([...e.future,t]),...y$(e.savepoint,0,x$(t))}}function T$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...C$(r,t.at-i.length),...t.below]}function E$(e,t){if(v$(t.after)&&!v$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!v$(t.after)&&v$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function D$(e,t){return e.map(e=>e.filter(e=>!t.has(p$(e)))).filter(e=>e.length>0)}function O$(e){return e.map(k$).join(`, `)}function k$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function A$(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 j$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(A$))}function M$(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(A$)&&j$(t.below)}function N$(e){if(typeof e!=`object`||!e)return!1;let t=e;return j$(t.past)&&j$(t.future)&&(t.savepoint===void 0||M$(t.savepoint))}function P$(e,t){let n=e=>e.kind===`file`||u$(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 F$(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(N$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,P$(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}),gt(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 I$=e=>!u$(e)&&!uP(e)&&e!==`update.dismissed`;var L$=class{past=J.observable.map(void 0,{deep:!1});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,I$,(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 q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.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){(0,J.runInAction)(()=>{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 R$={inside:()=>[],defaultOf:()=>yi,menus:[]},z$=e=>`${e.key}\0${e.member}`;function B$(e){let t=new Map,n=n=>{let r=`${n.name}\0${C_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:nz(a,C_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(z$(e))??new Map;n.set(z$(t),t),o.set(z$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(z$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of tx(e.presets))d(ix(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Mi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(z$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(z$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(z$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const V$=new WeakMap;function H$(e){let t=V$.get(e);if(t!==void 0)return t;let n=B$(e);return V$.set(e,n),n}function U$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function W$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function G$(e,t,n){let r=(r,i,a)=>{let o=U$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const K$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function q$(e,t){let n={...e};for(let e of K$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const J$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Y$(e){let t=e=>({kind:`failed`,reason:e});if(!J$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!J$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!ZM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${ZM.join(` or `)}`)}return{kind:`ok`,value:e}}function X$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Z$=e=>xq(e,`doctor-marks.json`,{},Y$),Q$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},$$=(e,t)=>e.includes(t)?e:[...e,t],e1=e=>xq(e,`doctor-clicked-terminals.json`,[],Q$);var t1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const n1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},r1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),i1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=r1(e,t);return r===void 0?n:r.projectDir},a1=(e,t)=>r1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function o1(e){let t=new Map;for(let n of e.split(`
200
+ `)||null}function qZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vH(t.layers,VH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??VH,l=a.find(e=>e.path===t.home)?.raw??{},u=new yS,d=new aA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=_Z(o,d,e,r.compile??gZ(r.signer),ZZ),n.push(...f.loadWarnings);let t=d.view();n.push(...bZ(o,t,e,QZ)),t.dispose(),MU(o),eL(o),p=JZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Hq(o),authoredRoots:WZ(c,l),fileHeldSettings:vU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>IZ(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},sources:p}}function JZ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function YZ(e,t,n,r){let i=performance.now(),a=rH(wq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[uH(e,t),cH(a),QV(o)],l,u=null;try{l=qZ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof Q_&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:KZ(c),state:null,error:e instanceof Q_||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:KZ(c),state:l,error:null}}function XZ(e,t,n){return qZ(e,{layers:[],home:``,repo:t},[],n)}const ZZ=new Set([`directory`]),QZ=new Set([`view`]);function $Z(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new LZ;bZ(e.config,l,t,QZ);let d=()=>YH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),$q(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});WX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var eQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=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??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{};let{dir:n,name:r}=Xx(Cq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{files:[],dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??SZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=UZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,BZ(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??XZ(t,a.repos.plugins,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=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=ja();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(UZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=$Z(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return YZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}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,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,HZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,BZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let n=GZ(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}latestView(){return[...this.views.values()].at(-1)??null}};const tQ=16384;var nQ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=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,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,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:Ze,sourceDigest:et(),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},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},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,J.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,J.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,J.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,J.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;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}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.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await p.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await p.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Math.round(performance.now()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.rmSync(this.writingPath,{force:!0}),p.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};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`:by(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(_t(e),{force:!0});return}gt(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:Wi(e)}function mQ(e,t){return e!==null&&Ki(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(!Gb(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=zH,vQ=_Q.segments,yQ=_Q.presets,bQ=_Q.root;function xQ(e,t,n,r){if(!mQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function SQ(e,t){let n=Cj(t);return t.scope===`segment-palette`&&xQ(e,[`segments`,t.segment],vQ[t.segment],n.join(`.`)),n}function CQ(e){return Wi(ea(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:Ki(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&&xa(a.fragment)?a:null}function OQ(e,t){let n=ba(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(Ca(r,n))return i;throw new q(`${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):Cj(t)}function NQ(e,{unit:t}){return t===null?e:ma(e,t.path,ea(t.value),Qi)}function PQ(e){let t=Sj(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 q(`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 q)||e.above.length===0?t:new q(`${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 Q_)return null;throw e}}function HQ(e,t){return vH(t===null?e.above:[e.path,...e.above],VH,{entered:()=>{},warned:()=>{}},{repo:e.repo,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 Q_?new q(`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:Ki(r,Cj(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])=>ma(e,SQ(pQ(e),FQ(t)),uQ(t,n),Qi),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=Da(NQ(s,c),c.path,i,a,ea(o));if(l===null)throw new q(`${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(!Ca(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ji(e,c):ea(s.value);if(a!==`#`)return ma(e,[...i,`rows`,a],l,Qi);if(DQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ma(e,i,l,Qi)}return e}function $Q(e,t){return ga(e,t,t[0]===`presets`&&t.length>2&&!UH(t[1])?2:0)}function e$(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 t$(e){let t=e===null?void 0:Ki(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function n$(e,t){let n=new Set([...HH,...t$(e),...t.above.flatMap(e=>Object.keys(Li.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(vA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(vA(e)))}function r$(e,t,n,r,i,a){let o=dQ(t.path),s=pQ(o??``),c=n$(s,t),l=[`presets`,c],u=zQ(t,()=>DQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ji(o??``,u.fragment):ea(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],ea(r)]]],f=i.map(([e,t])=>{let n=xj(c,e);return[SQ(s,FQ(n)),uQ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ma(e,t,n,Qi),ma(o??``,l,`{}`,Qi));return IQ(e,t,o,zQ(t,()=>ZQ(p,t.path,a.map(e=>({...e,preset:c})),QQ)),LQ),c}function i$(e,t,n,r){let i=dQ(t.path);IQ(e,t,i,ma(i??``,[`themeDefaults`,n],ea(r),Qi),LQ)}function a$(e,t,n){if(UH(n))throw new q(`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||Ki(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ki(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 o$(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}=s$(c,s.path,r,()=>{let e=qQ(t,c).config;return tx(e.presets).map(t=>ix(e,t).node)});if(l===null)throw new q(`${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 s$(e,t,n,r){switch(n.op){case`remove`:return{after:Ta(e,t,n.target),placed:null};case`insert`:{let i=VI(n.segment,n.anchor,r());return{after:Ea(e,t,i,n.anchor,n.relation),placed:i}}}}const c$={load:()=>({}),save:()=>{}},l$=new Set(Ty.map(e=>e.sessionKey)),u$=e=>l$.has(e)||e.startsWith(Fj),d$=8*1024*1024,f$={past:[],future:[]},p$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var m$=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=c$){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)??f$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??f$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(p$(n));r.set(p$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:rQ(this.sessionState,e=>u$(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:S$(i,n),o=r.get(e),s=o===void 0?a:E$(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 q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,w$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`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(p$)),a=n.net.filter(e=>!i.has(p$(e))),o=_$(D$(T$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(k$).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 q(`redo: nothing to redo`);let a=[...n,i],o=_$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...y$(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(p$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:D$(n,t),future:D$(i,t),...a!==void 0&&{savepoint:{at:D$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(p$(e))),below:D$(a.below,t)}}}),new q(`${r}: ${o.map(k$).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){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||h$(n)>d$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,g$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${d$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function h$(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 g$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...y$(n,1,[])}:{past:e,future:t.slice(1),...y$(n,0,[])}}function _$(e){return e.slice(-50)}const v$=e=>e===Lj.member;function y$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:b$(e.net,n),below:e.below}}}function b$(e,t){let n=new Map(e.map(e=>[p$(e),e]));for(let e of t){let t=n.get(p$(e));n.set(p$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const x$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function S$(e,t){let n=[...e.past,t],r=_$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...y$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...C$(e.future,a),...i.below]},n.length-r.length,t)}}function C$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function w$(e,t){return{past:e.past.slice(0,-1),future:_$([...e.future,t]),...y$(e.savepoint,0,x$(t))}}function T$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...C$(r,t.at-i.length),...t.below]}function E$(e,t){if(v$(t.after)&&!v$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!v$(t.after)&&v$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function D$(e,t){return e.map(e=>e.filter(e=>!t.has(p$(e)))).filter(e=>e.length>0)}function O$(e){return e.map(k$).join(`, `)}function k$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function A$(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 j$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(A$))}function M$(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(A$)&&j$(t.below)}function N$(e){if(typeof e!=`object`||!e)return!1;let t=e;return j$(t.past)&&j$(t.future)&&(t.savepoint===void 0||M$(t.savepoint))}function P$(e,t){let n=e=>e.kind===`file`||u$(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 F$(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(N$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,P$(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}),gt(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 I$=e=>!u$(e)&&!uP(e)&&e!==`update.dismissed`;var L$=class{past=J.observable.map(void 0,{deep:!1});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,I$,(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 q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.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){(0,J.runInAction)(()=>{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 R$={inside:()=>[],defaultOf:()=>yi,menus:[]},z$=e=>`${e.key}\0${e.member}`;function B$(e){let t=new Map,n=n=>{let r=`${n.name}\0${C_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:nz(a,C_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(z$(e))??new Map;n.set(z$(t),t),o.set(z$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(z$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of tx(e.presets))d(ix(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Mi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(z$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(z$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(z$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const V$=new WeakMap;function H$(e){let t=V$.get(e);if(t!==void 0)return t;let n=B$(e);return V$.set(e,n),n}function U$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function W$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function G$(e,t,n){let r=(r,i,a)=>{let o=U$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const K$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function q$(e,t){let n={...e};for(let e of K$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const J$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Y$(e){let t=e=>({kind:`failed`,reason:e});if(!J$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!J$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!ZM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${ZM.join(` or `)}`)}return{kind:`ok`,value:e}}function X$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Z$=e=>xq(e,`doctor-marks.json`,{},Y$),Q$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},$$=(e,t)=>e.includes(t)?e:[...e,t],e1=e=>xq(e,`doctor-clicked-terminals.json`,[],Q$);var t1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const n1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},r1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),i1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=r1(e,t);return r===void 0?n:r.projectDir},a1=(e,t)=>r1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function o1(e){let t=new Map;for(let n of e.split(`
201
201
  `)){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*s1(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 c1={pullRequests:e=>Wq(e).showPullRequest===!0,rateLimits:e=>Uq(e,`block`)||Uq(e,`weekly`)};function l1(e,t){let n=new Map;for(let r of D_(ix(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=>L_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,Bq(e,t,n.get(t))])),a=e=>r.filter(t=>c1[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
202
202
  /*!
203
203
  * Copyright (c) Squirrel Chat et al., All rights reserved.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.160.0",
3
+ "version": "1.160.1",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -102,9 +102,9 @@
102
102
  "typescript": "^5.0.0"
103
103
  },
104
104
  "optionalDependencies": {
105
- "@promptctl/cc-candybar-darwin-arm64": "1.160.0",
106
- "@promptctl/cc-candybar-darwin-x64": "1.160.0",
107
- "@promptctl/cc-candybar-linux-arm64": "1.160.0",
108
- "@promptctl/cc-candybar-linux-x64": "1.160.0"
105
+ "@promptctl/cc-candybar-darwin-arm64": "1.160.1",
106
+ "@promptctl/cc-candybar-darwin-x64": "1.160.1",
107
+ "@promptctl/cc-candybar-linux-arm64": "1.160.1",
108
+ "@promptctl/cc-candybar-linux-x64": "1.160.1"
109
109
  }
110
110
  }