@promptctl/cc-candybar 1.157.0 → 1.158.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +76 -76
- 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.157.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`9221fcf37de8bc8c90a8ddf6a275fb4e57bb2d4cb64a2f381910744c75f25a9c`}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.158.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`688b4dc3f21b65922b73cbabc03fb46def20d767d18b8f61e0498528fe1f7bd3`}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?)
|
|
@@ -69,14 +69,14 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
69
69
|
`).map(e=>n+e).join(`
|
|
70
70
|
`)}function AD(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function jD(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw yE(`join`,2,`list of strings/primitives`,`list element of type ${MD(e)}`);n.push(String(e))}return n.join(e)}function MD(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function ND(e){return SD(e,`-`)}function PD(e){return e.toLowerCase()}function FD(e,t){return`\n${kD(e,t)}`}function ID(e){return e.replace(/\s+/g,``)}function LD(e,t,n){return n===1?e:t}function RD(...e){return e.map(e=>`"${e}"`).join(` `)}function zD(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function BD(e,t){return t.repeat(Math.max(0,e))}function VD(e,t,n){return sD(e,n).join(t)}function HD(e){return SD(e,`_`)}function UD(e,t){let n=sD(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function WD(e,t){return sD(e,t)}function GD(e,t,n){let r=KD(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function KD(e,t,n){if(n===0)return[];let r=sD(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function qD(...e){return e.map(e=>`'${e}'`).join(` `)}function JD(e,t,n){let r=oD(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function YD(e){let t=``;for(let n of e)XD(n)?t+=n.toLowerCase():ZD(n)?t+=n.toUpperCase():t+=n;return t}function XD(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function ZD(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function QD(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function $D(e){return e.trim()}function eO(e,t){if(e.length===0)return t;let n=new Set(oD(e)),r=oD(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function tO(e,t){return t.startsWith(e)?t.slice(e.length):t}function nO(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function rO(e,t){let n=oD(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function iO(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function aO(e){return e.toUpperCase()}function oO(e,t){return sO(e,`
|
|
71
71
|
`,t)}function sO(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
72
|
-
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function cO(e,t,n){return sO(e,t,n)}function lO(){return{abbrev:{fn:(e,t)=>cD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>lD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>wD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>TD(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ED(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>DD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>OD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>kD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>AD(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>jD(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>ND(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>PD(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>FD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>ID(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>LD(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>RD(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>zD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>BD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>VD(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>HD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>UD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>WD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>GD(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>qD(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>JD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>YD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>QD(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>$D(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>eO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>tO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>nO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>rO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>iO(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>aO(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>oO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>cO(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function uO(e,t){let n=dO(e),r=n.copy();return r.style=md(n.style,t),r}function dO(e){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function fO(e){return{fn:(t=>uO(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function pO(e){return{fn:((t,n)=>uO(n,new V({[e]:z.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function mO(e,t){return new V({[e]:t})}function hO(){let e={};for(let t of cd)e[t]=fO(mO(t,!0)),e[`not_${t}`]=fO(mO(t,!1));for(let[t,n]of Object.entries(ud))e[t]=fO(mO(n,!0));return e}const gO={fn:((e,t)=>uO(t,V.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},_O={fn:((e,t)=>uO(t,new V({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function vO(){return{fg:pO(`color`),bg:pO(`bgcolor`),...hO(),link:_O,style:gO}}function yO(e,t){let n;try{n=Yc(e.trim())}catch(n){throw n instanceof jc?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return bO(n,t,JSON.stringify(e))}function bO(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function xO(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function SO(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const CO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`darken`),t).hex)),wO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`lighten`),-t).hex)),TO={min:0,max:100,note:`0 = from, 100 = toward`},EO=xO([`string`,`string`,`float`],((e,t,n)=>Xc(yO(e,`mix`),yO(t,`mix`),SO(n,`mix`,`percentage`,TO)/100).hex)),DO={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},OO=xO([`string`],(e=>Pl(yO(e,`contrastOn`)).hex)),kO={depth:R.TRUECOLOR},AO=e=>xO([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Fl(yO(t,`readableOn`),yO(n,`readableOn`),SO(r,`readableOn`,`ratio`,DO),i,void 0,a).hex})),jO={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function MO(){let e={};for(let[t,n]of Object.entries(jO)){let r=t;e[n]=xO([`string`,`float`],((e,t)=>{let i={...ml,[r]:SO(t,n,`amount`)};return B.fromRgba(yO(e,n)).applyKey(i).toRgba().hex}))}return e}function NO(e=()=>kO){return{darken:CO,lighten:wO,mix:EO,contrastOn:OO,readableOn:AO(e),...MO()}}function PO(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:bO(El(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function FO(e){return{color:{fn:(t=>El(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new $u(Bu(n),PO(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function IO(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function LO(e){return{frames:{fn:((...t)=>rh(new nh(IO(`frame`,t,dO).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=IO(`color`,t,e=>yO(e,`stepped`));return n[Yu(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function RO(e){return{...vO(),...NO(e)}}new V({color:`red`,dim:!0});const zO=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,BO=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function VO(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(zO);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(BO);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function HO(e){let t=e.match(BO);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function UO(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function WO(e){return e.toLocaleString()}function GO(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function KO(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const qO=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],JO=qO.length;function YO(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(JO-1));o+=qO[t]}return o}function XO(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function ZO(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const QO=Rg(),$O=[...o_];function ek(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>UO(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Zx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Xx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Qx(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>QO,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>$O,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ZO(`sparkline`,[`width`],n),YO(XO(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>KO(e,GO(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function tk(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const nk=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>tk(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function rk(){return{formatInteger:{fn:e=>WO(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>VO(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`}}}}const ik=e=>e.getTime()/1e3,ak=e=>new Date(e*1e3);let ok=null;function sk(e,t){if(ok!==null)throw Error(`a draw is already in progress: draws do not nest`);return ok={at:e,anim:t},{[Symbol.dispose]:()=>{ok=null}}}function ck(e){if((0,J._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(ok===null)throw Error(`the clock was read outside a draw (${e})`);return ok}const lk={now:()=>ak(ck(`now`).at),animatedAt:()=>ck(`animatedAt`).anim},uk=new Set([`now`,`ago`]);function dk(e,t){return Object.fromEntries(Object.entries(VT(e)).filter(([e])=>uk.has(e)===t))}const fk=dk(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),pk=[e=>dk(e.now,!0),e=>LO(e.animatedAt),e=>Object.fromEntries(Object.entries(LO(()=>e.now().getTime()/1e3)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),nk];function mk(e){return Object.assign({},...e.map(e=>e(lk)))}const hk=new Set(Object.keys(mk(pk)));function gk(e){return new Set([...hk,...Object.keys(mk(e))])}const _k={readableOn:AO},vk=new Set(Object.keys(_k));function yk(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return ow({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,missingKey:`error`,funcs:{...YT(),...lO(),...LE(),...aD(),...jw(),...dE(),...lE(),...fk,...RO(r),...Object.fromEntries(Object.entries(_k).map(([e,t])=>[e,t(r)])),...mk([...pk,...e.clockFuncs??[]]),...ek(),...rk(),...n??{}}})}function bk(e){return xk(e,new Set(e.names()),``)}function xk(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!Ck(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:wk(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return xk(e,t,a)}})}function Sk(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function Ck(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function wk(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new $x(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const Tk=/\r\n|\r|\n/g,Ek=e=>P(e.replace(Tk,` `).trim());function Dk(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(Tk,` `))}}const Ok=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}};var kk=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};function Ak(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function jk(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const Mk=`session.id`;function Nk(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await pt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function Pk(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await pe(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function Fk(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}function Ik(e){try{return b(e)}catch{return e}}function Lk(e){try{return ee(e).isDirectory()}catch{return!1}}function Rk(e){let t=Ik(e);return Lk(t)?{dir:t,name:null,leaf:!0}:Wx(t)}const zk=e=>`${e.dir}\0${e.name??``}`;var Bk=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:Rk(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=Rk(e);if(t.watcher!==null&&zk(n)===zk(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},Vk=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ve(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ge(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ge(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const Hk={read:()=>Oa,drawnAt:()=>{throw new $x(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function Uk(e,t){let n=e;for(let e of t.split(`.`)){if(n===Oa)return Oa;if(typeof n!=`object`||!n)return;n=n[e]}return n}function Wk(e,t){if(t===Oa)return Oa;if(t===void 0)return I(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return I(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function Gk(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Xx(e):t===`number`?Zx(e):Qx(e)}function Kk(e){return e===`number`?0:e===`boolean`?!1:``}var qk=class e{lastErrors=new Map;policyFaults=J.observable.map(void 0,{deep:!1});watchMgr=new Bk;ttlMgr=new Vk;cleanups=[];runs=new Map;newKeys=J.observable.set();reads=new kk;abort=new AbortController;inputs=J.observable.box(Hk,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=yk({drawnAt:this.drawnAt});sourceNames=J.observable.array([],{deep:!1});publishedNow=(0,J.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.sessionState=n}view(){return new e(new pS(this.store),this.defaultEmptyValue,this.sessionState,this)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Yx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>Wk(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i===Oa)throw this.lastErrors.delete(e),new $x(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=Gk(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,Nk(t,n.cwd,this.abort.signal),Ak(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Pk(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,J.runInAction)(()=>this.sourceNames.push(e)),this.registerCachePolicy(e,n,n=>this.runSource(e,t,i,n))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,Ek,t.default,n);case`regex`:return this.scalarPublisher(e,Dk(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=Fk(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,Da(a,i))}}documentPublisher(e,t,n){let r=t===void 0?Oa:P(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?F:o,c=Fk(s,Ok,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n,r){let i=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));this.track(e,i,r)}track(e,t,n){if((0,J.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,J.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,J.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}async settled(e){return await this.inFlight(AbortSignal.timeout(e)),this.awaited()}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(bk(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=Gk(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=eS(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(Mk);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(Mk):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,J.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`);break;case`ttl`:{n(`new-key`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`),t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return P(r.evaluate(bk(this.store)).map(e=>e.plain).join(``))}catch(e){return eS(e)===void 0?I(`cache key: ${e instanceof Error?e.message:String(e)}`):Oa}},()=>n(`new-key`));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?P(e.map(e=>e.value).join(`,`)):Oa},()=>n(`new-key`));break}}onReads(e,t,n){let r,i=(0,J.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return Gk(this.defaultEmptyValue,t)}catch{return Kk(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,J.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function Jk(e,t){let n=dy[e],r=yy(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const Yk=Object.fromEntries([...Dy].map(([e,t])=>[t,Jk(e,t)])),Xk={subscribers:`number`,fps:`number`,shown:`boolean`},Zk=Object.keys(Xk),Qk={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[Mk]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...Yk,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Fv.flatMap(e=>Zk.map(t=>[zv(e,t),{kind:`input`,path:zv(e,t),type:Xk[t],default:Rv[t]}]))),[Lv(`by`)]:{kind:`input`,path:Lv(`by`),default:Iv.by},[Lv(`fps`)]:{kind:`input`,path:Lv(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},$k={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`};function eA(e){let t=e.split(`.`,1)[0];return Object.hasOwn($k,t)?t:void 0}const tA=Object.fromEntries(Ug.map(e=>[e,Dy.get(e)]));function nA(e){return Ug.find(t=>tA[t]===e)}const rA=`ne .tmux.pane ""`;function iA(e,t,n){let r=new Set,i=e=>{for(let t of Dx(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of E_(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(Mk);for(let t of Object.values(e.actions)){r.add(Mk);for(let[,e]of px(t))i(e);let e=`set`in t?Oy.get(t.set):void 0,n=`persist`in t?Dy.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function aA(e,t,n){let r=Hx({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of iA(e,t,n.helpers)){if(Vx(a,r))continue;let e=Qk[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function oA(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const sA=`groups.`,cA=`menus.`,lA=`menupages.`,uA=`edit.`,X=`candybar.`,dA=[sA,cA,lA,uA,X];function fA(e){return dA.some(t=>e.startsWith(t))}function pA(e){let t=oA(e);return dA.find(e=>t.startsWith(oA(e)))}function mA(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function hA(e){return e}function gA(e,t,n){return n===void 0?cA+oA(e)+`.`+oA(t):_A(n)}function _A(e){return cA+oA(e)}function vA(e,t){return e+`.`+t}function yA(e){return lA+e}const bA=[`closeOnPick`,`paged`,`key`,`distribution`],xA=e=>bA.includes(e),SA=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Eh.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function CA(e){for(let t of Object.keys(e))if(!xA(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${SA}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Dh(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Eh.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:kh(r)}}const wA=e=>`from`in e?e.from:e.themes;function TA(e,t,n){return e===`bool`?v_(t)!==null:`min`in e?y_(t,e)!==null:cx(wA(e),n).members.includes(t)}function EA(e,t){if(e===`bool`)return g_.join(` or `);if(!(`min`in e)){let n=wA(e),{members:r}=cx(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function DA(e){return{label:e.label,domain:OA(e.domain)}}function OA(e){return e===`theme`?{themes:ax}:e===`bool`||`min`in e?e:{from:e}}function kA(e,t,n,r,i){let a=Ci(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...g_]}},variables:{}};if(`from`in o)return AA(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return AA(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function AA(e,t,n,r,i){let a={variable:n,key:n,member:t},o=vA(n,t),s=`${t}.open`,c=yA(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:N(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ai(n,yi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const jA=Object.fromEntries(Object.entries(dy).map(([e,t])=>[e,t.spec]));function MA(e){return dy[e].domain}function NA(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:G(e.source,[...n.split(`.`),r])})}}}function PA(e){return NA(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function FA(e){return NA(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function IA(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Wg(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const LA={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},RA={noun:`globals key`,fields:jA,removed:LA},zA={preset:PA(`a preset`),menuGlyph:FA(`a preset`)},BA={noun:`preset globals key`,fields:{...jA,...zA},removed:LA};function VA(e){return ZA(e)&&!(e in zA)}const HA=`is decided later than any rule could be settled`,UA={noun:`editGlobals key`,removed:LA,fields:{...jA,preset:PA(`the editGlobals fragment`),menuGlyph:FA(`the editGlobals fragment`),palette:IA(jA.palette,`the editGlobals fragment`,HA),style:IA(jA.style,`the editGlobals fragment`,HA),effect:IA(jA.effect,`the editGlobals fragment`,HA)}},WA={noun:`theme default key`,fields:{...Object.fromEntries(hy.map(e=>[e,jA[e]])),style:IA(jA.style,`a theme's default`,`is the look that theme wears by name`)}};function GA(e,t){if(!sv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${cv(t)}`,line:G(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Fg(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=lv(e,WA,t,i);a!==null&&(n[r]=a)}return n}function KA(e,t,n){return n===void 0?{}:lv(e,RA,t,n)??{}}function qA(e,t,n){return lv(e,BA,t,n)??{}}function JA(){return Av(BA)}function YA(e,t,n){return lv(e,UA,t,n)??{}}const XA=new Set(Object.keys(jA));function ZA(e){return XA.has(e)}function QA(e){return Object.hasOwn(LA,e)?LA[e]:void 0}function $A(){return[...XA]}const ej=new Map(Object.entries(dy).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function tj(e){let t=new Map;for(let[n,r]of ej){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const nj=/^segments\.([^.]+)\.palette$/,rj=/^presets\.(.+)\.root$/,ij=/^presets\.(.+)\.globals\.([^.]+)$/,aj=/^themeDefaults\.(.+)\.([^.]+)$/;function oj(e){return`presets.${e}.root`}function sj(e,t){return`themeDefaults.${e}.${t}`}const cj=e=>hy.includes(e);function lj(e,t){return`presets.${e}.globals.${t}`}function uj(e){if(ZA(e))return{scope:`globals`,field:e};let t=nj.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=ij.exec(e);if(n&&VA(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=aj.exec(e);if(r&&cj(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=rj.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function dj(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const fj=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],pj=[...fj,`other`],mj={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},hj=ow({fromString:e=>e}),gj=`${X}menu`,_j=`open`,vj={variable:gj,key:gj,member:_j},yj=`edit.mode`,bj=`edit.configure`,xj=`edit.toggle`,Sj=`arrange`,Cj=`${uA}draft.`;function wj(e,t){return`${e}:${t}`}const Tj={variable:yj,key:yj,member:Sj},Ej=Ti(Tj);function Dj(e){try{return hj.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Oj(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Dj(e))return!0;return!1}function kj(e,t){if(mA(e,t,uA,`edit mode`),!Oj(t))return;let{variables:n,actions:r}=Aj();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Aj(){return{variables:{[yj]:{...Ai(yj,yi),within:[vj]},[bj]:{...Ai(bj,yi),within:[Tj]}},actions:{[xj]:N(yj,Sj),"edit.unconfigure":{set:bj,to:yi}}}}const jj=`open`;function Mj(e,t,n,r){let i={variable:e,key:e,member:jj};return r.variables[e]={...Ai(e,yi),...n.length>0&&{within:n}},r.actions[e]=N(e,jj),r.segments[e]={template:Di(e,`(?)`,`✕`),...Nj(n)},wi(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function Nj(e){let[t,...n]=e;return t===void 0?{}:{when:Ti(t,...n)}}const Pj=`none`;function Fj(e){return El(e,`background`)}var Ij=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Lj(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=Rj(n,i),l=c!==Pj,u=l?c===void 0?o:zj(a,c,`bg`):Fj(a);e.bg=u;let d=Rj(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Xh(a,e,t))(u):void 0:zj(a,d,`fg`);return new V({...l&&{bgcolor:z.fromRgba(u)},...f!==void 0&&{color:z.fromRgba(f)}})}function Rj(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function zj(e,t,n){try{return El(e,t)}catch(e){throw e instanceof Tl?new Ij(t,n,e.message):e}}const Bj=`🔧`,Vj={help:[`-h`,`--help`],version:[`-V`,`--version`]},Hj=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],Uj=Object.fromEntries(Hj.map(e=>[e.member,e.label])),Wj={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},Gj=Object.keys(Wj),Kj=ky(e=>Sy[e].place),qj=e=>Object.hasOwn(Wj,e),Jj=(e,t)=>e===t||qj(e)&&Jj(Kj[Wj[e].beside],t),Yj=e=>qj(e)?`${Yj(Kj[Wj[e].beside])} › ${Wj[e].trigger}`:e===`door`?`first line`:Uj[e],Xj=e=>Yj(Kj[e]),Zj=()=>[`door`,...Hj.map(e=>e.member)].flatMap(e=>[e,...Gj.filter(t=>Jj(t,e))]).map(e=>({path:Yj(e),names:Cy.filter(t=>Kj[t]===e)})).filter(({names:e})=>e.length>0),Qj=e=>`${Pv[e].label} is off — turn it on in the settings menu's ${Xj(Pv[e].setting)}, or set globals.${Pv[e].setting}: true`,$j=[...new Set(Object.values(Pv).map(e=>Xj(e.setting)))].join(` or `),eM=Math.max(...Object.values(Sy).map(e=>e.configKey.length))+2,tM=[`✚ inserts`,`✖ removes`,`${Bj} configures`,`↺ resets layout`],nM={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},rM=`
|
|
72
|
+
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function cO(e,t,n){return sO(e,t,n)}function lO(){return{abbrev:{fn:(e,t)=>cD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>lD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>wD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>TD(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>ED(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>DD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>OD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>kD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>AD(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>jD(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>ND(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>PD(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>FD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>ID(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>LD(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>RD(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>zD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>BD(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>VD(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>HD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>UD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>WD(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>GD(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>qD(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>JD(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>YD(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>QD(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>$D(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>eO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>tO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>nO(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>rO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>iO(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>aO(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>oO(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>cO(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function uO(e,t){let n=dO(e),r=n.copy();return r.style=md(n.style,t),r}function dO(e){if(!(e instanceof W))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function fO(e){return{fn:(t=>uO(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function pO(e){return{fn:((t,n)=>uO(n,new V({[e]:z.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function mO(e,t){return new V({[e]:t})}function hO(){let e={};for(let t of cd)e[t]=fO(mO(t,!0)),e[`not_${t}`]=fO(mO(t,!1));for(let[t,n]of Object.entries(ud))e[t]=fO(mO(n,!0));return e}const gO={fn:((e,t)=>uO(t,V.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},_O={fn:((e,t)=>uO(t,new V({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function vO(){return{fg:pO(`color`),bg:pO(`bgcolor`),...hO(),link:_O,style:gO}}function yO(e,t){let n;try{n=Yc(e.trim())}catch(n){throw n instanceof jc?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return bO(n,t,JSON.stringify(e))}function bO(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function xO(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function SO(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const CO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`darken`),t).hex)),wO=xO([`string`,`int`],((e,t)=>Ml(yO(e,`lighten`),-t).hex)),TO={min:0,max:100,note:`0 = from, 100 = toward`},EO=xO([`string`,`string`,`float`],((e,t,n)=>Xc(yO(e,`mix`),yO(t,`mix`),SO(n,`mix`,`percentage`,TO)/100).hex)),DO={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},OO=xO([`string`],(e=>Pl(yO(e,`contrastOn`)).hex)),kO={depth:R.TRUECOLOR},AO=e=>xO([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Fl(yO(t,`readableOn`),yO(n,`readableOn`),SO(r,`readableOn`,`ratio`,DO),i,void 0,a).hex})),jO={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function MO(){let e={};for(let[t,n]of Object.entries(jO)){let r=t;e[n]=xO([`string`,`float`],((e,t)=>{let i={...ml,[r]:SO(t,n,`amount`)};return B.fromRgba(yO(e,n)).applyKey(i).toRgba().hex}))}return e}function NO(e=()=>kO){return{darken:CO,lighten:wO,mix:EO,contrastOn:OO,readableOn:AO(e),...MO()}}function PO(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:bO(El(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function FO(e){return{color:{fn:(t=>El(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new $u(Bu(n),PO(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function IO(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function LO(e){return{frames:{fn:((...t)=>rh(new nh(IO(`frame`,t,dO).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=IO(`color`,t,e=>yO(e,`stepped`));return n[Yu(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function RO(e){return{...vO(),...NO(e)}}new V({color:`red`,dim:!0});const zO=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,BO=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function VO(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(zO);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(BO);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function HO(e){let t=e.match(BO);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function UO(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function WO(e){return e.toLocaleString()}function GO(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function KO(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const qO=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],JO=qO.length;function YO(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(JO-1));o+=qO[t]}return o}function XO(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function ZO(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const QO=Rg(),$O=[...o_];function ek(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>UO(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(Zx(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Xx(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Qx(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>QO,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>$O,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(ZO(`sparkline`,[`width`],n),YO(XO(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>KO(e,GO(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function tk(e,t,n,r){let i=n*6e4-(t*1e3-r);if(i<3e5||e<=0)return-1;let a=e/i;return Math.max(0,Math.round((100-e)/a/6e4))}const nk=e=>({minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e.now().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},etaMinutes:{fn:(t,n,r)=>tk(t,n,r,e.now().getTime()),argTypes:[`float`,`int`,`int`],arity:{kind:`exact`}}});function rk(){return{formatInteger:{fn:e=>WO(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>VO(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>HO(e),argTypes:[`string`],arity:{kind:`exact`}}}}const ik=e=>e.getTime()/1e3,ak=e=>new Date(e*1e3);let ok=null;function sk(e,t){if(ok!==null)throw Error(`a draw is already in progress: draws do not nest`);return ok={at:e,anim:t},{[Symbol.dispose]:()=>{ok=null}}}function ck(e){if((0,J._isComputingDerivation)())throw Error(`the clock was read by a value that keeps its answer (${e}): a template reaching a time variable or a clock function by a name it does not spell (index, get) is not known to read the instant — name it: {{ .clock }}`);if(ok===null)throw Error(`the clock was read outside a draw (${e})`);return ok}const lk={now:()=>ak(ck(`now`).at),animatedAt:()=>ck(`animatedAt`).anim},uk=new Set([`now`,`ago`]);function dk(e,t){return Object.fromEntries(Object.entries(VT(e)).filter(([e])=>uk.has(e)===t))}const fk=dk(()=>{throw Error(`a sprig date function other than now and ago read the clock: add it to SPRIG_CLOCK_READERS`)},!1),pk=[e=>dk(e.now,!0),e=>LO(e.animatedAt),e=>Object.fromEntries(Object.entries(LO(()=>e.now().getTime()/1e3)).map(([e,t])=>[`realtime${e.replace(/^./,e=>e.toUpperCase())}`,t])),nk];function mk(e){return Object.assign({},...e.map(e=>e(lk)))}const hk=new Set(Object.keys(mk(pk)));function gk(e){return new Set([...hk,...Object.keys(mk(e))])}const _k={readableOn:AO},vk=new Set(Object.keys(_k));function yk(e){let{drawnAt:t,extraFuncs:n}=e,r=()=>({depth:t()});return ow({fromString:e=>new W(e),toString:e=>e.plain,isT:e=>e instanceof W,missingKey:`error`,funcs:{...YT(),...lO(),...LE(),...aD(),...jw(),...dE(),...lE(),...fk,...RO(r),...Object.fromEntries(Object.entries(_k).map(([e,t])=>[e,t(r)])),...mk([...pk,...e.clockFuncs??[]]),...ek(),...rk(),...n??{}}})}function bk(e){return xk(e,new Set(e.names()),``)}function xk(e,t,n){return new Proxy(Object.create(null),{has(r,i){if(typeof i!=`string`)return!1;let a=n?`${n}.${i}`:i;if(t.has(a))return!Ck(e,a);let o=`${a}.`;for(let e of t)if(e.startsWith(o))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a)){if(e.getKind(a)!==`document`)return e.read(a);let t=e.readDocument(a);return t.kind===`absent`?void 0:wk(a,t)}let o=`${a}.`;for(let n of t)if(n.startsWith(o))return xk(e,t,a)}})}function Sk(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function Ck(e,t){return e.getKind(t)===`document`&&e.readDocument(t).kind===`absent`}function wk(e,t){switch(t.kind){case`ok`:return t.value;case`pending`:throw new $x(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}const Tk=/\r\n|\r|\n/g,Ek=e=>P(e.replace(Tk,` `).trim());function Dk(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?I(`regex no-match`):P(n.replace(Tk,` `))}}const Ok=e=>{try{return P(JSON.parse(e))}catch(e){return I(`JSON parse failed: ${e.message}`)}};var kk=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const Ak=[`first`,`period`,`change`,`request`,`supersede`];var jk=class{tallies=new Map;constructor(e=Me){this.logger=e}declare(e){let t=`${e.scope}/${e.name}`,n=this.tallies.get(t)??{name:e.name,scope:e.scope,refreshes:{},failures:0,lastMs:null};for(let t of e.refresh)n.refreshes[t]??=0;return this.tallies.set(t,n),new Nk(n,this.logger)}snapshot(){return[...this.tallies.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>({...e,refreshes:{...e.refreshes}}))}totals(){let e=Object.fromEntries(Ak.map(e=>[e,0]));for(let t of this.tallies.values())for(let n of Ak)e[n]+=t.refreshes[n]??0;return e}};const Mk={first:!0,period:!0,change:!0,request:!1,supersede:!0};var Nk=class{constructor(e,t){this.tally=e,this.logger=t}record(){return{...this.tally,refreshes:{...this.tally.refreshes}}}recorded(e,t,n,r){this.tally.refreshes[t]=(this.tally.refreshes[t]??0)+1,this.tally.lastMs=r,n.kind===`failed`&&this.tally.failures++;let i=n.kind===`failed`;if(!i&&!Mk[t])return;let a=i?` reason=${JSON.stringify(n.reason)}`:``;this.logger(i?`warn`:`info`,`${this.tally.name} refresh ${e} by=${t} outcome=${n.kind}${a} took=${r}ms`)}};function Pk(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(E(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function Fk(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const Ik=`session.id`;function Lk(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await pt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?P(r.stdout):I(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function Rk(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await pe(e,{encoding:`utf8`,signal:n});return P(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return I(`file unreadable: ${e}`)}}}}function zk(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?I(`${r.reason} in ${n}`):r}function Bk(e){switch(e.kind){case`never`:return[`first`];case`ttl`:return[`first`,`period`];case`watch_file`:case`key`:case`depends_on`:return[`first`,`change`]}}function Vk(e){let t=!1;return()=>{e(`new-key`,t?`change`:`first`),t=!0}}function Hk(e){try{return b(e)}catch{return e}}function Uk(e){try{return ee(e).isDirectory()}catch{return!1}}function Wk(e){let t=Hk(e);return Uk(t)?{dir:t,name:null,leaf:!0}:Wx(t)}const Gk=e=>`${e.dir}\0${e.name??``}`;var Kk=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:Wk(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=Wk(e);if(t.watcher!==null&&Gk(n)===Gk(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},qk=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:ve(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(ge(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())ge(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};const Jk={read:()=>Oa,drawnAt:()=>{throw new $x(`colorCompatibility.effective`,`the drawn depth has no value yet: no view source is bound`)}};function Yk(e,t){let n=e;for(let e of t.split(`.`)){if(n===Oa)return Oa;if(typeof n!=`object`||!n)return;n=n[e]}return n}function Xk(e,t){if(t===Oa)return Oa;if(t===void 0)return I(`variable "${e}": the view's payload has no "${e}": its declaration did not take the source the preset reads`);switch(typeof t==`object`&&t?t.kind:void 0){case`ok`:case`absent`:case`failed`:return t;default:return I(`variable "${e}": the view's payload holds no source reading at "${e}"`)}}function Zk(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Xx(e):t===`number`?Zx(e):Qx(e)}function Qk(e){return e===`number`?0:e===`boolean`?!1:``}var $k=class e{lastErrors=new Map;policyFaults=J.observable.map(void 0,{deep:!1});watchMgr=new Kk;ttlMgr=new qk;cleanups=[];runs=new Map;newKeys=J.observable.set();reads=new kk;askedBy=new Map;abort=new AbortController;inputs=J.observable.box(Jk,{deep:!1});drawnAt=()=>this.inputs.get().drawnAt();engine=yk({drawnAt:this.drawnAt});sourceNames=J.observable.array([],{deep:!1});publishedNow=(0,J.computed)(()=>({values:this.sourceNames.map(e=>this.store.stored(e)),faults:[...this.policyFaults.values()]}));published(){return this.publishedNow.get()}sessionState;constructor(e,t=``,n,r=null,i=new jk){this.store=e,this.defaultEmptyValue=t,this.parent=r,this.ledger=i,this.sessionState=n}view(){return new e(new pS(this.store),this.defaultEmptyValue,this.sessionState,this,this.ledger)}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,Yx(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,I(t))}declareSourceDocument(e){this.store.defineDerivedDocument(e,()=>Xk(e,this.inputs.get().read(e)))}own(e){this.cleanups.push(e)}declareInput(e,t,n,r,i){this.store.defineDerived(e,n,i,()=>this.inputAt(e,t,n,r))}inputAt(e,t,n,r){let i=this.inputs.get().read(t);if(i===Oa)throw this.lastErrors.delete(e),new $x(e,`variable "${e}" has no value yet: its source has not answered`);if(i===void 0)return this.fallbackOf(e,n,r,`input path "${t}" not found in payload`);try{let t=Zk(i,n);return this.lastErrors.delete(e),t}catch(t){return this.fallbackOf(e,n,r,t instanceof Error?t.message:String(t))}}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,Lk(t,n.cwd,this.abort.signal),Pk(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,Rk(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where);(0,J.runInAction)(()=>this.sourceNames.push(e));let a=this.ledger.declare({name:`var.${e}`,scope:this.parent===null?`directory`:`view`,refresh:Bk(n)});this.registerCachePolicy(e,n,(n,r)=>this.runSource(e,t,i,n,r,a))}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,Ek,t.default,n);case`regex`:return this.scalarPublisher(e,Dk(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=zk(n,t,r);return this.noteOutcome(e,a),this.store.setBox(e,Da(a,i)),a}}documentPublisher(e,t,n){let r=t===void 0?Oa:P(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?F:o,c=zk(s,Ok,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};return u?i=setTimeout(d,250):d(),c}}runSource(e,t,n,r,i,a){this.askedBy.set(e,i);let o=this.reads.run(e,()=>{let r=this.askedBy.get(e)??i,o=Date.now();return t.read().then(e=>a.recorded(`where=${as(t.where)}`,r,n(e),Date.now()-o),e=>{if(e!==this.abort.signal.reason)throw e})});this.track(e,o,r)}track(e,t,n){if((0,J.runInAction)(()=>{t.kind===`started`&&(this.runs.set(e,t.done),this.newKeys.delete(e)),n===`new-key`&&this.newKeys.add(e)}),t.kind===`queued`)return;let r=t.done;r.finally(()=>(0,J.runInAction)(()=>{this.runs.get(e)===r&&(this.runs.delete(e),this.newKeys.delete(e))}))}async inFlight(e){try{await(0,J.when)(()=>this.awaited().length===0,{signal:e})}catch(t){if(!e.aborted)throw t}}awaited(){return[...this.newKeys,...this.parent?.awaited()??[]]}async settled(e){return await this.inFlight(AbortSignal.timeout(e)),this.awaited()}declareTemplate(e,t,n){let r=this.engine.parse(t);this.declareDerived(e,n.type,n.derivation,()=>r.evaluate(bk(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){let n=this.engine.parse(`{{ date .layout now }}`),r={layout:t.format};this.declareDerived(e,`string`,`projection`,()=>n.evaluate(r).map(e=>e.plain).join(``),t.varDefault)}declareDerived(e,t,n,r,i){this.store.defineDerived(e,t,n,()=>{try{let n=Zk(r(),t);return this.lastErrors.delete(e),n}catch(t){let n=eS(t);if(n!==void 0)throw this.lastErrors.delete(e),n;let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),i===void 0)throw Error(`variable "${e}": ${r}`);return i}})}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(Ik);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(Ik):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}bindInputs(e){(0,J.runInAction)(()=>this.inputs.set(e))}getLastError(e){if(!this.declaredHere(e))return this.parent?.getLastError(e);let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return new Map([...this.parent?.cachePolicyFaults()??[],...this.policyFaults])}declaredHere(e){return this.store.has(e)&&!(this.parent?.store.has(e)??!1)}dispose(){this.abort.abort();for(let e of this.cleanups)e();return this.cleanups.length=0,this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:n(`new-key`,`first`);break;case`ttl`:{n(`new-key`,`first`);let e=this.ttlMgr.subscribe(t.durationMs,()=>n(`re-read`,`period`));this.cleanups.push(e);break}case`watch_file`:{n(`new-key`,`first`);let r=this.watchMgr.subscribe(t.path,()=>n(`re-read`,`change`),t=>this.notePolicy(e,I(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template);this.onReads(e,()=>{try{return P(r.evaluate(bk(this.store)).map(e=>e.plain).join(``))}catch(e){return eS(e)===void 0?I(`cache key: ${e instanceof Error?e.message:String(e)}`):Oa}},Vk(n));break}case`depends_on`:this.onReads(e,()=>{let e=t.varNames.map(e=>this.store.changeKey(e));return e.every(e=>e.kind===`ok`)?P(e.map(e=>e.value).join(`,`)):Oa},Vk(n));break}}onReads(e,t,n){let r,i=(0,J.reaction)(t,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===r)&&(r=t.value,n())},{fireImmediately:!0});this.cleanups.push(i)}fallbackOf(e,t,n,r){if(this.recordError(e,r),n!==void 0)return n;try{return Zk(this.defaultEmptyValue,t)}catch{return Qk(t)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){(0,J.runInAction)(()=>{t.kind===`failed`?this.policyFaults.get(e)?.message!==t.reason&&this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)})}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function eA(e,t){let n=dy[e],r=yy(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const tA=Object.fromEntries([...Dy].map(([e,t])=>[t,eA(e,t)])),nA={subscribers:`number`,fps:`number`,shown:`boolean`},rA=Object.keys(nA),iA={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[Ik]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...tA,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(Fv.flatMap(e=>rA.map(t=>[zv(e,t),{kind:`input`,path:zv(e,t),type:nA[t],default:Rv[t]}]))),[Lv(`by`)]:{kind:`input`,path:Lv(`by`),default:Iv.by},[Lv(`fps`)]:{kind:`input`,path:Lv(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},aA={today:`the day the draw is at`,feeds:`the frames a lane was sent up to the draw's instant`,drawing:`who the draw is for`};function oA(e){let t=e.split(`.`,1)[0];return Object.hasOwn(aA,t)?t:void 0}const sA=Object.fromEntries(Ug.map(e=>[e,Dy.get(e)]));function cA(e){return Ug.find(t=>sA[t]===e)}const lA=`ne .tmux.pane ""`;function uA(e,t,n){let r=new Set,i=e=>{for(let t of Dx(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of E_(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(Ik);for(let t of Object.values(e.actions)){r.add(Ik);for(let[,e]of px(t))i(e);let e=`set`in t?Oy.get(t.set):void 0,n=`persist`in t?Dy.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function dA(e,t,n){let r=Hx({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of uA(e,t,n.helpers)){if(Vx(a,r))continue;let e=iA[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function fA(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const pA=`groups.`,mA=`menus.`,hA=`menupages.`,gA=`edit.`,X=`candybar.`,_A=[pA,mA,hA,gA,X];function vA(e){return _A.some(t=>e.startsWith(t))}function yA(e){let t=fA(e);return _A.find(e=>t.startsWith(fA(e)))}function bA(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:G(e.source,[`root`])})}function xA(e){return e}function SA(e,t,n){return n===void 0?mA+fA(e)+`.`+fA(t):CA(n)}function CA(e){return mA+fA(e)}function wA(e,t){return e+`.`+t}function TA(e){return hA+e}const EA=[`closeOnPick`,`paged`,`key`,`distribution`],DA=e=>EA.includes(e),OA=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${Eh.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function kA(e){for(let t of Object.keys(e))if(!DA(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${OA}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Dh(r))throw Error(`{{ menu }} option "distribution" must be one of: ${Eh.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:kh(r)}}const AA=e=>`from`in e?e.from:e.themes;function jA(e,t,n){return e===`bool`?v_(t)!==null:`min`in e?y_(t,e)!==null:cx(AA(e),n).members.includes(t)}function MA(e,t){if(e===`bool`)return g_.join(` or `);if(!(`min`in e)){let n=AA(e),{members:r}=cx(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function NA(e){return{label:e.label,domain:PA(e.domain)}}function PA(e){return e===`theme`?{themes:ax}:e===`bool`||`min`in e?e:{from:e}}function FA(e,t,n,r,i){let a=Ci(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...g_]}},variables:{}};if(`from`in o)return IA(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return IA(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function IA(e,t,n,r,i){let a={variable:n,key:n,member:t},o=wA(n,t),s=`${t}.open`,c=TA(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:N(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:Ai(n,yi),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const LA=Object.fromEntries(Object.entries(dy).map(([e,t])=>[e,t.spec]));function RA(e){return dy[e].domain}function zA(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:G(e.source,[...n.split(`.`),r])})}}}function BA(e){return zA(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function VA(e){return zA(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function HA(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Wg(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:G(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const UA={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},WA={noun:`globals key`,fields:LA,removed:UA},GA={preset:BA(`a preset`),menuGlyph:VA(`a preset`)},KA={noun:`preset globals key`,fields:{...LA,...GA},removed:UA};function qA(e){return rj(e)&&!(e in GA)}const JA=`is decided later than any rule could be settled`,YA={noun:`editGlobals key`,removed:UA,fields:{...LA,preset:BA(`the editGlobals fragment`),menuGlyph:VA(`the editGlobals fragment`),palette:HA(LA.palette,`the editGlobals fragment`,JA),style:HA(LA.style,`the editGlobals fragment`,JA),effect:HA(LA.effect,`the editGlobals fragment`,JA)}},XA={noun:`theme default key`,fields:{...Object.fromEntries(hy.map(e=>[e,LA[e]])),style:HA(LA.style,`a theme's default`,`is the look that theme wears by name`)}};function ZA(e,t){if(!sv(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${cv(t)}`,line:G(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Fg(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:G(e.source,[`themeDefaults`,r])});continue}let a=lv(e,XA,t,i);a!==null&&(n[r]=a)}return n}function QA(e,t,n){return n===void 0?{}:lv(e,WA,t,n)??{}}function $A(e,t,n){return lv(e,KA,t,n)??{}}function ej(){return Av(KA)}function tj(e,t,n){return lv(e,YA,t,n)??{}}const nj=new Set(Object.keys(LA));function rj(e){return nj.has(e)}function ij(e){return Object.hasOwn(UA,e)?UA[e]:void 0}function aj(){return[...nj]}const oj=new Map(Object.entries(dy).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function sj(e){let t=new Map;for(let[n,r]of oj){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const cj=/^segments\.([^.]+)\.palette$/,lj=/^presets\.(.+)\.root$/,uj=/^presets\.(.+)\.globals\.([^.]+)$/,dj=/^themeDefaults\.(.+)\.([^.]+)$/;function fj(e){return`presets.${e}.root`}function pj(e,t){return`themeDefaults.${e}.${t}`}const mj=e=>hy.includes(e);function hj(e,t){return`presets.${e}.globals.${t}`}function gj(e){if(rj(e))return{scope:`globals`,field:e};let t=cj.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=uj.exec(e);if(n&&qA(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=dj.exec(e);if(r&&mj(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=lj.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function _j(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const vj=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],yj=[...vj,`other`],bj={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},xj=ow({fromString:e=>e}),Sj=`${X}menu`,Cj=`open`,wj={variable:Sj,key:Sj,member:Cj},Tj=`edit.mode`,Ej=`edit.configure`,Dj=`edit.toggle`,Oj=`arrange`,kj=`${gA}draft.`;function Aj(e,t){return`${e}:${t}`}const jj={variable:Tj,key:Tj,member:Oj},Mj=Ti(jj);function Nj(e){try{return xj.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function Pj(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&Nj(e))return!0;return!1}function Fj(e,t){if(bA(e,t,gA,`edit mode`),!Pj(t))return;let{variables:n,actions:r}=Ij();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function Ij(){return{variables:{[Tj]:{...Ai(Tj,yi),within:[wj]},[Ej]:{...Ai(Ej,yi),within:[jj]}},actions:{[Dj]:N(Tj,Oj),"edit.unconfigure":{set:Ej,to:yi}}}}const Lj=`open`;function Rj(e,t,n,r){let i={variable:e,key:e,member:Lj};return r.variables[e]={...Ai(e,yi),...n.length>0&&{within:n}},r.actions[e]=N(e,Lj),r.segments[e]={template:Di(e,`(?)`,`✕`),...zj(n)},wi(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function zj(e){let[t,...n]=e;return t===void 0?{}:{when:Ti(t,...n)}}const Bj=`none`;function Vj(e){return El(e,`background`)}var Hj=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function Uj(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=Wj(n,i),l=c!==Bj,u=l?c===void 0?o:Gj(a,c,`bg`):Vj(a);e.bg=u;let d=Wj(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:Xh(a,e,t))(u):void 0:Gj(a,d,`fg`);return new V({...l&&{bgcolor:z.fromRgba(u)},...f!==void 0&&{color:z.fromRgba(f)}})}function Wj(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function Gj(e,t,n){try{return El(e,t)}catch(e){throw e instanceof Tl?new Hj(t,n,e.message):e}}const Kj=`🔧`,qj={help:[`-h`,`--help`],version:[`-V`,`--version`]},Jj=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],Yj=Object.fromEntries(Jj.map(e=>[e.member,e.label])),Xj={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},Zj=Object.keys(Xj),Qj=ky(e=>Sy[e].place),$j=e=>Object.hasOwn(Xj,e),eM=(e,t)=>e===t||$j(e)&&eM(Qj[Xj[e].beside],t),tM=e=>$j(e)?`${tM(Qj[Xj[e].beside])} › ${Xj[e].trigger}`:e===`door`?`first line`:Yj[e],nM=e=>tM(Qj[e]),rM=()=>[`door`,...Jj.map(e=>e.member)].flatMap(e=>[e,...Zj.filter(t=>eM(t,e))]).map(e=>({path:tM(e),names:Cy.filter(t=>Qj[t]===e)})).filter(({names:e})=>e.length>0),iM=e=>`${Pv[e].label} is off — turn it on in the settings menu's ${nM(Pv[e].setting)}, or set globals.${Pv[e].setting}: true`,aM=[...new Set(Object.values(Pv).map(e=>nM(e.setting)))].join(` or `),oM=Math.max(...Object.values(Sy).map(e=>e.configKey.length))+2,sM=[`✚ inserts`,`✖ removes`,`${Kj} configures`,`↺ resets layout`],cM={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},lM=`
|
|
73
73
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
74
74
|
|
|
75
75
|
Usage: cc-candybar [options]
|
|
76
76
|
|
|
77
77
|
Standalone Commands:
|
|
78
|
-
${
|
|
79
|
-
${
|
|
78
|
+
${qj.help.join(`, `).padEnd(25)}Show this help
|
|
79
|
+
${qj.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
|
|
80
80
|
|
|
81
81
|
Debugging:
|
|
82
82
|
CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
|
|
@@ -93,21 +93,21 @@ Configuration:
|
|
|
93
93
|
the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
|
|
94
94
|
and 💾 save, which appears while you have unsaved changes and writes them to
|
|
95
95
|
your config file. Under it are its
|
|
96
|
-
tabs, ${
|
|
97
|
-
${
|
|
96
|
+
tabs, ${Jj.map(e=>e.label).join(`, `)};
|
|
97
|
+
${Yj.session} holds quick actions and commands, ${Yj.layout} a new preset.
|
|
98
98
|
A change applies to this session at once.
|
|
99
99
|
Where each setting is in the menu: the globals field that sets it in a
|
|
100
100
|
config file, then the control's label.
|
|
101
|
-
${
|
|
101
|
+
${rM().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${Sy[e].configKey.padEnd(oM)}${Sy[e].label}`)]).join(`
|
|
102
102
|
`)}
|
|
103
103
|
The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
|
|
104
104
|
failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
|
|
105
105
|
|
|
106
106
|
Anywhere the bar shows (?), clicking it reveals these same instructions
|
|
107
|
-
in place. In edit mode: ${
|
|
107
|
+
in place. In edit mode: ${sM.join(`, `)}.
|
|
108
108
|
|
|
109
|
-
Animation lanes (experimental; toggles in the settings menu's ${
|
|
110
|
-
${Fv.map(e=>` ${Pv[e].label}\n${
|
|
109
|
+
Animation lanes (experimental; toggles in the settings menu's ${aM}):
|
|
110
|
+
${Fv.map(e=>` ${Pv[e].label}\n${cM[e].map(e=>` ${e}`).join(`
|
|
111
111
|
`)}`).join(`
|
|
112
112
|
`)}
|
|
113
113
|
|
|
@@ -141,14 +141,14 @@ Subcommands:
|
|
|
141
141
|
${Fv.join(`, `)}:
|
|
142
142
|
the experimental lane this stream serves,
|
|
143
143
|
which streams only while its toggle in the settings
|
|
144
|
-
menu's ${
|
|
144
|
+
menu's ${aM} is on.
|
|
145
145
|
bar-pane PANE Draw the bar of the Claude Code session in tmux
|
|
146
146
|
pane PANE (e.g. %3) in this pane, as the daemon
|
|
147
147
|
pushes it, while this pane is shown. The bar is
|
|
148
148
|
drawn at PANE's width, so split PANE with -v for a
|
|
149
149
|
pane under it that fits. Experimental:
|
|
150
150
|
runs while ${Pv.pane.label} is on in the settings
|
|
151
|
-
menu's ${
|
|
151
|
+
menu's ${nM(Pv.pane.setting)}.
|
|
152
152
|
|
|
153
153
|
Config tooling:
|
|
154
154
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -174,31 +174,31 @@ Config tooling:
|
|
|
174
174
|
config [--json] The effective merged config. (All three query the
|
|
175
175
|
running daemon; none spawn one.)
|
|
176
176
|
|
|
177
|
-
`,
|
|
178
|
-
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return UM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${YM[e]}`)])}}},ZM="re-run `cc-candybar install`";function QM(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${ZM}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${ZM}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${ZM}`)}const $M={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${ZM}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${ZM}`};case`lost`:return UM([...QM(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function eN({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function tN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?ZM:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function nN(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${tN(e,`native`)}`];let{bundle:i,source:a}=eN(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${tN(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${tN(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const rN=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},iN={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${rN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:UM([...new Set(i.flatMap(e=>nN(n,r,e)))])}};function aN({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||ir(e.identity,t.value.through)):[]}function oN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const sN={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?oN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return UM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=aN(e.value,n),u=UM([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${tr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${tr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&sr(o.charge.bytes,s)?[`the daemon holds ${dr(o.charge)} of its ${tr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},cN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function lN(e,t){let n=AM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?MM(e.terminal):{kind:`unknown`}}function uN({identified:e,tmuxClient:t},n){let r=jM(e),i=lN(e,n),a=AM(e)===null?cN:`${cN}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${NM}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const dN={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return UM(uN(t,n))}}},fN=e=>e.filter(e=>e.role===`statusline`),pN={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>gN(e,mN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:hN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:rN(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},mN=e=>{let t=fN(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},hN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function gN(e,t){let n=PM(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return hN(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return LM(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const _N=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function vN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return jM(e);case`bundling`:case`unread`:case`configured`:return[bM(e.name),e.version].filter(e=>e!==null).join(` `)}}function yN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return AM(e);case`bundling`:case`unread`:return bM(e.name);case`configured`:{let t=bM(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function bN(e){let t=yN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${_N(e.glyphs)}`}}const xN={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=bN(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=vN(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${_N(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=gM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:TM(i.version,e);if(t===!0)return{ok:!0};let n=bM(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${_N(n)} — set a Nerd Font as its font`)}}}};function SN(e){return e.join(`, `)}function CN(e){return`or set missingData: "ignore" on ${SN(e)}`}function wN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${SN(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${SN(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${CN(t)}`]:[`${SN(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${CN(t)}`]}function TN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${SN(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${SN(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${SN(n)}: ${rN(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${SN(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${SN(n)}`]:[]}const EN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>UM([...wN(e.pullRequests),...TN(e.rateLimits,t)])};function DN({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${BM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const ON=[XM,iN,sN,$M,dN,KM,qM,JM,pN,xN,EN,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${rN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:UM(e.value.flatMap(DN))}],kN=ON.filter(e=>e.takesMark);function AN(e){return ON.map(t=>({check:t,verdict:t.probe(e)}))}function jN(e){return ON.find(t=>t.name===e)}const MN=`${X}doctor.`;function NN(e){let t=`${MN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function PN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?AM(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function FN(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function IN(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=eN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const LN=e=>`${e>=0?`+`:``}${tr(e)}`;function RN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${oN(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${aN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${LN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function zN(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function BN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>VN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=fN(r.flatMap(e=>e.bars));return`frames=${fM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function VN(e){let t=PM(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function HN(e){let t=FM(e,WM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function UN(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function WN(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=bN(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function GN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function KN(e){return e.flatMap(({check:e,verdict:t})=>{let n=NN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:h_},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:GN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const qN={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function JN(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries(qN).map(([t,n])=>[`${e}${t}`,n]))}}const YN=`armed`,XN=`disarmed`,ZN=`.armed`,QN=e=>e.endsWith(ZN);function $N(e,t,n){let r=`${e}${ZN}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${YN}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:YN},[a]:{set:r,to:XN},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:XN}},disarm:a}}const eP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function tP(e){return typeof e==`string`&&eP.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function nP(e){let t=tP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const rP=[`/compact`,`/model`],iP=`/clear`;function aP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=$N(`${e}clear`,{arm:iP,confirm:`${iP} ✓ confirm`},[n]);return{template:rP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${rA} }}`,actions:{...Object.fromEntries(rP.map(e=>[t(e),{slash:nP(e)}])),...r.actions,[n]:{slash:nP(iP)}},variables:r.variables,disarm:r.disarm}}const oP=Array.from({length:10},(e,t)=>(t+1)*1e5),sP=oP[0],cP=oP[oP.length-1];function lP(e){let t;try{t=eo(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=sP&&n<=cP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${sP}–${cP} tokens)`)}function uP(e,t){let n=Math.min(t??cP,cP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:oP.filter(e=>e<r).at(-1)??0,higher:oP.find(e=>e>r&&e<=n)??0}}function dP(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${rA} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:nP(`/autocompact auto`)},...Object.fromEntries(oP.map(t=>[`${e}${t}`,{slash:nP(`/autocompact ${t}`)}]))}}}const fP=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,pP=`${X}edit`,mP=`${X}toolbar`,hP=JN(X),gP=`${X}commands`,_P=aP(`${gP}.`),vP=`${X}autocompact`,yP=dP(`${vP}.`,fP),bP=e=>({kind:`segment`,name:e}),xP=`${X}tab`,SP=e=>`${xP}.${e}`,CP=e=>`${SP(e)}.toggle`,wP=e=>({variable:xP,key:xP,member:e}),TP=`${X}save`,EP=`${X}preset.save`,DP=`${X}preset.delete`,OP=e=>`${X}${e}`,kP=e=>`${X}apply.${e}`,AP=e=>`${X}reset.${e}`,jP=`${X}themeDefault.save`,MP=`${X}themeDefault.differs`,NP=`${X}themeDefault.theme`,PP={when:`{{ .${MP} }}`,template:`{{ action "${jP}" (printf "⤓ default for %s" .${NP}) }} {{ swatch "${kP(`theme`)}" .${NP} }}`},FP=`${X}resetAll`,IP=`${gj}.toggle`,LP=`${X}undo`,RP=`${X}back`,zP=`${RP}.step`,BP=`${X}navigation.back`,VP=RP,HP={template:`{{ if gt .${BP} 0 }}{{ action "${RP}" "◁" }}{{ else }}{{ fg (${iM}) "◁" }}{{ end }}`},UP=`${X}redo`,WP=`${X}doctor`,GP=`${WP}.run`,KP=e=>`${WP}.fix.${e}`,qP=(e,t)=>`${WP}.mark.${e}.${t}`,JP=e=>`${WP}.${e}`,YP={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},XP=_A(`${X}pickers`),ZP=e=>`${X}${e}`,QP=e=>`${ZP(e)}.toggle`,$P=e=>qj(e)?_A(`${X}${e}Pickers`):XP,eF=e=>{let t=$P(Kj[Wj[e].beside]);return{variable:t,key:t,member:e}},tF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${DP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},nF=(e,t)=>`${X}list.${e}.${t}`,rF=e=>`${X}resettable.${e}`,iF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${rF(e)}`).join(` `)})`,aF=Fv.map(e=>[Pv[e].setting,e]),oF={variables:{},actions:{},segments:{}},sF=Object.fromEntries(aF.map(([e,t])=>[e,Mj(`${X}help.${e}`,nM[t],[],oF)])),cF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],lF=e=>{let t=t=>`.${zv(e,t)}`,n=cF.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${Sy[Pv[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},uF=`{{ if eq .${Lv(`by`)} "feed" }} {{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ end }}`,dF=Object.fromEntries(aF.map(([e,t])=>[e,lF(t)])),fF=Object.keys(Sy).map(e=>{let t=Sy[e],n=MA(t.configKey),r=kA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,kP(e),$P(Kj[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>tF[e])}}),pF=e=>fF.filter(t=>Kj[t.name]===e),mF=e=>fF.filter(t=>Jj(Kj[t.name],e)),hF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${iF(mF(e).map(e=>e.name))}))`,gF=e=>Gj.filter(t=>Wj[t].beside===e),_F=e=>pF(e).flatMap(e=>[kF(e),...[sF[e.name]].filter(e=>e!==void 0),...gF(e.name).map(e=>wi(ZP(e),eF(e),IF(e),`drop`))]);new Set(fF.flatMap(e=>[e.sessionKey,e.configKey]));const vF=$N(FP,{arm:`⟲`,confirm:`⟲ reset all?`},fF.map(e=>AP(e.name))),yF=[`unsaved`,`history.undo`,`history.redo`],bF=e=>`${X}${e}`,xF=bF(`unsaved`),SF=(e,t)=>({body:t,shown:`(gt .${bF(e)} 0)`}),CF=[SF(`unsaved`,`{{ action "${TP}" (printf "💾 save %d" .${xF}) }}`),SF(`history.undo`,`{{ action "${LP}" "↶" }}`),SF(`history.redo`,`{{ action "${UP}" "↷" }}`),{body:vF.template,shown:`(or ${iF(fF.map(e=>e.name))} ${vF.armed})`}],wF={when:`{{ or ${CF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+CF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},TF=[{step:vF,place:`door`},{step:_P,place:`session`}],EF=e=>e.map(e=>e.step.disarm),DF=EF(TF),OF=EF(TF.filter(e=>e.place!==`door`));function kF(e){let t=OP(e.name);return e.control.kind===`inline`?bP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>bP(nF(e.name,n)))},`drop`)}function AF(e){return e===gj}function jF(e){let t=bP(gj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[jF(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function MF(e){return NF(e)>0?e:jF(e)}function NF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&AF(n.name)&&(t+=1);return t}function PF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&AF(e.name)||e.opens!==void 0&&PF(e.opens.body,!0):e.children.some(e=>PF(e,n))}const FF={door:{direction:`horizontal`,content:[bP(VP)],after:[bP(pP),bP(TP)]},session:{direction:`vertical`,content:[bP(mP),{kind:`container`,direction:`horizontal`,children:[bP(gP),bP(vP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[bP(EP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[bP(WP),...ON.map(e=>bP(JP(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[bP(jP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function IF(e){let{direction:t,content:n,after:r}=FF[e];return{kind:`container`,direction:t,children:[...n,..._F(e),...r]}}function LF(e){return e.kind===`segment`?AF(e.name)?wi(e.name,vj,zF,`above`):e:BF(e)}function RF(){return{kind:`container`,direction:`vertical`,children:[IF(`door`),{kind:`container`,direction:`horizontal`,children:Hj.map(({member:e})=>wi(SP(e),wP(e),IF(e),`drop`))}]}}const zF=RF();function BF(e){return{...e,children:e.children.map(e=>LF(e))}}function VF(e){let t={variables:{[gj]:Ai(gj,yi)},actions:{[IP]:N(gj,_j),[gj]:{do:[IP,...DF]},[GP]:{doctor:`run`},...hP.actions,..._P.actions,...yP.actions,[TP]:{save:!0},[LP]:{undo:!0},[zP]:{back:!0},[RP]:{do:[zP,...DF]},[UP]:{redo:!0},[EP]:{preset:`save`},[jP]:{themeDefault:`save`},[DP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[gj]:{template:`{{ $door := ${Oi(gj,ki(e),ki(`✖`))} }}{{ if ${Ei(vj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+uF},[mP]:{template:hP.template},[gP]:{template:_P.template,when:_P.when},[vP]:{template:yP.template,bg:yP.bg,when:yP.when},[VP]:HP,[TP]:wF,[jP]:PP,[EP]:{template:`{{ action "${EP}" "+ preset" }}`},[WP]:{template:`{{ action "${GP}" "🩺 doctor" }}`},[pP]:{template:`{{ action "${xj}" "✎ arrange" "✎ done" }}`}}};t.variables[MP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[NP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[BP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of yF)t.variables[bF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[xP]=Ai(xP,`session`);for(let{member:e,label:n}of Hj){t.actions[CP(e)]=N(xP,e),t.actions[SP(e)]={do:[CP(e),...OF]};let r=hF(e);t.segments[SP(e)]={template:`{{ ${Oi(SP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,_P.variables,vF.variables),UF(t),HF(t),t}function HF(e){for(let t of ON){let n=NN(t.name),r=KP(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?zM:[];for(let n of i)e.actions[qP(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${qP(t.name,e)}" "${YP[e]}" }}`).join(``);e.segments[JP(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${m_}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function UF(e){for(let t of fF){Object.assign(e.actions,t.control.actions);let n=AP(t.name);e.actions[n]={reset:t.configKey},e.variables[rF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${rF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[OP(t.name)]={template:`${t.control.template}${dF[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[nF(t.name,r)]=n})}Object.assign(e.actions,vF.actions),Object.assign(e.variables,oF.variables),Object.assign(e.actions,oF.actions),Object.assign(e.segments,oF.segments);for(let t of Gj){let n=eF(t);e.actions[QP(t)]=N(n.key,n.member),e.segments[ZP(t)]={template:`{{ action "${QP(t)}" ${hF(t)(Wj[t].trigger)} }}`}}}function WF(e){let{variables:t,actions:n}=Aj();Object.assign(e.variables,t),Object.assign(e.actions,n)}function GF(e){let t=VF(e.globals.menuGlyph??`🍫`);WF(t);let n={...e.presets},r=[];for(let t of Qb(e.presets)){let{node:i}=tx(e,t),a=LF(MF(i));r.push(a),n[t]={...ex(e.presets,t),root:a}}let i=aA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const KF=`${uA}live`,qF=[`☐ live`,`☑ live`],JF=`${uA}done`,YF=`${uA}cancel`,XF=`${uA}rewind`,ZF=`${uA}changes`,QF=`(gt .${ZF} 0)`,$F=`(or ${QF} (gt .${xF} 0))`,eI={variable:KF,key:KF,member:`open`};function tI(e){return`${uA}configuring.p${e}`}function nI(e){return`and ${Ei(Tj)} (not ${Ei(eI)}) (ne .${tI(e)} "true")`}function rI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${bj} "${Ci(e)}")`).join(` `)} false }}`}}function iI(e,t,n){return`{{ if ${nI(e)} }}${t}{{ else }}${n}{{ end }}`}const aI=`{{ and ${Ei(Tj)} .preset.customized }}`,oI=fA;function sI(e){return new Map([...ox(e),...lI(e)])}const cI=`${uA}addable`;function lI(e){return new Map([[cI,{members:Object.keys(e.segments).filter(e=>!oI(e)),library:{groups:pj.map(e=>({id:e,label:mj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function uI(e,t,n){return n.segments[e]={template:t,when:Ej,bg:Pj},{kind:`segment`,name:e}}function dI(e,t,n){let r=`${uA}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function fI(e){return`{{ if ${Ei(Tj)} }}${e}{{ end }}`}function pI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(Tj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function mI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function hI(e,t,n){return`${Cj}${e}.${t}.${n}`}function gI(e,t,n,r){let i=S_(n),a=`${uA}${e.presetIdent}`,o=wj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=_A(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:yi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:bj,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=hI(e.presetIdent,i,r),l=`${Cj}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:G_(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=kA(DA(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return wi(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${Bj}" }}`,ref:{variable:bj,key:bj,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const _I=`${uA}label:`;function vI(e){if(e.startsWith(_I)){let t=e.slice(_I.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function yI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${_I}${a}:${e.name}`;i.segments[o]={template:`{{ "${Ci(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(B_.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...wi(o,r.ref,r.body,`drop`,pI([r.ref],`{{ ${nI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function bI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${uA}${i}.insert.${t}`,s=`${uA}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:cI,anchor:n,relation:r};let c=hA(o),l=gA(s,o,void 0),u=yA(l),d=vA(l,c);return a.variables[l]={...Ai(l,yi),within:[Tj]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=N(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Yh}`}) $m }}{{ end }}`}}function xI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!oI(e.name)),i=e=>xI(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=T_(o,i);if(oI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[bI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=bI(t,u,c,`after`),f=dI(t,u,c),p=t.segments[o.name],m=gI(t,u,o,V_(p)),h=fI(f),g=fI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>uI(e.host,e.template,t.artifacts)),{...yI(o,p,t,m),lead:h,trail:g},{...s,when:iI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},uI(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:pI(mI(n),iI(t.presetIdent,`true`,e.when))}}}function SI(e,t,n,r,i,a,o){let s=`${uA}${t}.resetLayout`,c=`${uA}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:aI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},CI(e,o)]}}function CI(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),CI(n,t)]}:{...e,children:[...e.children,t]}}function wI(e,t,n,r,i,a){let{node:o}=tx(e,t),s={presetIdent:oA(t),rootKey:oj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=xI(o,s);return n.variables[tI(s.presetIdent)]=rI(s.configured),SI(c,s.presetIdent,s.rootKey,n,r,i,a)}function TI(e){let t={variables:{},actions:{},segments:{}},n=Mj(`${uA}help`,tM,[Tj],t);t.variables[KF]=Ai(KF,yi),t.actions[KF]=N(KF,eI.member),t.segments[KF]={template:Di(KF,...qF),when:Ej};let r={kind:`segment`,name:KF},i=n;t.variables[ZF]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[JF]={do:[TP,xj]},t.segments[JF]={template:`{{ if ${$F} }}{{ action "${JF}" "✓ save" }}{{ else }}{{ action "${JF}" "✓ done" }}{{ end }}`,when:Ej},t.actions[XF]={rewind:!0},t.actions[YF]={do:[XF,xj]},t.segments[YF]={template:`{{ action "${YF}" "↩ cancel" }}`,when:`{{ and ${Ei(Tj)} ${QF} }}`};let a=[{kind:`segment`,name:JF},{kind:`segment`,name:YF}],o={...e.presets},s=[];for(let n of Qb(e.presets)){let c=wI(e,n,t,a,r,i);s.push(c),o[n]={...ex(e.presets,n),root:c}}let c=aA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function EI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function DI(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function OI(e,t,n){let r=w_(e,new Set(n.map(C_).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const kI=/^-?\d+$/;function AI(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function jI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!kI.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function MI(e,t,n){return r=>r?kI.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function NI(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!kI.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function PI(e){return e===`config`?`set-config`:`set-state`}function FI(e,t,n){return t.kind===`int`?jI(`menu page "${e}"`):t.kind===`range`?MI(t.min,t.max,`${n} stepper "${e}"`):AI(t.allowed,`${n} "${e}"`,PI(n))}function II(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:NI(e,n,t)}))}function LI(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of II(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,FI(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function RI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};LI(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=LI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const zI=RI({},`config`,KI);function BI(e,t){return zI.register(e,t)}function VI(e){return zI.gateFor(e)}function HI(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[EI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[EI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.insertSegmentFrom,t).members.map(t=>EI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function UI(e,t){let n=tj(e).get(t);return n===void 0?null:String(n)}function WI(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?uj(n.persist):null;e?.scope===`preset-root`&&t.add(oj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function GI(e){let t=sI(e);return[...WI(e),...Object.values(e.actions).flatMap(e=>HI(e,t))]}function KI(e){return II(GI(e),`config`)}function qI(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:XI(t.segments,JI(t.segments,e.segments??{})),root:Jb(e.root??Vb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:XI(t.presets,YI(t.presets,e.presets??{})),themeDefaults:XI(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function JI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function YI(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function XI(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function ZI(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${M_.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):eL(e,`${t}.cache`,n.cache)}function QI(e){return{required:!0,json:tL(),parse:(t,n,r,i)=>ZI(t,n,i,e)??void 0}}const $I={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&rL(n)?{ttl:n}:mv(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return mv(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=Ev(`cache.watch_file`,n);return r===null?{watch_file:n}:mv(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:mv(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:mv(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:mv(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function eL(e,t,n){return hv(e,$I,t,n)}function tL(){return Nv($I)}const nL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function rL(e){return nL.test(e)}const iL=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function aL(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function oL(e){let t=iL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${aL(t)}`}function sL(e){let t=iL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${aL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const cL=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),lL=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function uL(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function dL(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?lL.get(e.field):void 0;if(n===void 0){let e=[...lL.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${uL(n.declare)} under a name of your own`}function fL(e,t,n){if(n===void 0)return{};if(!sv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${cv(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=gv(e,IL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function pL(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${cv(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function mL(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return rv(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const hL={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:mv(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?gL(e,t,n):mv(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:mv(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function gL(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return mv(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:mv(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function _L(){return{required:!1,json:Nv(hL),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:hv(e,hL,`${t}.parse`,r.parse)??void 0)}}function vL(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>sv(r.parse)&&`json`in r.parse?yL(e,t,r.default):iv(e,t,r,`default`)}}function yL(e,t,n){if(n!==void 0)return bL(n)?n:mv(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function bL(e){return e!==null&&xL(e)}function xL(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(xL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(xL)}default:return!1}}const SL={value:pL(),default:bv()};function CL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:cL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const wL={path:CL(),type:Ov([`string`,`number`,`boolean`]),default:mL()},TL={name:Tv(),default:bv()},EL={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:_L(),cache:QI(`file`),default:vL()},DL={command:Tv(),parse:_L(),cache:QI(`shell`),default:vL()};function OL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const kL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:mL()},AL=OL(`a template variable recomputes whenever a variable it reads changes`),jL={layout:Tv(),default:bv()},ML=OL(`a time variable reads the instant its render is drawn at`),NL={key:Tv(),default:bv()},PL=`kind`;function FL(e,t,n={}){return{..._v(PL,e,t),parse:(r,i,a)=>{uv(r,n,i,a);let o=dv(r,t,i,a);return o===null?null:{kind:e,...o}}}}const IL={tag:PL,noun:`source kind`,memberNoun:`variable`,arms:{literal:FL(`literal`,SL),input:FL(`input`,wL),env:FL(`env`,TL),file:FL(`file`,EL),shell:FL(`shell`,DL),template:FL(`template`,kL,AL),time:FL(`time`,jL,ML),state:FL(`state`,NL)},retired:{git:dL}};function LL(){return Mv(IL)}function RL(){return{type:`object`,additionalProperties:LL()}}const zL=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`}]]);function BL(e){let t=zL.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment)`}}const VL=/^[A-Za-z_][A-Za-z0-9_]*$/,HL={pattern:VL.source},UL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},WL={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...HL}}}]},default:UL}},GL=[`label`,`domain`,`default`],KL=[`min`,`max`,`step`,`atLeast`];function qL(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function JL(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return qL(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return qL(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?qL(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(sv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!KL.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:qL(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return qL(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function YL(e,t,n){if(!sv(n))return qL(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))GL.includes(r)||qL(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${GL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||qL(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=JL(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!XL(n.default)||!W_(o,n.default)?qL(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function XL(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const ZL={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${R_}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function QL(e){return B_.includes(e)}function $L(){return{required:!1,json:{type:`object`,propertyNames:{...HL,not:{enum:[...B_]}},additionalProperties:WL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return qL(e,a,`${a} must be an object of name → { label, domain, default }, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!VL.test(t)){qL(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(QL(t)){qL(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${ZL[t]}`);continue}let r=YL(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const eR=dA.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function tR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${eR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!fA(i)?i:qL(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${dA.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function nR(){return{required:!1,json:{type:`object`,propertyNames:HL,additionalProperties:UL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return qL(e,a,`a placement's "settings" must be an object of setting name → value, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))XL(n)?o[t]=n:qL(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function rR(e){return new Set(Object.keys(e.segments).filter(e=>!fA(e)))}function iR(e,t,n){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${cv(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=lv(e,n.has(i)?uR:lR,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function aR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?mv(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${BL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function oR(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function sR(){return{required:!1,json:RL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return fL(e,`${t}.${n}`,i)}}}const cR={template:aR(),description:bv(),group:Ov(fj),width:oR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:sR(),settings:$L(),missingData:Ov(F_)},lR={noun:`segment key`,fields:cR},uR={noun:`segment key`,fields:{...cR,template:bv()}},dR=`#/definitions/LayoutNode`,fR={kind:`container`,direction:`vertical`,children:[]};function pR(e){return{required:!0,json:{const:e},parse:()=>e}}function mR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function hR(){return{required:!0,json:{enum:[...b_]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&b_.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${b_.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function gR(e){return{required:!0,json:{type:`array`,items:{$ref:dR}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${cv(a)}`,line:G(t.source,[`root`])}),[])}}}const _R={noun:`layout-node key`,fields:{kind:pR(`segment`),name:mR(),when:bv(),id:tR(),settings:nR()}},vR=()=>Ov(Eh),yR={noun:`layout-node key`,fields:{kind:pR(`container`),direction:hR(),children:gR(vv(()=>wR)),when:bv(),distribution:vR()}};function bR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const xR={noun:`layout-node key`,fields:{seg:bR(),when:bv(),id:tR(),settings:nR()}},SR={noun:`layout-node key`,fields:{h:gR(vv(()=>wR)),when:bv(),distribution:vR()}},CR={noun:`layout-node key`,fields:{v:gR(vv(()=>wR)),when:bv(),distribution:vR()}},wR=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),fR):{kind:`segment`,name:n};if(!sv(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${cv(n)}`,line:G(e.source,[`root`])}),fR;if(n.kind===`container`)return lv(e,yR,t,n)??fR;if(n.kind===`segment`)return lv(e,_R,t,n)??fR;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
177
|
+
`,uM=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,dM={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function fM(e){let t=e[dM.socket]??``,n=e[dM.pane]??``;if(t===``||n===``)return null;let r=e[dM.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const pM=[`moves`,`can-move`,`still`];function mM(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const hM=[`carried`,`missing`,`unanswered`];function gM(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:mM(e)===`no`?`unanswered`:`missing`}function _M(e){return{path:e.transcript_path,answered:mM(e)===`yes`}}const vM=[...pM,`failed`,`drawing`],yM=[`statusline`,`frames`],bM=e=>e?.kind===`frames`?`frames`:`statusline`;var xM=class{seen=new Map;see(e,t,n,r){let i=bM(t.client),a=JSON.stringify([e,i]),o=this.seen.get(a);o!==void 0&&o.order>r||(this.seen.delete(a),this.seen.set(a,{sessionId:e,said:{...t,role:i},at:n,order:r}),this.seen.size>64&&this.seen.delete(this.seen.keys().next().value))}list(e){return[...this.seen.values()].map(({sessionId:t,said:n,at:r})=>({...n,sessionId:t,ago:e-r}))}ofSession(e,t){return this.list(t).filter(t=>t.sessionId===e)}};const SM={kitty:{label:`kitty`,xtversion:`kitty`,program:null,programVersion:!0,term:`xterm-kitty`,links:{since:`0.19.0`},glyphs:{kind:`bundled`,since:`0.36.0`}},wezterm:{label:`WezTerm`,xtversion:`WezTerm`,program:`WezTerm`,programVersion:!0,term:`wezterm`,links:{since:null},glyphs:{kind:`bundled`,since:`20230712`}},ghostty:{label:`Ghostty`,xtversion:`ghostty`,program:`ghostty`,programVersion:!0,term:`xterm-ghostty`,links:{since:null},glyphs:{kind:`bundled`,since:null}},iterm2:{label:`iTerm2`,xtversion:`iTerm2`,program:`iTerm.app`,programVersion:!0,term:null,links:{since:`3.1`},glyphs:{kind:`configured`}},alacritty:{label:`Alacritty`,xtversion:`alacritty`,program:null,programVersion:!0,term:`alacritty`,links:{since:`0.11.0`},glyphs:{kind:`configured`}},"apple-terminal":{label:`Terminal`,xtversion:null,program:`Apple_Terminal`,programVersion:!0,term:null,links:null,glyphs:{kind:`unread`}},vscode:{label:`VS Code`,xtversion:null,program:`vscode`,programVersion:!1,term:null,links:{since:`1.72`},glyphs:{kind:`unread`}}},CM=e=>SM[e];function wM(e){return CM(e).glyphs.kind===`bundled`}function TM(e){return CM(e).glyphs.kind===`configured`}const EM=e=>CM(e).label,DM=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function OM(e,t){let n=t.codePointAt(0);return DM.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&jM(e,t)===!0)}const kM=Object.keys(SM);function AM(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function jM(e,t){let n=AM(e),r=AM(t);if(n===null)return null;for(let e=0;e<Math.max(n.length,r.length);e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i}return!0}function MM(e){for(let t of kM){let n=CM(t).xtversion;if(n!==null&&e.toLowerCase().startsWith(n.toLowerCase())){let r=e.slice(n.length).replace(/^[\s(]+/,``);return{name:t,version:/^[^\s)]+/.exec(r)?.[0]??null}}}return null}function NM(e){let t=kM.find(t=>CM(t).term===e);return t===void 0?null:{name:t,version:null}}function PM(e){let t=MM(e.termtype)??NM(e.termname);if(t!==null)return{kind:`known`,terminal:t};let n=/^[^\s(]*/.exec(e.termtype)[0];return n===``?{kind:`unnamed`,term:e.termname}:{kind:`unknown`,called:n}}function FM(e){let t=e.TERM_PROGRAM,n=kM.find(e=>CM(e).program===t),r=n===void 0?NM(e.TERM):{name:n,version:CM(n).programVersion?e.TERM_PROGRAM_VERSION??null:null};return r===null?t===void 0||t===`tmux`?{kind:`unnamed`,term:e.TERM??``}:{kind:`unknown`,called:t}:{kind:`known`,terminal:r}}function IM(e){switch(e.kind){case`known`:return EM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function LM(e){switch(e.kind){case`known`:return EM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function RM({name:e,version:t}){let n=CM(e).links;if(n===null)return{kind:`none`};if(n.since===null)return{kind:`draws`};if(t===null)return{kind:`unsaid`,since:n.since};let r=jM(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const zM=kM.filter(e=>CM(e).links!==null).map(EM).join(`, `);function BM(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!oo(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!oo(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function VM(e,t){if(e.kind===`failed`)return e;let n=e.value.find(e=>Object.hasOwn(e.env,t));return{kind:`ok`,value:n===void 0?{kind:`unset`}:{kind:`set`,value:n.env[t],from:{scope:n.scope,path:n.path}}}}const HM=[`managed`,`project`],UM=e=>!HM.includes(e.scope),WM={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:ro(t.projectDir)}),user:e=>({scope:`user`,path:e})},GM=[`drawn`,`boxes`],KM=1024*1024,qM=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function JM(e){switch(e.kind){case`claude-settings`:return`${e.kind} ${e.path.join(`.`)}=${JSON.stringify(e.value)} file=${JSON.stringify(e.file.path)} scope=${e.file.scope}`;case`post-mortems-read`:return`${e.kind} through=${e.through}`}}function YM(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const XM=dM.truecolor;function ZM(e,t){switch(e.kind){case`unreported`:return{ok:!1,reason:"the client reported no tmux facts — re-run `cc-candybar install` to stage a current client"};case`outside`:return{ok:!0};case`inside`:return e.client.kind===`failed`?{ok:!1,reason:`tmux could not be asked: ${e.client.reason}`}:e.client.value===null?{ok:!0}:t(e.client.value,e.hint)}}const QM={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>ZM(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=VM(t.sources,XM);if(r.kind===`failed`)return{ok:!1,reason:r.reason};let i=r.value;if(i.kind===`set`&&typeof i.value==`string`&&i.value!==``)return{ok:!1,reason:`${XM} is set in ${i.from.path} — restart Claude Code to apply`};let a=`Claude Code renders the bar in 256 colours inside tmux`,o=e=>({ok:!1,reason:a,fix:{kind:`claude-settings`,file:e,path:[`env`,XM],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=WM[i.from.scope](i.from.path,t.at);return s===null?{ok:!1,reason:`${a} — the value that counts is in managed settings, ${i.from.path}: set ${XM} to "1" there`}:o(s)})},$M={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>ZM(e,e=>e.utf8?{ok:!0}:{ok:!1,reason:"tmux draws this terminal without UTF-8, so every glyph on the bar arrives as `_` — attach with `tmux -u`, or set a UTF-8 LC_ALL/LC_CTYPE/LANG in the shell that runs tmux"})},eN={name:`termWidth`,label:`terminal width`,takesMark:!1,probe:({width:e})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.columns===null?{ok:!1,reason:`${qM(e.value.of)} measured no width (no COLUMNS, and no terminal to ask — or the daemon refused the width sent, which the bar's red strip names), so the bar is laid out as if the terminal were 120 columns wide`}:{ok:!0,note:`${e.value.columns} columns, as ${qM(e.value.of)} measured`}},tN={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},nN={name:`config`,label:`config`,takesMark:!1,probe:({config:e})=>{switch(e.kind){case`failed`:{let[t=`the config failed to load`,...n]=[...e.error.split(`
|
|
178
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return YM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${tN[e]}`)])}}},rN="re-run `cc-candybar install`";function iN(e){if(e.kind===`failed`)return[`Launch Services could not be asked which app opens cc-candybar:// — ${e.reason}`];if(e.value===null)return[`no app is registered for cc-candybar:// — ${rN}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${rN}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${rN}`)}const aN={name:`urlHandler`,label:`URL handler`,takesMark:!1,probe:({urlHandler:e})=>{switch(e.kind){case`unsupported`:return{ok:!0};case`unprobed`:return{ok:!1,reason:e.reason};case`arrived`:return e.handler===e.bar?{ok:!0}:{ok:!1,reason:e.handler===null?`the URL handler does not report its version, so it is older than the bar (${e.bar}) — ${rN}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${rN}`};case`lost`:return YM([...iN(e.opener),e.unopened===null?`a cc-candybar:// link was opened and did not arrive at the daemon`:`a cc-candybar:// link could not be opened — ${e.unopened}`])}}};function oN({bundle:e,checkout:t},n){return{bundle:n.bundle.kind===`failed`?{kind:`unresolved`,reason:n.bundle.reason}:n.bundle.value===e?{kind:`same`}:{kind:`other`,path:n.bundle.value},source:n.client!==`native`||t===null?{kind:`uncompared`}:t.rustSource.kind===`failed`?{kind:`unreadable`,root:t.root,reason:t.rustSource.reason}:n.source===null?{kind:`unstamped`}:n.source===t.rustSource.value?{kind:`same`}:{kind:`other`,root:t.root}}}function sN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?rN:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function cN(e,t,n){let{checkout:r}=e;if(n.kind===`unreported`)return[`the bar is drawn by a statusline client too old to say what it is — ${sN(e,`native`)}`];let{bundle:i,source:a}=oN(e,n);switch(i.kind){case`unresolved`:return[`the statusline client's bundle cannot be resolved: ${i.reason}`];case`other`:return[`the statusline client runs ${i.path}, not the daemon's ${e.bundle} — ${sN(e,n.client)}`];case`same`:break}if(n.client===`node`&&(t||r!==null))return[`the bar is drawn by the Node fallback, which starts node on every render — ${sN(e,`native`)}`];switch(a.kind){case`uncompared`:case`same`:return[];case`unreadable`:return[`${a.root}/rust-client could not be read: ${a.reason}`];case`unstamped`:return["the native client carries no source stamp, so which source it was built from is unknown — run `just install-rust`"];case`other`:return[`the native client was built from other source than ${a.root}/rust-client holds — run \`just install-rust\``]}}const lN=e=>{let t=`restarted since the bar was drawn, or has served 64 newer sessions`;return e.kind===`clicked`?`this daemon holds no render of this bar (it ${t})`:`this daemon holds no render of session ${e.sessionId}'s bar (its statusLine does not run cc-candybar — a \`claude -p\` session draws none — or the daemon ${t}; unset CLAUDE_CODE_SESSION_ID to judge every bar drawn recently)`},uN={name:`install`,label:`install`,takesMark:!1,probe:({install:e,sighted:t})=>{if(e.kind===`failed`)return{ok:!1,reason:`the daemon could not be asked which clients draw the bar: ${e.reason}`};let{daemon:n,nativeShipped:r,clients:i}=e.value;return i.length===0?{ok:!1,reason:t.kind===`recent`?`no statusline client has drawn a bar for this daemon in the last ${300/60} minutes — run the doctor again once the bar has redrawn; if it never does, the statusLine command does not run cc-candybar`:`${lN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:YM([...new Set(i.flatMap(e=>cN(n,r,e)))])}};function dN({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||ir(e.identity,t.value.through)):[]}function fN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const pN={name:`daemon`,label:`daemon`,takesMark:!1,probe:({daemon:{serving:e,processes:t,read:n}})=>{let r=t.kind===`failed`?[`the process table could not be read: ${t.reason}`]:[],i=t.kind===`ok`?fN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return YM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=dN(e.value,n),u=YM([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${tr(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${tr(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&sr(o.charge.bytes,s)?[`the daemon holds ${dr(o.charge)} of its ${tr(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},mN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function hN(e,t){let n=IM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?RM(e.terminal):{kind:`unknown`}}function gN({identified:e,tmuxClient:t},n){let r=LM(e),i=hN(e,n),a=IM(e)===null?mN:`${mN}, and the doctor remembers it for this terminal`,o=(()=>{switch(i.kind){case`draws`:return[];case`none`:return[`${r} draws no links (OSC 8), so nothing on the bar can be clicked — run Claude Code in a terminal that draws them: ${zM}`];case`older`:return[`${r} ${i.version} draws no links (OSC 8 came in ${i.since}) — update ${r}`];case`unsaid`:return[`${r} draws links (OSC 8) since ${i.since}, and did not say which release this is — ${a}`];case`unknown`:return[`the doctor does not know whether ${r} draws links (OSC 8) — ${a}`]}})(),s=n.kind===`failed`&&i.kind!==`draws`?[`the terminals a doctor click came back from could not be read: ${n.reason}`]:[],c=i.kind===`none`||t===null||t.features.includes(`hyperlinks`)?[]:[`tmux does not pass links through to ${r} — add \`set -as terminal-features ",${t.termname}:hyperlinks"\` to tmux.conf, then detach and reattach (tmux 3.4 or later)`];return[...o,...s,...c]}const _N={name:`links`,label:`links`,takesMark:!1,probe:({sighted:e,terminal:t,clicked:n})=>{if(e.kind===`clicked`&&e.via===`link`)return{ok:!0};switch(t.kind){case`unreported`:return{ok:!1,reason:"the client reported no terminal — re-run `cc-candybar install` to stage a current client"};case`unasked`:return{ok:!1,reason:`tmux could not be asked which terminal is attached: ${t.reason}`};case`seen`:return YM(gN(t,n))}}},vN=e=>e.filter(e=>e.role===`statusline`),yN={name:`effectRefresh`,label:`effect refresh`,takesMark:!1,probe:({frames:e,claudeSettings:{origin:t,elsewhere:n},sighted:r})=>{let i=[t,...n].flatMap(({sources:e,bars:t})=>SN(e,bN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:xN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:lN(r));let[o,...s]=i.flatMap(e=>e.ok?[]:[e]);if(o===void 0)return a;let c=[...new Set(s.map(e=>e.reason))].filter(e=>e!==o.reason);return c.length===0?o:{...o,more:c}}},bN=e=>{let t=vN(e).map(e=>e.frame);return t.includes(`moves`)?{kind:`moving`,wearing:`the bar moves (an effect, a fade, or an animated segment)`}:t.includes(`can-move`)?{kind:`moving`,wearing:`the bar can start moving (an open menu, which flashes and closes on its own, a globals.effect rule, placements that fade in and out, or a placement with an effect of its own that is not drawn now)`}:t.includes(`still`)?{kind:`still`}:t.includes(`drawing`)?{kind:`unknown`,unseen:`the bar's latest render has not finished`}:t.length>0?{kind:`unknown`,unseen:`the bar's recent renders failed`}:e.length>0?{kind:`unknown`,unseen:"only a `cc-candybar frames` display has drawn this bar, not Claude Code's statusline"}:{kind:`none`}},xN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function SN(e,t){let n=BM(e);if(n.kind===`present`&&n.refreshInterval===1)return{ok:!0,note:`statusLine.refreshInterval is 1 in ${n.from.path}`};switch(t.kind){case`none`:return null;case`still`:return{ok:!0};case`unknown`:return xN(t.unseen);case`moving`:break}let{wearing:r}=t;switch(n.kind){case`unread`:return{ok:!1,reason:`${r}, and Claude Code's settings could not be read: ${n.reason}`};case`absent`:return{ok:!1,reason:`${r}, and no settings file Claude Code reads here sets a statusLine (read: ${n.read.join(`, `)||`none`}) — the one that runs the bar comes from --settings, MDM or server-managed settings, which the doctor cannot read; set "refreshInterval": 1 beside its command there`};case`not-an-object`:return{ok:!1,reason:`${r}, and ${n.from.path} sets statusLine to ${JSON.stringify(n.value)}, not a statusLine object — ${n.from.scope===`user`?"re-run `cc-candybar install` to write one":`replace it there with the statusLine object that runs cc-candybar`}`};case`present`:{let{from:e,refreshInterval:t}=n,i=t===void 0?`its statusLine sets no refreshInterval, so Claude Code redraws it only on events`:typeof t==`number`&&t>1?`its statusLine redraws it only every ${t} s`:`its statusLine.refreshInterval is ${JSON.stringify(t)}, not a number of seconds Claude Code accepts (its minimum is 1)`;return UM(e)?{ok:!1,reason:`${r}, but ${i} (statusLine from ${e.path})`,fix:{kind:`claude-settings`,file:e,path:[`statusLine`,`refreshInterval`],value:1}}:{ok:!1,reason:`${r}, but ${i} — its statusLine is in ${e.scope===`managed`?`managed settings`:`the project's shared settings`}, ${e.path}: set "refreshInterval": 1 there`}}}}const CN=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function wN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return LM(e);case`bundling`:case`unread`:case`configured`:return[EM(e.name),e.version].filter(e=>e!==null).join(` `)}}function TN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return IM(e);case`bundling`:case`unread`:return EM(e.name);case`configured`:{let t=EM(e.name);return e.font.kind===`ok`?`${t} with ${e.font.value.font} (${e.font.value.from})`:`${t}, its font unread: ${e.font.reason}`}}}function EN(e){let t=TN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${CN(e.glyphs)}`}}const DN={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=EN(e),r=e=>t.kind===`failed`&&n!==void 0?{ok:!1,reason:e,more:[`the mark book could not be read: ${t.reason}`]}:{ok:!1,reason:e,...n!==void 0&&{sighting:n}},i=e.terminal,a=wN(i);switch(n===void 0||t.kind===`failed`?null:t.value.nerdFont?.[n.id]??null){case`drawn`:return{ok:!0};case`boxes`:return r(`${a} draws ${CN(e.glyphs)} as boxes — set a Nerd Font as its font`);case null:break}switch(i.kind){case`unreported`:return r("the client reported no terminal — re-run `cc-candybar install` to stage a current client");case`unasked`:return r(`tmux could not be asked which terminal is attached: ${i.reason}`);case`unknown`:case`unnamed`:case`unread`:return r(`the doctor cannot read ${a}'s font`);case`bundling`:{let e=SM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:jM(i.version,e);if(t===!0)return{ok:!0};let n=EM(i.name);return r(t===null?`${n} ships Nerd Font symbols since ${e}, and did not say which release this is`:`${a} ships no Nerd Font symbols (they came in ${e}) — update ${n}, or set a Nerd Font as its font`)}case`configured`:{if(i.font.kind===`failed`)return r(`the doctor cannot read ${a}'s font: ${i.font.reason}`);let{font:e,from:t,lacks:n}=i.font.value;return n===null?r(`${a} is set to ${e} (${t}), which is not installed — install it or set a Nerd Font`):n.length===0?{ok:!0}:r(`${a} draws with ${e} (${t}), which has no ${CN(n)} — set a Nerd Font as its font`)}}}};function ON(e){return e.join(`, `)}function kN(e){return`or set missingData: "ignore" on ${ON(e)}`}function AN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${ON(t)}: whether the forge CLI is ready could not be asked: ${n.reason}`];if(n.value===null)return[];let{cli:r,host:i,status:a}=n.value;return a===`ready`?[]:a===`missing`?[`${ON(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${kN(t)}`]:[`${ON(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${kN(t)}`]}function jN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${ON(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${ON(n)}: no session of this Claude Code has drawn a bar for this daemon in the last ${300/60} minutes, so whether it sends rate_limits is unseen — run the doctor again once the bar has redrawn`:`${ON(n)}: ${lN(t)}, so whether Claude Code sends rate_limits is unseen — run the doctor again once the bar has redrawn`]:r.value.includes(`missing`)&&!r.value.includes(`carried`)?[`${ON(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${ON(n)}`]:[]}const MN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>YM([...AN(e.pullRequests),...jN(e.rateLimits,t)])};function NN({path:e,answered:t,read:n}){switch(n.kind){case`absent`:return t?[`the transcript ${e} does not exist, though Claude Code has answered in its session — the bar's session cost, metrics and activity read nothing`]:[];case`failed`:return[`the transcript ${e} cannot be read: ${n.reason}`];case`ok`:{let{lines:t,unparsed:r,whole:i}=n.value;return r===0?[]:[`${r} of the ${t} lines ${i?`in`:`in the last ${KM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const PN=[nN,uN,pN,aN,_N,QM,$M,eN,yN,DN,MN,{name:`sessionData`,label:`session data`,takesMark:!1,probe:({transcripts:e,sighted:t})=>e.kind===`failed`?{ok:!1,reason:e.reason}:e.value.length===0?{ok:!1,reason:t.kind===`recent`?`no session has drawn a bar for this daemon in the last ${300/60} minutes, so no transcript was named — run the doctor again once the bar has redrawn`:`${lN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:YM(e.value.flatMap(NN))}],FN=PN.filter(e=>e.takesMark);function IN(e){return PN.map(t=>({check:t,verdict:t.probe(e)}))}function LN(e){return PN.find(t=>t.name===e)}const RN=`${X}doctor.`;function zN(e){let t=`${RN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function BN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?IM(e.identified):null,i=t.kind===`failed`?`unread`:r===null?`-`:t.value.includes(r)?`yes`:`no`;return`tmuxLinks=${n===null?`-`:n.features.includes(`hyperlinks`)?`yes`:`no`} clicked=${i}`}function VN(e,t){let n=e.kind===`seen`?e.tmuxClient:null;return`cols=${t.kind===`failed`?`failed widthOf=-`:`${t.value.columns??`-`} widthOf=${t.value.of.kind}`} clientUtf8=${n===null?`-`:n.utf8?`yes`:`no`}`}function HN(e){if(e.kind===`failed`)return`clients=unasked`;let{daemon:t,clients:n}=e.value;return`clients=${n.map(e=>{if(e.kind===`unreported`)return`unreported/-/-`;let{bundle:n,source:r}=oN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const UN=e=>`${e>=0?`+`:``}${tr(e)}`;function WN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${fN(e,t.value).map(e=>e.pid).join(`,`)||`-`}`;if(e.kind===`failed`)return`${r} memory=unasked postMortems=unasked`;let{memory:i,limit:a,postMortems:o}=e.value,s=o.kind===`failed`||n.kind===`failed`?`unread`:`${dN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${UN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function GN(e){return`data=pr:${(()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`})()},rateLimits:${(()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`})()}`}function KN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>qN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=vN(r.flatMap(e=>e.bars));return`frames=${vM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function qN(e){let t=BM(e);switch(t.kind){case`unread`:return`failed`;case`absent`:case`not-an-object`:return t.kind;case`present`:return`${t.from.scope}:${t.refreshInterval===void 0?`-`:JSON.stringify(t.refreshInterval)}`}}function JN(e){let t=VM(e,XM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function YN(e){if(e.kind===`failed`)return`transcripts=failed`;let t=t=>e.value.filter(e=>e.read.kind===t).length,n=e.value.reduce((e,t)=>e+(t.read.kind===`ok`?t.read.value.unparsed:0),0);return`transcripts=${t(`ok`)}/${t(`absent`)}/${t(`failed`)} unparsed=${n}`}function XN(e,t){if(e.kind===`none`)return`glyphs=- terminal=- font=- mark=-`;let{glyphs:n,terminal:r}=e,i=[...n].map(e=>e.codePointAt(0).toString(16)),a=(()=>{switch(r.kind){case`unreported`:case`unasked`:return r.kind;case`unknown`:return`unknown:${JSON.stringify(r.called)}`;case`unnamed`:return`unnamed:${JSON.stringify(r.term)}`;case`bundling`:case`unread`:case`configured`:return`${r.name}@${r.version??`-`}`}})(),o=(()=>{if(r.kind!==`configured`)return`-`;if(r.font.kind===`failed`)return`failed`;let{font:e,lacks:t}=r.font.value;return`${JSON.stringify(e)}:${t===null?`not-installed`:`lacks${t.length}`}`})(),s=EN(e),c=t.kind===`failed`?`unread`:s===void 0?`-`:t.value.nerdFont?.[s.id]??`-`;return`glyphs=${i.join(`,`)} terminal=${a} font=${o} mark=${c}`}function ZN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function QN(e){return e.flatMap(({check:e,verdict:t})=>{let n=zN(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:h_},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:ZN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const $N={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function eP(e){let t=t=>`${e}${t}`;return{template:`{{ action "${t(`copySession`)}" "⎘ id" }}{{ if ne .resume_command "" }} {{ action "${t(`copyResume`)}" "⎘ resume" }}{{ end }} {{ action "${t(`openProject`)}" "↗ proj" }} {{ action "${t(`openTranscript`)}" "↗ log" }}{{ if ne .git.repoUrl "" }} {{ link .git.repoUrl "↗ repo" }}{{ end }}{{ if ne .config_path "" }} {{ action "${t(`openConfig`)}" "↗ config" }}{{ end }}`,actions:Object.fromEntries(Object.entries($N).map(([t,n])=>[`${e}${t}`,n]))}}const tP=`armed`,nP=`disarmed`,rP=`.armed`,iP=e=>e.endsWith(rP);function aP(e,t,n){let r=`${e}${rP}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${tP}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:tP},[a]:{set:r,to:nP},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:nP}},disarm:a}}const oP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function sP(e){return typeof e==`string`&&oP.test(e)?{kind:`line`,line:e}:{kind:`refused`,reason:`a slash command is "/" then its name, e.g. "/compact" or "/model opus", on one line with no control characters, got ${JSON.stringify(e)}`}}function cP(e){let t=sP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const lP=[`/compact`,`/model`],uP=`/clear`;function dP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=aP(`${e}clear`,{arm:uP,confirm:`${uP} ✓ confirm`},[n]);return{template:lP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${lA} }}`,actions:{...Object.fromEntries(lP.map(e=>[t(e),{slash:cP(e)}])),...r.actions,[n]:{slash:cP(uP)}},variables:r.variables,disarm:r.disarm}}const fP=Array.from({length:10},(e,t)=>(t+1)*1e5),pP=fP[0],mP=fP[fP.length-1];function hP(e){let t;try{t=eo(e)}catch(e){return I(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?P(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=pP&&n<=mP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${pP}–${mP} tokens)`)}function gP(e,t){let n=Math.min(t??mP,mP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:fP.filter(e=>e<r).at(-1)??0,higher:fP.find(e=>e>r&&e<=n)??0}}function _P(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${lA} }}{{ if gt .autocompact.lower 0 }} {{ action (printf "${e}%d" .autocompact.lower) "−" }}{{ end }}{{ if gt .autocompact.higher 0 }} {{ action (printf "${e}%d" .autocompact.higher) "+" }}{{ end }}{{ if gt .autocompact.window 0 }} {{ action "${e}auto" "↺" }}{{ end }}{{ end }}{{ end }}`,bg:`{{ if ne .autocompact.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .autocompact.window 0) (ne .autocompact.error "") }}`,actions:{[`${e}auto`]:{slash:cP(`/autocompact auto`)},...Object.fromEntries(fP.map(t=>[`${e}${t}`,{slash:cP(`/autocompact ${t}`)}]))}}}const vP=e=>`{{ if ge ${e} 1000000 }}{{ printf "%.1f" (divf ${e} 1000000) }}M{{ else if ge ${e} 1000 }}{{ printf "%.1f" (divf ${e} 1000) }}K{{ else }}{{ ${e} }}{{ end }}`,yP=`${X}edit`,bP=`${X}toolbar`,xP=eP(X),SP=`${X}commands`,CP=dP(`${SP}.`),wP=`${X}autocompact`,TP=_P(`${wP}.`,vP),EP=e=>({kind:`segment`,name:e}),DP=`${X}tab`,OP=e=>`${DP}.${e}`,kP=e=>`${OP(e)}.toggle`,AP=e=>({variable:DP,key:DP,member:e}),jP=`${X}save`,MP=`${X}preset.save`,NP=`${X}preset.delete`,PP=e=>`${X}${e}`,FP=e=>`${X}apply.${e}`,IP=e=>`${X}reset.${e}`,LP=`${X}themeDefault.save`,RP=`${X}themeDefault.differs`,zP=`${X}themeDefault.theme`,BP={when:`{{ .${RP} }}`,template:`{{ action "${LP}" (printf "⤓ default for %s" .${zP}) }} {{ swatch "${FP(`theme`)}" .${zP} }}`},VP=`${X}resetAll`,HP=`${Sj}.toggle`,UP=`${X}undo`,WP=`${X}back`,GP=`${WP}.step`,KP=`${X}navigation.back`,qP=WP,JP={template:`{{ if gt .${KP} 0 }}{{ action "${WP}" "◁" }}{{ else }}{{ fg (${uM}) "◁" }}{{ end }}`},YP=`${X}redo`,XP=`${X}doctor`,ZP=`${XP}.run`,QP=e=>`${XP}.fix.${e}`,$P=(e,t)=>`${XP}.mark.${e}.${t}`,eF=e=>`${XP}.${e}`,tF={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},nF=CA(`${X}pickers`),rF=e=>`${X}${e}`,iF=e=>`${rF(e)}.toggle`,aF=e=>$j(e)?CA(`${X}${e}Pickers`):nF,oF=e=>{let t=aF(Qj[Xj[e].beside]);return{variable:t,key:t,member:e}},sF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${NP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},cF=(e,t)=>`${X}list.${e}.${t}`,lF=e=>`${X}resettable.${e}`,uF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${lF(e)}`).join(` `)})`,dF=Fv.map(e=>[Pv[e].setting,e]),fF={variables:{},actions:{},segments:{}},pF=Object.fromEntries(dF.map(([e,t])=>[e,Rj(`${X}help.${e}`,cM[t],[],fF)])),mF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],hF=e=>{let t=t=>`.${zv(e,t)}`,n=mF.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${Sy[Pv[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ realtimeFrames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},gF=`{{ if eq .${Lv(`by`)} "feed" }} {{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ end }}`,_F=Object.fromEntries(dF.map(([e,t])=>[e,hF(t)])),vF=Object.keys(Sy).map(e=>{let t=Sy[e],n=RA(t.configKey),r=FA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,FP(e),aF(Qj[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>sF[e])}}),yF=e=>vF.filter(t=>Qj[t.name]===e),bF=e=>vF.filter(t=>eM(Qj[t.name],e)),xF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${uF(bF(e).map(e=>e.name))}))`,SF=e=>Zj.filter(t=>Xj[t].beside===e),CF=e=>yF(e).flatMap(e=>[FF(e),...[pF[e.name]].filter(e=>e!==void 0),...SF(e.name).map(e=>wi(rF(e),oF(e),HF(e),`drop`))]);new Set(vF.flatMap(e=>[e.sessionKey,e.configKey]));const wF=aP(VP,{arm:`⟲`,confirm:`⟲ reset all?`},vF.map(e=>IP(e.name))),TF=[`unsaved`,`history.undo`,`history.redo`],EF=e=>`${X}${e}`,DF=EF(`unsaved`),OF=(e,t)=>({body:t,shown:`(gt .${EF(e)} 0)`}),kF=[OF(`unsaved`,`{{ action "${jP}" (printf "💾 save %d" .${DF}) }}`),OF(`history.undo`,`{{ action "${UP}" "↶" }}`),OF(`history.redo`,`{{ action "${YP}" "↷" }}`),{body:wF.template,shown:`(or ${uF(vF.map(e=>e.name))} ${wF.armed})`}],AF={when:`{{ or ${kF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+kF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},jF=[{step:wF,place:`door`},{step:CP,place:`session`}],MF=e=>e.map(e=>e.step.disarm),NF=MF(jF),PF=MF(jF.filter(e=>e.place!==`door`));function FF(e){let t=PP(e.name);return e.control.kind===`inline`?EP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>EP(cF(e.name,n)))},`drop`)}function IF(e){return e===Sj}function LF(e){let t=EP(Sj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[LF(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function RF(e){return zF(e)>0?e:LF(e)}function zF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&IF(n.name)&&(t+=1);return t}function BF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&IF(e.name)||e.opens!==void 0&&BF(e.opens.body,!0):e.children.some(e=>BF(e,n))}const VF={door:{direction:`horizontal`,content:[EP(qP)],after:[EP(yP),EP(jP)]},session:{direction:`vertical`,content:[EP(bP),{kind:`container`,direction:`horizontal`,children:[EP(SP),EP(wP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[EP(MP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[EP(XP),...PN.map(e=>EP(eF(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[EP(LP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function HF(e){let{direction:t,content:n,after:r}=VF[e];return{kind:`container`,direction:t,children:[...n,...CF(e),...r]}}function UF(e){return e.kind===`segment`?IF(e.name)?wi(e.name,wj,GF,`above`):e:KF(e)}function WF(){return{kind:`container`,direction:`vertical`,children:[HF(`door`),{kind:`container`,direction:`horizontal`,children:Jj.map(({member:e})=>wi(OP(e),AP(e),HF(e),`drop`))}]}}const GF=WF();function KF(e){return{...e,children:e.children.map(e=>UF(e))}}function qF(e){let t={variables:{[Sj]:Ai(Sj,yi)},actions:{[HP]:N(Sj,Cj),[Sj]:{do:[HP,...NF]},[ZP]:{doctor:`run`},...xP.actions,...CP.actions,...TP.actions,[jP]:{save:!0},[UP]:{undo:!0},[GP]:{back:!0},[WP]:{do:[GP,...NF]},[YP]:{redo:!0},[MP]:{preset:`save`},[LP]:{themeDefault:`save`},[NP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[Sj]:{template:`{{ $door := ${Oi(Sj,ki(e),ki(`✖`))} }}{{ if ${Ei(wj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+gF},[bP]:{template:xP.template},[SP]:{template:CP.template,when:CP.when},[wP]:{template:TP.template,bg:TP.bg,when:TP.when},[qP]:JP,[jP]:AF,[LP]:BP,[MP]:{template:`{{ action "${MP}" "+ preset" }}`},[XP]:{template:`{{ action "${ZP}" "🩺 doctor" }}`},[yP]:{template:`{{ action "${Dj}" "✎ arrange" "✎ done" }}`}}};t.variables[RP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[zP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[KP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of TF)t.variables[EF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[DP]=Ai(DP,`session`);for(let{member:e,label:n}of Jj){t.actions[kP(e)]=N(DP,e),t.actions[OP(e)]={do:[kP(e),...PF]};let r=xF(e);t.segments[OP(e)]={template:`{{ ${Oi(OP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,CP.variables,wF.variables),YF(t),JF(t),t}function JF(e){for(let t of PN){let n=zN(t.name),r=QP(t.name);for(let t of Object.values(n))e.variables[t]={kind:`state`,key:t,default:``};e.actions[r]={doctor:`fix`,check:t.name};let i=t.takesMark?GM:[];for(let n of i)e.actions[$P(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${$P(t.name,e)}" "${tF[e]}" }}`).join(``);e.segments[eF(t.name)]={when:`{{ ne .${n.verdict} "" }}`,template:`{{ if eq .${n.verdict} "ok" }}✓ ${t.label}{{ if ne .${n.reason} "" }} — {{ .${n.reason} }}{{ end }}{{ else }}✗ ${t.label} — {{ .${n.reason} }}{{ if eq .${n.fixable} "${m_}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function YF(e){for(let t of vF){Object.assign(e.actions,t.control.actions);let n=IP(t.name);e.actions[n]={reset:t.configKey},e.variables[lF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${lF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[PP(t.name)]={template:`${t.control.template}${_F[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[cF(t.name,r)]=n})}Object.assign(e.actions,wF.actions),Object.assign(e.variables,fF.variables),Object.assign(e.actions,fF.actions),Object.assign(e.segments,fF.segments);for(let t of Zj){let n=oF(t);e.actions[iF(t)]=N(n.key,n.member),e.segments[rF(t)]={template:`{{ action "${iF(t)}" ${xF(t)(Xj[t].trigger)} }}`}}}function XF(e){let{variables:t,actions:n}=Ij();Object.assign(e.variables,t),Object.assign(e.actions,n)}function ZF(e){let t=qF(e.globals.menuGlyph??`🍫`);XF(t);let n={...e.presets},r=[];for(let t of Qb(e.presets)){let{node:i}=tx(e,t),a=UF(RF(i));r.push(a),n[t]={...ex(e.presets,t),root:a}}let i=dA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const QF=`${gA}live`,$F=[`☐ live`,`☑ live`],eI=`${gA}done`,tI=`${gA}cancel`,nI=`${gA}rewind`,rI=`${gA}changes`,iI=`(gt .${rI} 0)`,aI=`(or ${iI} (gt .${DF} 0))`,oI={variable:QF,key:QF,member:`open`};function sI(e){return`${gA}configuring.p${e}`}function cI(e){return`and ${Ei(jj)} (not ${Ei(oI)}) (ne .${sI(e)} "true")`}function lI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Ej} "${Ci(e)}")`).join(` `)} false }}`}}function uI(e,t,n){return`{{ if ${cI(e)} }}${t}{{ else }}${n}{{ end }}`}const dI=`{{ and ${Ei(jj)} .preset.customized }}`,fI=vA;function pI(e){return new Map([...ox(e),...hI(e)])}const mI=`${gA}addable`;function hI(e){return new Map([[mI,{members:Object.keys(e.segments).filter(e=>!fI(e)),library:{groups:yj.map(e=>({id:e,label:bj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function gI(e,t,n){return n.segments[e]={template:t,when:Mj,bg:Bj},{kind:`segment`,name:e}}function _I(e,t,n){let r=`${gA}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function vI(e){return`{{ if ${Ei(jj)} }}${e}{{ end }}`}function yI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(jj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function bI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function xI(e,t,n){return`${kj}${e}.${t}.${n}`}function SI(e,t,n,r){let i=S_(n),a=`${gA}${e.presetIdent}`,o=Aj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=CA(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:yi},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:Ej,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=xI(e.presetIdent,i,r),l=`${kj}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:G_(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=FA(NA(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return wi(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${Kj}" }}`,ref:{variable:Ej,key:Ej,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const CI=`${gA}label:`;function wI(e){if(e.startsWith(CI)){let t=e.slice(CI.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function TI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${CI}${a}:${e.name}`;i.segments[o]={template:`{{ "${Ci(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(B_.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...wi(o,r.ref,r.body,`drop`,yI([r.ref],`{{ ${cI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function EI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${gA}${i}.insert.${t}`,s=`${gA}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:mI,anchor:n,relation:r};let c=xA(o),l=SA(s,o,void 0),u=TA(l),d=wA(l,c);return a.variables[l]={...Ai(l,yi),within:[jj]},a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=N(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${Ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${Yh}`}) $m }}{{ end }}`}}function DI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!fI(e.name)),i=e=>DI(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=T_(o,i);if(fI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[EI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=EI(t,u,c,`after`),f=_I(t,u,c),p=t.segments[o.name],m=SI(t,u,o,V_(p)),h=vI(f),g=vI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>gI(e.host,e.template,t.artifacts)),{...TI(o,p,t,m),lead:h,trail:g},{...s,when:uI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},gI(d.host,d.template,t.artifacts)]};n.push(e.direction===`vertical`?{kind:`container`,direction:`horizontal`,children:[_]}:_)}return{...e,children:n,...e.when!==void 0&&{when:yI(bI(n),uI(t.presetIdent,`true`,e.when))}}}function OI(e,t,n,r,i,a,o){let s=`${gA}${t}.resetLayout`,c=`${gA}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:dI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},kI(e,o)]}}function kI(e,t){if(e.kind===`segment`)return{kind:`container`,direction:`horizontal`,children:[e,t]};let n=e.children.at(-1);return e.direction===`vertical`&&n!==void 0&&(n.kind===`segment`||n.when===void 0)?{...e,children:[...e.children.slice(0,-1),kI(n,t)]}:{...e,children:[...e.children,t]}}function AI(e,t,n,r,i,a){let{node:o}=tx(e,t),s={presetIdent:fA(t),rootKey:fj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=DI(o,s);return n.variables[sI(s.presetIdent)]=lI(s.configured),OI(c,s.presetIdent,s.rootKey,n,r,i,a)}function jI(e){let t={variables:{},actions:{},segments:{}},n=Rj(`${gA}help`,sM,[jj],t);t.variables[QF]=Ai(QF,yi),t.actions[QF]=N(QF,oI.member),t.segments[QF]={template:Di(QF,...$F),when:Mj};let r={kind:`segment`,name:QF},i=n;t.variables[rI]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[eI]={do:[jP,Dj]},t.segments[eI]={template:`{{ if ${aI} }}{{ action "${eI}" "✓ save" }}{{ else }}{{ action "${eI}" "✓ done" }}{{ end }}`,when:Mj},t.actions[nI]={rewind:!0},t.actions[tI]={do:[nI,Dj]},t.segments[tI]={template:`{{ action "${tI}" "↩ cancel" }}`,when:`{{ and ${Ei(jj)} ${iI} }}`};let a=[{kind:`segment`,name:eI},{kind:`segment`,name:tI}],o={...e.presets},s=[];for(let n of Qb(e.presets)){let c=AI(e,n,t,a,r,i);s.push(c),o[n]={...ex(e.presets,n),root:c}}let c=dA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function MI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function NI(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function PI(e,t,n){let r=w_(e,new Set(n.map(C_).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const FI=/^-?\d+$/;function II(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function LI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!FI.test(t))return{ok:!1,reason:`${e} must be an integer, got "${t}"`};let n=t[0]===`-`,r=(n?t.slice(1):t).replace(/^0+/,``);return r===``?{ok:!0,value:`0`}:{ok:!0,value:n?`-${r}`:r}}}function RI(e,t,n){return r=>r?FI.test(r)?{ok:!0,value:String(Math.max(e,Math.min(t,parseInt(r,10))))}:{ok:!1,reason:`${n} must be an integer, got "${r}"`}:{ok:!1,reason:`${n} value is required`}}function zI(e,t,n=`state`){let r=t.filter(e=>e.kind===`range`),i=t.some(e=>e.kind===`int`),a=t.flatMap(e=>e.kind===`allow-list`?e.allowed:[]);if(r.length===0&&!i)return{kind:`allow-list`,allowed:[...new Set(a)]};let o=a.filter(e=>!FI.test(e));if(o.length>0)throw Error(`${n} action table: key "${e}" is an integer spec (a paged cursor or a bounded value) but a click writes non-integer value(s) to it (${o.join(`, `)}). A ${n} key has one key shape — point that click at a distinct key, or write an integer.`);if(i&&r.length>0)throw Error(`${n} action table: key "${e}" is declared as both a paged cursor (int) and a bounded value (range) — a ${n} key has one key shape. Use distinct keys.`);if(r.length>0){let t=Math.min(...r.map(e=>e.min)),i=Math.max(...r.map(e=>e.max)),o=a.filter(e=>{let n=parseInt(e,10);return n<t||n>i});if(o.length>0)throw Error(`${n} action table: key "${e}" is a bounded range [${t},${i}] but a click writes out-of-range value(s) to it (${o.join(`, `)}). The range gate would clamp them, storing a different value than the click renders — write an in-range integer, or point that click at a distinct key.`);return{kind:`range`,min:t,max:i}}return{kind:`int`}}function BI(e){return e===`config`?`set-config`:`set-state`}function VI(e,t,n){return t.kind===`int`?LI(`menu page "${e}"`):t.kind===`range`?RI(t.min,t.max,`${n} stepper "${e}"`):II(t.allowed,`${n} "${e}"`,BI(n))}function HI(e,t=`state`){let n=new Map;for(let{key:t,spec:r}of e){let e=n.get(t);e?e.push(r):n.set(t,[r])}return[...n].map(([e,n])=>({key:e,spec:zI(e,n,t)}))}function UI(e,t,n,r){let i=new Map(Object.entries(e)),a=new Map,o=new Set(t.map(e=>e.key));for(let{key:e,spec:t}of n)if(o.has(e)&&t.kind!==`allow-list`)throw Error(`${r} gate: key "${e}" is written by the daemon's own links as one of a list of values, and cannot be declared as ${t.kind===`int`?`a paged cursor (int)`:`a bounded value (range)`}. Use a distinct key.`);let s=[...t.map(({key:e,allowed:t})=>({key:e,spec:{kind:`allow-list`,allowed:t}})),...n];for(let{key:t,spec:n}of HI(s,r)){if(!t)throw Error(`${r} gate: key is required`);if(t.includes(`/`))throw Error(`${r} gate: key "${t}" contains "/" — the wire shape splits on "/" so a slash-bearing key cannot be addressed. Use a slash-free key.`);if(Object.hasOwn(e,t))throw Error(`${r} gate: key "${t}" is a built-in ${r} key and cannot be re-claimed (built-in keys: ${Object.keys(e).join(`, `)})`);i.set(t,VI(t,n,r)),n.kind===`range`&&a.set(t,{min:n.min,max:n.max})}return{validate(e,t){let n=i.get(e);return n?n(t):{ok:!1,reason:`unknown ${r} key "${e}" (have: ${[...i.keys()].join(`, `)})`}},listKeys:()=>[...i.keys()],rangeParamsFor:e=>a.get(e)??null}}function WI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};UI(e,[o],[],t),r.push(o),i++;let s=!0;return()=>{s&&(s=!1,r.splice(r.indexOf(o),1),i++)}},gateFor(o){let s=a.get(o);if(s?.epoch===i)return s.gate;let c=UI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const GI=WI({},`config`,QI);function KI(e,t){return GI.register(e,t)}function qI(e){return GI.gateFor(e)}function JI(e,t){return`persist`in e?`to`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`cycle`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:e.cycle}}]:`removeSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[MI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[MI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:cx(e.insertSegmentFrom,t).members.map(t=>MI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function YI(e,t){let n=sj(e).get(t);return n===void 0?null:String(n)}function XI(e){let t=new Set;for(let n of Object.values(e.actions)){`reset`in n&&t.add(n.reset);let e=`persist`in n?gj(n.persist):null;e?.scope===`preset-root`&&t.add(fj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function ZI(e){let t=pI(e);return[...XI(e),...Object.values(e.actions).flatMap(e=>JI(e,t))]}function QI(e){return HI(ZI(e),`config`)}function $I(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:nL(t.segments,eL(t.segments,e.segments??{})),root:Jb(e.root??Vb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:nL(t.presets,tL(t.presets,e.presets??{})),themeDefaults:nL(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function eL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.settings===void 0?n:{...n,settings:{...e[t]?.settings,...n.settings}}]))}function tL(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.globals===void 0?n:{...n,globals:{...e[t]?.globals,...n.globals}}]))}function nL(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function rL(e,t,n,r){return n.cache===void 0?(e.issues.push({path:`${t}.cache`,message:`${r} variables must declare a cache policy (one of: ${M_.join(`, `)})`,line:G(e.source,t.split(`.`))}),null):oL(e,`${t}.cache`,n.cache)}function iL(e){return{required:!0,json:sL(),parse:(t,n,r,i)=>rL(t,n,i,e)??void 0}}const aL={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&lL(n)?{ttl:n}:mv(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${K(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return mv(e,t,`cache.watch_file must be a path string, got ${K(n)}`);let r=Ev(`cache.watch_file`,n);return r===null?{watch_file:n}:mv(e,t,r)}},depends_on:{json:{type:`array`,items:{type:`string`}},parse:(e,t,n)=>Array.isArray(n)&&n.every(e=>typeof e==`string`)?{depends_on:n}:mv(e,t,`cache.depends_on must be an array of variable-name strings, got ${K(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:mv(e,t,`cache.key must be a non-empty template string, got ${K(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:mv(e,t,`cache.never must be the literal boolean true, got ${K(n)}`)}}};function oL(e,t,n){return hv(e,aL,t,n)}function sL(){return Nv(aL)}const cL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function lL(e){return cL.test(e)}const uL=new Map([[`session.budget.amount`,{segment:`session`,setting:`budget`}],[`session.budget.warningThreshold`,{segment:`session`,setting:`warnAt`}],[`today.budget.amount`,{segment:`today`,setting:`budget`}],[`today.budget.warningThreshold`,{segment:`today`,setting:`warnAt`}],[`block.budget.heatThreshold`,{segment:`block`,setting:`warnAt`}],[`block.budget.warningThreshold`,{segment:`block`,setting:`errorAt`}],[`weekly.budget.heatThreshold`,{segment:`weekly`,setting:`warnAt`}],[`weekly.budget.warningThreshold`,{segment:`weekly`,setting:`errorAt`}],[`burn.eta.errorMinutes`,{segment:`burnrate`,setting:`errorWithin`}],[`burn.eta.warnMinutes`,{segment:`burnrate`,setting:`warnWithin`}]]);function dL(e){return`it became the "${e.setting}" setting of each "${e.segment}" placement — set it on the placement where a row places "${e.segment}" ({ seg: "${e.segment}", settings: { ${e.setting}: <value> } }), or redeclare segments.${e.segment}.settings.${e.setting} with the default every placement should start from`}function fL(e){let t=uL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${dL(t)}`}function pL(e){let t=uL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${dL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const mL=new Map([[`git.timeSinceCommit`,`the payload stores the commit's date as "git.committedAt" (epoch seconds), and the bundled template variable "git.timeSinceCommit" computes its age at the draw: drop this declaration`],[`block.etaMinutes`,`the bundled template variable "block.etaMinutes" computes it at the draw: drop this declaration`],[`weekly.etaMinutes`,`the bundled template variable "weekly.etaMinutes" computes it at the draw: drop this declaration`]]),hL=new Map([[`branch`,{read:`.git.branch`,declare:{kind:`input`,path:`git.branch`,default:``},note:`when HEAD is on no branch it reads "detached", where this kind read ""`}],[`sha`,{read:`.git.sha`,declare:{kind:`input`,path:`git.sha`,default:``}}],[`dirty`,{read:`(ne .git.status "clean")`,declare:{kind:`template`,template:`{{ ne .git.status "clean" }}`,type:`boolean`}}],...[`ahead`,`behind`,`stash`].map(e=>[e,{read:`.git.${e}`,declare:{kind:`input`,path:`git.${e}`,type:`number`,default:0}}])]);function gL(e){let t=e=>typeof e==`string`&&e.includes(`"`)&&!e.includes(`'`)?`'${e}'`:JSON.stringify(e);return`{ ${Object.entries(e).map(([e,n])=>`${e}: ${t(n)}`).join(`, `)} }`}function _L(e){let t=`kind "git" is retired: every git fact is an input over the payload's git lane, which the bundled default already declares — drop this declaration and`,n=typeof e.field==`string`?hL.get(e.field):void 0;if(n===void 0){let e=[...hL.values()].map(({read:e})=>e);return`${t} read whichever of ${e.slice(0,-1).join(`, `)} or ${e.at(-1)} it stood for, where it was read`}let r=n.note===void 0?``:` (${n.note})`;return`${t} read ${n.read} where it was read${r}, or declare ${gL(n.declare)} under a name of your own`}function vL(e,t,n){if(n===void 0)return{};if(!sv(n))return e.issues.push({path:t,message:`${t} must be an object, got ${cv(n)}`,line:G(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=gv(e,HL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function yL(){return{required:!0,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.value;if(typeof i!=`string`&&typeof i!=`number`&&typeof i!=`boolean`){e.issues.push({path:`${t}.value`,message:`literal value must be string|number|boolean, got ${cv(i)}`,line:G(e.source,t.split(`.`))});return}return i}}}function bL(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return rv(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const xL={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:mv(e,t,`parse.text must be the literal boolean true, got ${K(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?SL(e,t,n):mv(e,t,`parse.regex must be a pattern string, got ${K(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:mv(e,t,`parse.json must be the literal boolean true, got ${K(n)}`)}}};function SL(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return mv(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:mv(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function CL(){return{required:!1,json:Nv(xL),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:G(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:hv(e,xL,`${t}.parse`,r.parse)??void 0)}}function wL(){return{required:!1,json:{type:[`string`,`number`,`boolean`,`array`,`object`],description:`The value published when the source fails: a string under the text/regex parse arms, any non-null JSON value under the json arm`},parse:(e,t,n,r)=>sv(r.parse)&&`json`in r.parse?TL(e,t,r.default):iv(e,t,r,`default`)}}function TL(e,t,n){if(n!==void 0)return EL(n)?n:mv(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${K(n)}`)??void 0}function EL(e){return e!==null&&DL(e)}function DL(e){if(e===null)return!0;switch(typeof e){case`string`:case`boolean`:return!0;case`number`:return Number.isFinite(e);case`object`:{if(Array.isArray(e))return e.every(DL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(DL)}default:return!1}}const OL={value:yL(),default:bv()};function kL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:mL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const AL={path:kL(),type:Ov([`string`,`number`,`boolean`]),default:bL()},jL={name:Tv(),default:bv()},ML={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:CL(),cache:iL(`file`),default:wL()},NL={command:Tv(),parse:CL(),cache:iL(`shell`),default:wL()};function PL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const FL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:bL()},IL=PL(`a template variable recomputes whenever a variable it reads changes`),LL={layout:Tv(),default:bv()},RL=PL(`a time variable reads the instant its render is drawn at`),zL={key:Tv(),default:bv()},BL=`kind`;function VL(e,t,n={}){return{..._v(BL,e,t),parse:(r,i,a)=>{uv(r,n,i,a);let o=dv(r,t,i,a);return o===null?null:{kind:e,...o}}}}const HL={tag:BL,noun:`source kind`,memberNoun:`variable`,arms:{literal:VL(`literal`,OL),input:VL(`input`,AL),env:VL(`env`,jL),file:VL(`file`,ML),shell:VL(`shell`,NL),template:VL(`template`,FL,IL),time:VL(`time`,LL,RL),state:VL(`state`,zL)},retired:{git:_L}};function UL(){return Mv(HL)}function WL(){return{type:`object`,additionalProperties:UL()}}const GL=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}],[`ceiling`,{kind:`removed`}]]);function KL(e){let t=GL.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`;case`removed`:return` (the built-in segment "${e}" was removed: the program it showed draws it through a cc-candybar plugin of its own now — delete this reference, or place that plugin's segment)`}}const qL=/^[A-Za-z_][A-Za-z0-9_]*$/,JL={pattern:qL.source},YL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},XL={type:`object`,additionalProperties:!1,required:[`label`,`domain`,`default`],properties:{label:{type:`string`,pattern:`^[^\\n\\r]+$`},domain:{anyOf:[{const:`bool`},{type:`array`,items:{type:`string`,pattern:`^[^/\\n\\r]+$`},minItems:1,uniqueItems:!0},{type:`object`,additionalProperties:!1,required:[`min`,`max`],properties:{min:{type:`integer`},max:{type:`integer`},step:{type:`integer`,minimum:1},atLeast:{type:`string`,...JL}}}]},default:YL}},ZL=[`label`,`domain`,`default`],QL=[`min`,`max`,`step`,`atLeast`];function $L(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function eR(e,t,n){if(n===`bool`)return`bool`;if(Array.isArray(n)){let r=n.filter(e=>typeof e==`string`);if(n.length===0||r.length!==n.length)return $L(e,t,`a list domain must be a non-empty list of words, got ${JSON.stringify(n)}`);if(new Set(r).size!==r.length)return $L(e,t,`a list domain names each word once, got ${JSON.stringify(n)}`);let i=r.filter(e=>e===``||e.includes(`/`)||/[\n\r]/.test(e));return i.length>0?$L(e,t,`a list domain's words must be non-empty, slash-free, and newline-free — configure mode writes each on the set-state wire — got ${JSON.stringify(i)}`):r}if(sv(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!QL.includes(e)).length===0&&Number.isInteger(r)&&Number.isInteger(i)&&r<=i&&Number.isInteger(a)&&a>=1&&(o===void 0||typeof o==`string`)?{min:r,max:i,step:a,...o!==void 0&&{atLeast:o}}:$L(e,t,`a range domain is { min, max, step?, atLeast? } with integers min ≤ max, a whole step ≥ 1, and atLeast naming another range setting, got ${JSON.stringify(n)}`)}return $L(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function tR(e,t,n){if(!sv(n))return $L(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))ZL.includes(r)||$L(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${ZL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||$L(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${K(r)}`);let a=eR(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!nR(n.default)||!W_(o,n.default)?$L(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function nR(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const rR={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${R_}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function iR(e){return B_.includes(e)}function aR(){return{required:!1,json:{type:`object`,propertyNames:{...JL,not:{enum:[...B_]}},additionalProperties:XL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return $L(e,a,`${a} must be an object of name → { label, domain, default }, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!qL.test(t)){$L(e,`${a}.${t}`,`setting name "${t}" is read as .settings.${t} in a template, so it must be an identifier (letters, digits, _; not starting with a digit)`);continue}if(iR(t)){$L(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${rR[t]}`);continue}let r=tR(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const oR=_A.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function sR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${oR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!vA(i)?i:$L(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${_A.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function cR(){return{required:!1,json:{type:`object`,propertyNames:JL,additionalProperties:YL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return $L(e,a,`a placement's "settings" must be an object of setting name → value, got ${cv(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))nR(n)?o[t]=n:$L(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function lR(e){return new Set(Object.keys(e.segments).filter(e=>!vA(e)))}function uR(e,t,n){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${cv(t)}`,line:G(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=lv(e,n.has(i)?gR:hR,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function dR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?mv(e,`${t}.${n}`,`${t} declares no template — only a segment the bundled default declares may omit it (inheriting the bundled template); a segment of your own needs its own${KL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function fR(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${K(i)}`,line:G(e.source,[...t.split(`.`),n])})}}}}function pR(){return{required:!1,json:WL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return vL(e,`${t}.${n}`,i)}}}const mR={template:dR(),description:bv(),group:Ov(vj),width:fR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:pR(),settings:aR(),missingData:Ov(F_)},hR={noun:`segment key`,fields:mR},gR={noun:`segment key`,fields:{...mR,template:bv()}},_R=`#/definitions/LayoutNode`,vR={kind:`container`,direction:`vertical`,children:[]};function yR(e){return{required:!0,json:{const:e},parse:()=>e}}function bR(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}function xR(){return{required:!0,json:{enum:[...b_]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&b_.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${b_.join(`, `)} (got ${JSON.stringify(i)})`,line:G(e.source,[`root`])}),`vertical`)}}}function SR(e){return{required:!0,json:{type:`array`,items:{$ref:_R}},parse:(t,n,r,i)=>{let a=i[r];return Array.isArray(a)?a.map((i,a)=>e(t,`${n}.${r}[${a}]`,i)):(t.issues.push({path:`${n}.${r}`,message:`a container must have a "children" array of layout nodes, got ${cv(a)}`,line:G(t.source,[`root`])}),[])}}}const CR={noun:`layout-node key`,fields:{kind:yR(`segment`),name:bR(),when:bv(),id:sR(),settings:cR()}},wR=()=>Ov(Eh),TR={noun:`layout-node key`,fields:{kind:yR(`container`),direction:xR(),children:SR(vv(()=>AR)),when:bv(),distribution:wR()}};function ER(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${K(i)}`,line:G(e.source,[`root`])}),``)}}}const DR={noun:`layout-node key`,fields:{seg:ER(),when:bv(),id:sR(),settings:cR()}},OR={noun:`layout-node key`,fields:{h:SR(vv(()=>AR)),when:bv(),distribution:wR()}},kR={noun:`layout-node key`,fields:{v:SR(vv(()=>AR)),when:bv(),distribution:wR()}},AR=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:G(e.source,[`root`])}),vR):{kind:`segment`,name:n};if(!sv(n))return e.issues.push({path:t,message:`a layout node must be a string (segment name) or an object with "kind" / "seg" / "h" / "v", got ${cv(n)}`,line:G(e.source,[`root`])}),vR;if(n.kind===`container`)return lv(e,TR,t,n)??vR;if(n.kind===`segment`)return lv(e,CR,t,n)??vR;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
179
179
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
180
|
-
New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),fR;if(n.kind===`group`){let r=lv(e,jR,t,n);return r===null?fR:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),NR(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),fR}if(a){let r=lv(e,xR,t,n);return r===null?fR:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=lv(e,SR,t,n);return r===null?fR:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=lv(e,CR,t,n);return r===null?fR:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),fR};function TR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:zb.source},additionalProperties:{$ref:dR}},parse:(e,t,n,r)=>{let i=r[n];if(!sv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${cv(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!zb.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=wR(e,`${t}.${n}.${r}`,o)}return a}}}const ER={noun:`root key`,fields:{rows:TR(),when:bv(),distribution:vR()}};function DR(e,t,n){return sv(n)&&`rows`in n?lv(e,ER,t,n)??{rows:{}}:wR(e,t,n)}function OR(){return{required:!0,json:{type:`string`,pattern:zb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!zb.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${yi}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function kR(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function AR(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=nv(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const jR={noun:`layout-node key`,fields:{kind:pR(`group`),name:OR(),label:AR(),open:xv(),direction:Ov(b_),key:kR(),bg:bv(),fg:bv(),when:bv(),distribution:vR(),children:gR(vv(()=>wR))}};function MR(e){return e.key??`groups.`+e.name}function NR(e){let t=sA+e.name;return wi(t,{variable:t,key:MR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function PR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function FR(e,t){mA(e,t,sA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&PR(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&MR(t)===MR(r)&&PR(e,t.path,`group "${t.name}" shares key "${MR(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=MR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&PR(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=sA+e.name,r=MR(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ai(r,i.get(r)),o[t]=N(r,e.name),s[t]={template:Di(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const IR=`menu`,LR=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,RR=e=>e.kind===`call`&&e.name===`dict`,zR=e=>e.kind===`literal`&&typeof e.value!=`object`,BR=e=>xi(``,e,2)===void 0;function VR(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&RR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(RR))return t(`whose options (dict …) is not its last argument — ${LR}`);if(i!==void 0&&a===void 0&&!zR(i)&&BR(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=xi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${LR}`);let c=a===void 0?{}:ZT(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=CA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=pA(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${_A(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function HR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===IR).map(VR)}catch{return`parse-failed`}}function UR(e,t){let n=HR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:gA(t,e.apply,e.options.key),member:hA(e.apply)}]:[])}function WR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(IR)}catch{return!1}}function GR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function KR(e,t){mA(e,t,cA,`{{ menu }} helpers`),mA(e,t,lA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))WR(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&WR(i)&&GR(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of E_(Kb(t.root)))typeof n.when==`string`&&WR(n.when)&&GR(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!WR(r))continue;let n=HR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:qR(r.apply);n!==void 0&&GR(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function qR(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(hA(e)===`closed`)return`whose apply action is named "${yi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function JR(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Qb(e.presets)){let a=new Map,s=new Map;for(let c of E_(tx(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,HR(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=S_(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||qR(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=hA(i),f=gA(u,i,l.key),p=yA(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=vA(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=N(f,d),n[f]=Ai(f,yi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function YR(e,t,n){if(t===void 0)return{};if(!sv(t))return Z(e,`actions`,`actions must be an object, got ${cv(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=XR(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function XR(e,t,n,r){if(!sv(n))return Z(e,t,`${t} must be an action object, got ${cv(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=dx.filter(e=>e in n);return i.length===1?QR(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${dx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function ZR(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const QR=e=>({set:(e,t,n)=>Pz(e,t,n,`set`,Az),persist:(e,t,n)=>Pz(e,t,n,`persist`,jz),copy:$R(`copy`),open:$R(`open`),reset:ez,undo:nz(`undo`),redo:nz(`redo`),back:nz(`back`),rewind:nz(`rewind`),save:nz(`save`),preset:rz,themeDefault:iz,doctor:oz,slash:sz,run:uz(e),do:dz});function $R(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=nv(t,n,r,e);return i===null?null:{[e]:i}}}function ez(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=fz(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const tz={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function nz(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${tz[e]}), got ${K(r[e])}`),null)}}function rz(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=nv(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function iz(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}const az={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function oz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(az,r),a=i?az[r]:[...new Set(Object.values(az).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(az).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?kN:ON;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${K(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return zM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${zM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function sz(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=tP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const cz=[`run`,`env`,`refreshes`],lz=/^[A-Za-z_][A-Za-z0-9_]*$/;function uz(e){return(t,n,r)=>{for(let e of Object.keys(r))cz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${cz.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${K(a)}`);let o=r.env??{};(!sv(o)||Object.entries(o).some(([e,t])=>!lz.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${K(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${K(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}lz.source;function dz(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function fz(e,t,n,r,i,a){let o=nv(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const pz={set:`the SessionState key to write`,persist:`the config globals field to write`};function mz(e,t,n,r){let i=pz[r],a=fz(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function hz(e){return e===`set`?`set-state`:`set-config`}const gz={to:Fz(`set`)},_z={to:Fz(`persist`)},vz={from:Iz(`set`)},yz={from:Iz(`persist`)},bz={min:Vz(),max:Vz(),by:Vz()},xz={int:Rz()},Sz={cycle:Lz(`set`)},Cz={cycle:Lz(`persist`)},wz={removeSegment:zz(`removeSegment`)},Tz={insertSegment:zz(`insertSegment`),anchor:zz(`anchor`),relation:Bz()},Ez={insertSegmentFrom:Iz(`persist`),anchor:zz(`anchor`),relation:Bz()},Dz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Oz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function kz(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>dv(e,t,n,r),c=kv(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?yv(s,...n):s}}const Az=[kz(`set`,gz),kz(`set`,vz),kz(`set`,bz,[Dz,Oz]),kz(`set`,xz),kz(`set`,Sz)],jz=[kz(`persist`,_z),kz(`persist`,yz),kz(`persist`,bz,[Dz,Oz]),kz(`persist`,Cz),kz(`persist`,wz),kz(`persist`,Tz,[],[`insertSegment`]),kz(`persist`,Ez,[],[`insertSegmentFrom`])];function Mz(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function Nz(e){let t=Mz(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function Pz(e,t,n,r,i){let a=mz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${Nz(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Fz(e){let t=hz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>fz(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function Iz(e){let t=hz(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function Lz(e){let t=hz(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${cv(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Rz(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function zz(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=nv(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Bz(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function Vz(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function Hz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Uz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Wz(e,t){if(!sv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${cv(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(c_(r)){e.issues.push({path:`styles.${r}`,message:Hz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Uz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const Gz={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:DR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:JA(),parse:(e,t,n,r)=>r[n]===void 0?void 0:qA(e,`${t}.${n}`,r[n])}}};function Kz(e,t){if(!sv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${cv(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=lv(e,Gz,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function qz(e,t){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${cv(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}function Jz({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...px(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Nx(e,t)?Object.keys(n):jx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=Xz(n=>i(n).flatMap(n=>[...Dx(n,t).keys()].map(t=>({path:t,reaches:Bx(t,e)}))));return{ofTemplate:a,calls:Xz(e=>new Set(i(e).flatMap(e=>[...Fx(e,t)]))),ofVariable:t=>[...P_(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...N_(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function Yz(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function Xz(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const Zz=new WeakMap;function Qz(e){let t=Zz.get(e);return t===void 0&&(t=Jz({names:new Set([...zx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),Zz.set(e,t)),t}function $z(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const eB=new WeakMap;function tB(e){let t=eB.get(e);return t===void 0&&(t=rB(e),eB.set(e,t)),t}function nB(e){return tB(e).projections}function rB(e){let t=new Map(zx(e)),n=new Map,r={reads:Qz(e),projections:n,clock:hk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=Yz(e,r),i=t===void 0?null:eA(t);i&&n.set(e,`reads the draw's "${i}" (${$k[i]})`)}let i=aB(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=$z(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Ug)if(!a.has(t))for(let n of i[t]){let i=$z(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=Yz(r,i);if(t===void 0||n.has(r))continue;let o=nA(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function iB(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Ug.flatMap(n=>{let r=t[n];return Wg(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function aB(e){let t=iB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function oB(e,t){return $z(e,tB(t))}function sB(e){return t=>$z(t,e)!==null}const cB={cell:e=>`${e} sets "distribution" on a container inside a cell — everything inside a cell wears that cell's colour, so it would place nothing. Set it on the row whose children are the cells (the horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function lB(e,t){let n=new Map;for(let e of Object.keys(t)){let t=oA(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function uB(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Wg(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:c_(i)?Hz(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),lB(e,t.presets);let i=Hx(t);for(let t of i.names)t!==`settings`&&!t.startsWith(pB)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let a=(t,n,r)=>{NF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gj}" ${NF(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),PF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${gj}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r});let i=o(t,`bar`);i!==void 0&&e.issues.push({path:n,message:cB[i](n),line:r});let a=new Map;for(let e of E_(t)){if(e.kind!==`segment`)continue;let t=S_(e);a.set(t,[...a.get(t)??[],e])}for(let[t,i]of a){if(i.length<2)continue;let o=i[1].name,s=w_(o,new Set(a.keys()));e.issues.push({path:n,message:`${n} has ${i.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`cell`)return`cell`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||x_[e.direction]===`cell`);return x_[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:x_[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,D_(t,n)]):e.opens===void 0?[]:[[e.opens.body,O_(t)]];function*l(e,t){for(let[n,r]of e){let e=o(n,t);e!==void 0&&(yield[e,r]),yield*l(c(n,r),s(n,t))}}let u=(n,r)=>{let a=Kb(n),o=Hb(n)?Object.entries(n.rows).map(([e,t])=>[t,`${r}.rows.${e}`]):c(a,r);for(let[t,n]of l(o,s(a,`bar`)))e.issues.push({path:n,message:cB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of qb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(kB(e,`${o}.when`,a.when,i,{line:n}),DB(e,`${o}.when`,a.when,n),OB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(AF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${gj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${gj}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${BL(a.name)}`,line:n}),xB(e,t,a,o,n)}}};n.root!==void 0&&u(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&u(t.root,`presets.${e}.root`);let d=new Map([[`root`,Gb(t.root)]]);for(let e of Qb(t.presets)){let{node:n,path:r}=tx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));IB(e,t,i,()=>!0)}const dB=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function fB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!Qb(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${BL(i)}`,line:c})},p=new Set(C_(tx(t,a).node)),m=(r,i)=>{!zL.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${BL(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const pB=`settings.`;function mB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>pB+e)])}}function hB(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=vB(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of U_(n,_B(n)))i(e,`the defaults do not stand together: ${t}`)}function gB(e){return vB(e).length>0||U_(e,_B(e)).length>0}function _B(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function vB(e){let t=t=>H_(yB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(yB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${bB(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function yB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function bB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function xB(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=V_(a),s=`${r}: placement "${S_(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:W_(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Fg(a):``}, but it must be ${J_(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>W_(o[e],t))||gB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function SB(e,t,n,r,i){for(let[a,o]of P_(n))kB(e,`${t}.${a}`,o,r,{segCtx:i})}function CB(e,t,n,r,i){if(!(!N_(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const wB=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function TB(e,t,n,r){if(!N_(n))return;let i=n=>G(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=oB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${wB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=nB(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${wB}`,line:i(`depends_on`)})})}}function EB(e,t){let n=new Map(zx(t)),r=Qz(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>tA[e]===n||tA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${tA[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=Yz(e,a),s=o===void 0?void 0:nA(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of iB(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:G(e.source,[...n])})}}function DB(e,t,n,r){try{hj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function OB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of jx(r,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,o))continue;let r=s===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(c!==null){AB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function kB(e,t,n,r,i){for(let[a,o]of Dx(n,r.helpers)){if(Vx(a,r))continue;if(a.startsWith(pB)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){AB(e,o,`Template references unknown variable ".${a}"${sL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Vx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:sL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function AB(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function jB(e,t,n,r,i){let a=n.set,o=MA(Sy[r].configKey),s=`${a} takes ${EA(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=PB(n,i);if(c===NB){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!TA(o,e.value,i));if(l.length!==0){if(a===Sy.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>c_(e.value)))){let r=Sy.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:Hz(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=MB?r.join(`, `):`${r.slice(0,MB).join(`, `)} and ${r.length-MB} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const MB=3,NB=Symbol(`any integer`);function PB(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?cx(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:NB}function FB(e,t){return Object.entries(e).filter(([e])=>t(e))}function IB(e,t,n,r){let i=sI(t),a=sx(i);for(let[n,o]of FB(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${ux(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ey.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Ay.get(o.set);s!==void 0&&jB(e,n,o,s,i)}for(let[n,i]of FB(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&mx(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of FB(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, plugins.<plugin>.<source>; a plugin names its own sources bare)`,line:G(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of FB(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=uj(r);if(o===null){let t=QA(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${$A().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:G(e.source,[`actions`,n,a])});continue}let s=dB.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){fB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Qb(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Fg(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${BL(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}for(let[i,a]of FB(t.variables,r)){SB(e,`variables.${i}`,a,n);let t=oL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of FB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))SB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);hB(e,i,r);let o=mB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(kB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),OB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of FB(t.variables,r))CB(e,`variables.${i}`,a,n),TB(e,`variables.${i}`,a,t);EB(e,t);for(let[i,a]of FB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))CB(e,`segments.${i}.vars.${r}`,o,n,i),TB(e,`segments.${i}.vars.${r}`,o,t)}function LB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=RB(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function RB(e){let t=new Map,n=new Map,r=Qz(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function zB(e,t,n){let r=new Map([...Rx(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:G(e.source,[...d])})}}}function BB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function VB(e,t){return s.resolve(e,BB(t))}function HB(e,t){return typeof t==`string`&&t!==``?VB(e,t):void 0}function UB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const WB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),GB=`plugin.json5`,KB=/^[a-z][a-z0-9_]*$/;function qB(e){let t=s.basename(s.dirname(e));return KB.test(t)?t:void 0}const JB=`plugins.`;function YB(e){return`${JB}${e}.data`}function XB(e){return`${e}.json`}function ZB(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:QB(e)}}}function QB(e){return e instanceof Z_?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function $B(e,t){return e.map(e=>VB(s.dirname(t),e))}function eV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=qB(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${GB}, and the folder's name is the plugin's: move this file to <dir>/<name>/${GB} and list that`;return o(t,a===void 0?e.config:iV(rV(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${KB}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=rV(e.config,a),u=ZB(()=>{let i=p.readFileSync(n,`utf-8`),o=qI(uV(n,a,{source:i,json:Ii.default.parse(i)},t),l);return bV(n,a,o),r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,iV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function tV(e){let t=nV(e);return e=>e===t||e.startsWith(`${t}.`)}function nV(e){return`${JB}${e}`}function rV(e,t){let n=tV(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function iV(e,t,n){return{...e,variables:{...e.variables,[nV(t)]:{kind:`dropped`,reason:UB(n),definition:n.path}}}}function aV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function oV(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments),...Object.keys(e.config.helpers),...Object.keys(e.config.actions)].map(aV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:UB(e)}));return t=>{let i=aV(t);if(i===void 0)return[];let a=e.config.variables[nV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function sV(e,t){let n=Qb(e.presets).flatMap(t=>[...E_(tx(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,cV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=aV(t),r=n===void 0?void 0:e.variables[nV(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>jx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Lx(t,e.helpers)]),e.helpers),f=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(l(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),p=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition),...f.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(f.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${nV(aV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function cV(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,lV(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function lV(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function uV(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Z_(e,a)};if(!sv(r))return a.push({path:``,message:`a plugin definition must be an object, got ${cv(r)}`}),o();for(let e of Object.keys(r))WB.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...WB].join(`, `)}`});let c=r.data===void 0?void 0:CV(r.data,e,i,a),l=r.sources===void 0?{}:yV(r.sources,e,a);if(a.length>0)return o();let u={source:n,issues:a,allowedPalettes:new Set(Rg()),groups:[]},d=c===void 0?{}:fL(u,`data`,{[YB(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=fL(u,`variables`,r.variables);for(let[e,n]of[[`variables`,Object.keys(f)],[`sources`,Object.keys(l)]])n.includes(`data`)&&a.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${YB(t)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(l))Object.hasOwn(f,e)&&a.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${JB}${t}.${e}): give one of them another name`});let m={variables:{...d,...fV(t,l),...fV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,mV(t,n)])))},segments:fV(t,hV(t,iR(u,r.segments,new Set))),helpers:fV(t,qz(u,r.helpers)),actions:fV(t,gV(t,YR(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of dV(m))try{hj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*dV(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of P_(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of P_(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of px(n))yield[`actions.${t}.${e}`,r]}function fV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${JB}${e}.${t}`,n]))}function pV(e,t){return`${JB}${e}.${t}`}function mV(e,t){return t.kind===`state`?{...t,key:pV(e,t.key)}:t}function hV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,mV(e,n)]))}]))}function gV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:pV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>pV(e,t))}:n]))}const _V=KB,vV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function yV(e,t,n){if(!sv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${cv(e)}`}),{};let r=s.join(p.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(vV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!_V.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${_V}: it is the last segment of .${JB}<plugin>.${t})`});continue}let s=SV(o,vV,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function bV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=xV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=tV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${JB}${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new Z_(e,a)}function xV(e){return s.join(e.storage,XB(`<session id>`))}function SV(e,t,n){return!sv(t)||!sv(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?SV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function CV(e,t,n,r){if(typeof e==`string`&&e!==``)return VB(s.dirname(t),e);if(sv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(sv(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function wV(e){let t=[...[...(process.env.XDG_DATA_DIRS||DV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),TV(),...e===null?[]:[s.join(e,EV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function TV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const EV=s.join(`.cc-candybar`,`plugins`);function DV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function OV(e){let t=wV(e),n=new Map,r=[],i=[];for(let e of t){let t=kV(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,GB));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${GB}: move this file to ${s.join(e,`<name>`,GB)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function kV(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||AV(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function AV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function jV(e){return p.existsSync(s.join(e,`.git`))}function MV(e){let t=s.resolve(e);for(;;){if(jV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function NV(e){let t=MV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function PV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const FV=[`json5`,`json`];function IV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?FV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...FV.map(e=>s.join(r,`.cc-candybar.${e}`)),...FV.map(e=>`${LV()}.${e}`)])]}function LV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function RV(e,t,n){let r=[],i=new Map;for(let a of IV(e,t,n)){let e=PV(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:zV(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function zV(e){let t=LV();return e.find(e=>FV.some(n=>e===`${t}.${n}`))??`${t}.${FV[0]}`}function BV(e,t,n){let r=RV(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function VV(e){return HV(e).join(`
|
|
181
|
-
`)||null}function
|
|
180
|
+
New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),vR;if(n.kind===`group`){let r=lv(e,LR,t,n);return r===null?vR:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),zR(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:G(e.source,[`root`])}),vR}if(a){let r=lv(e,DR,t,n);return r===null?vR:{kind:`segment`,name:r.seg,...r.when!==void 0&&{when:r.when},...r.id!==void 0&&{id:r.id},...r.settings!==void 0&&{settings:r.settings}}}if(r){let r=lv(e,OR,t,n);return r===null?vR:{kind:`container`,direction:`horizontal`,children:r.h,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}if(i){let r=lv(e,kR,t,n);return r===null?vR:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:G(e.source,[`root`])}),vR};function jR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:zb.source},additionalProperties:{$ref:_R}},parse:(e,t,n,r)=>{let i=r[n];if(!sv(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${cv(i)}`,line:G(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!zb.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:G(e.source,[...t.split(`.`),n,r])});continue}a[r]=AR(e,`${t}.${n}.${r}`,o)}return a}}}const MR={noun:`root key`,fields:{rows:jR(),when:bv(),distribution:wR()}};function NR(e,t,n){return sv(n)&&`rows`in n?lv(e,MR,t,n)??{rows:{}}:AR(e,t,n)}function PR(){return{required:!0,json:{type:`string`,pattern:zb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!zb.test(i)||i===`closed`){e.issues.push({path:`${t}.${n}`,message:`a group "name" must be an identifier (letters, digits, _; not starting with a digit) and not the reserved "${yi}", got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}function FR(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${K(i)}`,line:G(e.source,[`root`])});return}return i}}}}function IR(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=nv(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:G(e.source,[...t.split(`.`),n])});return}return i}}}}const LR={noun:`layout-node key`,fields:{kind:yR(`group`),name:PR(),label:IR(),open:xv(),direction:Ov(b_),key:FR(),bg:bv(),fg:bv(),when:bv(),distribution:wR(),children:SR(vv(()=>AR))}};function RR(e){return e.key??`groups.`+e.name}function zR(e){let t=pA+e.name;return wi(t,{variable:t,key:RR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function BR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function VR(e,t){bA(e,t,pA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&BR(e,t.path,`duplicate group name "${t.name}" — group names must be unique (they name the synthesized state var, action, and toggle segment)`),r.add(t.name);for(let t of n)for(let r of n)t!==r&&t.path.startsWith(`${r.path}.`)&&RR(t)===RR(r)&&BR(e,t.path,`group "${t.name}" shares key "${RR(t)}" with its ancestor group "${r.name}" — a shared key holds ONE open group, so an ancestor and a descendant cannot share one. Sibling accordions share a key; nested groups use distinct keys.`);let i=new Map;for(let t of n){let n=RR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&BR(e,t.path,`groups "${r}" and "${t.name}" share key "${n}" and both declare open: true — a shared key holds one open group; pick one`),i.set(n,t.name)}}let a={},o={},s={};for(let e of n){let t=pA+e.name,r=RR(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=Ai(r,i.get(r)),o[t]=N(r,e.name),s[t]={template:Di(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const HR=`menu`,UR=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,WR=e=>e.kind===`call`&&e.name===`dict`,GR=e=>e.kind===`literal`&&typeof e.value!=`object`,KR=e=>xi(``,e,2)===void 0;function qR(e){let t=e=>({kind:`issue`,message:e}),[n,...r]=e.argExprs;if(n===void 0)return t(`with no arguments — it takes an apply-action name and its trigger text (e.g. {{ menu "applyTheme" "▸" "▾" }})`);if(n.kind!==`literal`||typeof n.value!=`string`)return t(`whose apply action is not a string literal — a menu's identity is its apply-action name, which must be a literal so it can be gated at load (e.g. {{ menu "applyTheme" "▸" "▾" }})`);let i=r[r.length-1],a=i!==void 0&&WR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(WR))return t(`whose options (dict …) is not its last argument — ${UR}`);if(i!==void 0&&a===void 0&&!GR(i)&&KR(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=xi(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${UR}`);let c=a===void 0?{}:ZT(a);if(c===null)return t(`whose options (dict …) is not fully literal — every option value must be a literal so the menu can be gated at load (a dynamic entry like (dict "key" .x) cannot)`);let l;try{l=kA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=yA(u);if(e!==void 0)return t(`whose accordion key "${u}" lands in the reserved "${e}" namespace — a key is collapsed to an identifier (${JSON.stringify(u)} becomes "${CA(u)}"), so it would share one open-state key with the synthesized accordion that owns that namespace instead of grouping only your own menus. Name the group without the reserved prefix`)}return{kind:`ok`,apply:n.value,options:l}}function JR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===HR).map(qR)}catch{return`parse-failed`}}function YR(e,t){let n=JR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:SA(t,e.apply,e.options.key),member:xA(e.apply)}]:[])}function XR(e){let t=ow({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(HR)}catch{return!1}}function ZR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function QR(e,t){bA(e,t,mA,`{{ menu }} helpers`),bA(e,t,hA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))XR(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:G(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&XR(i)&&ZR(e,`segments.${t}.${n}`,`segment "${t}" uses {{ menu }} in its "${n}" — a menu is only valid in a segment's "template" (its placement is published only there; "${n}" needs a ${n===`when`?`predicate`:`color`}). Move the {{ menu }} into the template.`)}if(t.root!==void 0)for(let n of E_(Kb(t.root)))typeof n.when==`string`&&XR(n.when)&&ZR(e,`root`,`a layout node's "when" predicate uses {{ menu }} — a menu is only valid in a segment's "template", not a node predicate. Move it into a segment.`);for(let[t,{template:r}]of Object.entries(n)){if(r===void 0||!XR(r))continue;let n=JR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:$R(r.apply);n!==void 0&&ZR(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function $R(e){if(e===``)return`with an empty apply-action name — an empty member aliases the absent-state sentinel ("") so the menu would render open before any click. Name the apply action`;if(xA(e)===`closed`)return`whose apply action is named "${yi}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function ez(e,t){let n={},r={},i=new Map,a=new Set,o=(e,n)=>{let r=`segments.${e}`;a.has(`${r}\0${n}`)||(a.add(`${r}\0${n}`),t.push({path:r,message:n}))};for(let t of Qb(e.presets)){let a=new Map,s=new Map;for(let c of E_(tx(e,t).node)){if(c.kind!==`segment`)continue;let t=e.segments[c.name];if(t===void 0)continue;i.has(c.name)||i.set(c.name,JR(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=S_(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||$R(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=xA(i),f=SA(u,i,l.key),p=TA(f),m=l.key===void 0?`ind ${u} ${i}`:`key ${l.key}`,h=[f,p].find(e=>{let t=a.get(e);return t!==void 0&&t!==m});if(h!==void 0){o(c.name,`two {{ menu }} disclosures normalize to the same state key ("${h}") but were declared differently — distinct names that differ only by non-alphanumeric characters (e.g. "a-b" vs "a_b") collapse to one key and would silently share open-state. Rename so they don't collide.`);continue}a.set(f,m),a.set(p,m);let g=wA(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=N(f,d),n[f]=Ai(f,yi),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}function tz(e,t,n){if(t===void 0)return{};if(!sv(t))return Z(e,`actions`,`actions must be an object, got ${cv(t)}`),{};let r=Object.create(null);for(let[i,a]of Object.entries(t)){let t=nz(e,`actions.${i}`,a,n);t!==null&&(r[i]=t)}return r}function Z(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function nz(e,t,n,r){if(!sv(n))return Z(e,t,`${t} must be an action object, got ${cv(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let i=dx.filter(e=>e in n);return i.length===1?iz(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${dx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function rz(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const iz=e=>({set:(e,t,n)=>Bz(e,t,n,`set`,Iz),persist:(e,t,n)=>Bz(e,t,n,`persist`,Lz),copy:az(`copy`),open:az(`open`),reset:oz,undo:cz(`undo`),redo:cz(`redo`),back:cz(`back`),rewind:cz(`rewind`),save:cz(`save`),preset:lz,themeDefault:uz,doctor:fz,slash:pz,run:gz(e),do:_z});function az(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);let i=nv(t,n,r,e);return i===null?null:{[e]:i}}}function oz(e,t,n){for(let r of Object.keys(n))r!==`reset`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a reset action. Expected only: reset`);let r=vz(e,t,`reset`,n,`reset key must be non-empty (the config globals field to clear)`,e=>`reset key "${e}" contains "/" — keys must be slash-free`);return r===null?null:{reset:r}}const sz={undo:`it steps the session's settings history`,redo:`it steps the session's settings history`,back:`it steps the session's navigation history`,rewind:`it steps the session's settings history back to where edit mode opened`,save:`it saves the session's unsaved settings`};function cz(e){return(t,n,r)=>{for(let i of Object.keys(r))i!==e&&Z(t,`${n}.${i}`,`Unknown key "${i}" on a ${e} action. Expected only: ${e}`);return r[e]===!0?{[e]:!0}:(Z(t,`${n}.${e}`,`${e} must be the literal true (it takes no key — ${sz[e]}), got ${K(r[e])}`),null)}}function lz(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${K(r)}`),null;if(r===`save`)return{preset:`save`};let a=nv(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function uz(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${K(n.themeDefault)}`),null)}const dz={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function fz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(dz,r),a=i?dz[r]:[...new Set(Object.values(dz).flat())];for(let r of Object.keys(n))a.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a doctor action. Expected only: ${a.join(`, `)}`);if(!i)return Z(e,`${t}.doctor`,`doctor must be ${Object.keys(dz).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?FN:PN;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${K(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return GM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${GM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function pz(e,t,n){for(let r of Object.keys(n))r!==`slash`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a slash action. Expected only: slash`);let r=sP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const mz=[`run`,`env`,`refreshes`],hz=/^[A-Za-z_][A-Za-z0-9_]*$/;function gz(e){return(t,n,r)=>{for(let e of Object.keys(r))mz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${mz.join(`, `)}`);let i=t.issues.length,a=r.run;(!Array.isArray(a)||a.length===0||a.some(e=>typeof e!=`string`)||a[0]===``)&&Z(t,`${n}.run`,`run must list the program and its arguments, each a template string, the program first and not empty, got ${K(a)}`);let o=r.env??{};(!sv(o)||Object.entries(o).some(([e,t])=>!hz.test(e)||typeof t!=`string`))&&Z(t,`${n}.env`,`env must map variable names (letters, digits and _, not starting with a digit) to template strings, got ${K(o)}`);let s=r.refreshes??[];return(!Array.isArray(s)||s.some(e=>typeof e!=`string`||e===``))&&Z(t,`${n}.refreshes`,`refreshes must list the names of the sources the program writes, got ${K(s)}`),`dir`in e||Z(t,`${n}.run`,`a run action runs in the directory of the file that declares it, and ${e.text} is no file`),t.issues.length>i||!(`dir`in e)?null:{run:a,env:o,refreshes:s,cwd:e.dir}}}hz.source;function _z(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${K(r)}`),null):{do:r}}function vz(e,t,n,r,i,a){let o=nv(e,t,r,n);if(o===null)return null;let s=`${t}.${n}`;return o===``?(Z(e,s,i),null):o.includes(`/`)?(Z(e,s,a(o)),null):o}const yz={set:`the SessionState key to write`,persist:`the config globals field to write`};function bz(e,t,n,r){let i=yz[r],a=vz(e,t,r,n,`${r} key must be non-empty (${i})`,e=>`${r} key "${e}" contains "/" — keys must be slash-free`);return a===null?null:{[r]:a}}function xz(e){return e===`set`?`set-state`:`set-config`}const Sz={to:Vz(`set`)},Cz={to:Vz(`persist`)},wz={from:Hz(`set`)},Tz={from:Hz(`persist`)},Ez={min:qz(),max:qz(),by:qz()},Dz={int:Wz()},Oz={cycle:Uz(`set`)},kz={cycle:Uz(`persist`)},Az={removeSegment:Gz(`removeSegment`)},jz={insertSegment:Gz(`insertSegment`),anchor:Gz(`anchor`),relation:Kz()},Mz={insertSegmentFrom:Hz(`persist`),anchor:Gz(`anchor`),relation:Kz()},Nz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Pz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Fz(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>dv(e,t,n,r),c=kv(t);return{detect:a,allowed:[...o,...i],label:i.join(`/`),json:{type:`object`,properties:{...Object.fromEntries(o.map(e=>[e,{type:`string`}])),...c.properties},required:[...o,...c.required??[]],additionalProperties:!1},parse:n.length?yv(s,...n):s}}const Iz=[Fz(`set`,Sz),Fz(`set`,wz),Fz(`set`,Ez,[Nz,Pz]),Fz(`set`,Dz),Fz(`set`,Oz)],Lz=[Fz(`persist`,Cz),Fz(`persist`,Tz),Fz(`persist`,Ez,[Nz,Pz]),Fz(`persist`,kz),Fz(`persist`,Az),Fz(`persist`,jz,[],[`insertSegment`]),Fz(`persist`,Mz,[],[`insertSegmentFrom`])];function Rz(e){let t=[`"to" (a literal value)`,`"from" (an option domain — a registered domain name like "themes"/"endcaps"/"styles", or an inline array of literal values)`,`"min"/"max"/"by" (a bounded step)`];return e===`set`&&t.push(`"int" (an unbounded integer cursor)`),t.push(`"cycle" (an enumerated domain stepped in order)`),e===`persist`&&t.push(`"removeSegment" (remove a named segment from the layout)`,`"insertSegment"/"anchor"/"relation" (insert a named segment before/after an existing one)`,`"insertSegmentFrom"/"anchor"/"relation" (insert a segment PICKED from an option domain before/after an existing one)`),t}function zz(e){let t=Rz(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function Bz(e,t,n,r,i){let a=bz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${zz(r)}${o.length>1?` — found: ${o.map(e=>e.label).join(`, `)}`:``}`),null;let s=o[0];for(let i of Object.keys(n))s.allowed.includes(i)||Z(e,`${t}.${i}`,`Unknown key "${i}" on this ${r} action. Expected one of: ${s.allowed.join(`, `)}`);let c=s.parse(e,t,n);return a===null||c===null?null:{...a,...c}}function Vz(e){let t=xz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>vz(n,r,i,a,`${e} value must be non-empty — an empty value cannot be delivered on the ${t} wire`,t=>`${e} value "${t}" contains "/" — ${e} values must be slash-free`)??void 0}}function Hz(e){let t=xz(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${K(o)}`)}}}function Uz(e){let t=xz(e);return{required:!0,json:{type:`array`,items:{type:`string`,minLength:1},minItems:2,uniqueItems:!0},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(!Array.isArray(o)||o.some(e=>typeof e!=`string`)){Z(n,s,`cycle must be an array of strings (the enumerated values a click steps through), got ${cv(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function Wz(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${K(r[n])}`);return}return!0}}}function Gz(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=nv(t,n,i,r);if(a===null)return;let o=`${n}.${r}`;if(a===``){Z(t,o,`${e} must be non-empty (a segment name)`);return}if(a.includes(`/`)||a.includes(`:`)){Z(t,o,`${e} "${a}" contains "/" or ":" — segment names in a layout op must be free of both (the click wire's own delimiter and layout-ops.ts's op-token delimiter)`);return}return a}}}function Kz(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${K(i)}`);return}return i}}}function qz(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${K(i)}`);return}return i}}}function Jz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Yz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Xz(e,t){if(!sv(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${cv(t)}`,line:G(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:G(e.source,[`styles`,r])});continue}if(c_(r)){e.issues.push({path:`styles.${r}`,message:Jz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Yz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const Zz={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:NR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:ej(),parse:(e,t,n,r)=>r[n]===void 0?void 0:$A(e,`${t}.${n}`,r[n])}}};function Qz(e,t){if(!sv(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${cv(t)}`,line:G(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:G(e.source,[`presets`,r])});continue}let t=lv(e,Zz,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function $z(e,t){if(t===void 0)return{};if(!sv(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${cv(t)}`,line:G(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${K(i)}`,line:G(e.source,[`helpers`,r])});continue}n[r]=i}return n}function eB({names:e,helpers:t,actions:n}){let r=(e,t)=>{let i=Object.hasOwn(n,e)?n[e]:void 0;return i===void 0||t.has(e)?[]:(t.add(e),[...[...px(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Nx(e,t)?Object.keys(n):jx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=nB(n=>i(n).flatMap(n=>[...Dx(n,t).keys()].map(t=>({path:t,reaches:Bx(t,e)}))));return{ofTemplate:a,calls:nB(e=>new Set(i(e).flatMap(e=>[...Fx(e,t)]))),ofVariable:t=>[...P_(t).flatMap(([e,t])=>a(t).map(t=>({...t,field:e}))),...N_(t)&&`depends_on`in t.cache?t.cache.depends_on.map(t=>({path:t,reaches:e.has(t)?[t]:[],field:`cache.depends_on`})):[]]}}function tB(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function nB(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const rB=new WeakMap;function iB(e){let t=rB.get(e);return t===void 0&&(t=eB({names:new Set([...zx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),rB.set(e,t)),t}function aB(e,t){for(let n of t.reads.calls(e))if(t.clock.has(n))return`calls "${n}"`;for(let{reaches:n}of t.reads.ofTemplate(e))for(let e of n){let n=t.projections.get(e);if(n!==void 0)return`reads "${e}", which ${n}`}return null}const oB=new WeakMap;function sB(e){let t=oB.get(e);return t===void 0&&(t=lB(e),oB.set(e,t)),t}function cB(e){return sB(e).projections}function lB(e){let t=new Map(zx(e)),n=new Map,r={reads:iB(e),projections:n,clock:hk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=tB(e,r),i=t===void 0?null:oA(t);i&&n.set(e,`reads the draw's "${i}" (${aA[i]})`)}let i=dB(e),a=new Map;for(let e=!0;e;){e=!1;for(let[i,a]of t){if(a.kind!==`template`||n.has(i))continue;let t=aB(a.template,r);t!==null&&(n.set(i,t),e=!0)}for(let t of Ug)if(!a.has(t))for(let n of i[t]){let i=aB(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=tB(r,i);if(t===void 0||n.has(r))continue;let o=cA(t),s=o===void 0?void 0:a.get(o);s!==void 0&&(n.set(r,`reads the ${o} rule, which ${s}`),e=!0)}}return r}function uB(e){return[[[`globals`],e.globals],...Object.entries(e.presets??{}).map(([e,t])=>[[`presets`,e,`globals`],t.globals??{}])].flatMap(([e,t])=>Ug.flatMap(n=>{let r=t[n];return Wg(r)?[{at:[...e,n],slot:n,rule:r}]:[]}))}function dB(e){let t=uB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function fB(e,t){return aB(e,sB(t))}function pB(e){return t=>aB(t,e)!==null}const mB={cell:e=>`${e} sets "distribution" on a container inside a cell — everything inside a cell wears that cell's colour, so it would place nothing. Set it on the row whose children are the cells (the horizontal container), or, on the bar, on the root, which places the rows.`,bar:e=>`${e} sets "distribution" on a vertical container none of whose children is a segment or a horizontal container — a bar row's hue is placed by the innermost vertical container it stacks through, so it would place nothing. Set it on that container, or on the row whose children are the cells (the horizontal container).`,band:e=>`${e} sets "distribution" on a vertical container in a disclosure body — a body's items are placed along their rows, never by which row they sit on, so it would place nothing. Set it on the row whose children are the items (the horizontal container), or give a group \`direction: 'horizontal'\`.`};function hB(e,t){let n=new Map;for(let e of Object.keys(t)){let t=fA(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:G(e.source,[`presets`])})}function gB(e,t,n){let r=[[[`globals`],t.globals.style,`globals.endcaps`],[[`editGlobals`],t.editGlobals.style,`editGlobals.endcaps`],...Object.entries(t.presets).map(([e,t])=>[[`presets`,e,`globals`],t.globals?.style,`presets.${e}.globals.endcaps`]),...Object.entries(t.themeDefaults).map(([e,t])=>[[`themeDefaults`,e],t.style,`globals.endcaps`])];for(let[n,i,a]of r){if(i===void 0||Wg(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:c_(i)?Jz(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:G(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:G(e.source,[`globals`,`preset`])}),hB(e,t.presets);let i=Hx(t);for(let t of i.names)t!==`settings`&&!t.startsWith(yB)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:G(e.source,[`variables`,t])});let a=(t,n,r)=>{zF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Sj}" ${zF(t)} times — it may appear at most once per layout (it is one disclosure, and one state key holds one open state). Remove all but the placement you want; removing every placement puts the menu at its default position.`,line:r}),BF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Sj}" under a \`when\` or inside a disclosure body — the menu is visible under every condition, so its placement may not be gated. Move it to an ungated position, or remove it to put the menu at its default position.`,line:r});let i=o(t,`bar`);i!==void 0&&e.issues.push({path:n,message:mB[i](n),line:r});let a=new Map;for(let e of E_(t)){if(e.kind!==`segment`)continue;let t=S_(e);a.set(t,[...a.get(t)??[],e])}for(let[t,i]of a){if(i.length<2)continue;let o=i[1].name,s=w_(o,new Set(a.keys()));e.issues.push({path:n,message:`${n} has ${i.length} placements with the id "${t}" — an id names one placement (its settings, its menus' open state, and edit mode all address it), so give each its own: { seg: "${o}", id: "${s}" }. A placement without an "id" takes its segment's name.`,line:r})}};function o(e,t){if(e.kind===`segment`||e.distribution===void 0)return;if(t===`cell`)return`cell`;let n=t===`bar`&&e.children.some(e=>e.kind===`segment`||x_[e.direction]===`cell`);return x_[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:x_[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,D_(t,n)]):e.opens===void 0?[]:[[e.opens.body,O_(t)]];function*l(e,t){for(let[n,r]of e){let e=o(n,t);e!==void 0&&(yield[e,r]),yield*l(c(n,r),s(n,t))}}let u=(n,r)=>{let a=Kb(n),o=Hb(n)?Object.entries(n.rows).map(([e,t])=>[t,`${r}.rows.${e}`]):c(a,r);for(let[t,n]of l(o,s(a,`bar`)))e.issues.push({path:n,message:mB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of qb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(FB(e,`${o}.when`,a.when,i,{line:n}),NB(e,`${o}.when`,a.when,n),PB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(IF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Sj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Sj}"`,line:n});continue}Object.prototype.hasOwnProperty.call(t.segments,a.name)||e.issues.push({path:o,message:`${r} entry "${a.name}" does not match any declared segment${KL(a.name)}`,line:n}),DB(e,t,a,o,n)}}};n.root!==void 0&&u(n.root,`root`);for(let[e,t]of Object.entries(n.presets??{}))t.root!==void 0&&u(t.root,`presets.${e}.root`);let d=new Map([[`root`,Gb(t.root)]]);for(let e of Qb(t.presets)){let{node:n,path:r}=tx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));HB(e,t,i,()=>!0)}const _B=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function vB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!Qb(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:c});return}if(r===`reset`)return;let l=`removeSegment`in o,u=`insertSegment`in o,d=`insertSegmentFrom`in o;if(!l&&!u&&!d){e.issues.push({path:s,message:`actions.${n}: "${i}" is a "presets.<name>.root" target and can only be paired with "removeSegment", "insertSegment", or "insertSegmentFrom" (not "to"/"from"/"cycle"/bounded — those have no meaning as a tree op)`,line:c});return}let f=(r,i)=>{Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" is not a declared segment (have: ${Object.keys(t.segments).join(`, `)})${KL(i)}`,line:c})},p=new Set(C_(tx(t,a).node)),m=(r,i)=>{!GL.has(i)||p.has(i)||Object.prototype.hasOwnProperty.call(t.segments,i)||e.issues.push({path:s,message:`actions.${n}: ${r} "${i}" names no placement${KL(i)}`,line:c})};`removeSegment`in o&&m(`removeSegment`,o.removeSegment),`insertSegment`in o&&f(`insertSegment`,o.insertSegment),(`insertSegment`in o||`insertSegmentFrom`in o)&&m(`anchor`,o.anchor)}const yB=`settings.`;function bB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>yB+e)])}}function xB(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:G(e.source,[`segments`,t,`settings`,n])})},a=wB(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of U_(n,CB(n)))i(e,`the defaults do not stand together: ${t}`)}function SB(e){return wB(e).length>0||U_(e,CB(e)).length>0}function CB(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function wB(e){let t=t=>H_(TB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(TB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${EB(e,n).join(`, `)||`none`})`}];let i=[n];for(let e=r;e!==void 0;e=t(e)){if(e===n)return i.every(e=>n<=e)?[{setting:n,message:`atLeast closes a cycle (${[...i,n].join(` ≥ `)}) — every setting on it could only ever equal the rest`}]:[];if(i.includes(e))return[];i.push(e)}return[]})}function TB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function EB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function DB(e,t,n,r,i){let a=Object.prototype.hasOwnProperty.call(t.segments,n.name)?t.segments[n.name]:void 0;if(a===void 0)return;let o=V_(a),s=`${r}: placement "${S_(n)}" of segment "${n.name}"`;for(let[t,a]of Object.entries(n.settings??{})){let c=Object.prototype.hasOwnProperty.call(o,t)?o[t]:void 0,l=c===void 0?`sets "${t}", which segment "${n.name}" does not declare (it has: ${Object.keys(o).join(`, `)})`:W_(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Fg(a):``}, but it must be ${J_(c)}`;l!==void 0&&e.issues.push({path:r,message:`${s} ${l}`,line:i})}let c=Object.fromEntries(Object.entries(o).map(([e,t])=>[e,n.settings?.[e]??t.default]));if(!(!Object.entries(c).every(([e,t])=>W_(o[e],t))||SB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function OB(e,t,n,r,i){for(let[a,o]of P_(n))FB(e,`${t}.${a}`,o,r,{segCtx:i})}function kB(e,t,n,r,i){if(!(!N_(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:G(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}const AB=`it reads the instant a frame is drawn at, which changes every frame, and a cache policy re-runs its source when a stored value changes — re-run it on a period instead: cache: { ttl: "<duration>" }`;function jB(e,t,n,r){if(!N_(n))return;let i=n=>G(e.source,[...t.split(`.`),`cache`,n]);if(`key`in n.cache){let a=fB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${AB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=cB(r);n.cache.depends_on.forEach((n,r)=>{let o=a.get(n);o!==void 0&&e.issues.push({path:`${t}.cache.depends_on[${r}]`,message:`cache.depends_on names "${n}", which ${o}: ${AB}`,line:i(`depends_on`)})})}}function MB(e,t){let n=new Map(zx(t)),r=iB(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>sA[e]===n||sA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${sA[e]}", the ${e}'s own name`;for(let e of r){let n=a(e,t);if(n!==null)return n}}return null},a=(e,t)=>{if(t.has(e))return null;t.add(e);let a=n.get(e),o=tB(e,a),s=o===void 0?void 0:cA(o);if(s!==void 0)return`reads "${e}", the ${s}'s own name`;for(let n of r.ofVariable(a)){let r=i([n],t);if(r!==null)return n.field===`template`?`reads "${e}", which ${r}`:`reads "${e}", whose ${n.field} ${r}`}return null};for(let{at:n,rule:a}of uB(t)){let t=i(r.ofTemplate(a),new Set);if(t===null)continue;let o=n.join(`.`);e.issues.push({path:o,message:`${o} ${t}: a rule decides that name, so it cannot read it — read the data the rule is about instead`,line:G(e.source,[...n])})}}function NB(e,t,n,r){try{xj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function PB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of jx(r,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,o))continue;let r=s===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(c!==null){IB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function FB(e,t,n,r,i){for(let[a,o]of Dx(n,r.helpers)){if(Vx(a,r))continue;if(a.startsWith(yB)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??G(e.source,t.split(`.`))});continue}if(o!==null){IB(e,o,`Template references unknown variable ".${a}"${pL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Vx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:pL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function IB(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:G(e.source,[`helpers`,t])})}function LB(e,t,n,r,i){let a=n.set,o=RA(Sy[r].configKey),s=`${a} takes ${MA(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:G(e.source,[`actions`,t,`min`])});return}let c=BB(n,i);if(c===zB){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:G(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!jA(o,e.value,i));if(l.length!==0){if(a===Sy.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>c_(e.value)))){let r=Sy.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:Jz(`actions.${t}.to`,n.to,`set: "${r}", to`),line:G(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:G(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=RB?r.join(`, `):`${r.slice(0,RB).join(`, `)} and ${r.length-RB} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:G(e.source,[`actions`,t,n])})}}}const RB=3,zB=Symbol(`any integer`);function BB(e,t){return`to`in e?[{field:`to`,value:e.to}]:`cycle`in e?e.cycle.map(e=>({field:`cycle`,value:e})):`from`in e?cx(e.from,t).members.map(e=>({field:`from`,value:e})):`min`in e?[{field:`min`,value:String(e.min)},{field:`max`,value:String(e.max)}]:zB}function VB(e,t){return Object.entries(e).filter(([e])=>t(e))}function HB(e,t,n,r){let i=pI(t),a=sx(i);for(let[n,o]of VB(t.actions,r)){let[t,r]=`from`in o?[`from`,o.from]:`insertSegmentFrom`in o?[`insertSegmentFrom`,o.insertSegmentFrom]:[null,null];if(t!==null&&typeof r==`string`&&!a.includes(r)){e.issues.push({path:`actions.${n}.${t}`,message:`actions.${n} ${t}: references ${ux(r,i)}`,line:G(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;Ey.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:G(e.source,[`actions`,n,`set`])});let s=Ay.get(o.set);s!==void 0&&LB(e,n,o,s,i)}for(let[n,i]of VB(t.actions,r))`do`in i&&i.do.forEach((r,a)=>{let o=Object.prototype.hasOwnProperty.call(t.actions,r)?t.actions[r]:void 0,s=o===void 0?`references unknown action "${r}"`:`do`in o?`"${r}" is itself a do action — list its members here instead`:i.do.indexOf(r)===a?a>0&&mx(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:G(e.source,[`actions`,n,`do`])})});for(let[n,i]of VB(t.actions,r))if(`run`in i)for(let r of i.refreshes){let i=Object.hasOwn(t.variables,r)?t.variables[r]:void 0;i?.kind!==`source`&&e.issues.push({path:`actions.${n}.refreshes`,message:`actions.${n} refreshes "${r}", which ${i===void 0?`is not declared`:`is a ${i.kind} variable`}: a run refreshes only a declared source (by its full name, plugins.<plugin>.<source>; a plugin names its own sources bare)`,line:G(e.source,[`actions`,n,`refreshes`])})}for(let[n,i]of VB(t.actions,r)){let r=`persist`in i?i.persist:`reset`in i?i.reset:null;if(r===null)continue;let a=`persist`in i?`persist`:`reset`,o=gj(r);if(o===null){let t=ij(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${aj().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:G(e.source,[`actions`,n,a])});continue}let s=_B.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){vB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Qb(t.presets).includes(o.preset)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names preset "${o.preset}" which is not declared (have: ${Qb(t.presets).join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Fg(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:G(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${KL(o.segment)}`,line:G(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:G(e.source,[`actions`,n,a])})}}for(let[i,a]of VB(t.variables,r)){OB(e,`variables.${i}`,a,n);let t=fL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of VB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))OB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);xB(e,i,r);let o=bB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(FB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),PB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of VB(t.variables,r))kB(e,`variables.${i}`,a,n),jB(e,`variables.${i}`,a,t);MB(e,t);for(let[i,a]of VB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))kB(e,`segments.${i}.vars.${r}`,o,n,i),jB(e,`segments.${i}.vars.${r}`,o,t)}function UB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=WB(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:G(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function WB(e){let t=new Map,n=new Map,r=iB(e),i=(e,i,a)=>{t.set(e,{declarationPath:a.join(`.`),linePathParts:a}),n.set(e,new Set(r.ofVariable(i).flatMap(({reaches:e})=>e)))};for(let[t,n]of Object.entries(e.variables))i(t,n,[`variables`,t]);for(let[t,n]of Object.entries(e.segments))for(let[e,r]of Object.entries(n.vars??{}))i(`${t}.${e}`,r,[`segments`,t,`vars`,e]);return{graph:n,nodeInfo:t}}function GB(e,t,n){let r=new Map([...Rx(t)].map(([e,,t])=>[e,t]));for(let[t,i]of r){let a=t.split(`.`);for(let o=1;o<a.length;o++){let s=a.slice(0,o).join(`.`),c=r.get(s);if(c===void 0||!(n.checked(t)||n.checked(s)))continue;let[l,u,d]=n.authored(t)?[t,s,i]:[s,t,c],f=n.authored(t)===n.authored(s)?`Rename one so neither name starts with the other.`:`"${u}" is declared outside this file (the bundled default, a plugin, or a control the bar builds), so rename "${l}".`;e.issues.push({path:d.join(`.`),message:`variable "${t}" is declared under the variable "${s}" — a read of ".${t}" would name both, "${t}" and a field of "${s}". ${f}`,line:G(e.source,[...d])})}}}function KB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function qB(e,t){return s.resolve(e,KB(t))}function JB(e,t){return typeof t==`string`&&t!==``?qB(e,t):void 0}function YB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const XB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),ZB=`plugin.json5`,QB=/^[a-z][a-z0-9_]*$/;function $B(e){let t=s.basename(s.dirname(e));return QB.test(t)?t:void 0}const eV=`plugins.`;function tV(e){return`${eV}${e}.data`}function nV(e){return`${e}.json`}function rV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:iV(e)}}}function iV(e){return e instanceof Z_?e.issues.map(e=>e.path===``||e.message.includes(e.path)?e.message:`${e.path}: ${e.message}`).join(`; `):e instanceof Error?e.message:String(e)}function aV(e,t){return e.map(e=>qB(s.dirname(t),e))}function oV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=$B(n),o=(t,r)=>{let i=new Map(e.rendering);return a!==void 0&&r!==e.config&&i.delete(a),{...e,config:r,rendering:i,dropped:[...e.dropped,{path:n,plugin:a,reason:t}]}};if(s.basename(n)!==`plugin.json5`){let t=`a plugin is a folder holding its ${ZB}, and the folder's name is the plugin's: move this file to <dir>/<name>/${ZB} and list that`;return o(t,a===void 0?e.config:uV(lV(e.config,a),a,{path:n,plugin:a,reason:t}))}if(a===void 0)return o(`its folder "${s.basename(s.dirname(n))}" is not a plugin name (one matching ${QB}: it prefixes every name the plugin declares)`,e.config);let c=i.get(a);if(c!==void 0)return o(`plugin "${a}" is already listed, from ${c}`,e.config);i.set(a,n);let l=lV(e.config,a),u=rV(()=>{let i=p.readFileSync(n,`utf-8`),o=$I(gV(n,a,{source:i,json:Ii.default.parse(i)},t),l);return EV(n,a,o),r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,uV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function sV(e){let t=cV(e);return e=>e===t||e.startsWith(`${t}.`)}function cV(e){return`${eV}${e}`}function lV(e,t){let n=sV(t),r=e=>Object.fromEntries(Object.entries(e).filter(([e])=>!n(e)));return[e.variables,e.segments,e.helpers,e.actions].some(e=>Object.keys(e).some(n))?{...e,variables:r(e.variables),segments:r(e.segments),helpers:r(e.helpers),actions:r(e.actions)}:e}function uV(e,t,n){return{...e,variables:{...e.variables,[cV(t)]:{kind:`dropped`,reason:YB(n),definition:n.path}}}}function dV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function fV(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments),...Object.keys(e.config.helpers),...Object.keys(e.config.actions)].map(dV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:YB(e)}));return t=>{let i=dV(t);if(i===void 0)return[];let a=e.config.variables[cV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function pV(e,t){let n=Qb(e.presets).flatMap(t=>[...E_(tx(e,t).node)]).flatMap(e=>e.kind===`segment`?[e]:[]),r=[...new Set([...n.map(e=>e.name),...Object.keys(e.segments)])].map(e=>({name:e,cause:t(e)})).filter(({cause:e})=>e.length>0),i=Object.fromEntries(r.map(({name:e,cause:t})=>[e,mV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=dV(t),r=n===void 0?void 0:e.variables[cV(n)];return r?.kind===`dropped`?{definition:r.definition,notice:r.reason}:void 0},o=Object.values(e.variables).some(e=>e.kind===`dropped`),s=o?Object.values(e.segments).flatMap(e=>[`template`,`bg`,`fg`,`when`].flatMap(t=>e[t]===void 0?[]:[e[t]])):[],c=o?Object.values(e.actions).flatMap(e=>`do`in e?[...e.do]:[]):[],l=(e,t)=>[...new Set(e)].flatMap(e=>{let n=e in t?void 0:a(e);return n===void 0?[]:[[e,n]]}),u=l([...s.flatMap(t=>jx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Lx(t,e.helpers)]),e.helpers),f=Object.entries(e.actions).flatMap(([t,n])=>{if(!(`run`in n))return[];let r=new Map(l(n.refreshes,e.variables));return r.size===0?[]:[{name:t,action:{...n,refreshes:n.refreshes.filter(e=>!r.has(e))},causes:[...r.values()]}]}),p=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition),...f.flatMap(({causes:e})=>e.map(e=>e.definition))]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(f.map(({name:e,action:t})=>[e,t])),...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${cV(dV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function mV(e,t,n){let r=`⚠ ${e}: ${t.join(`; `)}`,i=new Map;for(let e of n)for(let[t,n]of Object.entries(e.settings??{})){let e=i.get(t);i.set(t,e===void 0?[n]:[...e,n])}let a=Object.fromEntries([...i].map(([e,t])=>[e,hV(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function hV(e,t){let[n]=t,r=t.filter(e=>typeof e==`number`);return typeof n==`boolean`?{label:e,domain:`bool`,default:n}:typeof n==`number`?{label:e,domain:{min:Math.min(...r),max:Math.max(...r),step:1},default:n}:{label:e,domain:[...new Set(t.map(String))],default:n}}function gV(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Z_(e,a)};if(!sv(r))return a.push({path:``,message:`a plugin definition must be an object, got ${cv(r)}`}),o();for(let e of Object.keys(r))XB.has(e)||a.push({path:e,message:e===`plugin`?`a plugin definition does not name itself: its name is its folder's ("${t}") — remove "plugin"`:`a plugin definition may not declare "${e}". Expected only: ${[...XB].join(`, `)}`});let c=r.data===void 0?void 0:kV(r.data,e,i,a),l=r.sources===void 0?{}:TV(r.sources,e,a);if(a.length>0)return o();let u={source:n,issues:a,allowedPalettes:new Set(Rg()),groups:[]},d=c===void 0?{}:vL(u,`data`,{[tV(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=vL(u,`variables`,r.variables);for(let[e,n]of[[`variables`,Object.keys(f)],[`sources`,Object.keys(l)]])n.includes(`data`)&&a.push({path:`${e}.data`,message:`"data" names the plugin's data file (.${tV(t)}), declared by the definition's own "data" key: give this ${e===`sources`?`source`:`variable`} another name`});for(let e of Object.keys(l))Object.hasOwn(f,e)&&a.push({path:`sources.${e}`,message:`source "${e}" and variable "${e}" are one name (.${eV}${t}.${e}): give one of them another name`});let m={variables:{...d,...vV(t,l),...vV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,bV(t,n)])))},segments:vV(t,xV(t,uR(u,r.segments,new Set))),helpers:vV(t,$z(u,r.helpers)),actions:vV(t,SV(t,tz(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of _V(m))try{xj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*_V(e){for(let[t,n]of Object.entries(e.variables??{}))for(let[e,r]of P_(n))yield[`variables.${t}.${e}`,r];for(let[t,n]of Object.entries(e.segments??{})){for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[e,r]of Object.entries(n.vars??{}))for(let[n,i]of P_(r))yield[`segments.${t}.vars.${e}.${n}`,i]}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))for(let[e,r]of px(n))yield[`actions.${t}.${e}`,r]}function vV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${eV}${e}.${t}`,n]))}function yV(e,t){return`${eV}${e}.${t}`}function bV(e,t){return t.kind===`state`?{...t,key:yV(e,t.key)}:t}function xV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,bV(e,n)]))}]))}function SV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:yV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>yV(e,t))}:n]))}const CV=QB,wV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function TV(e,t,n){if(!sv(e))return n.push({path:`sources`,message:`"sources" must be an object of named sources, got ${cv(e)}`}),{};let r=s.join(p.realpathSync(s.dirname(t)),`session`),i=JSON.stringify(wV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!CV.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${CV}: it is the last segment of .${eV}<plugin>.${t})`});continue}let s=OV(o,wV,e);for(let{field:e,is:t}of s)n.push({path:e,message:`${e} ${t}: what is built is a source ${i} — a session's JSON file in the plugin's managed storage, re-read when it changes`});s.length===0&&(a[t]={kind:`source`,storage:r})}return a}function EV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=DV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=sV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${eV}${t}.`.length)}`,message:`sources ${n.map(e=>`.${e}`).join(` and `)} read the same file, ${e}: a session's file is one document, read by one source`}));if(a.length>0)throw new Z_(e,a)}function DV(e){return s.join(e.storage,nV(`<session id>`))}function OV(e,t,n){return!sv(t)||!sv(e)?JSON.stringify(e)===JSON.stringify(t)?[]:[{field:n,is:`is ${JSON.stringify(e)}`}]:[...new Set([...Object.keys(t),...Object.keys(e)])].flatMap(r=>{let i=`${n}.${r}`;return Object.hasOwn(t,r)?Object.hasOwn(e,r)?OV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function kV(e,t,n,r){if(typeof e==`string`&&e!==``)return qB(s.dirname(t),e);if(sv(e)&&Object.keys(e).length===1&&typeof e.checkout==`string`&&e.checkout!==``){let t=e.checkout;if(s.isAbsolute(t)||t.startsWith(`~`)||s.normalize(t).split(s.sep)[0]===`..`){r.push({path:`data.checkout`,message:`data.checkout "${t}" must be a path inside the checkout, relative to its root (like ".lit/statusline.json"): no absolute path, "~" or ".."`});return}if(n===null){r.push({path:`data.checkout`,message:`data is read from the session's checkout, and this load has no session`});return}return s.resolve(n.root,t)}if(sv(e)&&`project`in e){r.push({path:`data.project`,message:`data: { project } is now data: { checkout }: the same path, relative to the root of the git checkout the session works in (a linked worktree is its own checkout)`});return}r.push({path:`data`,message:`"data" must be the path of the plugin's JSON data file relative to this definition, or { checkout: "<path>" } relative to the root of the session's checkout`})}function AV(e){let t=[...[...(process.env.XDG_DATA_DIRS||NV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),jV(),...e===null?[]:[s.join(e,MV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function jV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const MV=s.join(`.cc-candybar`,`plugins`);function NV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function PV(e){let t=AV(e),n=new Map,r=[],i=[];for(let e of t){let t=FV(e);if(`error`in t){r.push(t);continue}for(let r of t.folders)n.delete(r),n.set(r,s.join(e,r,ZB));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${ZB}: move this file to ${s.join(e,`<name>`,ZB)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function FV(e){try{let t=p.readdirSync(e,{withFileTypes:!0}).filter(e=>!e.name.startsWith(`.`)).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)),n=t=>t.isDirectory()||IV(e,t);return{folders:t.filter(n).map(e=>e.name),files:t.filter(e=>!n(e)).map(e=>e.name)}}catch(t){return t.code===`ENOENT`?{folders:[],files:[]}:{path:e,error:t.message}}}function IV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function LV(e){return p.existsSync(s.join(e,`.git`))}function RV(e){let t=s.resolve(e);for(;;){if(LV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function zV(e){let t=RV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function BV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const VV=[`json5`,`json`];function HV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?VV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...VV.map(e=>s.join(r,`.cc-candybar.${e}`)),...VV.map(e=>`${UV()}.${e}`)])]}function UV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function WV(e,t,n){let r=[],i=new Map;for(let a of HV(e,t,n)){let e=BV(a);if(e===`absent`)continue;if(e!==`present`){r.push(e);continue}let t=s.join(p.realpathSync(s.dirname(a)),s.basename(a).replace(/\.(json5|json)$/,``));i.has(t)||i.set(t,a)}let a=[...i.values()].reverse();if(n===void 0)return{kind:`chain`,layers:a,home:GV(a),unchecked:r};let[o]=r,c=n;return a.length>0?{kind:`chain`,layers:a,home:c,unchecked:r}:o===void 0?{kind:`missing`,path:n,home:c}:{kind:`unreadable`,...o,home:c}}function GV(e){let t=UV();return e.find(e=>VV.some(n=>e===`${t}.${n}`))??`${t}.${VV[0]}`}function KV(e,t,n){let r=WV(e,t,n),i=r.kind===`chain`?r.layers:[];return{path:r.home,above:i.filter(e=>e!==r.home),projectDir:e??null,cwd:t??null}}function qV(e){return JV(e).join(`
|
|
181
|
+
`)||null}function JV(e){switch(e.kind){case`chain`:return e.unchecked.map(e=>`Config location could not be checked: ${e.path} — ${e.error}`);case`missing`:return[`Config file not found: ${e.path} — rendering the bundled default until it appears`];case`unreadable`:return[`Config file could not be read: ${e.path} — ${e.error} — rendering the bundled default until it can be`]}}function YV(e,t){let n=HV(e,t).filter(e=>BV(e)===`present`),r=new Map;for(let e of n){let t=s.dirname(e),n=s.basename(e).replace(/\.(json5|json)$/,``),i=s.join(t,n);r.has(i)||r.set(i,[]),r.get(i).push(e)}let i=[...r.values()].filter(e=>e.length>1);return i.length===0?null:`config-extension collision: ${i.map(e=>{let[t,...n]=e;return`${t} shadows ${n.join(`, `)}`}).join(`; `)} — remove the duplicate`}function XV(e,t,n,r){return e===null?{...oH,config:$I(oH.raw,t)}:QV(e,p.readFileSync(e,`utf-8`),t,n,r)}const ZV={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function QV(e,t,n,r,i){let a=lH(e,t,i,(t,a)=>{let o=oV(aV(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>iH(t,n,r,e,i)),s=fV(o,r.beneath.dropped);return{inherited:new Set([...lR(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=pV($I(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(YB)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const $V=new WeakMap;function eH(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,nH(e)])]),a=$V.get(n)??new Map;$V.set(n,a);let o=JSON.stringify([t.projectDir,t.checkout?.root??null]),s=a.get(o);if(s?.key===i)return s.layer;let c=oV(e,t,{config:n,rendering:new Map},(e,t,n)=>iH(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function tH(e,t,n){return oV(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>iH(e,t,n,`<plugin install>`,void 0)).dropped}function nH(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function rH(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:zV(r.cwd)},s=PV(o.projectDir),c=eH(s.definitions,o,t,a),l={...c,dropped:[...c.dropped,...s.strays]};n.warned(s.unchecked.map(e=>`Plugin folder could not be listed: ${e.path} — ${e.error}`));let u=l.config,d=[];for(let t of e){n.entered(t);let e=d.at(-1)?.plugins,r=QV(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(YB));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:sH(XV(null,u,ZV),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:sH(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),sH(e,e.path,a);throw n.entered(v.path),e}}function iH(e,t,n,r,i){if(n){sH(aH(e),r,i);return}let a=sV(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(HB(s,e,Hx(e),a),UB(s,e,a),GB(s,e,{checked:a,authored:a}),o.length>0)throw new Z_(r,o)}function aH(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const oH={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function sH({config:e,raw:t,source:n},r=`<config>`,i=new Set(Rg())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(gB(o,e,t),UB(o,e),a.length>0)throw new Z_(r,a);let s=ez(e,a);if(a.length>0)throw new Z_(r,a);let c=jI(ZF(s)),l=new Set([...Rx({variables:t.variables??{},segments:t.segments??{}})].map(([e])=>e));if(GB(o,c,{checked:()=>!0,authored:e=>l.has(e)}),a.length>0)throw new Z_(r,a);return c}function cH(e,t,n=new Set(Rg()),r=uH){return lH(e,t,n,()=>({inherited:r,layer:null})).raw}function lH(e,t,n,r){let i=dH(e,t),a=ev(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Rg()),groups:[]};if(!sv(i))throw new Z_(e,[{path:``,message:`Config root must be an object, got ${cv(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:mH({...c,issues:[]},i.plugins)??[],sv(i.segments)?Object.keys(i.segments):[]),d=fH(c,i,l,rz(e));if(s.length>0)throw new Z_(e,s,o);return{raw:d,warnings:o,layer:u}}const uH=new Set;function dH(e,t){try{return Ii.default.parse(t)}catch(t){let n=t;throw new Z_(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function fH(e,t,n,r){for(let n of Object.keys(t))pH.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...pH].join(`, `)}`,line:G(e.source,[n])});let i={};return t.globals!==void 0&&(i.globals=QA(e,`globals`,t.globals)),t.variables!==void 0&&(i.variables=vL(e,`variables`,t.variables)),t.segments!==void 0&&(i.segments=uR(e,t.segments,n)),t.layout!==void 0&&e.issues.push({path:`layout`,message:`"layout" is no longer supported — use "root" with the A-grammar instead.
|
|
182
182
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
183
183
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
184
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(i.root=DR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=YR(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(i.styles=Wz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=GA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=Kz(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=YA(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=qz(e,t.helpers)),t.plugins!==void 0&&(i.plugins=cH(e,t.plugins)),FR(e,i),KR(e,i),kj(e,i),mA(e,i,X,`the global settings menu`),i}const sH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function cH(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${cv(t)}`,line:G(e.source,[`plugins`])})}const lH={},uH=aP(`commands.`),dH=dP(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),fH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,pH=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${fH}) (basename .project_dir) (ne (${fH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,mH=`{{ ${iM} }}`,hH={min:0,max:100,step:5},gH={warnAt:{label:`warning at %`,domain:hH,default:50},errorAt:{label:`error at %`,domain:{...hH,atLeast:`warnAt`},default:80}};function _H(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:hH,default:80}}}const vH={globals:{palette:`tokyo-night`},variables:{...uH.variables,...Qk,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:pH},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:mH,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:JN(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:uH.template,when:uH.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:_H(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:_H(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:gH,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:gH,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${Yh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:dH.template,bg:dH.bg,when:dH.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...JN(``).actions,...uH.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...dH.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:lH,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Yh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${iM}) 2 (readableOn (color "accent") (bgOf) ${Yh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Yh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:fP(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},yH=new Set([vH.globals.palette,...Object.keys(vH.themeDefaults),...Object.values(vH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),bH=qI(nH(`<default>`,JSON.stringify(vH),yH),vH),xH=Qb(bH.presets);function SH(e){return xH.includes(e)}const CH=Object.freeze({});function wH(e,t){return e.kind===`decided`?t[e.name]??CH:CH}function TH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const EH=e=>Bv(t=>e[Pv[t].setting]);function DH(e,t,n,r){let i=_y(e);return Lg(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function OH(e,t){return $b(t(`preset`),e.globals.preset,e.presets)}function kH(e,t,n){let r=OH(e,t),i=nx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Lb(a.palette,t(`theme`),i.palette),s=TH(i,wH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,DH(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yg(a.style,t(`style`),s.style,e.styles),effect:a_(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function AH(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?m_:h_;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const jH=Object.entries(Sy),MH=new Set(wy.map(e=>e.sessionKey)),NH=()=>!1;function PH(e,t){return kH(e,e=>MH.has(e)?t(e):null,NH)}const FH=[`preset`,`theme`];function IH(e,t,n){let r=new Set(FH.slice(0,n).map(e=>Sy[e].sessionKey));return kH(e,e=>r.has(e)?t(e):null,NH)}function LH(e,t){let n=Array.from({length:FH.length+1},(n,r)=>IH(e,t,r));return e=>{let t=FH.indexOf(e);return n[t===-1?FH.length:t]}}function RH(e,t,n,r){return e.flatMap(([e,i])=>{let a=AH(t,e);return a===null||a===AH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function zH(e,t,n){return AH(PH(e,t),n)}function BH(e,t){let n=PH(e,t);return RH(jH,n,LH(e,t),t=>VH(e,n.preset,t.configKey))}function VH(e,t,n){return n in(ex(e.presets,t).globals??{})?lj(t,n):n}function HH(e,t,n){let r=$b(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=uj(n);return{key:i?.scope===`globals`?VH(e,r,i.field):n,globals:nx(e,r)}}function UH(e,t){let{preset:n}=PH(e,t);return KH(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:K_(a,s);return c===void 0||G_(c)===G_(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function WH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Qb(e.presets).flatMap(n=>{let i=KH(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return U_(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:K_(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const GH=new WeakMap;function KH(e,t){let n=GH.get(e)??new Map;GH.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(tx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=V_(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function qH(e,t){let n=PH(e,t);return{from:n.preset,globals:ex(e.presets,n.preset).globals??{},picks:RH(jH.filter(([e])=>e!==`preset`),n,LH(e,t),e=>e.configKey),placements:UH(e,t)}}function JH(e,t){return kH({...e,globals:{palette:t},presets:{}},()=>null,NH)}function YH(e,t){let n=PH(e,t),r=AH(n,`theme`);if(r===null)return{kind:`rule`};let i=JH(e,r),a=nx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,AH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==AH(i,e))}}function XH(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...VA(e)?xH.map(t=>lj(t,e)):[],...cj(e)?Rg().map(t=>sj(t,e)):[]]}}function ZH(e){return new Set(wy.map(e=>e.configKey).filter(t=>XH(t).fileKeys.some(t=>eU(e,$H(t)))))}function QH(e,t,n){let r=BH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=YH(e,n);return{unsaved:r.length+UH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function $H(e){let t=uj(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return dj(t)}function eU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&eU(e[n],r)}const tU=Rg(),nU=new Set(tU),rU=new Set(o_),iU=e=>e?nU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${tU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},aU=e=>e?rU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},oU=new Set([`1`,`true`]),sU=new Set([`0`,`false`]),cU={endcaps:aU,theme:iU,"toolbar-expanded":e=>oU.has(e)?{ok:!0,value:`1`}:sU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},lU=RI(cU,`state`,gU);function uU(e,t){return lU.register(e,t)}function dU(e){return lU.gateFor(e)}function fU(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function pU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(cU,e.key))}function mU(e,t,n){let r=Ay.get(n);if(r!==void 0)return zH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function hU(e){let t=sI(e);return pU(Object.values(e.actions).flatMap(e=>fU(e,t)))}function gU(e){return II(hU(e))}const _U=`update.dismissed`,vU=`updateNotice`,yU=Sy.updateNotice.sessionKey;function bU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const xU=e=>`${e.version} [${Xe(e.digest)}]`;function SU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:xU(e.newer),running:xU(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:uo(e.newer),running:uo(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${po}@${uo(e.newer)}`,`install`]}}}}const CU={kind:`idle`},wU={kind:`running`};function TU(e,t,n){if(e===null)return[];let r=bU(e);if(!n.enabled||n.dismissed===r)return[];let i=SU(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
185
|
-
`),c=pi([{verb:Wr,args:[s]}]),l=t.kind===`running`?yb(`[${i.busy}]`,c):yb(`[${i.act}]`,pi([{verb:ii,args:[n.sessionId]}]));return[{severity:_b,message:s,lines:[[yb(a,c),l,yb(`[dismiss]`,pi([{verb:Rr,args:[n.sessionId,
|
|
186
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:
|
|
187
|
-
`,1)[0]??``}function
|
|
188
|
-
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function
|
|
189
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function
|
|
190
|
-
`).length:0)}async getRemotesAsync(e){let t=BW(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return EW(await this.execGitAsync(TW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=AW(e);return(n===null?null:MW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=jW(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return pt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=wW(t);return n===`github`?FW(`gh pr view`,await this.execForgeAsync(yW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,RW):n===`gitlab`?FW(`glab mr view`,await this.execForgeAsync(yW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,zW):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=mW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(LW(t.value)):t}};const HW=(e,t)=>E(t);function UW(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const WW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var GW=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??HW}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:[...t.files,...t.dirs.map(e=>e.path)].map(e=>({path:e,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=UW(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.files)try{let i=p.watch(r,{persistent:!1},(e,n)=>t(WW(n)));i.on(`error`,n(r)),e.watchers.push(i)}catch(e){i(r,e)}for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(WW(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function KW(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var qW=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function JW(){return J.observable.box(YW(`unread`),{deep:!1})}function YW(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function XW(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function ZW(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(YW(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function QW(e,t){e.reading.get().kind===`pending`&&XW(e,t)}function $W(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function eG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function tG(e){for(;;){let t=e();if(!$W(t))return t;await t.landed}}function nG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function rG(e){return{current:()=>e}}function iG(e){return tG(()=>e.current())}const aG=`pass`,oG={okMs:5*6e4,failedMs:45e3};function sG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function cG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function lG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}function uG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function dG(e){e.missed=!0,ZW(e,`unread`)}function fG(e,t){return e.missed&&e.reading.get().kind===`pending`&&XW(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function pG(e,t){let n=eG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:eG(t)})}function mG(e){return t=>I(`${e} threw: ${String(t)}`)}var hG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;refreshCount=0;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new VW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new GW({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,refreshes:this.refreshCount,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return rG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>pG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new kk,watcher:this.watchers.acquire(`git:${e}`,lG(n),()=>this.changed(e)),period:new qW(()=>{r.refresh.share(aG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(aG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&dG(n),n.missed&&e.asked.add(`pr`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(aG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:JW(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=cG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(sG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=e.asked.size===0?`period`:[...e.asked].join(`,`);e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(mG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;this.refreshCount++;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,XW(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of pW(n.value))s.add(e)});for(let t of s)this.logger(`warn`,`git refresh failed (${e.root}): ${t}`);let c=uG(a),l=i===null||r.length===0?`-`:c===void 0?fG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.logger(`info`,`git refresh ${e.root} by=${n} values=${r.length} failed=${s.size} pr=${l} took=${Date.now()-t}ms`)}prSource(e){let t={period:new qW(()=>{this.readPr(e,t)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:JW(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(mG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(dG(t),`owed`):(ZW(t,`unread`),t.missed=!1,this.readPr(e,t),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,XW(t,a.outcome),t.period.landed(KW(oG,a.outcome),a.at),`recalled`)}readPr(e,t){let n=t.key;if(t.inFlight?.key===n)return t.inFlight.done;let r=t.remote,i=(r.kind===`ok`?this.inner.resolvePullRequest(e.root,r.value).catch(mG(`PR lookup`)):Promise.resolve(r.kind===`failed`?r:F)).then(r=>{if(t.inFlight?.key===n&&(t.inFlight=null),this.repos.get(e.root)!==e)return;r.kind===`failed`&&this.logger(`warn`,`git refresh failed (${e.root}): git.pr: ${r.reason}`);let i=Date.now();t.seen.delete(n),t.seen.set(n,{outcome:r,at:i});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==n||t.missed||(XW(t,r),t.period.landed(KW(oG,r),i))});return t.inFlight={key:n,done:i},i}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())QW(n,t);e.pr!==null&&QW(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},gG=class{static CACHE_DIR=bt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const _G={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var vG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await gG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await gG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(_G).length} models`),this.executionCache=_G,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(_G).length} models`),_G)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const yG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function bG(e){if(typeof e==`string`)return yG.exec(e)?.[1]}function xG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function SG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function CG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=xG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?bG(SG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function wG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function TG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await EG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function EG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function DG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Fa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Va(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=FG(i,t,s.value);let c=MG(Ha(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function OG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(AG(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=SG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||kG.test(r)?`claude-code`:`prompt`}const kG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function AG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function jG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=OG(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:CG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function MG(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function NG(e){let t=MG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return jG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function PG(e){let t=[];for(let n of e.split(`
|
|
191
|
-
`)){let e=NG(n);e&&t.push(e)}return t}function FG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function IG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function LG(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Va(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=FG(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,Ha(c,e=>PG(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var RG=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}},zG=class{counts;failures=0;constructor(e,t,n){this.name=e,this.logger=n,this.counts=Object.fromEntries(t.map(e=>[e,0]))}recorded(e,t,n,r){this.counts[t]++,n.kind===`failed`&&this.failures++;let i=n.kind===`failed`?` reason=${JSON.stringify(n.reason)}`:``;this.logger(n.kind===`failed`?`warn`:`info`,`${this.name} refresh ${e} by=${t} outcome=${n.kind}${i} took=${r}ms`)}stats(e){return{entries:e,refreshes:{...this.counts},failures:this.failures}}},BG=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=new zG(e.name,[`first`,`period`,`change`,`supersede`],e.logger)}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>eG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,ZW(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;return{...this.refreshes.stats(this.entries.size),held:e}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:JW(),holders:0,flight:null,changed:!1,superseding:0,revisit:VG(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();UG(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{XW(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),QW(e,I(`${this.spec.name} entry dropped`))}};function VG(e,t){if(e===null)return new HG(t.holdReturned);let n=new qW(t.period);return{landed:t=>n.landed(KW(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var HG=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function UG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function WG(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const GG={okMs:60*1e3,failedMs:10*1e3},KG={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},qG={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function JG(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function YG(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function XG(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const ZG={entries:0,cost:0,breakdown:XG(),days:new Map};async function QG(e,t){let n=JG(new Date(YG())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await vG.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=JG(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...KG};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function $G(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function eK(e){let t=0,n=0,r=XG(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...KG};$G(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:qG,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function tK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function nK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!tK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...KG};$G(r,t),n.set(e,r)}return n}async function rK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function iK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function aK(e,t){(0,J.runInAction)(()=>e.set(t))}var oK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new RG;scans;daySets=new Map;speedFlight=new RG;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Me,this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new BG({name:`today`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??GG,maxEntries:8,logger:this.log});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}async getUsageInfo(e,t){let n=await this.refreshed(e,t?.transcript_path);return n.kind===`failed`?n:P(iK(n.kind===`ok`?n.value.sessionInfo:qG,t))}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Oa;let r=n.failure.get();return r===null?P(iK(n.record?.sessionInfo??qG,t)):I(r)}async refreshed(e,t,n){let r=await this.ingest(e,t,this.renderTally,n);return aK(this.hold(e).failure,r.kind===`failed`?r.reason:null),r}async refreshToday(e,t){await iG(e),await this.refreshed(t?.session_id??``,t?.transcript_path)}declareToday(e,t){let n=wG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=JG(ak(n)),o={...KG},s=e.sums.get(a);s!==void 0&&$G(o,s);let c=tK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&$G(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}async observeSpeed(e,t,n){if(!e)return F;let r=ja(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.refreshed(e,t,r);if(i.kind===`failed`)return aK(this.hold(e).speed,i),i;let a=WG(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift();let c=P({...s!==void 0&&{prev:s},cur:a,samples:[...o]});return aK(this.hold(e).speed,c),c})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Oa:F}async ingest(e,t,n,r){if(!e)return F;let i=r??ja(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,P(a);if(!t)return a?P(a):F;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&this.stored(e,l),P(l)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new rS(`today over ${e.join(`,`)}`,()=>nK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await DG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of IG(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await LG(e,r,ZG,QG);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of IG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...eK(i),mainStamp:a})}async scan(e){try{let t=YG(),n=await TG(e),r=[];for(let e of n){let n=await EG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await EG(Ia(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ma(a)})}}let i=[],a={hits:0,misses:0};return await rK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${as(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=JG(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},sK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},cK=class{sessions;constructor(e,t,n=Me,r=256){this.empty=e,this.step=t,this.log=n,this.sessions=new sK(r)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ja(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=await LG(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(a.kind===`failed`)return this.store(e,r,a);if(a.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:o,longLines:s}=a.value;for(let e of IG(s))this.log(`info`,e);return this.store(e,o,{kind:`ok`,value:o.value})}answer(e){return this.sessions.get(e)?.answer??Oa}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function lK(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var uK=class{fold;constructor(e={}){this.fold=new cK(void 0,lK,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,dK(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,dK(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function dK(e){return e.context_window?.context_window_size??2e5}const fK={messageCount:0,nonPrompts:0,recent:[]},pK=new Set([`turn`,`interrupt`,`claude-code`]);function mK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!pK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function hK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var gK=class{fold;constructor(e={}){this.fold=new cK(fK,mK,e.logger)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?_K(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:_K(e,n,r)}};function _K(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:hK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const vK={command:null,todos:[],pending:[],done:[]};function yK(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function bK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function xK(e,t){if(t.isSidechain)return e;let n=bK(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=yK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function SK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>yK(e,t.name),[]),done:e.done}}var CK=class{fold;constructor(e={}){this.fold=new cK(vK,xK,e.logger)}async getActivityInfo(e,t){return wK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:wK(e,t)}};function wK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(SK(t.value))}function TK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function EK(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function DK(e,t,n,r){return EK(D(TK(e,t,n,r)),n)}async function OK(e,t,n,r){return EK(await pt(TK(e,t,n,r)),n)}const kK=3e4;var AK=class{names;constructor(e={}){this.names=new BG({name:`tmux`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:jK,every:{okMs:kK,failedMs:kK},maxEntries:64,logger:e.logger??Me})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function jK(e){let t=await OK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}var MK=class{known=new sK(64);refreshes;constructor(e=Me){this.refreshes=new zG(`autocompact`,[`request`],e)}window(e){let t=NK(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=lP(e);return this.refreshes.recorded(`path=${as(e)} stamp=${as(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oa}getStats(){return this.refreshes.stats(this.known.size)}};function NK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const PK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function FK(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var IK=class{known=new sK(256);refreshes;constructor(e=Me){this.refreshes=new zG(`cache`,[`request`],e)}async refresh(e,t){let n=ja(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oa}getStats(){return this.refreshes.stats(this.known.size)}async read(e,t,n){let r=Date.now(),i=await LK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function LK(e){let t=await RK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function RK(e){for(let t of[65536,1048576]){let n=await Ga(e,t);if(n.kind!==`ok`)return n;let r=zK(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function zK(e,t){let n=e.toString(`utf8`).split(`
|
|
192
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!PK.test(t))continue;let r=FK(t);if(r!=null)return r}return null}var BK=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const VK=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},HK=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,UK=e=>XB(e),WK=e=>s.join(e.storage.folder,UK(e.sessionId)),GK=e=>JSON.stringify([e.folder,e.generation]),KK=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var qK=class{sessions;folders=new Map;watched=new Map;faults=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??VK,this.sessions=new BG({name:`plugin storage`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(WK(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!HK(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${as(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(GK(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${GK(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(GK(e),i);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return n!==null&&this.faulted(i,`unusable`,n),this.sweep(e),i}closed(e){let t=GK(e.key);this.watched.delete(t),this.faults.delete(t),clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>KK(e.storage,n);switch(t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(UK(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{key:n,folder:r}=e,i;try{i=this.identityOf(n.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&HK(i,a)){t();return}n.generation===r.generation&&(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${as(n.folder)} generation=${n.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>KK(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(GK(r),`cannot refresh: ${r.folder} ${n}; reload the config or restart the daemon`),this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${as(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>KK(e.storage,r))}async read(e){let t=this.faults.get(GK(e.storage));if(t!==void 0)return I(t);let n=WK(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Ok(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${as(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&UK(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function JK(e){return{gitProvider:new hG({watchers:e.watchers,logger:e.logger}),usageStore:new oK({logger:e.logger}),contextProvider:new uK({logger:e.logger}),metricsProvider:new gK({logger:e.logger}),activityProvider:new CK({logger:e.logger}),tmuxService:new AK({logger:e.logger}),autoCompact:new MK(e.logger),cacheExpiry:new IK(e.logger),managedStorage:new qK({watchers:e.watchers,logger:e.logger}),faults:new BK,log:e.logger}}function YK(e){return Math.max(1,e-2)}function XK(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[qa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function ZK(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function QK(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:SH(e.preset)}}}const $K={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function eq(e,t){if(!t)return`-`;if(ka(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ka(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const tq=10*1e3;function nq(e,t){if(!(t<60))return e*3600/t}function rq(e,t,n,r){let i=r-t;if(i<50||i>tq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function iq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=rq(t.input,t.atMs,n.input,n.atMs),i=rq(t.output,t.atMs,n.output,n.atMs),a=rq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function aq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>tq)continue;let o=rq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function oq(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function sq(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>oq(C.hostname())),i=n(`user`,()=>C.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function cq(e,t){let n=nx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(tx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...lq(e,n.name));return dq(e,r)}function lq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function uq(e,t,n){return dq(e,[...lq(e,t),...n])}function dq(e,t){let n=Qz(e),r=new Map(zx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=Yz(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function fq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=cq(e,n);return t.set(n,i),i}}function pq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function mq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys($K).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const hq=new WeakMap;function gq(e){let t=hq.get(e);return t===void 0&&(t=_q(e),hq.set(e,t)),t}function _q(e){let t=t=>pq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function vq(e){return YK(e.termCols??120)}function yq(e){return Xa(Ya(e.claudeConfigDir))}async function bq(e,t){let{hookData:n,deps:r,hints:i}=e,a=gq(e.neededInputPaths),o=n.session_id,s=async(e,t,n)=>{if(!t)return;let i=null;try{await n()}catch(t){r.log(`error`,`${e} lane threw: ${T(t)}`),i=`${e}: ${String(t)}`}r.faults.refreshed(o,e,i)};await Promise.all([s(`session`,a.session,()=>r.usageStore.getUsageInfo(o,n)),s(`today`,a.today,()=>r.usageStore.refreshToday(r.lanes().today,n)),s(`context`,a.context,()=>r.contextProvider.getContextInfo(n)),s(`metrics`,a.metrics,()=>r.metricsProvider.getMetricsInfo(o,n)),s(`activity`,a.activity,()=>r.activityProvider.getActivityInfo(o,n)),s(`cache`,a.cache,()=>r.cacheExpiry.refresh(o,n.transcript_path)),s(`speed`,a.speed,()=>r.usageStore.observeSpeed(o,n.transcript_path,ak(t).getTime())),s(`autocompact`,a.autocompact,async()=>r.autoCompact.window(yq(i)))])}function xq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Sq(e,t){let n=rG(e);return{git:n,tmux:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Cq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,mq(n),t.workspace?.project_dir]}function wq(e,t,n,r,i){let a=gq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return rG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),rG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Cq(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(xq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Tq(e){let{hookData:t,deps:n}=e,r=gq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(yq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Eq(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function Dq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=gq(e.neededInputPaths),u=[],d=(e,t)=>{switch(e.kind){case`pending`:return Oa;case`failed`:u.push(e.reason);return;case`absent`:return;case`ok`:return t(e.value)}},f=e=>e.kind===`ok`?e.value:void 0,p=i.tmux??null,m=n.git.kind===`pending`?Oa:Bq(n.git,()=>Oa),h=sq(i);u.push(...h.failures);let g=n.tmuxSession.kind===`pending`?Oa:f(n.tmuxSession),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?Oa:Fq(n.autoCompact,f(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?Oa:Aq(f(n.usage)?.session.cost,f(n.metrics)?.sessionDuration):void 0,ee=d(n.speed,jq),x=d(n.usage,e=>Rq({cost:e.session.cost,tokens:e.session.tokens})),S=d(n.metrics,e=>Rq({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=d(n.activity,Iq),ne=d(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=d(n.cache,e=>({expiresAt:e})),ie=zq(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:zq(r.workspace.current_dir)??``,project_dir:zq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>zq(e)??e)}:r.workspace,C=r.session_id;return{payload:{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...m!==void 0&&{git:m},...p!==null&&{tmux:{pane:p.pane,...g!==void 0&&{session:g}}},host:h.host,...QK(a),history:t.history,navigation:{back:t.back},term:{cols:vq(i)},...c,...s!==null&&{configPath:s},resumeCommand:XK(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:kq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})},failures:u}}function Oq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function kq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Aq(e,t){let n=e!=null&&t!=null?nq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function jq(e){let t=iq(e),n=aq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Mq(e,t){return Dq(e,t,Tq(e))}function Nq({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return Oa;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?Oa:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function Pq(e,t){await bq(e,t),await tG(()=>{let t=Eq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Fq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return uP(e.value,t)}}function Iq(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=Lq(e.running),i=Lq(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function Lq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Rq(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function zq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Bq(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(sW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:cW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function Vq(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const Hq={kind:`hidden`},Uq={kind:`shown`};function Wq(e,t){try{return Vq(e,t)?Uq:Hq}catch(e){let t=eS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function Gq(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function Kq(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function qq({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function Jq({text:e,placement:t,lead:n,trail:r}){return{text:Yq(e),placement:t,...n!==void 0&&{lead:Yq(n)},...r!==void 0&&{trail:Yq(r)}}}function Yq(e){let t=e.blankCopy(e.plain);t.style=Hy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Hy(i).clearMetaAndLinks(),n,r);return t}function Xq(e){let t=qq(e);if(t.length===1)return e.text;let n=Gq(t);return n.style=e.text.style,n}function Zq(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=Gq(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:Gq([d,...c],a)},...l.length>0&&{trail:Gq([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(Kq(u,n,p),[{text:u,...f}])}const Qq=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function $q(e){return Math.max(0,...e.split(`
|
|
193
|
-
`).map(e=>Us(e.replace(
|
|
194
|
-
`);if(i.length>1)return n();let a=Math.max(0,t.width-$q(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];Kq(c,c.cellLength+a,n)}),n()}function tJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=nJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Hy(a.style)};if(e.style.link){i();let r=nJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function nJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>rJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function rJ(e,t){let n=e.copy();return n.style=t,n}function iJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function aJ(e,t){let{look:n}=iJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function oJ(e,t){let{layout:n}=iJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function sJ(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function cJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,lJ(e,t,o,n,r,i));return i}function lJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Dy.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=cx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:fJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:fJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:fx(n),argv:n.run.map(n=>fJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,fJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:fJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function uJ(e){return e.kind===`do`?uJ(e.head):e}function dJ(e){switch(uJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function fJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function pJ(e,t){return e.has(t)?Xx(e.read(t)):``}function mJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function hJ(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function gJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Hy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Hy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function _J(e,t){return Math.max(e.members.indexOf(pJ(t,e.stateVar)),0)}function vJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=pJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=pJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=pJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(_J(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[mJ(e.text,bk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[mJ(e.target,bk(r))]}],active:!1};case`persist-literal`:{let t=pJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=pJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(_J(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,mJ(e.name,bk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=bk(r),n=JSON.stringify({run:e.argv.map(e=>mJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,mJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,EI(e.op)]}],active:!1};case`do`:{let o=vJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>vJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,EI(r)]}],active:!1}}}}function yJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,_J(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function bJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=iJ(n,`action "${e}"`).store,{display:a,boundValue:o}=yJ(e,uJ(r),t,i),s=pJ(i,`session.id`),{effects:c,active:l}=vJ(r,a.plain,o,i,s,n.signer);return gJ(a,pi(c),l)}function xJ(e){return{action:{fn:(t,...n)=>bJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function SJ(e,t){return hJ(`✕`,pi([{verb:Rr,args:[pJ(e,`session.id`),t,yi]}]),!1)}function CJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function wJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function TJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function EJ(e,t,n){return V.combine([CJ(e,t,n),TJ(e,t,n)])}function DJ(e,t,n){return CJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function OJ(e){let t=z.fromRgba(Bh(e,`background`)),n=W.fromFragments(mh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Bh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const kJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},AJ=e=>new V({bold:e});function jJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>kJ(a,V.combine([DJ(e,{...n,distribution:t},i),AJ(o)]));let o=CJ(e.palette,a,i);return(e,t,i,a)=>MJ(i,V.combine([o,AJ(a)]),r(t,n))}const MJ=(e,t,n)=>kJ(W.fromFragments([kJ(e,t),kJ(` `,t),OJ(n)]));function NJ(e,t){return t===void 0?(e,t,n)=>kJ(n):(n,r,i)=>MJ(i,void 0,t(r,e))}function PJ(e,t,n,r,i){let a=CJ(e.palette,i,r);return(e,r,i,o)=>kJ(W.fromFragments([kJ(o?`[`:` `,a),OJ(n(r,t)),kJ(o?`]`:` `,a)]))}function FJ(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>IJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function IJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function LJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function RJ(e){return{current:null,drawnAt:e}}function zJ(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function BJ(e,t,n){return HJ(e,()=>n(zJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function VJ(e,t){return HJ(e,()=>(e.current=null,t()))}function HJ(e,t){let n=e.current;try{return t()}finally{e.current=n}}function UJ(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function WJ(e){return new W(e).cellLength}function GJ(e){let{width:t,chromeCols:n,padding:r}=iJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function KJ(e){let{padding:t,seamCols:n}=iJ(e,`a row fit`);return Math.max(1,GJ(e)-(WJ(`✕`)+2*t+n))}function qJ(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function JJ(e,t,n){let r=WJ(`←`)+1+WJ(`→`)+1,i=qJ(e,t,n);return(i.length>1?qJ(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function YJ(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function XJ(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function ZJ(e,t,n){let r=e.compiled.get(t),i=r&&uJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function QJ(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=iJ(a,`picker`).store,d=pJ(u,`session.id`),f=`stateVar`in t?pJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?KJ(a):GJ(a):1/0,h=(r.kind===`led`?0:WJ(`✕`)+1)+c.reduce((e,t)=>e+WJ(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?JJ(_.map(e=>e.cellLength),m,h):FJ(g.entries,g.groups,i),y=parseInt(pJ(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>pi([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>pi([...vJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>gJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[hJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>hJ(e,pi([...vJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(hJ(`←`,te(x-1),!1));let w=x<v.length-1?[hJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[YJ([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[YJ([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(YJ([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>WJ(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:Ny(a),s=` `.repeat(n-WJ(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(YJ([ae(p(r,LJ(c,m)),r)],i))}}return ce}function $J(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ZO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=XJ(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=ZJ(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=UJ(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=QJ(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,jJ(u,kh(void 0),aJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),TJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function eY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function tY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function nY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=iJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=pJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return YJ([],!0);let d=pJ(o,t.stateVar),f=eY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=pi(vJ(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=gJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):gJ(NJ(aJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(vJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=tY(e=>v(e).cellLength,u,WJ(`◀`)+1+y.cellLength+1+WJ(`▶`),KJ(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return YJ([...ee(-1).reverse(),hJ(`◀`,h(-1),!1),y,hJ(`▶`,h(1),!1),...ee(1)],!0)}function rY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ZO(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&dJ(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=ZJ(e,n,`carousel`),l=UJ(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return nY(n,c,e,jJ(l,kh(void 0),aJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function iY(e,t,n){let r=ZJ(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function aY(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function oY(e,t,n,r){let i=iY(e,t,n),a=r??pJ(iJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,aJ(e,`{{ ${n} }}`))}function sY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ZO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return OJ(oY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function cY(e,t,n){return{swatches:{fn:(r,i)=>{let a=iY(e,r,`swatches`),o=XJ(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=UJ(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=QJ(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,PJ(s,aJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),TJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=eY(l,pJ(iJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[aY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const lY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function uY(e,t,n,r){let i=ug(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Xh(e,n,r)});return[[wh(t).map((n,i)=>{let a=Vh(e,n);return{text:lY[i%lY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Bh(e,`warning`)),a(`error`,Bh(e,`error`))]]]}function dY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:wJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function fY(e,t,n,r,i){let a=uY(e,t,n,r).map(e=>dY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
195
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
196
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
184
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:G(e.source,[`layout`])}),t.root!==void 0&&(i.root=NR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=tz(e,t.actions,r)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:G(e.source,[`looks`])}),t.styles!==void 0&&(i.styles=Xz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=ZA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=Qz(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=tj(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=$z(e,t.helpers)),t.plugins!==void 0&&(i.plugins=mH(e,t.plugins)),VR(e,i),QR(e,i),Fj(e,i),bA(e,i,X,`the global settings menu`),i}const pH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function mH(e,t){if(Array.isArray(t)&&t.every(e=>typeof e==`string`&&e!==``))return t;e.issues.push({path:`plugins`,message:`"plugins" must be a list of plugin definition paths, got ${cv(t)}`,line:G(e.source,[`plugins`])})}const hH={},gH=dP(`commands.`),_H=_P(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),vH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,yH=`{{ \$dir := .current_dir }}{{ if and (ne .home "") (or (eq .home .current_dir) (hasPrefix (printf "%s/" .home) .current_dir)) }}{{ \$dir = printf "~%s" (trimPrefix .home .current_dir) }}{{ else }}{{ if or (eq .project_dir .current_dir) (hasPrefix (printf "%s/" .project_dir) .current_dir) }}{{ $dir = ternary (${vH}) (basename .project_dir) (ne (${vH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,bH=`{{ ${uM} }}`,xH={min:0,max:100,step:5},SH={warnAt:{label:`warning at %`,domain:xH,default:50},errorAt:{label:`error at %`,domain:{...xH,atLeast:`warnAt`},default:80}};function CH(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:xH,default:80}}}const wH={globals:{palette:`tokyo-night`},variables:{...gH.variables,...iA,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.committedAt":{kind:`input`,path:`git.committedAt`,type:`number`,default:0},"git.timeSinceCommit":{kind:`template`,type:`number`,template:`{{ if gt .git.committedAt 0 }}{{ sub (int (unixEpoch now)) .git.committedAt }}{{ else }}0{{ end }}`},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .block.nativeUtilization .block.resetsAt 300 }}`},"weekly.etaMinutes":{kind:`template`,type:`number`,template:`{{ etaMinutes .weekly.percentage .weekly.resetsAt 10080 }}`},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:yH},model:{group:`model-context`,description:`The active model's display name, followed by the effort gauge (a chevron ladder, climbing on a bubble at max) when an effort level is set.`,template:`✱ {{ formatModelName .model.display_name }}{{ if ne .effort.level "" }} {{ template "effortGauge" . }}{{ end }}`,when:`{{ ne .model.display_name "" }}`},sessionId:{group:`session-tools`,description:`The session id, truncated to 8 characters.`,template:`⌗{{ trunc 8 .session.id }}`,when:`{{ ne .session.id "" }}`},version:{group:`model-context`,description:`The Claude Code version reported in the hook payload.`,template:`◈ v{{ .version }}`,when:`{{ ne .version "" }}`},tmux:{group:`location`,description:`The tmux session name; hidden when not inside tmux.`,template:`tmux:{{ .tmux.session | default "none" }}`,when:`{{ ne .tmux.session "" }}`},host:{group:`location`,description:`user@host on a warning background, shown only over SSH.`,template:`⇄ {{ .host.user | default "?" }}@{{ .host.name | default "?" }}`,bg:`warning`,when:`{{ .host.ssh }}`},gitaculous:{group:`git`,description:`The git state: a summary (branch, ahead/behind, S/U/? flags) that the arrow at its right edge expands to every fact — repo, in-progress operation, sha, upstream ±, stash count, time since the last commit.`,template:`{{ if eq .git.detail "expanded" }}{{ template "gitExpanded" . }}{{ else }}{{ template "gitCollapsed" . }}{{ end }} {{ action "gitDetail" "▸" "◂" }}`,fg:bH,when:`{{ ne .git.branch "" }}`,settings:{aheadBehind:{label:`ahead/behind`,domain:`bool`,default:!0},flags:{label:`dirty flags`,domain:`bool`,default:!0},operation:{label:`operation`,domain:`bool`,default:!0},repo:{label:`repo name`,domain:`bool`,default:!0},sha:{label:`commit hash`,domain:`bool`,default:!0},stash:{label:`stash`,domain:`bool`,default:!0},upstream:{label:`upstream`,domain:`bool`,default:!0},age:{label:`time since commit`,domain:`bool`,default:!0}}},gitPr:{group:`git`,description:"The pull request open for this branch, as a link; `⚠ PR` when the forge lookup failed.",template:`{{ if eq .git.prState "open" }}{{ link .git.prUrl (printf "⇆ #%v" .git.prNumber) }}{{ else }}⚠ PR{{ end }}`,when:`{{ or (eq .git.prState "open") (ne .git.prError "") }}`},toolbar:{group:`session-tools`,description:`Quick actions: copy the session id, and open the project, transcript or repo.`,template:eP(``).template},commands:{group:`session-tools`,description:`Type /compact, /model or /clear into this session; /clear asks for a second click. Hidden when not inside tmux.`,template:gH.template,when:gH.when},themeSwitcher:{group:`session-tools`,description:"`◀ <theme> ▶`: the theme the bar is wearing; ◀ and ▶ switch this session to the previous or next theme, wrapping at the ends.",template:`{{ carousel "stepTheme" 0 }}`},session:{group:`cost-limits`,description:`This session's cost and token total, with a budget warning once a budget is configured.`,template:`§ {{ template "formatCost" .session.cost }} ({{ template "formatTokens" .session.tokens }}){{ template "budgetStatus" (dict "cost" .session.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:CH(0)},today:{group:`cost-limits`,description:`Today's cost and tokens across every session, with a budget warning once a budget is configured.`,template:`☉ {{ template "formatCost" .today.cost }} ({{ template "formatTokens" .today.tokens }}){{ template "budgetStatus" (dict "cost" .today.cost "budget" .settings.budget "warn" .settings.warnAt) }}`,settings:CH(50)},block:{group:`cost-limits`,description:`The 5-hour rate-limit block: percent used and time to reset, heating to warning then error.`,template:`◱ {{ round .block.nativeUtilization }}% ({{ template "formatResetCountdown" .block.resetsAt }})`,bg:`{{ ramp (round .block.nativeUtilization) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:SH,when:`{{ gt .block.resetsAt 0 }}`},weekly:{group:`cost-limits`,description:`The weekly rate-limit quota: percent used and time to reset, heating to warning then error.`,template:`◑ {{ round .weekly.percentage }}% ({{ template "formatResetCountdown" .weekly.resetsAt }})`,bg:`{{ ramp (round .weekly.percentage) "step" 0 (tint) .settings.warnAt "warning" .settings.errorAt "error" }}`,settings:SH,when:`{{ gt .weekly.resetsAt 0 }}`},burnrate:{group:`cost-limits`,description:`Spend per hour, with the projected time to the 5-hour and weekly limits.`,template:`⚡ {{ template "formatRate" .burn.costPerHour }} · {{ template "formatEta" .block.etaMinutes }} to 5h · {{ template "formatEta" .weekly.etaMinutes }} to wk`,bg:`{{ ramp .block.etaMinutes "step" -1 (tint) 0 "error" .settings.errorWithin "warning" .settings.warnWithin (tint) }}`,settings:{errorWithin:{label:`error within (min)`,domain:{min:0,max:300,step:5},default:30},warnWithin:{label:`warning within (min)`,domain:{min:0,max:300,step:5,atLeast:`errorWithin`},default:60}},when:`{{ or (gt .block.resetsAt 0) (gt .weekly.resetsAt 0) }}`},speed:{group:`activity`,description:`Token throughput for the latest exchange: output, input, and total.`,template:`⇅ out {{ template "formatSpeed" .speed.output }} · in {{ template "formatSpeed" .speed.input }} · tot {{ template "formatSpeed" .speed.total }}`,when:`{{ gt .session.tokens 0 }}`},tokenSparkline:{group:`activity`,description:`A sparkline of recent token throughput.`,template:`⚡ {{ sparkline .speed.history 24 }}`,when:`{{ ne .speed.history "" }}`},cacheTimer:{group:`activity`,description:"Minutes until the prompt cache expires, or `cold` once it has.",template:`◴ {{ if le (minutesUntilReset .cache.expiresAt) 0 }}cold{{ else }}{{ minutesUntilReset .cache.expiresAt }}m{{ end }}`,fg:`{{ readableOn (color (cascade (minutesUntilReset .cache.expiresAt) "0:error" "9:warning" "21:foreground")) (bgOf) ${Yh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:_H.template,bg:_H.bg,when:_H.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...eP(``).actions,...gH.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},..._H.actions},styles:{none:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:0},vivid:{hueShift:0,chromaScale:1.35,lightnessScale:1,lightnessShift:0},muted:{hueShift:0,chromaScale:.55,lightnessScale:1,lightnessShift:0},dim:{hueShift:0,chromaScale:1,lightnessScale:.85,lightnessShift:0},bright:{hueShift:0,chromaScale:1,lightnessScale:1,lightnessShift:.08},inverted:{hueShift:0,chromaScale:1,lightnessScale:-1,lightnessShift:1}},themeDefaults:hH,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${Yh} }}{{ \$climb := frames 1 (index \$glyphs 1) 1 (index \$glyphs 3) 1 (index \$glyphs 4) }}{{ if eq \$ord 5 }}{{ fg \$bubble "" }}{{ bg \$bubble (fg \$climbing \$climb) }}{{ fg \$bubble "" }}{{ else }}{{ fg (ramp $ord "step" 0 (${uM}) 2 (readableOn (color "accent") (bgOf) ${Yh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${Yh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ $age := .git.timeSinceCommit }}{{ if and .settings.age (gt $age 0) }} ◷ {{ template "formatTimeSince" $age }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:vP(`.`),formatTokens:`{{ template "formatTokenCount" . }} tokens`,formatToolTally:`{{ $names := splitList "," . }}{{ range $i, $pair := $names }}{{ if lt $i 2 }}{{ if $i }} {{ end }}{{ $kv := splitList ":" $pair }}{{ index $kv 0 }}{{ if ne (index $kv 1) "1" }}×{{ index $kv 1 }}{{ end }}{{ end }}{{ end }}{{ if gt (len $names) 2 }} +{{ sub (len $names) 2 }}{{ end }}`,formatRate:`{{ if lt . 0 }}—/hr{{ else }}{{ template "formatCost" . }}/hr{{ end }}`,formatEta:`{{ if lt . 0 }}—{{ else }}{{ template "formatLongTimeRemaining" . }}{{ end }}`,formatSpeed:`{{ if lt . 0 }}—{{ else }}{{ template "formatTokenCount" (round .) }}/s{{ end }}`,formatTokenBreakdown:`{{ $first := true }}{{ if gt .input 0 }}{{ template "formatTokenCount" .input }} in{{ $first = false }}{{ end }}{{ if gt .output 0 }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" .output }} out{{ $first = false }}{{ end }}{{ if or (gt .cacheCreation 0) (gt .cacheRead 0) }}{{ if not $first }} + {{ end }}{{ template "formatTokenCount" (add .cacheCreation .cacheRead) }} cached{{ $first = false }}{{ end }}{{ if $first }}0 tokens{{ end }}`,budgetStatus:`{{ if or (le .budget 0) (lt .cost 0) }}{{ else }}{{ $pct := minf 100 (mulf (divf .cost .budget) 100) }}{{ $p := printf "%.0f%%" $pct }}{{ if ge $pct .warn }} !{{ $p }}{{ else }}{{ if ge $pct 50 }} +{{ $p }}{{ else }} {{ $p }}{{ end }}{{ end }}{{ end }}`,formatTimeSince:`{{ if lt . 60 }}{{ . }}s{{ else if lt . 3600 }}{{ div . 60 }}m{{ else if lt . 86400 }}{{ div . 3600 }}h{{ else if lt . 604800 }}{{ div . 86400 }}d{{ else }}{{ div . 604800 }}w{{ end }}`,formatDuration:`{{ if lt . 60 }}{{ printf "%.0f" . }}s{{ else if lt . 3600 }}{{ printf "%.0f" (divf . 60) }}m{{ else if lt . 86400 }}{{ printf "%.1f" (divf . 3600) }}h{{ else }}{{ printf "%.1f" (divf . 86400) }}d{{ end }}`,formatResponseTime:`{{ if lt . 60 }}{{ printf "%.1f" . }}s{{ else }}{{ printf "%.1f" (divf . 60) }}m{{ end }}`,formatLongTimeRemaining:`{{ if ge . 1440 }}{{ $d := div . 1440 }}{{ $h := div (mod . 1440) 60 }}{{ if gt $h 0 }}{{ $d }}d {{ $h }}h{{ else }}{{ $d }}d{{ end }}{{ else if ge . 60 }}{{ $h := div . 60 }}{{ $m := mod . 60 }}{{ if gt $m 0 }}{{ $h }}h {{ $m }}m{{ else }}{{ $h }}h{{ end }}{{ else }}{{ . }}m{{ end }}`,formatResetCountdown:`{{ template "formatLongTimeRemaining" (add 1 (minutesUntilReset .)) }}`}},TH=new Set([wH.globals.palette,...Object.keys(wH.themeDefaults),...Object.values(wH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),EH=$I(cH(`<default>`,JSON.stringify(wH),TH),wH),DH=Qb(EH.presets);function OH(e){return DH.includes(e)}const kH=Object.freeze({});function AH(e,t){return e.kind===`decided`?t[e.name]??kH:kH}function jH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const MH=e=>Bv(t=>e[Pv[t].setting]);function NH(e,t,n,r){let i=_y(e);return Lg(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function PH(e,t){return $b(t(`preset`),e.globals.preset,e.presets)}function FH(e,t,n){let r=PH(e,t),i=nx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Lb(a.palette,t(`theme`),i.palette),s=jH(i,AH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,NH(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yg(a.style,t(`style`),s.style,e.styles),effect:a_(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function IH(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?m_:h_;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const LH=Object.entries(Sy),RH=new Set(wy.map(e=>e.sessionKey)),zH=()=>!1;function BH(e,t){return FH(e,e=>RH.has(e)?t(e):null,zH)}const VH=[`preset`,`theme`];function HH(e,t,n){let r=new Set(VH.slice(0,n).map(e=>Sy[e].sessionKey));return FH(e,e=>r.has(e)?t(e):null,zH)}function UH(e,t){let n=Array.from({length:VH.length+1},(n,r)=>HH(e,t,r));return e=>{let t=VH.indexOf(e);return n[t===-1?VH.length:t]}}function WH(e,t,n,r){return e.flatMap(([e,i])=>{let a=IH(t,e);return a===null||a===IH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function GH(e,t,n){return IH(BH(e,t),n)}function KH(e,t){let n=BH(e,t);return WH(LH,n,UH(e,t),t=>qH(e,n.preset,t.configKey))}function qH(e,t,n){return n in(ex(e.presets,t).globals??{})?hj(t,n):n}function JH(e,t,n){let r=$b(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=gj(n);return{key:i?.scope===`globals`?qH(e,r,i.field):n,globals:nx(e,r)}}function YH(e,t){let{preset:n}=BH(e,t);return QH(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:K_(a,s);return c===void 0||G_(c)===G_(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function XH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Qb(e.presets).flatMap(n=>{let i=QH(e,n);return[...new Set(i.filter(e=>r.has(e.key)).map(e=>e.id))].flatMap(e=>{let n=i.filter(t=>t.id===e);return U_(Object.fromEntries(n.map(e=>[e.setting,e.decl])),Object.fromEntries(n.map(e=>{let n=r.get(e.key)??t(e.key),i=n===null?void 0:K_(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const ZH=new WeakMap;function QH(e,t){let n=ZH.get(e)??new Map;ZH.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(tx(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=V_(e.segments[t.name])[n];return{id:r,setting:n,key:i,decl:a,saved:t.settings?.[n]??a.default}})),a=[...new Map(i.map(e=>[e.key,e])).values()];return n.set(t,a),a}function $H(e,t){let n=BH(e,t);return{from:n.preset,globals:ex(e.presets,n.preset).globals??{},picks:WH(LH.filter(([e])=>e!==`preset`),n,UH(e,t),e=>e.configKey),placements:YH(e,t)}}function eU(e,t){return FH({...e,globals:{palette:t},presets:{}},()=>null,zH)}function tU(e,t){let n=BH(e,t),r=IH(n,`theme`);if(r===null)return{kind:`rule`};let i=eU(e,r),a=nx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,IH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==IH(i,e))}}function nU(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...qA(e)?DH.map(t=>hj(t,e)):[],...mj(e)?Rg().map(t=>pj(t,e)):[]]}}function rU(e){return new Set(wy.map(e=>e.configKey).filter(t=>nU(t).fileKeys.some(t=>oU(e,aU(t)))))}function iU(e,t,n){let r=KH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=tU(e,n);return{unsaved:r.length+YH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function aU(e){let t=gj(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return _j(t)}function oU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&oU(e[n],r)}const sU=Rg(),cU=new Set(sU),lU=new Set(o_),uU=e=>e?cU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${sU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},dU=e=>e?lU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},fU=new Set([`1`,`true`]),pU=new Set([`0`,`false`]),mU={endcaps:dU,theme:uU,"toolbar-expanded":e=>fU.has(e)?{ok:!0,value:`1`}:pU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},hU=WI(mU,`state`,SU);function gU(e,t){return hU.register(e,t)}function _U(e){return hU.gateFor(e)}function vU(e,t){return`set`in e?`to`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:[e.to]}}]:`from`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:cx(e.from,t).members}}]:`int`in e?[{key:e.set,spec:{kind:`int`}}]:`cycle`in e?[{key:e.set,spec:{kind:`allow-list`,allowed:e.cycle}}]:[{key:e.set,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function yU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(mU,e.key))}function bU(e,t,n){let r=Ay.get(n);if(r!==void 0)return GH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function xU(e){let t=pI(e);return yU(Object.values(e.actions).flatMap(e=>vU(e,t)))}function SU(e){return HI(xU(e))}const CU=`update.dismissed`,wU=`updateNotice`,TU=Sy.updateNotice.sessionKey;function EU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const DU=e=>`${e.version} [${Xe(e.digest)}]`;function OU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:DU(e.newer),running:DU(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:uo(e.newer),running:uo(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${po}@${uo(e.newer)}`,`install`]}}}}const kU={kind:`idle`},AU={kind:`running`};function jU(e,t,n){if(e===null)return[];let r=EU(e);if(!n.enabled||n.dismissed===r)return[];let i=OU(e),a=`${i.headline}: ${i.newer}. You're on ${i.running}.`,o=t.kind===`failed`&&t.identity===r?[`${i.act} failed: ${t.reason}`]:[],s=[a,...o].join(`
|
|
185
|
+
`),c=pi([{verb:Wr,args:[s]}]),l=t.kind===`running`?yb(`[${i.busy}]`,c):yb(`[${i.act}]`,pi([{verb:ii,args:[n.sessionId]}]));return[{severity:_b,message:s,lines:[[yb(a,c),l,yb(`[dismiss]`,pi([{verb:Rr,args:[n.sessionId,CU,r]}])),yb(`[disable]`,pi([{verb:Kr,args:[n.sessionId,wU,`false`]},{verb:Rr,args:[n.sessionId,TU,`false`]}]))],...o.map(e=>[yb(e,c)])]}]}function MU(e,t){return e.kind===`stale`?{kind:`source`,root:e.root,newer:e.source,running:e.running}:e.kind===`not-source-checkout`&&t!==null&&t.kind===`stale`?{kind:`release`,newer:t.latest,running:t.installed}:null}function NU(e){switch(e.kind){case`current`:return[`info`,`build: current ${DU(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${DU(e.source)}, running ${DU(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function PU(e){switch(e.kind){case`current`:return[`info`,`release: current ${uo(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${uo(e.latest)}, running ${uo(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${uo(e.installed)}, latest ${uo(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function FU(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const IU=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function LU(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=IU(e.stderr)??e.error??IU(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function RU(){let e=[KI(wU,[`false`]),gU(TU,[`false`]),gU(CU,[])];return()=>e.forEach(e=>e())}function zU(e){let{entryUrl:t,intervalMs:n,releaseIntervalMs:r,registryUrl:i,fetchImpl:a,onApplied:o,log:s}=e,c={kind:`unchecked`,reason:`not sampled yet`},l=null,u=kU,d=null,f=FU(s),p=FU(s),m=()=>MU(c,l);function h(){let e=m(),t=e===null?null:EU(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:gU(CU,[t])})}function g(){c=nt(t,$e),f(NU(c)),h()}async function _(){l=ho(Ze,await mo(po,a,i)),p(PU(l)),h()}return{arm(){RU(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>jU(m(),u,e),act(){let e=m();if(e===null)throw new q(`apply-update: nothing newer is known to apply`);let t=OU(e);if(u.kind===`running`)throw new q(`apply-update: already ${t.busy}`);u=AU,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),pt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=kU,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=LU(n);u={kind:`failed`,identity:EU(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function BU(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function VU(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function HU(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:BU(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=BU(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!VU(t,n)){a(`info`,`binary ${n.kind===`absent`?`gone`:`changed`} (${e}); shutting down`),c&&clearInterval(c),i();return}}};return{arm(){for(let{path:e,stamp:t}of o)t.kind===`failed`&&a(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);c=setInterval(l,n),c.unref()},checkNow:l}}const UU=`${Iy}${Fy}`;function WU(e){return`${UU}⚠ cc-candybar: ${GU(e)}${Ly}\n`}function GU(e){switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:return`daemon rejected request: ${Py(e.message,60)}`;case`render_failed`:return`render failed: ${Py(e.message,60)}`;case`switched_off`:return`switched off: ${Py(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Py(e.message,60)}`}}function KU(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
186
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:WU(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const qU=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function JU(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===R.STANDARD&&e.number!==void 0?qU[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const YU={bold:`bold`,dim:`dimColor`,italic:`italic`,underline:`underline`,strike:`strikethrough`,reverse:`inverse`,blink:null,blink2:null,conceal:null,underline2:null,frame:null,encircle:null,overline:null},XU=Object.keys(YU);function ZU(e,t){let n=JU(t.color),r=JU(t.bgcolor),i={};for(let e of XU){if(t[e]!==!0)continue;let n=YU[e];if(n===null)throw Error(`frames: the band cannot draw ${e} text`);i[n]=!0}return{text:e,...n!==void 0&&{color:n},...r!==void 0&&{backgroundColor:r},...i,...t.link!==void 0&&{href:t.link}}}const QU=new V;function $U(e){return{ok:!0,band:new zp().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(ZU(t.slice(r,i.start),QU)),n.push(ZU(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(ZU(t.slice(r),QU)),n})}}function eW(e){let t=KU(mn(e)).output;try{return $U(t)}catch(e){return $U(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}function tW(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const nW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function rW(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case R.STANDARD:{let t=e.number===void 0?void 0:nW[e.number];if(t!==void 0)return t;break}case R.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case R.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case R.DEFAULT:case R.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const iW={bold:`bold`,dim:`dim`,italic:`italics`,underline:`underscore`,strike:`strikethrough`,reverse:`reverse`,blink:`blink`,conceal:`hidden`,underline2:`double-underscore`,overline:`overline`,blink2:null,frame:null,encircle:null},aW=Object.keys(iW);function oW(e){return e.replaceAll(`#`,`##`)}function sW(e){let t=aW.filter(t=>e[t]===!0).map(e=>{let t=iW[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${rW(e.color)}`,`bg=${rW(e.bgcolor)}`,...t].join(`,`)}]`}const cW=new V;function lW(e){let t={},n=(e,n)=>{let r=sW(n)+oW(e);if(n.link===void 0)return r;let i=tW(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new zp().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof V))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),cW)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),cW)),r.join(``)}),links:t}}function uW(e){let t=KU(mn(e)).output;try{return lW(t)}catch(e){return lW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}const dW={band:e=>JSON.stringify(eW(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:uW(e)})};function fW(e){let t=typeof e==`string`?e===``?`is empty`:e===`.`||e===`..`?`is ${JSON.stringify(e)}, which names a folder, not a session`:/[/\\\0]/.test(e)?`contains a path separator or NUL: ${JSON.stringify(e)}`:Buffer.byteLength(e,`utf8`)>250?`is longer than 250 bytes`:null:`is not a string: ${JSON.stringify(e)??String(e)}`;return t===null?{ok:!0,id:e}:{ok:!1,problem:t}}function pW(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function mW(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?I(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const hW={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},gW={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function _W(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}const vW={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function yW(e){return Object.keys(vW).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${vW[t]}: ${n.reason}`]:[]})}function bW(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(xW(e,t))}function xW(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??SW(t.stderr)].filter(Boolean).join(`, `)}`}function SW(e){return e.trim().split(`
|
|
187
|
+
`,1)[0]??``}function CW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function wW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const TW={github:`gh`,gitlab:`glab`};function EW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const DW=/^[A-Za-z]:[\\/]/;function OW(e){let t=e.trim();if(DW.test(t))return null;let n=t.match(/^(?:[^@/]+@)?(\[[^\]]+\]):(.*)$/)??t.match(/^(?:[^@/:]+@)?([^/:]+):(?!\/\/)(.*)$/),r=n?`ssh://${n[1]}/${n[2].replace(/^\/+/,``)}`:t,i;try{i=new URL(r)}catch{return null}return{scheme:i.protocol.replace(/:$/,``),host:i.hostname.toLowerCase(),port:i.port,path:i.pathname.replace(/^\/+/,``).replace(/\/+$/,``)}}function kW(e){return OW(e)?.host||null}function AW(e){let t=kW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const jW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function MW(e){let t=bW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?NW(t.value):[]}}function NW(e){let t=new Map;for(let n of e.split(`
|
|
188
|
+
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function PW(e){return e.urls.find(e=>zW(e)!==null)??e.urls[0]??null}function FW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function IW(e){let t=FW(e);return t?PW(t):null}function LW(e){let t=FW(e);return t?t.urls.find(e=>AW(e)!==null)??PW(t):null}function RW(e){let t=(OW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function zW(e){let t=OW(e);if(!t)return null;let n=t.scheme===`https`?{scheme:`https`,port:t.port}:t.scheme===`http`?{scheme:`http`,port:t.port}:t.scheme===`ssh`||t.scheme===`git`?{scheme:`https`,port:``}:null;if(!n||!t.host)return null;let r=t.path.replace(/\.git$/,``);if(!r)return null;let i=n.port?`${t.host}:${n.port}`:t.host;return`${n.scheme}://${i}/${r}`}function BW(e){let t=IW(e);return t===null?null:zW(t)}function VW(e,t,n,r){return t.ok?r(t.stdout):EW(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??SW(t.stderr)].filter(Boolean).join(`, `)}`)}function HW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function UW(e){let t=`detached`,n=F,r=F,i=F,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
189
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function WW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!HW(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=_W(`gh pr view`,hW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function GW(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!HW(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=_W(`glab mr view`,gW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function KW(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var qW=class{isGitRepo(e){return LV(e)}async execGitAsync(e,t){return pt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=RV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=CW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=CW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=CW(s,BW)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return wW(bW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=wW(bW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
|
|
190
|
+
`).length:0)}async getRemotesAsync(e){let t=KW(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return MW(await this.execGitAsync(jW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=IW(e);return(n===null?null:RW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=LW(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return pt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=AW(t);return n===`github`?VW(`gh pr view`,await this.execForgeAsync(TW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,WW):n===`gitlab`?VW(`glab mr view`,await this.execForgeAsync(TW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,GW):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=bW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(UW(t.value)):t}};const JW=(e,t)=>E(t);function YW(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const XW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var ZW=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??JW}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:[...t.files,...t.dirs.map(e=>e.path)].map(e=>({path:e,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=YW(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.files)try{let i=p.watch(r,{persistent:!1},(e,n)=>t(XW(n)));i.on(`error`,n(r)),e.watchers.push(i)}catch(e){i(r,e)}for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(XW(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function QW(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var $W=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function eG(){return J.observable.box(tG(`unread`),{deep:!1})}function tG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function nG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function rG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(tG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function iG(e,t){e.reading.get().kind===`pending`&&nG(e,t)}function aG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function oG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function sG(e){for(;;){let t=e();if(!aG(t))return t;await t.landed}}function cG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function lG(e){return{current:()=>e}}function uG(e){return sG(()=>e.current())}const dG=`pass`,fG={okMs:5*6e4,failedMs:45e3};function pG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function mG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function hG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function gG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}function _G(e){return e.find(e=>e.kind===`ok`)?.value.branch}function vG(e){e.missed=!0,rG(e,`unread`)}function yG(e,t){return e.missed&&e.reading.get().kind===`pending`&&nG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function bG(e,t){let n=oG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:oG(t)})}function xG(e){return t=>I(`${e} threw: ${String(t)}`)}var SG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new qW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new jk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new ZW({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return lG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>bG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new kk,watcher:this.watchers.acquire(`git:${e}`,gG(n),()=>this.changed(e)),period:new $W(()=>{r.refresh.share(dG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(dG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&vG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(dG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:eG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=hG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(mG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(xG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,nG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of yW(n.value))s.add(e)});let c=_G(a),l=i===null||r.length===0?`-`:c===void 0?yG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,pG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new $W(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:eG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(xG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(vG(t),`owed`):(rG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,nG(t,a.outcome),t.period.landed(QW(fG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(xG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${as(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(nG(t,i),t.period.landed(QW(fG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())iG(n,t);e.pr!==null&&iG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},CG=class{static CACHE_DIR=bt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const wG={"claude-haiku-4-5-20251001":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-haiku-4-5":{name:`Claude Haiku 4.5`,input:1,output:5,cache_write_5m:1.25,cache_write_1h:2,cache_read:.1},"claude-opus-4-20250514":{name:`Claude Opus 4`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-opus-4-1-20250805":{name:`Claude Opus 4.1`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-sonnet-4-20250514":{name:`Claude Sonnet 4`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-4-opus-20250514":{name:`Claude 4 Opus`,input:15,output:75,cache_write_5m:18.75,cache_write_1h:30,cache_read:1.5},"claude-4-sonnet-20250514":{name:`Claude 4 Sonnet`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-sonnet-4-5-20250929":{name:`Claude Sonnet 4.5`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3},"claude-opus-4-5":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-5-20251101":{name:`Claude Opus 4.5`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-opus-4-6-20260205":{name:`Claude Opus 4.6`,input:5,output:25,cache_write_5m:6.25,cache_write_1h:10,cache_read:.5},"claude-sonnet-4-6":{name:`Claude Sonnet 4.6`,input:3,output:15,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3}};var TG=class{static executionCache=null;static modelPricingCache=new Map;static GITHUB_PRICING_URL=`https://raw.githubusercontent.com/promptctl/cc-candybar/main/pricing.json`;static async loadDiskCache(){let e=Date.now()-1440*60*1e3;return await CG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await CG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(wG).length} models`),this.executionCache=wG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(wG).length} models`),wG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const EG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function DG(e){if(typeof e==`string`)return EG.exec(e)?.[1]}function OG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function kG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function AG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=OG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?DG(kG(n)):void 0;if(!(r.length===0&&i.length===0&&a===void 0&&o===void 0))return{...r.length>0&&{started:r},...i.length>0&&{finished:i},...a!==void 0&&{todos:a},...o!==void 0&&{command:o}}}function jG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function MG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await NG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function NG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function PG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Fa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await Va(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=HG(i,t,s.value);let c=zG(Ha(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function FG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(LG(t)===`tool_result`)return`tool-result`;let n=typeof e.origin==`object`&&e.origin!==null?e.origin.kind:void 0;if(n!==void 0&&n!==`human`)return`turn`;let r=kG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||IG.test(r)?`claude-code`:`prompt`}const IG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function LG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function RG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=FG(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:AG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function zG(e){let t=e.trim();if(!t)return{kind:`blank`};try{let e=JSON.parse(t);return typeof e==`object`&&e&&!Array.isArray(e)?{kind:`object`,value:e}:{kind:`unparsed`,reason:`not a JSON object`}}catch(e){return{kind:`unparsed`,reason:String(e)}}}function BG(e){let t=zG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return RG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function VG(e){let t=[];for(let n of e.split(`
|
|
191
|
+
`)){let e=BG(n);e&&t.push(e)}return t}function HG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function UG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function WG(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Va(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=HG(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,Ha(c,e=>VG(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var GG=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}},KG=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>oG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,rG(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:eG(),holders:0,flight:null,changed:!1,superseding:0,revisit:qG(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();YG(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{nG(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),iG(e,I(`${this.spec.name} entry dropped`))}};function qG(e,t){if(e===null)return new JG(t.holdReturned);let n=new $W(t.period);return{landed:t=>n.landed(QW(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var JG=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function YG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function XG(e,t){let n=e?e.input+e.cacheCreation+e.cacheRead:0,r=e?e.output:0;return{input:n,output:r,total:n+r,atMs:t}}const ZG={okMs:60*1e3,failedMs:10*1e3},QG={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},$G={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function eK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function tK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function nK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const rK={entries:0,cost:0,breakdown:nK(),days:new Map};async function iK(e,t){let n=eK(new Date(tK())),r=e.entries,i=e.cost,a={...e.breakdown},o=new Map;for(let[t,r]of e.days)t>=n&&o.set(t,{...r});for(let e of t){let t=e.message?.usage;if(!t)continue;r++;let s=e.costUSD??await TG.calculateCostForEntry(e.raw);i+=s,a.input+=t.input_tokens||0,a.output+=t.output_tokens||0,a.cacheCreation+=t.cache_creation_input_tokens||0,a.cacheRead+=t.cache_read_input_tokens||0;let c=eK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...QG};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function aK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function oK(e){let t=0,n=0,r=nK(),i=new Map;for(let{value:a}of e.values()){t+=a.entries,n+=a.cost,r.input+=a.breakdown.input,r.output+=a.breakdown.output,r.cacheCreation+=a.breakdown.cacheCreation,r.cacheRead+=a.breakdown.cacheRead;for(let[e,t]of a.days){let n=i.get(e)??{...QG};aK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:$G,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function sK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function cK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!sK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...QG};aK(r,t),n.set(e,r)}return n}async function lK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function uK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function dK(e,t){(0,J.runInAction)(()=>e.set(t))}var fK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new GG;scans;daySets=new Map;speedFlight=new GG;requestFlight=new GG;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Me,this.ledger=e.ledger??new jk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new KG({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??ZG,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=ja(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:P(uK(t.kind===`ok`?t.value.sessionInfo:$G,e))},speed:t=>this.observed(e,r,t),today:async e=>{await uG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return Oa;let r=n.failure.get();return r===null?P(uK(n.record?.sessionInfo??$G,t)):I(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${as(e)}`,`request`,a,Date.now()-i),dK(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=jG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=eK(ak(n)),o={...QG},s=e.sums.get(a);s!==void 0&&aK(o,s);let c=sK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&aK(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return F;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return dK(this.hold(e).speed,t),t;let r=XG(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=P({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return dK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??Oa:F}async ingest(e,t,n,r){if(!e)return F;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,P(i);if(!t)return i?P(i):F;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),P(c)):l===void 0?P(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new rS(`today over ${e.join(`,`)}`,()=>cK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await PG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of UG(r.longLines))this.log(`info`,e);let i=new Map,a=``;for(let e of[t,...r.paths]){let r=n?.files.get(e),o=await WG(e,r,rK,iK);if(o.kind===`failed`)return o;if(o.kind===`absent`){r&&i.set(e,r);continue}let{folded:s,longLines:c}=o.value;for(let e of UG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...oK(i),mainStamp:a})}async scan(e){try{let t=tK(),n=await MG(e),r=[];for(let e of n){let n=await NG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await NG(Ia(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Ma(a)})}}let i=[],a={hits:0,misses:0};return await lK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${as(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=eK(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},pK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},mK=class{sessions;constructor(e,t,n,r=Me,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new pK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=ja(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await WG(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${as(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of UG(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??Oa}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function hK(e,t){let n=t.message?.usage;return!n?.input_tokens||t.isSidechain===!0?e:n.input_tokens+(n.cache_read_input_tokens||0)+(n.cache_creation_input_tokens||0)}var gK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(void 0,hK,(e.ledger??new jk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,_K(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,_K(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function _K(e){return e.context_window?.context_window_size??2e5}const vK={messageCount:0,nonPrompts:0,recent:[]},yK=new Set([`turn`,`interrupt`,`claude-code`]);function bK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!yK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function xK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var SK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(vK,bK,(e.ledger??new jk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?CK(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:CK(e,n,r)}};function CK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:xK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const wK={command:null,todos:[],pending:[],done:[]};function TK(e,t){let n=e.findIndex(e=>e.name===t);return n<0?[...e,{name:t,count:1}]:e.map((e,t)=>t===n?{name:e.name,count:e.count+1}:e)}function EK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function DK(e,t){if(t.isSidechain)return e;let n=EK(e,t),r=t.activity;if(r===void 0)return n;let i=n.pending,a=n.done;r.started!==void 0&&(i=[...i,...r.started]);for(let e of r.finished??[]){let t=i.findIndex(t=>t.id===e);t<0||(a=TK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function OK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>TK(e,t.name),[]),done:e.done}}var kK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new mK(wK,DK,(e.ledger??new jk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return AK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:AK(e,t)}};function AK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(OK(t.value))}function jK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function MK(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function NK(e,t,n,r){return MK(D(jK(e,t,n,r)),n)}async function PK(e,t,n,r){return MK(await pt(jK(e,t,n,r)),n)}const FK=3e4;var IK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new KG({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:LK,every:{okMs:FK,failedMs:FK},maxEntries:64,logger:t,ledger:e.ledger??new jk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function LK(e){let t=await PK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}const RK=6e4,zK={okMs:RK,failedMs:RK};function BK(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function VK(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var HK=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:zK,maxEntries:1,logger:t,ledger:e.ledger??new jk(t)};this.name=new KG({...n,name:`host.name`,read:()=>VK(`name`,()=>BK(C.hostname()))}),this.user=new KG({...n,name:`host.user`,read:()=>VK(`user`,()=>C.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},UK=class{known=new pK(64);refreshes;constructor(e=Me,t=new jk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=WK(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=hP(e);return this.refreshes.recorded(`path=${as(e)} stamp=${as(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function WK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const GK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function KK(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var qK=class{known=new pK(256);refreshes;constructor(e=Me,t=new jk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=ja(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??Oa}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await JK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function JK(e){let t=await YK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function YK(e){for(let t of[65536,1048576]){let n=await Ga(e,t);if(n.kind!==`ok`)return n;let r=XK(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function XK(e,t){let n=e.toString(`utf8`).split(`
|
|
192
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!GK.test(t))continue;let r=KK(t);if(r!=null)return r}return null}var ZK=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const QK=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},$K=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,eq=e=>nV(e),tq=e=>s.join(e.storage.folder,eq(e.sessionId)),nq=e=>JSON.stringify([e.folder,e.generation]),rq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var iq=class{sessions;folders=new Map;watched=new Map;faults=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??QK,this.sessions=new KG({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(tq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new jk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!$K(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${as(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(nq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${nq(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(nq(e),i);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return n!==null&&this.faulted(i,`unusable`,n),this.sweep(e),i}closed(e){let t=nq(e.key);this.watched.delete(t),this.faults.delete(t),clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>rq(e.storage,n);switch(t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(eq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{key:n,folder:r}=e,i;try{i=this.identityOf(n.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&$K(i,a)){t();return}n.generation===r.generation&&(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${as(n.folder)} generation=${n.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>rq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(nq(r),`cannot refresh: ${r.folder} ${n}; reload the config or restart the daemon`),this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${as(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>rq(e.storage,r))}async read(e){let t=this.faults.get(nq(e.storage));if(t!==void 0)return I(t);let n=tq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Ok(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${as(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&eq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function aq(e){let{logger:t,ledger:n}=e;return{hostService:new HK({logger:t,ledger:n}),gitProvider:new SG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new fK({logger:t,ledger:n}),contextProvider:new gK({logger:t,ledger:n}),metricsProvider:new SK({logger:t,ledger:n}),activityProvider:new kK({logger:t,ledger:n}),tmuxService:new IK({logger:t,ledger:n}),autoCompact:new UK(t,n),cacheExpiry:new qK(t,n),managedStorage:new iq({watchers:e.watchers,logger:t,ledger:n}),faults:new ZK,log:e.logger}}function oq(e){return Math.max(1,e-2)}function sq(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[qa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function cq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function lq(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:OH(e.preset)}}}const uq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function dq(e,t){if(!t)return`-`;if(ka(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return ka(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const fq=10*1e3;function pq(e,t){if(!(t<60))return e*3600/t}function mq(e,t,n,r){let i=r-t;if(i<50||i>fq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function hq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=mq(t.input,t.atMs,n.input,n.atMs),i=mq(t.output,t.atMs,n.output,n.atMs),a=mq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function gq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>fq)continue;let o=mq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function _q(e,t){let n=nx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(tx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...vq(e,n.name));return bq(e,r)}function vq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function yq(e,t,n){return bq(e,[...vq(e,t),...n])}function bq(e,t){let n=iB(e),r=new Map(zx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=tB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function xq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=_q(e,n);return t.set(n,i),i}}function Sq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Cq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(uq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const wq=new WeakMap;function Tq(e){let t=wq.get(e);return t===void 0&&(t=Eq(e),wq.set(e,t)),t}function Eq(e){let t=t=>Sq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function Dq(e){return oq(e.termCols??120)}function Oq(e){return Xa(Ya(e.claudeConfigDir))}function kq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Aq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Tq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(ak(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Oq(a)))])}function jq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Mq(e,t){let n=lG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Nq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Cq(n),t.workspace?.project_dir]}function Pq(e,t,n,r,i){let a=Tq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return lG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),lG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Nq(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(jq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Fq(e){let{hookData:t,deps:n}=e,r=Tq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(Oq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Iq(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function Lq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Tq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return Oa;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?Oa:Xq(n.git,()=>Oa),m=n.tmuxSession.kind===`pending`?Oa:d(n.tmuxSession),h=n.hostName.kind===`pending`?Oa:d(n.hostName),g=n.hostUser.kind===`pending`?Oa:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?Oa:Gq(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?Oa:Bq(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,Vq),x=u(n.usage,e=>Jq({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>Jq({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,Kq),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=Yq(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:Yq(r.workspace.current_dir)??``,project_dir:Yq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>Yq(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...lq(a),history:t.history,navigation:{back:t.back},term:{cols:Dq(i)},...c,...s!==null&&{configPath:s},resumeCommand:sq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:zq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})}}function Rq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function zq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Bq(e,t){let n=e!=null&&t!=null?pq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Vq(e){let t=hq(e),n=gq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Hq(e,t){return Lq(e,t,Fq(e))}function Uq({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return Oa;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?Oa:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function Wq(e,t,n){await Aq(e,t,n),await sG(()=>{let t=Iq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Gq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return gP(e.value,t)}}function Kq(e){let t=e.todos.findIndex(e=>e.active),n=e.todos.length===0?void 0:{total:e.todos.length,completed:e.todos.filter(e=>e.done).length,...t>=0&&{position:t+1,active:e.todos[t].text}},r=qq(e.running),i=qq(e.done),a=r===void 0&&i===void 0?void 0:{...r!==void 0&&{running:r},...i!==void 0&&{done:i}};if(!(e.command===null&&n===void 0&&a===void 0))return{...e.command!==null&&{command:e.command},...n!==void 0&&{todo:n},...a!==void 0&&{tool:a}}}function qq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Jq(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function Yq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Xq(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(pW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:mW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function Zq(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const Qq={kind:`hidden`},$q={kind:`shown`};function eJ(e,t){try{return Zq(e,t)?$q:Qq}catch(e){let t=eS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function tJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function nJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function rJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function iJ({text:e,placement:t,lead:n,trail:r}){return{text:aJ(e),placement:t,...n!==void 0&&{lead:aJ(n)},...r!==void 0&&{trail:aJ(r)}}}function aJ(e){let t=e.blankCopy(e.plain);t.style=Hy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Hy(i).clearMetaAndLinks(),n,r);return t}function oJ(e){let t=rJ(e);if(t.length===1)return e.text;let n=tJ(t);return n.style=e.text.style,n}function sJ(e,t){let{width:n,justify:r,truncate:i,baseStyle:a,padding:o,placement:s,lead:c=[],trail:l=[]}=t;if(e.length===0)return[];let u=tJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:tJ([d,...c],a)},...l.length>0&&{trail:tJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(nJ(u,n,p),[{text:u,...f}])}const cJ=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function lJ(e){return Math.max(0,...e.split(`
|
|
193
|
+
`).map(e=>Us(e.replace(cJ,``))))}function uJ(e,t){let n=()=>e.map(e=>({owner:oJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=pb(e.map(oJ),t).split(`
|
|
194
|
+
`);if(i.length>1)return n();let a=Math.max(0,t.width-lJ(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];nJ(c,c.cellLength+a,n)}),n()}function dJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=fJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Hy(a.style)};if(e.style.link){i();let r=fJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function fJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>pJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function pJ(e,t){let n=e.copy();return n.style=t,n}function mJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function hJ(e,t){let{look:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function gJ(e,t){let{layout:n}=mJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function _J(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function vJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,yJ(e,t,o,n,r,i));return i}function yJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`set-option`,key:n.set,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}return`int`in n?{kind:`set-int`,key:n.set,stateVar:e}:`cycle`in n?{kind:`set-cycle`,key:n.set,stateVar:e,members:n.cycle}:{kind:`set-bounded`,key:n.set,by:n.by}}if(`persist`in n){let e=Dy.get(n.persist)??n.persist;if(`to`in n)return{kind:`persist-literal`,key:n.persist,value:n.to,stateVar:e};if(`from`in n){let t=cx(n.from,i);return{kind:`persist-option`,key:n.persist,stateVar:e,options:[...t.members],paletteOf:t.paletteOf,library:t.library}}if(`cycle`in n)return{kind:`persist-cycle`,key:n.persist,stateVar:e,members:n.cycle};if(`removeSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`remove`,target:n.removeSegment}};if(`insertSegment`in n)return{kind:`layout-op`,key:n.persist,op:{op:`insert`,segment:n.insertSegment,anchor:n.anchor,relation:n.relation}};if(`insertSegmentFrom`in n){let e=cx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:SJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:SJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:fx(n),argv:n.run.map(n=>SJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,SJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:SJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function bJ(e){return e.kind===`do`?bJ(e.head):e}function xJ(e){switch(bJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function SJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function CJ(e,t){return e.has(t)?Xx(e.read(t)):``}function wJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function TJ(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function EJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Hy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Hy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function DJ(e,t){return Math.max(e.members.indexOf(CJ(t,e.stateVar)),0)}function OJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[wJ(e.text,bk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[wJ(e.target,bk(r))]}],active:!1};case`persist-literal`:{let t=CJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=CJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(DJ(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,wJ(e.name,bk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=bk(r),n=JSON.stringify({run:e.argv.map(e=>wJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,wJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,MI(e.op)]}],active:!1};case`do`:{let o=OJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>OJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,MI(r)]}],active:!1}}}}function kJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,DJ(t,r)),boundValue:void 0};if(n.length>2)throw Error(`action "${e}" takes a display and an optional bound value, got ${n.length} arguments (per-state displays are a cycle action's form)`);return{display:n[0],boundValue:n[1]?.plain}}function AJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=mJ(n,`action "${e}"`).store,{display:a,boundValue:o}=kJ(e,bJ(r),t,i),s=CJ(i,`session.id`),{effects:c,active:l}=OJ(r,a.plain,o,i,s,n.signer);return EJ(a,pi(c),l)}function jJ(e){return{action:{fn:(t,...n)=>AJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function MJ(e,t){return TJ(`✕`,pi([{verb:Rr,args:[CJ(e,`session.id`),t,yi]}]),!1)}function NJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function PJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function FJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function IJ(e,t,n){return V.combine([NJ(e,t,n),FJ(e,t,n)])}function LJ(e,t,n){return NJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function RJ(e){let t=z.fromRgba(Bh(e,`background`)),n=W.fromFragments(mh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Bh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const zJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},BJ=e=>new V({bold:e});function VJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>zJ(a,V.combine([LJ(e,{...n,distribution:t},i),BJ(o)]));let o=NJ(e.palette,a,i);return(e,t,i,a)=>HJ(i,V.combine([o,BJ(a)]),r(t,n))}const HJ=(e,t,n)=>zJ(W.fromFragments([zJ(e,t),zJ(` `,t),RJ(n)]));function UJ(e,t){return t===void 0?(e,t,n)=>zJ(n):(n,r,i)=>HJ(i,void 0,t(r,e))}function WJ(e,t,n,r,i){let a=NJ(e.palette,i,r);return(e,r,i,o)=>zJ(W.fromFragments([zJ(o?`[`:` `,a),RJ(n(r,t)),zJ(o?`]`:` `,a)]))}function GJ(e,t,n){let r=t.map(t=>({label:t.label,indices:e.flatMap((e,n)=>e.group===t.id?[n]:[])})).filter(e=>e.indices.length>0);if(r.reduce((e,t)=>e+t.indices.length,0)!==e.length){let n=new Set(t.map(e=>e.id)),r=e.flatMap((e,t)=>n.has(e.group)?[]:[`#${t} (group "${e.group}")`]);throw Error(`library: ${r.join(`, `)} name a group the domain does not list (${[...n].join(`, `)})`)}return n?r.flatMap(e=>KJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function KJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function qJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function JJ(e){return{current:null,drawnAt:e}}function YJ(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function XJ(e,t,n){return QJ(e,()=>n(YJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function ZJ(e,t){return QJ(e,()=>(e.current=null,t()))}function QJ(e,t){let n=e.current;try{return t()}finally{e.current=n}}function $J(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function eY(e){return new W(e).cellLength}function tY(e){let{width:t,chromeCols:n,padding:r}=mJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function nY(e){let{padding:t,seamCols:n}=mJ(e,`a row fit`);return Math.max(1,tY(e)-(eY(`✕`)+2*t+n))}function rY(e,t,n){if(!Number.isFinite(t))return e.length>0?[e.map((e,t)=>t)]:[];let r=Math.max(1,t-n),i=[],a=[],o=0;for(let t=0;t<e.length;t++){let n=e[t];a.length===0?(a=[t],o=n):o+1+n<=r?(a.push(t),o+=1+n):(i.push(a),a=[t],o=n)}return a.length>0&&i.push(a),i}function iY(e,t,n){let r=eY(`←`)+1+eY(`→`)+1,i=rY(e,t,n);return(i.length>1?rY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function aY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function oY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function sY(e,t,n){let r=e.compiled.get(t),i=r&&bJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function cY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=mJ(a,`picker`).store,d=CJ(u,`session.id`),f=`stateVar`in t?CJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?nY(a):tY(a):1/0,h=(r.kind===`led`?0:eY(`✕`)+1)+c.reduce((e,t)=>e+eY(t.glyph)+1,0),g=t.library&&{groups:t.library.groups,entries:t.options.map(t.library.entry)},_=g===void 0?t.options.map((e,t)=>p(t,e)):[],v=g===void 0?iY(_.map(e=>e.cellLength),m,h):GJ(g.entries,g.groups,i),y=parseInt(CJ(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>pi([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>pi([...OJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>EJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[TJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>TJ(e,pi([...OJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(TJ(`←`,te(x-1),!1));let w=x<v.length-1?[TJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[aY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[aY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(aY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>eY(t.options[e])));for(let r of e.indices){let e=t.options[r],a=g.entries[r].description,o=a===void 0?void 0:Ny(a),s=` `.repeat(n-eY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(aY([ae(p(r,qJ(c,m)),r)],i))}}return ce}function lY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ZO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=oY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=sY(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=$J(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=cY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,VJ(u,kh(void 0),hJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),FJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function uY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function dY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function fY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=mJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=CJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return aY([],!0);let d=CJ(o,t.stateVar),f=uY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=pi(OJ(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=EJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):EJ(UJ(hJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(OJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=dY(e=>v(e).cellLength,u,eY(`◀`)+1+y.cellLength+1+eY(`▶`),nY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return aY([...ee(-1).reverse(),TJ(`◀`,h(-1),!1),y,TJ(`▶`,h(1),!1),...ee(1)],!0)}function pY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ZO(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&xJ(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=sY(e,n,`carousel`),l=$J(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return fY(n,c,e,VJ(l,kh(void 0),hJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function mY(e,t,n){let r=sY(e,t,n);if(!(`stateVar`in r))throw Error(`${n} references action "${t}", which inserts a segment and holds no current value — a ${n} needs a { set, from } or { persist, from } action`);if(r.paletteOf===void 0)throw Error(`${n} references action "${t}", whose options are not colour-valued — a swatch draws the palette an option puts in force, as the "themes", "placementThemes" and "styles" domains do`);return r}function hY(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function gY(e,t,n,r){let i=mY(e,t,n),a=r??CJ(mJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,hJ(e,`{{ ${n} }}`))}function _Y(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ZO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return RJ(gY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function vY(e,t,n){return{swatches:{fn:(r,i)=>{let a=mY(e,r,`swatches`),o=oY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=$J(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=cY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,WJ(s,hJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),FJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=uY(l,CJ(mJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[hY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const yY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function bY(e,t,n,r){let i=ug(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Xh(e,n,r)});return[[wh(t).map((n,i)=>{let a=Vh(e,n);return{text:yY[i%yY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Bh(e,`warning`)),a(`error`,Bh(e,`error`))]]]}function xY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:PJ({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function SY(e,t,n,r,i){let a=bY(e,t,n,r).map(e=>xY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
195
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function CY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ZO(`themePreview`,[`applyAction`],i),r!==void 0&&typeof r!=`string`)throw Error(`themePreview: applyAction must name a declared action, got ${JSON.stringify(r)}`);let{palette:a,decor:o}=hJ(e,`{{ themePreview }}`);return SY(r===void 0?a:gY(e,r,`themePreview`),o,{...$J(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),nY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const wY=e=>e.slice(e.lastIndexOf(`.`)+1),TY=(e,t)=>{let n=new W(wY(e));return n.truncate(t,{marker:`…`}),n.plain};function EY(e,t){let n=e.map(e=>e.map(({name:e})=>eY(wY(e)))),r=e=>n.every(n=>n.reduce((t,n)=>t+Math.min(n,e)+2,0)<=t),i=Math.max(1,...n.flat());for(;i>1&&!r(i);)--i;return i}function DY(e,t,n,r){let i=EY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${TY(s,i)} `,{style:PJ(Ng(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
196
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}const OY=`layoutPreview`;function kY(e,t){return{[OY]:{fn:()=>DY(gJ(e,`{{ layoutPreview }}`),hJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),nY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function AY(e,t,n,r){let i=$J(r.activeSegment,`{{ menu }}`),a=r.action,o=SA(i.placementId,e,n.key),s=TA(o),c=xA(e),l=mJ(a,`menu`).store,u=CJ(l,o)===c,d=CJ(l,`session.id`),f=u?yi:c,p=TJ(Si(`{{ menu "${e}" }}`,t,2,+!!u),pi([{verb:Rr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=ug(i.palette,i.disclosure,t).plane,l=sY(a,e,`menu`);return cY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,yi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,VJ(i,n.distribution,hJ(a,`{{ menu }}`),l.paletteOf,t,c),FJ(i.palette,c,t))})():[]),p}const jY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function MY(e,t){let n=t[t.length-1],r=jY(n)?n:void 0,i=r===void 0?t:t.slice(0,-1),a=i.findIndex(e=>typeof e!=`string`);if(a!==-1)throw Error(`{{ menu "${e}" }} display #${a+1} is not text (${JSON.stringify(i[a])}) — a menu binds its trigger text, then an optional trailing (dict …) of options`);return{displays:i,options:kA(r??{})}}function NY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=MY(t,n);return AY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function PY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=FY(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function FY(e,t,n){return!Number.isFinite(e)||!Number.isFinite(t)||t<=0?0:Math.min(n,Math.max(0,Math.round(e/t*n)))}function IY(e){let t={fn:(()=>{let t=$J(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>$J(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=$J(e,`{{ keptOn }}`),i=El(r,t),a=El(r,n),o=_c(Ll(i,R.TRUECOLOR),Ll(a,R.TRUECOLOR)),s=Math.min(Yh,Math.max(o,3));return(Il(i,e.drawnAt(),(e,t)=>_c(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=FO(()=>$J(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...LY(s)];return PY({value:e,max:t,width:n,filled:r,empty:a,colourAt:c===void 0?void 0:e=>String(i.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...i,bgOf:t,tint:n,keptOn:r,gauge:a}}function LY(e){return e.flatMap(e=>{let t=e.indexOf(`:`),n=t<0?NaN:Number(e.slice(0,t));if(!Number.isFinite(n))throw Error(`{{ gauge }} stop "${e}" must be "<position>:<colour>", e.g. "80:error" or "80:#ff0000"`);return[n,e.slice(t+1)]})}function RY(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>vk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const zY={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},BY=new WeakMap;function VY(e){let t=BY.get(e);return t===void 0&&(t=HY(e),BY.set(e,t)),t}function HY(e){let t=new Map(zx(e)),n=iB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:zY[t.kind]])),i=new Map([...t].map(([e,t])=>[e,RY(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function UY(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
197
197
|
`)){n.push(r);continue}let e=r.split(`
|
|
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 PY(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 FY=e=>e.kind===`failed`?Hq:e;function IY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function LY(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 RY(e){return{...e,cells:e.cells.map(Jq)}}function zY(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,...BY(e,r)]}function BY(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 VY(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:zY(e.direction,e.children.map((t,i)=>n(t,[...r,HY(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function HY(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const UY={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:kh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,D_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),zY(e.direction,e.children.map((n,r)=>t.renderChild(n,FY(t.gate),HY(e,r))))}},WY={drop:e=>e.place,above:()=>`above`},GY={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},KY={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:S_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,O_(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,qY(e,t))};function qY(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=Sk(t.scope,e.settings);if(t.gate.kind===`failed`)return $Y(e,r,t,t.gate.message);try{let i=t.placement(e),a=IY(t.gate,i.gate());if(a.kind===`failed`)return $Y(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 $Y(e,r,t,s.message);let c=jb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Fj(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`?JY(f.variable):YY(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?XY(p.segment,u):ZY(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:Hq,h.disclosure).map(e=>({...e,place:WY[v.placement](e)})),b=(e,t,n)=>Zq(tJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?GY[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(QY(qq(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(qq)),[...ie,...re]}catch(n){return $Y(e,r,t,n.message??String(n))}}const JY=e=>({kind:`waiting`,variable:e});function YY(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=eS(e);if(t===void 0)throw e;return JY(t.variable)}}function XY(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:NY(tJ(r,c)).map((e,t)=>({cells:Zq(e,{...l,lead:t===0?tJ(i,c):[],trail:t===0?tJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:Zq(tJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function ZY(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=tJ(eX(e.lead,e,t,n),l),d=tJ(eX(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 Zq(tJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function QY(e){return e.reduce((e,t)=>e+t.cellLength,0)}function $Y(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:Zq([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Fj(n.palette)},lead:eX(e.lead,e,t,n),trail:eX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function eX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=eS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const tX={container:UY,segment:KY};function nX(e){return tX[e]}var rX=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?iX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const iX={kind:`hidden`},aX={palette:`theme`,style:`style`,effect:`effect`},oX=Dy.get(`colorCompatibility`),sX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function cX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function lX(e){if(e.ok)return e.value;throw e.error}const uX=e=>({read:()=>e}),dX=fh({basePalette:dh,palette:dh,decor:Eg});var fX=class{evaluated=0;memory=new rX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&dX(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=bk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(oX);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(sX,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 VY(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=vI(e);return i===void 0?[]:[{name:i,address:n,palette:jb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>d_(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=nA(e);return t===void 0?eA(e)===void 0?Uk(this.view.get().payload(),e):Uk(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()[aX[e]];if(t.kind===`decided`)return hX(t.name,null,null);let r=_X(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=vX(this.source,e,i.name,r.where,e=>{t=e}),hX(n,t,null)}case`pending`:return hX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],hX(n,Qg(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!gX(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)??Zg[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 Wq(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>VJ(this.source.activeSegment,()=>Wq(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new yX(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:sJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=eS(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:cX(e)}),lX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:vI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function pX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new fX(t,n,e,r);return e.views.set(t,a),a}function mX(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 hX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),gX=(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 _X(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 vX(e,t,n,r,i){switch(t){case`palette`:return Ib(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var yX=class{where=bX(fh({palette:dh,region:wg}));ground=bX(fh({colours:SX,bodyOpen:dh}));opened=bX(fh({colours:SX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Sk(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?uX(Uq):e.derive(`${t.id} when`,e.readsInstant(a),()=>VJ(r,()=>Wq(a,i))),this.open=d===void 0?uX(Hq):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>VJ(r,()=>Wq(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return TX(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 EX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?uX(OX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return DX(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}),AX(n,r,this.affixes.read())}};function bX(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 xX=(e,t)=>e.hex===t.hex,SX=fh({palette:dh,drawnAt:dh,tint:xX,text:xX,bg:xX,disclosure:Dg});function CX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const wX=e=>ug(e.palette,e.disclosure,e.drawnAt);function TX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return BJ(e,CX(t,c),e=>{let t=Lj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function EX(e,t,n,r,i,a){return BJ(e,CX(t,n),e=>(e.bg=i?wX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function DX(e,t,n,r,i,a,o){return BJ(e,CX(t,n),e=>(e.bg=r?wX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const OX={lead:[],trail:[],drops:[]};function kX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return CJ(t,wX(e).state,n)},get band(){return CJ(t,wX(e).plane,n)},get close(){return EJ(t,wX(e).state,n)},disclosure:r}}function AX(e,t,n){return{styles:kX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?wX(e).shortfalls:[]}}function jX(e,t,n,r,i,a,o){let s=TX(e,t,n,r,i,void 0,void 0,o);return AX(s,EX(e,t,s,a,!1,o),OX)}function MX(e,t,n,r,i){return kX(TX(e,t,n,r,i,void 0,void 0,{}))}function NX(e,t){return{payload:()=>e,selections:()=>t}}function PX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:jk(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 FX(e,t){switch(j_(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 IX(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:PX(n.cache),parse:FX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:PX(n.cache),parse:FX(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 LX(e,t){let n=HS.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 RX(e,t,n){let{compiled:r,loadWarnings:i}=BX(e,t,n.cwd,zX(n.signer),WX);return{...r,loadWarnings:i}}const zX=e=>(t,n)=>GX(n,e);function BX(e,t,n,r,i=WX){let a=VX(e),o=HX(a);return{compiled:r(o,a),compileKey:o,loadWarnings:UX(e,t,n,i)}}function VX(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Oy)n in t&&r.set(e,n);for(let[t,n]of L_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...nB(e)].sort(([e],[t])=>e<t?-1:1)}}function HX(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function UX(e,t,n,r){let i=jY(e),a=nB(e),o=[];for(let[s,c]of zx(e))if(r.has(i.get(s)))try{IX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const WX=new Set([`directory`,`view`]);function GX({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>iJ(i,`drawnAt`).registry.drawnAt(),o=RJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Qb(e.presets),u=sI(e),d=[e=>cY(i,o,e.now)],f=yk({extraFuncs:{...xJ(i),...sY(i),...$J(i,o),...rY(i,o),...pY(i,o),...yY(i,o),...CY(s),...EY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=LX(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=cJ(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=V_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>q_(t,e,a,t=>String(iJ(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}=tx(e,t);S.set(t,x(n,r))}let te=new Map(Ug.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of iB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:JX(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:Jz({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:gk(d)},re=sB(ne),ie=[...S.values()].flatMap(qX(y)).some(e=>re(m.get(e))),ae=ie?sB({...ne,clock:new Set([...ne.clock,vY])}):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 KX(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 qX=e=>t=>{let n=[];return VY(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 JX(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 YX=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function XX(e,t,n,r,i){let a=ZX(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function ZX(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Zg[e];case`failed`:return r({kind:`rule`,slot:e,message:Qg(t.where,e,`the rule failed — ${n.error}`)}),Zg[e]}}function QX(e){return $X(e).filter(e=>!e.name.startsWith(uA)).map(e=>e.id)}function $X(e){return e.kind===`container`?e.children.flatMap($X):[e,...e.opens===void 0?[]:$X(e.opens.body)]}function eZ(e,t,n,r,i,a,o,s,c=kH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return pX(t,n,r,NX(l,c)),nZ(e,t,n,r,l,a,o,s,c)}function tZ(...e){return eZ(...e).text}function nZ(e,t,n,r,i,a,o,s,c){try{var l=Aa();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new $y(``),g=h.clockAt(a,e_[c.animationSpeed]);l.u(sk(a,g.anim));let _=mX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:sb(v),padding:v.padding,seamCols:cb(v),preset:c.preset},i);let y=_.evaluated;l.u(sJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Ch[c.variation],shade:xh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,LY),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=vX(t,e,XX(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:Ib(C(`palette`),``,YX),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Nb(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Jv(c.idleSince,c.menuTimeout,a),pe=Bh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Xh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:LY,hold:RY},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:IY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${QX(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(jX(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,jg(a,n)),renderBody:(e,t,n)=>ye(e,t,Mg(n)),closeDisclosure:e=>SJ(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)=>MX(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 "${Xb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=PY(ye(be,Uq,Ag(x))).map(({line:e,row:t})=>{let n=eJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...fb(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||$X(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
|
-
`),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*
|
|
200
|
-
`)||null}function hZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=ZV(t.layers,bH,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??bH,l=a.find(e=>e.path===t.home)?.raw??{},u=new pS,d=new qk(u,o.globals.default_empty_value??``,r.sessionState),f,p;try{f=BX(o,d,e,r.compile??zX(r.signer),yZ),n.push(...f.loadWarnings);let t=d.view();n.push(...UX(o,t,e,bZ)),t.dispose(),dU(o),VI(o),p=gZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:fq(o),authoredRoots:fZ(c,l),fileHeldSettings:ZH(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>aZ(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 gZ(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 _Z(e,t,n,r){let i=RV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[UV(e,t),VV(i)],s,c=null;try{s=hZ(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Z_&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:mZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:mZ(o),state:s,error:null}}function vZ(e,t,n){return hZ(e,{layers:[],home:``,projectDir:t},[],n)}const yZ=new Set([`directory`]),bZ=new Set([`view`]);function xZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new oZ;UX(e.config,l,t,bZ);let d=()=>OH(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)}`),Sq(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()});pX(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 SZ=class{entries=new Map;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??{}}compileOf(e,t){return this.compiles.get(e)??GX(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=dZ(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`,lZ(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??vZ(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${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=Aa();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(dZ(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=xZ(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;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 _Z(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`,uZ(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`,lZ(n.layers,n.state));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)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=pZ(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 CZ=16384,wZ={entries:0,held:0,refreshes:{first:0,period:0,change:0,supersede:0},failures:0},TZ={...wZ,folders:0,faults:{unusable:0,refused:0,error:0},lost:0};var EZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;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<CZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%CZ}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,refreshes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{tmux:wZ,autocompact:{entries:0,refreshes:{request:0},failures:0},cache:{entries:0,refreshes:{request:0},failures:0},today:wZ,pluginStorage:TZ},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},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 DZ(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 OZ={load:()=>({}),save:()=>{},flush:()=>{}};var kZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=OZ,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 AZ(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 jZ=class{timer=null;pending=null;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 AZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const MZ=new Set([`1`,`true`]),NZ=new Set([`0`,`false`,``]);function PZ(e,t){let n=aQ(e),r=n.scope===`segment-palette`?`string`:yy(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(MZ.has(t))return`true`;if(NZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function FZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function IZ(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 LZ(e){return/^\s*$/.test(e)?null:Ui(e)}function RZ(e,t){return e!==null&&Gi(e,t)!==void 0}function zZ(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(zZ),...i}}return e}function BZ(e){if(!Hb(e))return zZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,zZ(t)])),...n}}const VZ=vH,HZ=VZ.segments,UZ=VZ.presets,WZ=VZ.root;function GZ(e,t,n,r){if(!RZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function KZ(e,t){let n=dj(t);return t.scope===`segment-palette`&&GZ(e,[`segments`,t.segment],HZ[t.segment],n.join(`.`)),n}function qZ(e){return Ui($i(e))}function JZ(){return Object.entries(WZ.rows).map(([e,t])=>{let n=zZ(t);return{path:[`root`],fragment:qZ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function YZ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function XZ(e,t){if(t===void 0)return null;let n=BZ(t);return{path:e,fragment:qZ(n),unit:{path:e,value:n}}}function ZZ(e,t){let n=[`presets`,t],r=[...n,`root`],i=UZ[t];GZ(e,n,i,r.join(`.`));let a=YZ(e,r)??XZ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function QZ(e,t){let n=ya(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 $Z(e,t){return[...JZ(),YZ(e,[`root`]),ZZ(e,t)].filter(e=>e!==null).reduce(QZ,new Map)}function eQ(e,t,n){for(let{node:r,...i}of $Z(e,t).values())if(Sa(r,n))return i;throw new q(`${tQ(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 tQ(e,t){return ZZ(e,t)?.path??[`root`]}function nQ(e,t){return t.scope===`preset-root`?tQ(e,t.preset):dj(t)}function rQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function iQ(e){let t=uj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function aQ(e){let t=iQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function oQ(e,t,n,r,i){i(t,n,_Q(t,r)),IZ(t.path,r,e.logger),e.record(t.path,n,r)}function sQ(e,t,n){let r=uQ(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 cQ=()=>{};function lQ(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 uQ(e,t,n){let r=dQ(e,t);if(r===null)return[];let i=new Set(hQ(mQ(r),mQ(n)));return hQ(pQ(e,r),pQ(e,n)).filter(e=>!i.has(e))}function dQ(e,t){try{return fQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function fQ(e,t){return ZV(t===null?e.above:[e.path,...e.above],bH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function pQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function mQ(e){return e.layers.at(-1)?.config??e.base}function hQ(e,t,n=``){return!gQ(e)||!gQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>hQ(e[r],t[r],n===``?r:`${n}.${r}`))}function gQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function _Q(e,t){try{return fQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function vQ(e,t){let n=aQ(t),r=LZ(FZ(e)??``),i=r===null?void 0:Gi(r,dj(n));return i!==void 0&&`value`in i?i.value:void 0}function yQ(e,t,n){bQ(e,t,n,[])}function bQ(e,t,n,r){let i=FZ(t.path),a=n.reduce((e,[t,n])=>pa(e,KZ(LZ(e),aQ(t)),PZ(t,n),Zi),i??``);oQ(e,t,i,lQ(t,()=>xQ(a,t.path,r,e=>e)),sQ)}function xQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=eQ(LZ(s),n,i),l=Ea(rQ(s,c),c.path,i,a,$i(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 SQ(e,t,n){let r=LZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of $Z(r,t)){if(!Sa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qi(e,c):$i(s.value);if(a!==`#`)return pa(e,[...i,`rows`,a],l,Zi);if(ZZ(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 pa(e,i,l,Zi)}return e}function CQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!SH(t[1])?2:0)}function wQ(e,t,n){let r=n.map(iQ),i=FZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>CQ(e,nQ(LZ(e),t)),i);a!==i&&oQ(e,t,i,a,cQ)}function TQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function EQ(e,t){let n=new Set([...xH,...TQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(oA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(oA(e)))}function DQ(e,t,n,r,i,a){let o=FZ(t.path),s=LZ(o??``),c=EQ(s,t),l=[`presets`,c],u=lQ(t,()=>ZZ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qi(o??``,u.fragment):$i(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$i(r)]]],f=i.map(([e,t])=>{let n=lj(c,e);return[KZ(s,aQ(n)),PZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return oQ(e,t,o,lQ(t,()=>xQ(p,t.path,a.map(e=>({...e,preset:c})),SQ)),sQ),c}function OQ(e,t,n,r){let i=FZ(t.path);oQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),sQ)}function kQ(e,t,n){if(SH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=FZ(t.path),a=LZ(i??``);if(i===null||a===null||Gi(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=Gi(a,[`globals`,`preset`]);oQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>CQ(e,t),i),cQ)}function AQ(e,t,n,r){let i=iQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=FZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=lQ(t,()=>eQ(LZ(a??``),i.preset,o)),c=rQ(a??``,s),{after:l,placed:u}=jQ(c,s.path,r,()=>{let e=_Q(t,c).config;return Qb(e.presets).map(t=>tx(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 oQ(e,t,a,l,sQ),u}function jQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=OI(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const MQ={load:()=>({}),save:()=>{}},NQ=new Set(wy.map(e=>e.sessionKey)),PQ=e=>NQ.has(e)||e.startsWith(Cj),FQ=8*1024*1024,IQ={past:[],future:[]},LQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var RQ=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=MQ){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)??IQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??IQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(LQ(n));r.set(LQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:DZ(this.sessionState,e=>PQ(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:KQ(i,n),o=r.get(e),s=o===void 0?a:XQ(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`,JQ(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(LQ)),a=n.net.filter(e=>!i.has(LQ(e))),o=VQ(ZQ(YQ(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($Q).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=VQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...UQ(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(LQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:ZQ(n,t),future:ZQ(i,t),...a!==void 0&&{savepoint:{at:ZQ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(LQ(e))),below:ZQ(a.below,t)}}}),new q(`${r}: ${o.map($Q).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):FZ(t.file)}write(e,t,n){t.kind===`file`?IZ(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||zQ(n)>FQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,BQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${FQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function zQ(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 BQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...UQ(n,1,[])}:{past:e,future:t.slice(1),...UQ(n,0,[])}}function VQ(e){return e.slice(-50)}const HQ=e=>e===Tj.member;function UQ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:WQ(e.net,n),below:e.below}}}function WQ(e,t){let n=new Map(e.map(e=>[LQ(e),e]));for(let e of t){let t=n.get(LQ(e));n.set(LQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const GQ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function KQ(e,t){let n=[...e.past,t],r=VQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...UQ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...qQ(e.future,a),...i.below]},n.length-r.length,t)}}function qQ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function JQ(e,t){return{past:e.past.slice(0,-1),future:VQ([...e.future,t]),...UQ(e.savepoint,0,GQ(t))}}function YQ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...qQ(r,t.at-i.length),...t.below]}function XQ(e,t){if(HQ(t.after)&&!HQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!HQ(t.after)&&HQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function ZQ(e,t){return e.map(e=>e.filter(e=>!t.has(LQ(e)))).filter(e=>e.length>0)}function QQ(e){return e.map($Q).join(`, `)}function $Q(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function e$(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 t$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(e$))}function n$(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(e$)&&t$(t.below)}function r$(e){if(typeof e!=`object`||!e)return!1;let t=e;return t$(t.past)&&t$(t.future)&&(t.savepoint===void 0||n$(t.savepoint))}function i$(e,t){let n=e=>e.kind===`file`||PQ(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 a$(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(r$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,i$(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 o$=e=>!PQ(e)&&!QN(e)&&e!==`update.dismissed`;var s$=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:DZ(e,o$,(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 c$={inside:()=>[],defaultOf:()=>yi,menus:[]},l$=e=>`${e.key}\0${e.member}`;function u$(e){let t=new Map,n=n=>{let r=`${n.name}\0${S_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:UR(a,S_(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(l$(e))??new Map;n.set(l$(t),t),o.set(l$(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(l$(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 Qb(e.presets))d(tx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ji(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(l$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(l$(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(l$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const d$=new WeakMap;function f$(e){let t=d$.get(e);if(t!==void 0)return t;let n=u$(e);return d$.set(e,n),n}function p$(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 m$(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 h$(e,t,n){let r=(r,i,a)=>{let o=p$(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 g$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function _$(e,t){let n={...e};for(let e of g$)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}}}function v$(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&>(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const y$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function b$(e){let t=e=>({kind:`failed`,reason:e});if(!y$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!y$(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 S$=e=>v$(e,`doctor-marks.json`,{},b$),C$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},w$=(e,t)=>e.includes(t)?e:[...e,t],T$=e=>v$(e,`doctor-clicked-terminals.json`,[],C$);var E$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const D$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},O$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),k$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=O$(e,t);return r===void 0?n:r.projectDir},A$=(e,t)=>O$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function j$(e){let t=new Map;for(let n of e.split(`
|
|
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*
|
|
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 WY(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 GY=e=>e.kind===`failed`?Qq:e;function KY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function qY(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 JY(e){return{...e,cells:e.cells.map(iJ)}}function YY(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,...XY(e,r)]}function XY(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 ZY(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:YY(e.direction,e.children.map((t,i)=>n(t,[...r,QY(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function QY(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const $Y={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:kh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,D_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),YY(e.direction,e.children.map((n,r)=>t.renderChild(n,GY(t.gate),QY(e,r))))}},eX={drop:e=>e.place,above:()=>`above`},tX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},nX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:S_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,O_(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,rX(e,t))};function rX(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=Sk(t.scope,e.settings);if(t.gate.kind===`failed`)return lX(e,r,t,t.gate.message);try{let i=t.placement(e),a=KY(t.gate,i.gate());if(a.kind===`failed`)return lX(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 lX(e,r,t,s.message);let c=jb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Vj(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`?iX(f.variable):aX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?oX(p.segment,u):sX(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:Qq,h.disclosure).map(e=>({...e,place:eX[v.placement](e)})),b=(e,t,n)=>sJ(dJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?tX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(cX(rJ(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(rJ)),[...ie,...re]}catch(n){return lX(e,r,t,n.message??String(n))}}const iX=e=>({kind:`waiting`,variable:e});function aX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=eS(e);if(t===void 0)throw e;return iX(t.variable)}}function oX(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:UY(dJ(r,c)).map((e,t)=>({cells:sJ(e,{...l,lead:t===0?dJ(i,c):[],trail:t===0?dJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:sJ(dJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function sX(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=dJ(uX(e.lead,e,t,n),l),d=dJ(uX(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 sJ(dJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function cX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function lX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:sJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Vj(n.palette)},lead:uX(e.lead,e,t,n),trail:uX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function uX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=eS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const dX={container:$Y,segment:nX};function fX(e){return dX[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?mX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const mX={kind:`hidden`},hX={palette:`theme`,style:`style`,effect:`effect`},gX=Dy.get(`colorCompatibility`),_X={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function vX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function yX(e){if(e.ok)return e.value;throw e.error}const bX=e=>({read:()=>e}),xX=fh({basePalette:dh,palette:dh,decor:Eg});var SX=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&&xX(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=bk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(gX);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(_X,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 ZY(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=wI(e);return i===void 0?[]:[{name:i,address:n,palette:jb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>d_(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=cA(e);return t===void 0?oA(e)===void 0?Yk(this.view.get().payload(),e):Yk(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()[hX[e]];if(t.kind===`decided`)return TX(t.name,null,null);let r=DX(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=OX(this.source,e,i.name,r.where,e=>{t=e}),TX(n,t,null)}case`pending`:return TX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],TX(n,Qg(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!EX(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)??Zg[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 eJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>ZJ(this.source.activeSegment,()=>eJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new kX(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:_J(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=eS(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:vX(e)}),yX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:wI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function CX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new SX(t,n,e,r);return e.views.set(t,a),a}function wX(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 TX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),EX=(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 DX(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 OX(e,t,n,r,i){switch(t){case`palette`:return Ib(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var kX=class{where=AX(fh({palette:dh,region:wg}));ground=AX(fh({colours:MX,bodyOpen:dh}));opened=AX(fh({colours:MX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Sk(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?bX($q):e.derive(`${t.id} when`,e.readsInstant(a),()=>ZJ(r,()=>eJ(a,i))),this.open=d===void 0?bX(Qq):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>ZJ(r,()=>eJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return FX(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 IX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?bX(RX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return LX(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}),BX(n,r,this.affixes.read())}};function AX(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 jX=(e,t)=>e.hex===t.hex,MX=fh({palette:dh,drawnAt:dh,tint:jX,text:jX,bg:jX,disclosure:Dg});function NX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const PX=e=>ug(e.palette,e.disclosure,e.drawnAt);function FX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return XJ(e,NX(t,c),e=>{let t=Uj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function IX(e,t,n,r,i,a){return XJ(e,NX(t,n),e=>(e.bg=i?PX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function LX(e,t,n,r,i,a,o){return XJ(e,NX(t,n),e=>(e.bg=r?PX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const RX={lead:[],trail:[],drops:[]};function zX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return NJ(t,PX(e).state,n)},get band(){return NJ(t,PX(e).plane,n)},get close(){return IJ(t,PX(e).state,n)},disclosure:r}}function BX(e,t,n){return{styles:zX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?PX(e).shortfalls:[]}}function VX(e,t,n,r,i,a,o){let s=FX(e,t,n,r,i,void 0,void 0,o);return BX(s,IX(e,t,s,a,!1,o),RX)}function HX(e,t,n,r,i){return zX(FX(e,t,n,r,i,void 0,void 0,{}))}function UX(e,t){return{payload:()=>e,selections:()=>t}}function WX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Fk(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 GX(e,t){switch(j_(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 KX(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:WX(n.cache),parse:GX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:WX(n.cache),parse:GX(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 qX(e,t){let n=HS.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 JX(e,t,n){let{compiled:r,loadWarnings:i}=XX(e,t,n.cwd,YX(n.signer),eZ);return{...r,loadWarnings:i}}const YX=e=>(t,n)=>tZ(n,e);function XX(e,t,n,r,i=eZ){let a=ZX(e),o=QX(a);return{compiled:r(o,a),compileKey:o,loadWarnings:$X(e,t,n,i)}}function ZX(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of Oy)n in t&&r.set(e,n);for(let[t,n]of L_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...cB(e)].sort(([e],[t])=>e<t?-1:1)}}function QX(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function $X(e,t,n,r){let i=VY(e),a=cB(e),o=[];for(let[s,c]of zx(e))if(r.has(i.get(s)))try{KX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const eZ=new Set([`directory`,`view`]);function tZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>mJ(i,`drawnAt`).registry.drawnAt(),o=JJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=Qb(e.presets),u=pI(e),d=[e=>vY(i,o,e.now)],f=yk({extraFuncs:{...jJ(i),..._Y(i),...lY(i,o),...pY(i,o),...CY(i,o),...kY(i,o),...NY(s),...IY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=qX(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=vJ(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=V_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>q_(t,e,a,t=>String(mJ(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 fX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=tx(e,t);S.set(t,x(n,r))}let te=new Map(Ug.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of uB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:iZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:eB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:gk(d)},re=pB(ne),ie=[...S.values()].flatMap(rZ(y)).some(e=>re(m.get(e))),ae=ie?pB({...ne,clock:new Set([...ne.clock,OY])}):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 nZ(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 rZ=e=>t=>{let n=[];return ZY(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 iZ(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 aZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function oZ(e,t,n,r,i){let a=sZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function sZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Zg[e];case`failed`:return r({kind:`rule`,slot:e,message:Qg(t.where,e,`the rule failed — ${n.error}`)}),Zg[e]}}function cZ(e){return lZ(e).filter(e=>!e.name.startsWith(gA)).map(e=>e.id)}function lZ(e){return e.kind===`container`?e.children.flatMap(lZ):[e,...e.opens===void 0?[]:lZ(e.opens.body)]}function uZ(e,t,n,r,i,a,o,s,c=FH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return CX(t,n,r,UX(l,c)),fZ(e,t,n,r,l,a,o,s,c)}function dZ(...e){return uZ(...e).text}function fZ(e,t,n,r,i,a,o,s,c){try{var l=Aa();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new $y(``),g=h.clockAt(a,e_[c.animationSpeed]);l.u(sk(a,g.anim));let _=wX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:sb(v),padding:v.padding,seamCols:cb(v),preset:c.preset},i);let y=_.evaluated;l.u(_J(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Ch[c.variation],shade:xh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,qY),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=OX(t,e,oZ(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:Ib(C(`palette`),``,aZ),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Nb(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Jv(c.idleSince,c.menuTimeout,a),pe=Bh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Xh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:qY,hold:JY},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:KY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${cZ(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(VX(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,jg(a,n)),renderBody:(e,t,n)=>ye(e,t,Mg(n)),closeDisclosure:e=>MJ(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)=>HX(t.activeSegment,e,n,a,r.drawnAt())};return fX(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 "${Xb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=WY(ye(be,$q,Ag(x))).map(({line:e,row:t})=>{let n=uJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...fb(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||lZ(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
|
+
`),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*mZ(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 Qb(e.presets)){for(let n of E_(tx(e,t).node))n.when!==void 0&&(yield n.when);let n=nx(e,t);for(let e of Ug){let t=n[e];Wg(t)&&(yield t)}}for(let[,t]of pZ(e))for(let[,e]of P_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of px(t))yield e}function hZ(e,t){let n=iB(t),r=new Set,i=new Set,a=new Set;for(let e of mZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of jx(e,t.helpers))i.add(n);for(let n of Ix(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 Qb(t.presets))for(let n of E_(tx(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=>!vA(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 gZ=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 _Z(e){return Math.floor(Math.max(e/4,e*or-67108864))}const vZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function yZ(e,{plugins:t,config:n,compiled:r}){let{checkout:i,loaded:a,dropped:o,unreached:s}=t,c=i===null?`-`:`${i.git?`git`:`dir`}:${i.root}`,l=e=>{let t=$B(e),r=t===void 0?void 0:n.variables[tV(t)];return r?.kind===`file`?r.path:`none`},u=a.flatMap(e=>{let t=$B(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>sV(e)(t)&&t!==tV(e))),d=u.filter(([,e])=>e.kind===`source`).length,f=u.length-d;return`config load ${e.join(` < `)||`<default>`}: projections=${[...cB(n).keys()].join(`,`)||`-`} instantSegments=${nZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${a.length} sources=${d} pluginVariables=${f} dropped=${o.length} unplaced=${s.length} checkout=${c}`+a.map(e=>` +${e} data=${l(e)}`).join(``)+o.map(e=>` -${e.path} (${e.reason})`).join(``)+s.map(e=>` ~${e.path} (${e.reason})`).join(``)}function bZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function xZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function SZ(e,t){return new Set(Qb(e.presets).filter(n=>tx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function CZ(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...HV(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))]){let{dir:e,name:r}=Wx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of r){let{dir:t,name:r,leaf:i}=Wx(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 wZ(e){return e.filter(Boolean).join(`
|
|
200
|
+
`)||null}function TZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=rH(t.layers,EH,{entered:i,warned:e=>n.push(...e)},{projectDir:t.projectDir,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??EH,l=a.find(e=>e.path===t.home)?.raw??{},u=new pS,d=new $k(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=XX(o,d,e,r.compile??YX(r.signer),kZ),n.push(...f.loadWarnings);let t=d.view();n.push(...$X(o,t,e,AZ)),t.dispose(),_U(o),qI(o),p=EZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:xq(o),authoredRoots:SZ(c,l),fileHeldSettings:rU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>hZ(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 EZ(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 DZ(e,t,n,r){let i=WV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[YV(e,t),qV(i)],s,c=null;try{s=TZ(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Z_&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:wZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:wZ(o),state:s,error:null}}function OZ(e,t,n){return TZ(e,{layers:[],home:``,projectDir:t},[],n)}const kZ=new Set([`directory`]),AZ=new Set([`view`]);function jZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new gZ;$X(e.config,l,t,AZ);let d=()=>PH(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)}`),Mq(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()});CX(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 MZ=class{entries=new Map;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??{}}compileOf(e,t){return this.compiles.get(e)??tZ(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=xZ(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`,yZ(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??OZ(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${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=Aa();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(xZ(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=jZ(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;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 DZ(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`,bZ(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`,yZ(n.layers,n.state));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)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=CZ(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 NZ=16384;var PZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;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<NZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%NZ}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},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 FZ(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 IZ={load:()=>({}),save:()=>{},flush:()=>{}};var LZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=IZ,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 RZ(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 zZ=class{timer=null;pending=null;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 RZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const BZ=new Set([`1`,`true`]),VZ=new Set([`0`,`false`,``]);function HZ(e,t){let n=pQ(e),r=n.scope===`segment-palette`?`string`:yy(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(BZ.has(t))return`true`;if(VZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function UZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function WZ(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 GZ(e){return/^\s*$/.test(e)?null:Ui(e)}function KZ(e,t){return e!==null&&Gi(e,t)!==void 0}function qZ(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(qZ),...i}}return e}function JZ(e){if(!Hb(e))return qZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,qZ(t)])),...n}}const YZ=wH,XZ=YZ.segments,ZZ=YZ.presets,QZ=YZ.root;function $Z(e,t,n,r){if(!KZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function eQ(e,t){let n=_j(t);return t.scope===`segment-palette`&&$Z(e,[`segments`,t.segment],XZ[t.segment],n.join(`.`)),n}function tQ(e){return Ui($i(e))}function nQ(){return Object.entries(QZ.rows).map(([e,t])=>{let n=qZ(t);return{path:[`root`],fragment:tQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function rQ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function iQ(e,t){if(t===void 0)return null;let n=JZ(t);return{path:e,fragment:tQ(n),unit:{path:e,value:n}}}function aQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=ZZ[t];$Z(e,n,i,r.join(`.`));let a=rQ(e,r)??iQ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function oQ(e,t){let n=ya(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 sQ(e,t){return[...nQ(),rQ(e,[`root`]),aQ(e,t)].filter(e=>e!==null).reduce(oQ,new Map)}function cQ(e,t,n){for(let{node:r,...i}of sQ(e,t).values())if(Sa(r,n))return i;throw new q(`${lQ(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 lQ(e,t){return aQ(e,t)?.path??[`root`]}function uQ(e,t){return t.scope===`preset-root`?lQ(e,t.preset):_j(t)}function dQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function fQ(e){let t=gj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function pQ(e){let t=fQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function mQ(e,t,n,r,i){i(t,n,TQ(t,r)),WZ(t.path,r,e.logger),e.record(t.path,n,r)}function hQ(e,t,n){let r=vQ(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 gQ=()=>{};function _Q(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 vQ(e,t,n){let r=yQ(e,t);if(r===null)return[];let i=new Set(CQ(SQ(r),SQ(n)));return CQ(xQ(e,r),xQ(e,n)).filter(e=>!i.has(e))}function yQ(e,t){try{return bQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function bQ(e,t){return rH(t===null?e.above:[e.path,...e.above],EH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function xQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function SQ(e){return e.layers.at(-1)?.config??e.base}function CQ(e,t,n=``){return!wQ(e)||!wQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>CQ(e[r],t[r],n===``?r:`${n}.${r}`))}function wQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function TQ(e,t){try{return bQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function EQ(e,t){let n=pQ(t),r=GZ(UZ(e)??``),i=r===null?void 0:Gi(r,_j(n));return i!==void 0&&`value`in i?i.value:void 0}function DQ(e,t,n){OQ(e,t,n,[])}function OQ(e,t,n,r){let i=UZ(t.path),a=n.reduce((e,[t,n])=>pa(e,eQ(GZ(e),pQ(t)),HZ(t,n),Zi),i??``);mQ(e,t,i,_Q(t,()=>kQ(a,t.path,r,e=>e)),hQ)}function kQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=cQ(GZ(s),n,i),l=Ea(dQ(s,c),c.path,i,a,$i(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 AQ(e,t,n){let r=GZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of sQ(r,t)){if(!Sa(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?qi(e,c):$i(s.value);if(a!==`#`)return pa(e,[...i,`rows`,a],l,Zi);if(aQ(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 pa(e,i,l,Zi)}return e}function jQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!OH(t[1])?2:0)}function MQ(e,t,n){let r=n.map(fQ),i=UZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>jQ(e,uQ(GZ(e),t)),i);a!==i&&mQ(e,t,i,a,gQ)}function NQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function PQ(e,t){let n=new Set([...DH,...NQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(fA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(fA(e)))}function FQ(e,t,n,r,i,a){let o=UZ(t.path),s=GZ(o??``),c=PQ(s,t),l=[`presets`,c],u=_Q(t,()=>aQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?qi(o??``,u.fragment):$i(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],$i(r)]]],f=i.map(([e,t])=>{let n=hj(c,e);return[eQ(s,pQ(n)),HZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return mQ(e,t,o,_Q(t,()=>kQ(p,t.path,a.map(e=>({...e,preset:c})),AQ)),hQ),c}function IQ(e,t,n,r){let i=UZ(t.path);mQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),hQ)}function LQ(e,t,n){if(OH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=UZ(t.path),a=GZ(i??``);if(i===null||a===null||Gi(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=Gi(a,[`globals`,`preset`]);mQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>jQ(e,t),i),gQ)}function RQ(e,t,n,r){let i=fQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=UZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=_Q(t,()=>cQ(GZ(a??``),i.preset,o)),c=dQ(a??``,s),{after:l,placed:u}=zQ(c,s.path,r,()=>{let e=TQ(t,c).config;return Qb(e.presets).map(t=>tx(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 mQ(e,t,a,l,hQ),u}function zQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=PI(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const BQ={load:()=>({}),save:()=>{}},VQ=new Set(wy.map(e=>e.sessionKey)),HQ=e=>VQ.has(e)||e.startsWith(kj),UQ=8*1024*1024,WQ={past:[],future:[]},GQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var KQ=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=BQ){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)??WQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??WQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(GQ(n));r.set(GQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:FZ(this.sessionState,e=>HQ(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:e$(i,n),o=r.get(e),s=o===void 0?a:i$(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`,n$(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(GQ)),a=n.net.filter(e=>!i.has(GQ(e))),o=YQ(a$(r$(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(s$).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=YQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...ZQ(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(GQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:a$(n,t),future:a$(i,t),...a!==void 0&&{savepoint:{at:a$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(GQ(e))),below:a$(a.below,t)}}}),new q(`${r}: ${o.map(s$).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):UZ(t.file)}write(e,t,n){t.kind===`file`?WZ(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||qQ(n)>UQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,JQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${UQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function qQ(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 JQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...ZQ(n,1,[])}:{past:e,future:t.slice(1),...ZQ(n,0,[])}}function YQ(e){return e.slice(-50)}const XQ=e=>e===jj.member;function ZQ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:QQ(e.net,n),below:e.below}}}function QQ(e,t){let n=new Map(e.map(e=>[GQ(e),e]));for(let e of t){let t=n.get(GQ(e));n.set(GQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const $Q=e=>e.map(e=>({...e,before:e.after,after:e.before}));function e$(e,t){let n=[...e.past,t],r=YQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...ZQ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...t$(e.future,a),...i.below]},n.length-r.length,t)}}function t$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function n$(e,t){return{past:e.past.slice(0,-1),future:YQ([...e.future,t]),...ZQ(e.savepoint,0,$Q(t))}}function r$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...t$(r,t.at-i.length),...t.below]}function i$(e,t){if(XQ(t.after)&&!XQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!XQ(t.after)&&XQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function a$(e,t){return e.map(e=>e.filter(e=>!t.has(GQ(e)))).filter(e=>e.length>0)}function o$(e){return e.map(s$).join(`, `)}function s$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function c$(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 l$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(c$))}function u$(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(c$)&&l$(t.below)}function d$(e){if(typeof e!=`object`||!e)return!1;let t=e;return l$(t.past)&&l$(t.future)&&(t.savepoint===void 0||u$(t.savepoint))}function f$(e,t){let n=e=>e.kind===`file`||HQ(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 p$(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(d$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,f$(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 m$=e=>!HQ(e)&&!iP(e)&&e!==`update.dismissed`;var h$=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:FZ(e,m$,(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 g$={inside:()=>[],defaultOf:()=>yi,menus:[]},_$=e=>`${e.key}\0${e.member}`;function v$(e){let t=new Map,n=n=>{let r=`${n.name}\0${S_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:YR(a,S_(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(_$(e))??new Map;n.set(_$(t),t),o.set(_$(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(_$(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 Qb(e.presets))d(tx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=ji(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(_$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(_$(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(_$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const y$=new WeakMap;function b$(e){let t=y$.get(e);if(t!==void 0)return t;let n=v$(e);return y$.set(e,n),n}function x$(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 S$(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 C$(e,t,n){let r=(r,i,a)=>{let o=x$(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 w$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function T$(e,t){let n={...e};for(let e of w$)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}}}function E$(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&>(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const D$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function O$(e){let t=e=>({kind:`failed`,reason:e});if(!D$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!D$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!GM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${GM.join(` or `)}`)}return{kind:`ok`,value:e}}function k$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const A$=e=>E$(e,`doctor-marks.json`,{},O$),j$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},M$=(e,t)=>e.includes(t)?e:[...e,t],N$=e=>E$(e,`doctor-clicked-terminals.json`,[],j$);var P$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const F$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},I$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),L$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=I$(e,t);return r===void 0?n:r.projectDir},R$=(e,t)=>I$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function z$(e){let t=new Map;for(let n of e.split(`
|
|
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*B$(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 V$={pullRequests:e=>Cq(e).showPullRequest===!0,rateLimits:e=>Sq(e,`block`)||Sq(e,`weekly`)};function H$(e,t){let n=new Map;for(let r of E_(tx(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=>I_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,yq(e,t,n.get(t))])),a=e=>r.filter(t=>V$[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
|
|
202
202
|
/*!
|
|
203
203
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
204
204
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -226,9 +226,9 @@ Config tooling:
|
|
|
226
226
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
227
227
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
228
228
|
*/
|
|
229
|
-
function
|
|
229
|
+
function U$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function W$(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
230
230
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
231
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
231
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=U$(t.toml,t.ptr),i=W$(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
|
|
232
232
|
/*!
|
|
233
233
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
234
234
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -256,7 +256,7 @@ function F$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
256
256
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
257
257
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
258
258
|
*/
|
|
259
|
-
function
|
|
259
|
+
function G$(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
|
|
260
260
|
`:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
|
|
261
261
|
/*!
|
|
262
262
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -285,7 +285,7 @@ function L$(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
285
285
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
286
286
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
287
287
|
*/
|
|
288
|
-
let
|
|
288
|
+
let K$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var q$=class e extends Date{#e=!1;#t=!1;#n=null;constructor(e,t,n){let r=!0,i=!0,a=`Z`,o;if(typeof e==`string`)if(t)prep:{if(t<3){if(+e.slice(11,13)>23){e=``;break prep}t===2?(a=null,e+=`Z`):(o=e.charCodeAt(e.length-1))!==90&&o!==122&&(a=e.slice(e.length-6)),n&&(e=e.slice(0,10)+`T`+e.slice(11))}else t===4&&(e=+e.slice(0,2)>23?``:`0000-01-01T${e}Z`);r=t!==4,i=t!==3}else{let t=e.match(K$);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
|
|
289
289
|
/*!
|
|
290
290
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
291
291
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -313,7 +313,7 @@ let R$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
313
313
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
314
314
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
315
315
|
*/
|
|
316
|
-
function
|
|
316
|
+
function J$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Y$(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function X$(e,t){let n=e.p,r=e.s.charCodeAt(e.p);if(r===91||r===123){e.d--||Q.x(`document contains excessively nested structures. aborting.`,e);let t=r===91?s1(e):o1(e);return e.d++,t}return r===34||r===39?G$(e):r===116?((e.s.charCodeAt(++e.p)!==114||e.s.charCodeAt(++e.p)!==117||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!0):r===102?((e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==108||e.s.charCodeAt(++e.p)!==115||e.s.charCodeAt(++e.p)!==101)&&Q.x(`invalid value`,e,n),e.p++,!1):r===43||r===45?Z$(e,e.p,e.s.charCodeAt(++e.p),44-r,t):e.s.charCodeAt(e.p+4)===45&&e.s.charCodeAt(e.p+7)===45?e1(e,r,t):e.s.charCodeAt(e.p+2)===58?t1(e,r,t):Z$(e,e.p,r,0,t)}function Z$(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||Y$(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return Q$(e,t,16,i);if(a===98)return Q$(e,t,2,i);if(a===111)return Q$(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else J$(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!Y$(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:J$(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):$$(e,c,10,t)}function Q$(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Y$(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):J$(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),$$(e,o,n,t)}function $$(e,t,n,r){if(e.bi!==!0)int:{let i=parseInt(t,n);if(!Number.isSafeInteger(i)){if(e.bi)break int;Q.x(`integer value cannot be represented losslessly`,e,r)}return i}return BigInt(n===10?t:(n===2?`0b`:n===8?`0o`:`0x`)+t)}function e1(e,t,n){let r=e.p++,i;if(!J$(t)||!J$(e.s.charCodeAt(e.p++))||!J$(e.s.charCodeAt(e.p++))||!J$(e.s.charCodeAt(e.p++)))return Z$(e,e.p=r,t,0,n);if(e.p+=5,J$(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!J$(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return n1(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;J$(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return n1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return n1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return n1(e,e.s.slice(r,e.p),2,i,r)}function t1(e,t,n){let r=e.p;if(!J$(t)||!J$(e.s.charCodeAt(++e.p)))return Z$(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;J$(e.s.charCodeAt(++e.p)););return n1(e,e.s.slice(r,e.p),4,!1,r)}function n1(e,t,n,r,i,a){if(e.ld){let a=new q$(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
|
|
317
317
|
/*!
|
|
318
318
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
319
319
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -341,7 +341,7 @@ function B$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
341
341
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
342
342
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
343
343
|
*/
|
|
344
|
-
function
|
|
344
|
+
function r1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)break;if(t===13&&e.s.charCodeAt(e.p+1)===10){e.p++;break}(t<32&&t!==9||t===127)&&Q.x(`control characters are not allowed in comments`,e)}}function i1(e,t,n){let r;for(;e.p<e.s.length;){for(;e.p<e.s.length&&((r=e.s.charCodeAt(e.p))===32||r===9||!t&&(r===10||r===13&&e.s.charCodeAt(e.p+1)===10));)e.p++;if(n||r!==35)break;r1(e)}}
|
|
345
345
|
/*!
|
|
346
346
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
347
347
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -369,7 +369,7 @@ function Y$(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
369
369
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
370
370
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
371
371
|
*/
|
|
372
|
-
function
|
|
372
|
+
function a1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return r||Q.x(`unexpected end of key`,e),r===1&&i.push(e.s.slice(a,e.p)),e.p++,i;else o===46?(r||Q.x(`illegal empty bare key`,e),r===1&&i.push(e.s.slice(a,e.p)),r=0):!r&&(o===34||o===39)?(o===e.s.charCodeAt(e.p+1)&&o===e.s.charCodeAt(e.p+2)&&Q.x(`illegal quoted key: multiline strings are not allowed`,e),i.push(G$(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function o1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(i1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=a1(e);for(let n=0;n<c.length;n++){n&&(a=o?a[t]:a[t]=Object.create(null)),t=c[n],(o=Object.hasOwn(a,t))&&(typeof a[t]!=`object`||r.has(a[t]))&&Q.x(`trying to redefine an already defined value`,e,s);let i=t===`__proto__`;if(e.uk&&(i||t===`constructor`)){a=e.uk!==1&&Q.x(`document contains an unsafe property`,e,s);break}!o&&i&&Object.defineProperty(a,t,{enumerable:!0,configurable:!0,writable:!0})}o&&Q.x(`trying to redefine an already defined value`,e,s),i1(e,!0,!0);let l=X$(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),i1(e),(i=e.s.charCodeAt(e.p++))===125)return n;i!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished table`,e,t)}function s1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(i1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(X$(e,93)),i1(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
|
|
373
373
|
/*!
|
|
374
374
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
375
375
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -397,7 +397,7 @@ function Z$(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
397
397
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
398
398
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
399
399
|
*/
|
|
400
|
-
function
|
|
400
|
+
function c1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function l1(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function u1(e,t={}){let n={s:e,p:0,d:t.maxDepth??1e3,bi:t.integersAsBigInt??!1,ld:t.useLegacyDate??!0,uk:t.unsafeKeyBehaviour===`throw`?2:+(t.unsafeKeyBehaviour===`drop`)},r=Object.create(null),i=Object.create(null),a,o=!1,s=r,c=i;for(e.charCodeAt(0)===65279&&n.p++,i1(n);n.p<e.length;){if(e.charCodeAt(n.p)===91){let t=e.charCodeAt(++n.p)===91;a=n.p+=+t,o=!1;let l=a1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=c1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(l1(n,u,a),o=!0)}else{a=n.p;let e=c1(n,a1(n),s,c,0);!e&&!o&&l1(n,e,a),i1(n,!0,!0);let t=X$(n,void 0);e&&!o&&(e[1][e[0]]=t)}i1(n,!0),n.p<e.length&&(a=e.charCodeAt(n.p))!==10&&(a!==13||e.charCodeAt(n.p+1)!==10)&&Q.x(`each key-value declaration must be followed by an end-of-line`,n),i1(n)}return r}``.isWellFormed;
|
|
401
401
|
/*!
|
|
402
402
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
403
403
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -425,7 +425,7 @@ function e1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
|
|
|
425
425
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
426
426
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
427
427
|
*/
|
|
428
|
-
const
|
|
428
|
+
const d1=e=>e.codePointAt(0).toString(16).toUpperCase(),f1=String.raw`
|
|
429
429
|
ObjC.import("AppKit");
|
|
430
430
|
ObjC.import("CoreText");
|
|
431
431
|
function lacksOf(font, points) {
|
|
@@ -472,49 +472,49 @@ function run(argv) {
|
|
|
472
472
|
: iterm(argv[1], points),
|
|
473
473
|
);
|
|
474
474
|
}
|
|
475
|
-
`;function
|
|
476
|
-
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const
|
|
477
|
-
`,`:family=${
|
|
478
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function
|
|
475
|
+
`;function p1(e){let t=D({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,f1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new P$(`the font`);return{kind:`failed`,reason:`osascript failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}let n;try{n=JSON.parse(t.stdout)}catch{return{kind:`failed`,reason:`osascript answered ${JSON.stringify(t.stdout.trim())}, not JSON`}}return typeof n==`object`&&n&&`error`in n?{kind:`failed`,reason:n.error}:{kind:`ok`,value:n}}const m1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),h1=e=>[...e].map(d1).join(`,`);function g1(e,t){let n=p1([`font`,e.kind,e.name,h1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:m1(r)}}}function _1(e,t){if(e.font===null)return{kind:`failed`,reason:`iTerm2 profile ${JSON.stringify(e.name)} names no font`};let n=`iTerm2 profile ${JSON.stringify(e.name)}`+(e.nonAscii?`, its non-ASCII font`:``)+(e.powerline?`, built-in Powerline glyphs on`:``),r=e.lacks===null||!e.powerline?e.lacks:e.lacks.filter(e=>!OM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const v1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function y1(e,t,n){if(e.length===0)return{kind:`failed`,reason:t===null?`iTerm2 has no profiles in its preferences`:`iTerm2 has no profile named ${JSON.stringify(t)}`};let r=e.map(e=>_1(e,n));if(t!==null)return r[0];let i=r.find(e=>!v1(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function b1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=p1([`iterm`,r??``,h1(n)]);return i.kind===`failed`?i:y1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:m1(e.lacks)})),r,e)}function x1(e,t){let n=e.split(`
|
|
476
|
+
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const S1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function C1(e,t){let n=D({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
477
|
+
`,`:family=${S1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new P$(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return x1(n.stdout,t)}function w1(e,t){return process.platform===`darwin`?g1(e,t):C1(e.name,t)}function T1(e,t){let n=t||s.join(e,`.config`);return[s.join(n,`alacritty`,`alacritty.toml`),s.join(n,`alacritty.toml`),s.join(e,`.config`,`alacritty`,`alacritty.toml`),s.join(e,`.alacritty.toml`)]}function E1(e){return e===`darwin`?`Menlo`:`monospace`}const D1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function O1(e){let t=D1(e.font)?e.font:{},n=D1(t.normal)?t.normal:{},r=(D1(e.general)?e.general:{}).import??e.import??[];return{family:typeof n.family==`string`?n.family:null,imports:Array.isArray(r)?r.filter(e=>typeof e==`string`):[]}}function k1(e,t,n){let r;try{r=p.readFileSync(e,`utf8`)}catch(t){return{kind:`failed`,reason:`cannot read ${e}: ${t.message}`}}let i;try{i=u1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=O1(i);if(a.family!==null)return{kind:`ok`,value:{family:a.family,from:e}};if(n===5)return{kind:`ok`,value:null};let o=null;for(let r of a.imports){let i=r.startsWith(`~/`)?s.join(t,r.slice(2)):s.resolve(s.dirname(e),r);if(!p.existsSync(i))continue;let a=k1(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function A1(e,t){let n=C.homedir(),r=T1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:k1(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??E1(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=w1({kind:`family`,name:a},t);if(s.kind===`failed`)return s;let{font:c,lacks:l}=s.value;return{kind:`ok`,value:{font:c,from:c===a?o:`${o}; ${a} as fontconfig matches it`,lacks:l}}}const j1={iterm2:b1,alacritty:(e,t,n)=>A1(t,n)};function M1(e,t,n){return j1[e.name](e.version,t,n)}function N1(e){let t=e?.through;return typeof t==`string`||t===null?{kind:`ok`,value:{through:t}}:{kind:`failed`,reason:`names no post-mortem read`}}const P1=e=>E$(e,`doctor-post-mortems-read.json`,{through:null},N1);function F1(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const I1={realpath:e=>F1(()=>p.realpathSync(e)),checkoutOf:Qe,digest:e=>F1(()=>Ye(e)),nativeShipped:vo(process.platform,process.arch)};function L1(e,t,n){let r=e.realpath(t);if(r.kind===`failed`)return{kind:`failed`,reason:`the daemon's bundle ${t} cannot be resolved: ${r.reason}`};let i=e.checkoutOf(r.value);return{kind:`ok`,value:{daemon:{bundle:r.value,checkout:i===null?null:{root:i,rustSource:e.digest(s.join(i,`rust-client`))}},nativeShipped:e.nativeShipped,clients:n.map(t=>t===null?{kind:`unreported`}:{kind:`reported`,client:t.kind,bundle:e.realpath(t.bundle),source:t.source})}}}const R1=e=>({marks:A$(e),clicked:N$(e),postMortemsRead:P1(e)}),z1=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function B1(e){let t=e.replace(/\n$/,``);if(t===` `)return{kind:`ok`,value:null};let n=t.split(` `),[r,i,a,o,s]=n;return n.length!==5||!/^[1-9]\d*$/.test(o)||!/^[01]$/.test(s)?{kind:`failed`,reason:`tmux answered ${JSON.stringify(e)}, not the five fields asked for`}:{kind:`ok`,value:{features:r.split(`,`).filter(e=>e!==``),termtype:i,termname:a,pid:Number(o),utf8:s===`1`}}}const V1=/^(sshd|mosh-server)\b/;function H1(e,t){let n=z$(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of B$(n,t))if(V1.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function U1(e){let t=D({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new P$(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return H1(t.stdout,e)}const W1=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function G1(e,t){let n=[];for(let r of e.split(`
|
|
478
|
+
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function K1(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=W1.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function q1(){let e=D({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:G1(e.stdout,K1)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function J1(e){let t=NK(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new P$(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:B1(t.stdout)}function Y1(e){return{probeTmux:J1,remoteLogin:U1,fontInUse:M1,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??no(process.platform),install:I1,daemons:q1,forge:e0,transcript:Z1}}function X1(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
479
479
|
`)+1,i=n.lastIndexOf(`
|
|
480
480
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
481
|
-
`)){let t=
|
|
482
|
-
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const
|
|
483
|
-
`);let i=
|
|
481
|
+
`)){let t=zG(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function Z1(e){let t=Ka(e,KM+1);return t.kind===`ok`?P(X1(t.value.buf,t.value.fromStart)):t}function Q1(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const $1={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function e0(e){if(RV(e)===void 0)return{kind:`ok`,value:null};let t=MW(D({bin:`git`,args:[...jW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=LW(t.value);if(n===null)return{kind:`ok`,value:null};let r=AW(n);if(r===null)return{kind:`ok`,value:null};let i=TW[r],a=$1[r],o=a.loginHost(kW(n)),s=D({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return t0(i,o,a.nonZero,s)}function t0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):EW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:SW(r.stderr)}):{kind:`failed`,reason:xW(e,r)}}function n0(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
|
|
482
|
+
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const r0=e=>F1(()=>io(e));function i0(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Xa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:r0(e),bars:t.map(({role:e,frame:t})=>({role:e,frame:t}))});return{origin:o(e,i),elsewhere:[...a.values()].map(({at:e,bars:t})=>o(e,t))}}function a0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function o0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:FM(t),tmuxClient:null};case`inside`:{if(e.client.kind===`failed`)return{kind:`unasked`,reason:e.client.reason};let t=e.client.value;return t===null?{kind:`unasked`,reason:`tmux has no client attached to the pane's session`}:{kind:`seen`,identified:PM(t),tmuxClient:t}}}}function s0(e,t,n,r){if(t.kind!==`seen`)return t;let{identified:i,tmuxClient:a}=t,o=n.terminalEnv;if(i.kind!==`known`)return i;let{name:s,version:c}=i.terminal;if(wM(s))return{kind:`bundling`,name:s,version:c};if(!TM(s))return{kind:`unread`,name:s,version:c};let{ITERM_PROFILE:l,...u}=o??{},d=a===null?{kind:`ok`,value:n.ssh===!0}:e.remoteLogin(a.pid);return{kind:`configured`,name:s,version:c,font:d.kind===`failed`?{kind:`failed`,reason:`whether the terminal is remote could not be asked: ${d.reason}`}:d.value?{kind:`failed`,reason:`the terminal is on the far side of a remote login, so its font is on the machine it runs on`}:e.fontInUse({name:s,version:c},a===null?o??{}:u,r)}}function c0(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Ze};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function l0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function u0(e,t,n,r){return{pullRequests:l0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:l0(t.rateLimits,()=>r)}}function d0(e,t){let n=t.find(e=>e.role===`statusline`);return n===void 0?{kind:`failed`,reason:`the daemon holds no statusline render of session ${e} — none since it started, or dropped for newer sessions' renders, or only a frames display draws it, which reports no width — so no width a statusline client measured is known; run this again once the statusline has redrawn`}:{kind:`ok`,value:{columns:n.termCols,of:{kind:`session`,sessionId:e}}}}function f0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=FH(d.config,r,()=>!1),p=a0(e,t.tmux),m=o0(p,t.terminalEnv),h=[...new Set([...db(f),...ub(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:s0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:n0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:u0(e,H$(d.config,f.preset),n,a),transcripts:Q1(e,o),claudeSettings:i0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Xa(Ya(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function p0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;gt(e,pa($a(e),t.path,JSON.stringify(t.value),Qi));let r=e=>({...e,sources:r0(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||ir(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const m0={connectMs:200,budgetMs:500};async function h0(e){let n=e.includes(`--json`),r=await g0();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${un(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
483
|
+
`);let i=_0(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(T0(r.value))}function g0(){return rn(()=>({kind:`stats`}),m0,e=>`stats`in e?e.stats:void 0)}function _0(e,t=v0){let n=PZ.referenceSnapshot(),r=y0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=x0(e.version,e.sourceDigest??null),a=x0(Ze,et());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const v0=Object.keys(PZ.referenceSnapshot());function y0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!b0(e))return[];if(!b0(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...y0(e[i],t[i],a)):r.push(a)}return r}function b0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function x0(e,t){return`${e} [${t===null?`no digest`:Xe(t)}]`}function S0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function C0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function w0(e){return e<60?`${e}s`:e<3600?`${Math.floor(e/60)}m${e%60}s`:`${Math.floor(e/3600)}h${Math.floor(e%3600/60)}m`}function T0(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${x0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${w0(e.uptimeSec)}`),t.push(` rss ${S0(e.rssBytes)}`),t.push(` heapUsed ${S0(e.heapUsedBytes)}`),t.push(` heapTotal ${S0(e.heapTotalBytes)}`),t.push(` external ${S0(e.externalBytes)}`),t.push(` arrayBuffers ${S0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${C0(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${C0(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} faults ${a}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${S0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${S0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${S0(e.renderCache.accountedBytes)} / ${S0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
484
484
|
`)+`
|
|
485
|
-
`}const
|
|
486
|
-
`).join(` — `));let t=
|
|
487
|
-
`);return{inMode:n!==`0`,screen:r}}function U0(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function W0(e,t){let n=V0(e,`claude-input.type`,U0(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function G0(){return{read:H0,type:W0}}function K0(e){let t=oW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function q0(e){return J0(()=>decodeURIComponent(e))}function J0(e){try{return e()}catch(e){throw e instanceof URIError?new q(`malformed wire encoding: ${e.message}`):e}}function Y0(e,t){let n=D({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const X0=(e,t)=>Y0(q0(e),t),Z0=(e,t)=>{let n=D({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,q0(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},Q0=(e,t)=>Y0(q0(e),t),$0=(e,t)=>Y0(q0(e),t),e2=(e,t)=>{let n=K0(q0(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},t2=(e,t)=>{let[n=``,...r]=J0(()=>di(e)),i=K0(n),a=dU(g2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}a2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},n2=/^-?\d+$/;function r2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const i2=(e,t)=>{let[n=``,r=``,i=``]=J0(()=>di(e)),a=K0(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!n2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=g2(t,a),c=dU(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&n2.test(u)?o2(l,parseInt(u,10)):s2(`step-state`,r,l,mU(s,e=>t.sessionState.get(a,e),r)),f=r2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);a2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function a2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Cj));if(i.length===0)return;let a=WH(g2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function o2(e,t){return Math.max(e.min,Math.min(e.max,t))}function s2(e,t,n,r){if(r===null)return n.min;if(!n2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return o2(n,parseInt(r,10))}const c2=`render-origin`;function l2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function u2(e){return JSON.stringify(e)}function d2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function f2(e,t){let n=m2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function p2(e,t){let n=e.sessionState.get(t,c2);return n===null?null:d2(n)}function m2(e,t){let n=p2(e,t);return n===null?null:l2(n,e.sessionState,t)}function h2(e,t,n){let r=m2(e,t);if(r===null)return;let{path:i}=y2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function g2(e,t){return e.configFor(f2(e,t))}function _2(e,t){let n=p2(e,t);if(n===null)return null;let r=()=>e.lanes.of(l2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function v2(e,t){let n=m2(e,t);return n===null?c$:f$(e.configFor(n))}function y2(e){return BV(e.projectDir,e.cwd,e.configFile??void 0)}function b2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const x2=(e,t)=>{let[n=``,r=``,i=``]=J0(()=>di(e)),a=K0(n),o=f2(t,a),s=t.configFor(o),c=VI(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=y2(o),d=HH(s,e=>t.sessionState.get(a,e),r);yQ(b2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},S2=(e,t)=>{let[n=``,r=``,i=``]=J0(()=>di(e)),a=K0(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!n2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=f2(t,a),c=t.configFor(s),l=VI(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=y2(s),f=HH(c,e=>t.sessionState.get(a,e),r),p=vQ(d.path,f.key),m=typeof p==`number`?o2(u,p):s2(`step-config`,r,u,UI(f.globals,r)),h=r2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);yQ(b2(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},C2=(e,t)=>{let[n=``]=J0(()=>di(e)),r=K0(n),i=f2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=BH(a,o),c=UH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=dU(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});T2(`save`,l,c);let d=y2(i);bQ(b2(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(w2)].join(` `)} → ${d.path} (session=${r})`)},w2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function T2(e,t,n){for(let r of n){let n=t.validate(r.key,G_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const E2=(e,t)=>{let[n=``]=J0(()=>di(e)),r=K0(n),i=f2(t,r),a=t.configFor(i),o=qH(a,e=>t.sessionState.get(r,e)),s=dU(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});T2(`save-preset`,s,o.placements);let l=y2(i),u=DQ(b2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...wy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Sy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(w2)].join(` `)} → ${l.path} (session=${r})`)},D2=(e,t)=>{let[n=``]=J0(()=>di(e)),r=K0(n),i=f2(t,r),a=YH(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=y2(i);OQ(b2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(BH(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=hy.map(e=>Sy[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${hy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},O2=(e,t)=>{let[n=``,r=``]=J0(()=>di(e)),i=K0(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=f2(t,i),o=y2(a);kQ(b2(t,i),o,r),t.reloadConfig(a);let s=Sy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},k2=(e,t)=>{let[n=``,...r]=J0(()=>di(e)),i=K0(n),a=f2(t,i),o=VI(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=y2(a),l=r.map(XH),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);wQ(b2(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function A2(e,t){let n=(e,t)=>[...E_(tx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Qb(t.presets).flatMap(e=>n(t,e).map(t=>wj(oA(e),S_(t)))));return Qb(e.presets).flatMap(t=>n(e,t).map(e=>({member:wj(oA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function j2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[bj]:[]])}const M2=(e,t)=>{let[n=``,r=``,i=``]=J0(()=>di(e)),a=K0(n),o=f2(t,a),s=t.configFor(o),c=VI(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=DI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=y2(o),f=AQ(b2(t,a),d,r,u);t.reloadConfig(o);let p=j2(A2(s,t.configFor(o)),t.sessionState.get(a,bj)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},N2=(e,t)=>{let[n=``]=J0(()=>di(e)),r=K0(n);t.journal.commit();let i=t.history.undo(r);h2(t,r,i),t.dlog(`info`,`undo: restored ${QQ(i)} (session=${r})`)},P2=(e,t)=>{let n=K0(q0(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,dU(g2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},F2=(e,t)=>{let n=K0(q0(e));t.journal.commit();let r=t.history.rewind(n);h2(t,n,r),t.dlog(`info`,`rewind: put back ${QQ(r)||`nothing`} as edit mode found it (session=${n})`)},I2=(e,t)=>{let[n=``]=J0(()=>di(e)),r=K0(n);t.journal.commit();let i=t.history.redo(r);h2(t,r,i),t.dlog(`info`,`redo: re-applied ${QQ(i)} (session=${r})`)},L2=(e,t)=>{K0(q0(e)),t.applyUpdate()},R2=`client-hints`;function z2(e,t){let n=e.sessionState.get(t,R2);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function B2(e,t,n){let r=AN(n);e.sessionState.setBatch(t,KN(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${WN(n.nerdFont,n.marks)} ${PN(n.terminal,n.clicked)} ${FN(n.terminal,n.width)} ${IN(n.install)} ${RN(n.daemon)} ${zN(n.data)} ${UN(n.transcripts)} ${BN(n.frames,n.claudeSettings)} ${HN(n.claudeSettings.origin.sources)} (session=${t})`)}function V2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ik(new Date)),i;try{i=i0(e.doctor,z2(e,t),f2(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:A$(n,r)},r0(t,r),j1(e.doctorStores))}catch(e){throw e instanceof E$?new q(e.message):e}return{...i,urlHandler:e0(e.arrival),install:k1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:H2(e,i)}}function H2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?AM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>w$(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const U2=(e,t)=>{let n=K0(q0(e));B2(t,n,V2(t,n))},W2=(e,t)=>{let n=S0(q0(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},G2=(e,t)=>{let[n=``,r=``]=J0(()=>di(e)),i=K0(n),a=jN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=V2(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=a0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${HM(s.fix)} (session=${i})`),B2(t,i,c.value)},K2=(e,t)=>{let[n=``,r=``,i=``]=J0(()=>di(e)),a=K0(n),o=jN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!zM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${zM.join(` or `)}`);let s=V2(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>x$(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),B2(t,a,{...s,marks:u})},q2=(e,t)=>{let[n=``,r=``]=J0(()=>di(e)),i=K0(n),a=Object.values(t.configFor(f2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=B0(t.claudeInput,z2(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function J2([e=``,t=``,n=``,r=``],i){let a=K0(e),o=f2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=fx(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{..._$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:z2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const Y2=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=J0(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=J2(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},X2=`config-override`,Z2=new Map([[Br,X0],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=K0(J0(()=>decodeURIComponent(e.slice(0,n)))),i=J0(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,X2),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,X2,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,Z0],[Rr,t2],[zr,i2],[Kr,x2],[qr,S2],[Qr,k2],[Jr,C2],[Yr,E2],[Xr,D2],[Zr,O2],[$r,M2],[ei,N2],[ti,I2],[ni,P2],[ri,F2],[Ur,Q0],[Wr,$0],[Hr,e2],[ii,L2],[ai,U2],[oi,G2],[si,K2],[ci,W2],[li,q2],[`run`,Y2]]),Q2=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,Gr]);function $2(e,t){return e4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function e4(e){let t=e.find(e=>Q2.has(e.verb)),n=t===void 0?``:J0(()=>fi(t.value));return n===``?null:n}const t4=(e,t)=>{let n=[],r=!1,i=mi(e),a=e4(i);for(let{verb:e,value:a}of gi(i)){let i=Z2.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a&&$o(t.sessionState,a,n.join(`
|
|
488
|
-
`),ik(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function n4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:_2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>h$(e,e=>v2(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=m2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const r4=new Map([...Z2,[Lr,t4]].map(([e,t])=>[e,n4(t,t=>$2(e,t))]));Object.freeze([...r4.keys()]);function i4(e,t,n){n4((n,r)=>{let i=m$(v2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const a4=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),o4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],s4=[[`workspace.added_dirs`,`string-list`]];function c4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of o4){let i=d4(n,e);if(i==null)t.missingRequired.push(e);else{let n=l4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of s4){let i=d4(n,e),a=i===void 0?r:u4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))a4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function l4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function u4(e){return Array.isArray(e)&&e.every(e=>l4(e)===`string`)?`string-list`:l4(e)}function d4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function f4(e,t){switch(e){case`vars`:return{what:e,vars:p4(t)};case`segments`:return{what:e,segments:v4(t)};case`config`:return{what:e,config:S4(t)}}}function p4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=g4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=m4(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:h4(r.lastUpdatedMs())})}return o}function m4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function h4(e){return e===null?null:Math.max(0,Date.now()-e)}function g4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,_4(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,_4(i));return t}function _4(e){return e.kind}function v4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=b4(n),o=y4(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:x4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function y4(e){let t=new Map;for(let n of Qb(e.presets))for(let r of E_(tx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=S_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function b4(e){let t=[],n=new Set;for(let r of E_(Gb(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function x4(e,t,n){let r=new Set([...Dx(e,t).keys()].flatMap(e=>Bx(e,n)));return Array.from(r).sort()}function S4(e){return e===null?null:e.config}const C4=[`vars`,`segments`,`config`];function w4(e){return typeof e==`string`&&C4.includes(e)}function T4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>kH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Mq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...QH(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read().payload,failures:()=>s.read().failures,effective:()=>o.read(),selections:()=>o.read()}}}const E4={moving:1e3/30,still:1e3},D4=[`data`,`state`,`reload`,`visibility`];function O4(e){return Fv.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function k4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const A4=e=>({resp:e,bytes:JSON.stringify(e)}),j4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,M4=e=>Math.round(1e3/e);var N4=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Vv;let r=t-1,i=this.shown(n);return Bv(e=>{let a=n.rates.get(e);if(a===void 0)return Rv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:M4(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=M4(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:A4(t.resp),statusline:A4(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||j4(i,n).bytes!==j4(r,n).bytes)&&k4(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=j4(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:Qj(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps evaluated=${e.evaluated} woke=${D4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function P4(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const F4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,I4=`#{session_id} #{client_control_mode} #{pane_id}`;function L4(e){let t=new Set;for(let n of e.split(`
|
|
489
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
490
|
-
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function
|
|
485
|
+
`}const E0=e=>({kind:`ok`,value:e}),D0=e=>({kind:`failed`,reason:e});var O0=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const k0=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function A0(e){return k0.test(e)?e:null}function j0(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return E0(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return E0({app:n,missing:D0(`its script could not be read (${r.reason})`)});let i=ko(r.value);return E0({app:n,missing:i===null?D0("its script is not one `cc-candybar install` wrote"):E0([i.node,i.script].filter(t=>!e.exists(t)))})}async function M0(e,t){let n=e.now()+5e3;for(;e.now()<n;){await e.pause();let n=await e.daemon(),r=n.kind===`ok`?n.value.arrivals.find(e=>e.nonce===t):void 0;if(n.kind===`ok`&&r!==void 0)return{kind:`arrived`,handler:r.handler,bar:n.value.version}}return null}async function N0(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Ir}://${ci}/${n}`);return(r===null?await M0(e,n):null)??{kind:`lost`,unopened:r,opener:j0(e)}}function P0(e,t,n){let r=D({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?E0(r.stdout):D0(r.stderr.trim()||r.error||r.reason)}const F0=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ir}://probe"));u.isNil() ? "" : u.path.js`;async function I0(){let e=await g0();if(e.kind!==`ok`)return D0(un(e).split(`
|
|
486
|
+
`).join(` — `));let t=_0(e.value,[`handlerProbes`]);if(t!==null)return D0(t);let{version:n,handlerProbes:r}=e.value;return E0({version:n,arrivals:r})}function L0(){return{platform:process.platform,sockets:{own:St(),handler:Ct()},now:Date.now,nonce:ie,daemon:I0,open:e=>{let t=P0(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=P0(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,F0]);if(e.kind===`failed`)return e;let t=e.value.trim();return E0(t===``?null:t)},script:e=>P0(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Ao(e)]),exists:p.existsSync}}const R0=/^─{20,}/,z0=/^❯(\s|$)/,B0=/›\s*stashed$/;function V0(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>R0.test(e)?[t]:[]).at(-2);return n===void 0||!z0.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function H0(e){if(e.inMode)return{kind:`in-mode`};let t=V0(e);return t===null?{kind:`no-prompt`}:B0.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function U0(e){return/^❯\s*\S/u.test(V0(e)?.prompt??``)}const W0=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function G0(e){return e.screen.some(e=>W0.test(e))}const K0={"in-mode":`the Claude Code pane is in tmux copy mode — leave it (q) and click again`,stashed:`Claude Code is holding a stashed prompt (ctrl+s) — restore or send it, then click again`,"no-prompt":`Claude Code is not at its prompt (a dialog or picker is open) — close it and click again`};function q0(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function J0(e,t,n){let r=q0(t);if(r.kind===`refused`)return r;let i=r.hint,a=H0(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:K0[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function Y0(e,t,n,r){let i=NK(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function X0(e){let t=Y0(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
|
|
487
|
+
`);return{inMode:n!==`0`,screen:r}}function Z0(e,t,n){return[`load-buffer`,`-b`,t,`-`,`;`,...n.length===0?[]:[`send-keys`,`-t`,e,...n,`;`],`paste-buffer`,`-p`,`-d`,`-b`,t,`-t`,e,`;`,`send-keys`,`-t`,e,`Enter`]}function Q0(e,t){let n=Y0(e,`claude-input.type`,Z0(e.pane,`cc-candybar-slash`,[`C-s`]),t);return n.kind===`ok`?{kind:`typed`}:{kind:`refused`,reason:`cc-candybar typed a command moments ago — click again in a second (${n.reason})`}}function $0(){return{read:X0,type:Q0}}function e2(e){let t=fW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function t2(e){return n2(()=>decodeURIComponent(e))}function n2(e){try{return e()}catch(e){throw e instanceof URIError?new q(`malformed wire encoding: ${e.message}`):e}}function r2(e,t){let n=D({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const i2=(e,t)=>r2(t2(e),t),a2=(e,t)=>{let n=D({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,t2(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},o2=(e,t)=>r2(t2(e),t),s2=(e,t)=>r2(t2(e),t),c2=(e,t)=>{let n=e2(t2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},l2=(e,t)=>{let[n=``,...r]=n2(()=>di(e)),i=e2(n),a=_U(w2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}p2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},u2=/^-?\d+$/;function d2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const f2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!u2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=w2(t,a),c=_U(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&u2.test(u)?m2(l,parseInt(u,10)):h2(`step-state`,r,l,bU(s,e=>t.sessionState.get(a,e),r)),f=d2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);p2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function p2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(kj));if(i.length===0)return;let a=XH(w2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function m2(e,t){return Math.max(e.min,Math.min(e.max,t))}function h2(e,t,n,r){if(r===null)return n.min;if(!u2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return m2(n,parseInt(r,10))}const g2=`render-origin`;function _2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function v2(e){return JSON.stringify(e)}function y2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function b2(e,t){let n=S2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function x2(e,t){let n=e.sessionState.get(t,g2);return n===null?null:y2(n)}function S2(e,t){let n=x2(e,t);return n===null?null:_2(n,e.sessionState,t)}function C2(e,t,n){let r=S2(e,t);if(r===null)return;let{path:i}=D2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function w2(e,t){return e.configFor(b2(e,t))}function T2(e,t){let n=x2(e,t);if(n===null)return null;let r=()=>e.lanes.of(_2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function E2(e,t){let n=S2(e,t);return n===null?g$:b$(e.configFor(n))}function D2(e){return KV(e.projectDir,e.cwd,e.configFile??void 0)}function O2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const k2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=b2(t,a),s=t.configFor(o),c=qI(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=D2(o),d=JH(s,e=>t.sessionState.get(a,e),r);DQ(O2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},A2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!u2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=b2(t,a),c=t.configFor(s),l=qI(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=D2(s),f=JH(c,e=>t.sessionState.get(a,e),r),p=EQ(d.path,f.key),m=typeof p==`number`?m2(u,p):h2(`step-config`,r,u,YI(f.globals,r)),h=d2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);DQ(O2(t,a),d,[[f.key,g.value]]),t.reloadConfig(s),t.dlog(`info`,`step-config: ${f.key} ${m}→${g.value} (by ${o}) → ${d.path} (session=${a})`)},j2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=KH(a,o),c=YH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=_U(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});N2(`save`,l,c);let d=D2(i);OQ(O2(t,r),d,u,c),t.reloadConfig(i);for(let e of[...s.map(e=>e.sessionKey),...c.map(e=>e.key)])t.sessionState.clear(r,e);t.dlog(`info`,`save: ${[...u.map(([e,t])=>`${e}=${t}`),...c.map(M2)].join(` `)} → ${d.path} (session=${r})`)},M2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function N2(e,t,n){for(let r of n){let n=t.validate(r.key,G_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const P2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=t.configFor(i),o=$H(a,e=>t.sessionState.get(r,e)),s=_U(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});N2(`save-preset`,s,o.placements);let l=D2(i),u=FQ(O2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...wy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Sy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(M2)].join(` `)} → ${l.path} (session=${r})`)},F2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n),i=b2(t,r),a=tU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=D2(i);IQ(O2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(KH(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=hy.map(e=>Sy[e].sessionKey).filter(e=>!s.has(e));for(let e of c)t.sessionState.clear(r,e);t.dlog(`info`,`save-theme-default: ${a.theme} ${hy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},I2=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=b2(t,i),o=D2(a);LQ(O2(t,i),o,r),t.reloadConfig(a);let s=Sy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},L2=(e,t)=>{let[n=``,...r]=n2(()=>di(e)),i=e2(n),a=b2(t,i),o=qI(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=D2(a),l=r.map(nU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);MQ(O2(t,i),c,u),t.reloadConfig(a);for(let e of d)t.sessionState.clear(i,e);t.dlog(`info`,`reset-config: ${[...u,...d.map(e=>`session:${e}`)].join(` `)} ← ${c.path} (session=${i})`)};function R2(e,t){let n=(e,t)=>[...E_(tx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Qb(t.presets).flatMap(e=>n(t,e).map(t=>Aj(fA(e),S_(t)))));return Qb(e.presets).flatMap(t=>n(e,t).map(e=>({member:Aj(fA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function z2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Ej]:[]])}const B2=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=b2(t,a),s=t.configFor(o),c=qI(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=NI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=D2(o),f=RQ(O2(t,a),d,r,u);t.reloadConfig(o);let p=z2(R2(s,t.configFor(o)),t.sessionState.get(a,Ej)).filter(e=>t.sessionState.get(a,e)!==null);for(let e of p)t.sessionState.clear(a,e);t.dlog(`info`,`apply-layout-op: ${r} ${l.value} → ${d.path} placed=${JSON.stringify(f)} released=${JSON.stringify(p)} (session=${a})`)},V2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n);t.journal.commit();let i=t.history.undo(r);C2(t,r,i),t.dlog(`info`,`undo: restored ${o$(i)} (session=${r})`)},H2=(e,t)=>{let n=e2(t2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,_U(w2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},U2=(e,t)=>{let n=e2(t2(e));t.journal.commit();let r=t.history.rewind(n);C2(t,n,r),t.dlog(`info`,`rewind: put back ${o$(r)||`nothing`} as edit mode found it (session=${n})`)},W2=(e,t)=>{let[n=``]=n2(()=>di(e)),r=e2(n);t.journal.commit();let i=t.history.redo(r);C2(t,r,i),t.dlog(`info`,`redo: re-applied ${o$(i)} (session=${r})`)},G2=(e,t)=>{e2(t2(e)),t.applyUpdate()},K2=`client-hints`;function q2(e,t){let n=e.sessionState.get(t,K2);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function J2(e,t,n){let r=IN(n);e.sessionState.setBatch(t,QN(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${XN(n.nerdFont,n.marks)} ${BN(n.terminal,n.clicked)} ${VN(n.terminal,n.width)} ${HN(n.install)} ${WN(n.daemon)} ${GN(n.data)} ${YN(n.transcripts)} ${KN(n.frames,n.claudeSettings)} ${JN(n.claudeSettings.origin.sources)} (session=${t})`)}function Y2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ik(new Date)),i;try{i=f0(e.doctor,q2(e,t),b2(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:R$(n,r)},d0(t,r),z1(e.doctorStores))}catch(e){throw e instanceof P$?new q(e.message):e}return{...i,urlHandler:c0(e.arrival),install:L1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:X2(e,i)}}function X2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?IM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>M$(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const Z2=(e,t)=>{let n=e2(t2(e));J2(t,n,Y2(t,n))},Q2=(e,t)=>{let n=A0(t2(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},$2=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n),a=LN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=Y2(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=p0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${JM(s.fix)} (session=${i})`),J2(t,i,c.value)},e4=(e,t)=>{let[n=``,r=``,i=``]=n2(()=>di(e)),a=e2(n),o=LN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!GM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${GM.join(` or `)}`);let s=Y2(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>k$(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),J2(t,a,{...s,marks:u})},t4=(e,t)=>{let[n=``,r=``]=n2(()=>di(e)),i=e2(n),a=Object.values(t.configFor(b2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=J0(t.claudeInput,q2(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function n4([e=``,t=``,n=``,r=``],i){let a=e2(e),o=b2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=fx(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...T$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:q2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const r4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=n2(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=n4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},i4=`config-override`,a4=new Map([[Br,i2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=e2(n2(()=>decodeURIComponent(e.slice(0,n)))),i=n2(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,i4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,i4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,a2],[Rr,l2],[zr,f2],[Kr,k2],[qr,A2],[Qr,L2],[Jr,j2],[Yr,P2],[Xr,F2],[Zr,I2],[$r,B2],[ei,V2],[ti,W2],[ni,H2],[ri,U2],[Ur,o2],[Wr,s2],[Hr,c2],[ii,G2],[ai,Z2],[oi,$2],[si,e4],[ci,Q2],[li,t4],[`run`,r4]]),o4=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,Gr]);function s4(e,t){return c4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function c4(e){let t=e.find(e=>o4.has(e.verb)),n=t===void 0?``:n2(()=>fi(t.value));return n===``?null:n}const l4=(e,t)=>{let n=[],r=!1,i=mi(e),a=c4(i);for(let{verb:e,value:a}of gi(i)){let i=a4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a&&$o(t.sessionState,a,n.join(`
|
|
488
|
+
`),ik(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function u4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:T2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>C$(e,e=>E2(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=S2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const d4=new Map([...a4,[Lr,l4]].map(([e,t])=>[e,u4(t,t=>s4(e,t))]));Object.freeze([...d4.keys()]);function f4(e,t,n){u4((n,r)=>{let i=S$(E2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const p4=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),m4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],h4=[[`workspace.added_dirs`,`string-list`]];function g4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of m4){let i=y4(n,e);if(i==null)t.missingRequired.push(e);else{let n=_4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of h4){let i=y4(n,e),a=i===void 0?r:v4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))p4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function _4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function v4(e){return Array.isArray(e)&&e.every(e=>_4(e)===`string`)?`string-list`:_4(e)}function y4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function b4(e,t){switch(e){case`vars`:return{what:e,vars:x4(t)};case`segments`:return{what:e,segments:E4(t)};case`config`:return{what:e,config:A4(t)}}}function x4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=w4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=S4(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:C4(r.lastUpdatedMs())})}return o}function S4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function C4(e){return e===null?null:Math.max(0,Date.now()-e)}function w4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,T4(r));for(let[n,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))t.set(`${n}.${e}`,T4(i));return t}function T4(e){return e.kind}function E4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=O4(n),o=D4(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:k4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function D4(e){let t=new Map;for(let n of Qb(e.presets))for(let r of E_(tx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=S_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function O4(e){let t=[],n=new Set;for(let r of E_(Gb(e.root)))r.kind===`segment`&&e.segments[r.name]&&!n.has(r.name)&&(t.push(r.name),n.add(r.name));for(let r of Object.keys(e.segments))n.has(r)||(t.push(r),n.add(r));return t}function k4(e,t,n){let r=new Set([...Dx(e,t).keys()].flatMap(e=>Bx(e,n)));return Array.from(r).sort()}function A4(e){return e===null?null:e.config}const j4=[`vars`,`segments`,`config`];function M4(e){return typeof e==`string`&&j4.includes(e)}function N4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>FH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Hq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...iU(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const P4={moving:1e3/30,still:1e3},F4=[`data`,`state`,`reload`,`visibility`];function I4(e){return Fv.filter(t=>e[t].subscribers>0).map(t=>{let{subscribers:n,fps:r,shown:i}=e[t];return`${t}:${n}sub/${r}fps/${i?`shown`:`offscreen`}`}).join(`,`)||`-`}function L4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const R4=e=>({resp:e,bytes:JSON.stringify(e)}),z4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,B4=e=>Math.round(1e3/e);var V4=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Vv;let r=t-1,i=this.shown(n);return Bv(e=>{let a=n.rates.get(e);if(a===void 0)return Rv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:B4(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=B4(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:R4(t.resp),statusline:R4(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||z4(i,n).bytes!==z4(r,n).bytes)&&L4(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=z4(e.last.answers,t.lane);e.followers.get(t)!==r&&(t.frame(n,r),e.followers.set(t,r))}refuse(e,t){this.refused++,this.deps.log(`info`,`feed sid=${JSON.stringify(e)} refused lane=${t.lane} switched-off`),t.refused({ok:!1,error:iM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=Ak.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps evaluated=${e.evaluated} woke=${F4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${i} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function H4(e){let t=null;return e.on(`drain`,()=>{let n=t;t=null,n!==null&&e.write(n)}),n=>{if(e.writable){if(e.writableNeedDrain){t=n;return}e.write(n)}}}const U4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,W4=`#{session_id} #{client_control_mode} #{pane_id}`;function G4(e){let t=new Set;for(let n of e.split(`
|
|
489
|
+
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function K4(e,t){let n=new Set;for(let r of e.split(`
|
|
490
|
+
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function q4(e,t){let n=new Map;for(let t of e.split(`
|
|
491
491
|
`)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
|
|
492
|
-
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var
|
|
493
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
494
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=f3(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[s3(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${W4} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,d3(n));if(r===null||this.closed)return null;let i=p3(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,q4(r),e])}),i!==n.status){let e=X4(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,U4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,n3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,m3(n));if(i===null)return;let a=h3(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,_3);if(r===null||this.closed)return;let i=v3(r[0]??``);if(n.kind===`none`&&x3(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&x3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...G4,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${t3(`${this.deps.handler} ${b3(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,_3);if(r===null)return;let i=S3(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=S3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,i3(t));return n.kind===`ok`?a3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,i3(t)));return n.kind===`ok`?a3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,e3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,e3(t),n)))}};const w3=`CC_CANDYBAR_CONFIG`;function T3(e,t){return HB(t,e[w3])}const $=e=>({arity:e,keep:!0}),E3=e=>({arity:e,keep:!1}),D3={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":E3(`none`),"--background":E3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":E3(`optional`),"-c":E3(`none`),"--continue":E3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":E3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":E3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":E3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":E3(`optional`),"-h":E3(`none`),"--help":E3(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":E3(`none`),"--print":E3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":E3(`optional`),"--resume":E3(`optional`),"--safe-mode":$(`none`),"--session-id":E3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":E3(`optional`),"--tmux":E3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":E3(`none`),"--version":E3(`none`),"-w":E3(`optional`),"--worktree":E3(`optional`)},O3={resume:`--resume`,fresh:`--session-id`};function k3(e){return[O3[e.kind],e.sessionId]}const A3=e=>e.startsWith(`-`)&&e!==`-`;function j3(e,t){let n=P3(t);return n===null?{dir:e??t,args:[]}:e!==null&&M3(e,n.top)?{dir:e,args:[]}:{dir:e===null||P3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const M3=(e,t)=>e===t||e.startsWith(t+s.sep);function N3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!A3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=D3[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!A3(e)):o.arity===`variadic`?F3(n.slice(r),e=>!A3(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function P3(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function F3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const I3=`candybar-band@cc-candybar`,L3=s.join(`bin`,`cc-candybar-native`),R3=`@cc-candybar-bar-pane`,z3=nP(`/reload-plugins`),B3=e=>({kind:`done`,said:e});function V3(e){let t=z0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const H3={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Pv.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,L3);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${I3} from ${r}`,finished:U3(e,r,n)}},off:()=>B3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=V3(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Pv.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:K3(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>B3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=V3(e),i=n.barPanes(r);return i.length>0?B3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):B3(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=z0(e.hints.tmux);if(r.kind===`refused`)return B3(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return B3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>B3(`the daemon draws ${V3(e).pane}'s bar in its status line`),off:()=>B3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function U3(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,I3],r);let i=B0(n.claudeInput,e.hints.tmux,z3);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${I3} from ${t} and typed /reload-plugins into ${i.pane}`}const W3=new Set([qa,w3]);function G3(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function K3(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Pv.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=Z3(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Pv.statusline.label} off and on again`);let s=q3(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=N3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=G3(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>W3.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...k3(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=J3(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(j3(null,i.cwd),_))}let y=m(j3(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${Y3[g.kind](e.sessionId)}, and its statusline follows lane B`}function q3(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function J3(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const Y3={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},X3={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function Z3(e){let t=P0(e);return t.kind===`ready`?L0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:F0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:X3[t.kind]}var Q3=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Fv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),$o(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=H3[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function $3(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function e6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function t6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function n6(e,t,n){let r=$3(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const r6=2e3;function i6(e,t,n){let r=DK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function a6(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function o6(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const s6=`#{pane_id} #{${R3}}`;function c6(e,t){return e.split(`
|
|
495
|
-
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const
|
|
496
|
-
`);async function f6(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=a6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,d6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function p6(e,t){return a6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function m6(e){let t=await OK(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await p6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function h6(e){let{panePid:t,cwd:n,foreground:r}=await m6(e),i=await p6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await f6(r),o=j$(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:u6(i,r,t)}}function g6(e){return{claudeInput:G0(),barPanes:e=>c6(i6(e,[`list-panes`,`-a`,`-F`,s6]),e.pane),openBarPane:(e,t,n)=>{let r=i6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return i6(e,[`set-option`,`-p`,`-t`,r,R3,e.pane]),r},closePane:(e,t)=>void i6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void a6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:_$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:PV,paneClaude:h6,paneDir:async(e,t)=>{let n=Date.now()+r6;for(;;){let r=await m6(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${r6/1e3} s`);await be(100)}},launcherNode:e=>n6(e,e=>e6(e,p.constants.X_OK),t6),onPath:(e,t)=>{let n=$3(e,t,e=>e6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?o6(r.stdout):null;return i===null?(a6(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;ws(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void i6(e,U0(e.pane,`cc-candybar-lane`,[]),t)}}function _6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function v6(e,t){let n=`the bar is drawn in ${t.map(e=>Pv[e].elsewhere).join(` and `)}`,r=pi([{verb:Qr,args:[e,...t.map(e=>Pv[e].setting)]}]);return{channels:[{severity:vb,message:n,lines:[[yb(n,pi([{verb:Br,args:[n]}])),yb(`[⟲ draw it here]`,r)]]}]}}const y6={order:-1/0,text:null,failure:null};var b6=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??y6;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??y6;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}},x6=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?qv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function S6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function C6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function w6(e,t){for(let n of Object.entries(t))e.push(n)}const T6={ok:`info`,"bad-request":`warn`,threw:`error`};function E6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function D6(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...E6(t)];return{level:T6[t.kind],line:`render${r.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const O6=new EZ,k6=new b0,A6=new hM,j6=i(import.meta.url),M6=A1(yt());dt(O6.launchStats);const N6=new GW({counters:O6,logger:M}),P6=JK({watchers:N6,logger:M}),{gitProvider:F6,usageStore:I6,tmuxService:L6,autoCompact:R6,cacheExpiry:z6,managedStorage:B6}=P6,V6=new kZ,H6=new RQ(V6,M),U6=new s$,W6=new eb,G6=new x6({now:()=>ik(new Date),close:(e,t)=>i4(e,t,j8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),K6=Yo(),q6=new ls({supersede:(e,t)=>B6.supersede(e,t),launch:pt,state:V6,log:M,now:()=>ik(new Date)}),J6=[t.execPath,...t.execArgv],Y6=new Q3({edge:g6(e=>Z6.following(e)),host:{bundle:j6,node:J6,socket:St(),preload:Do(j6)},state:V6,log:M,now:()=>ik(new Date),defer:e=>void _e(e)}),X6=new C3({edge:{run:(e,t,n)=>OK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>DK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>Z6.subscribe(e,t),sessionInPane:(e,t)=>Z6.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...J6,j6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),Z6=new N4({render:(e,t)=>L8(e,t),watch:(e,t)=>(0,J.reaction)(()=>V6.revision(e),t),lanes:e=>z8(e),pin:e=>t8.pin(e),shown:e=>Q6.shown(e.hints.tmux),watching:()=>Q6.follow(),periods:E4,now:()=>performance.now(),log:M}),Q6=new B4({listPanes:e=>OK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,F4]),listClients:e=>OK({socket:e},`frames.visibility`,[`list-clients`,`-F`,I4]),sockets:()=>new Set(Z6.watched().flatMap(({req:e})=>$6(e))),onAnswer:(e,t)=>X6.answered(e,t),onChange:e=>Z6.wakeWhere(`visibility`,t=>$6(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function $6({hints:{tmux:e}}){return e==null?[]:[e.socket]}const e8=new b6(Pt(),e=>Z6.wake(e,`data`)),t8=new SZ({sessionState:V6,watchers:N6,log:M,storage:B6,signer:K6,declare:(e,t,n,r)=>wq(P6,e,t,n,r),source:T4({providers:P6,sessionState:V6,history:e=>H6.depth(e),navigation:(e,t)=>U6.depth(e,V6,dU(t))})},{budgetBytes:()=>(m8(),sZ(s8)),observers:{onReload:(e,t)=>{M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`);for(let e of t)Z6.wake(e,`reload`)},onViewChanged:e=>Z6.wake(e,`data`)}}),n8=60*1e3,r8=IU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:n8,stat:p.statSync,exit:()=>y8(0),log:M}),i8=NU({entryUrl:import.meta.url,intervalMs:n8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>r8.checkNow(),log:M});let a8=null,o8=null,s8=0;function c8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),y8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),y8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),y8(0)});try{h8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),y8(1);return}a8=bs(t.pid);let e=As(Ms(a8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),y8(1);return}o8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),V6.useStorage(new jZ(Ot(),500,M)),H6.useStorage(a$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),y8(0)}}),l8(ue.createServer({allowHalfOpen:!1},e=>{b8(e)}),St(),!1)}function l8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),y8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}u8(e,n)}),e.listen(n,()=>d8(n))}function u8(e,n){let r=us(ds(Et(n)),(e,t)=>ys(e,t,{readStartTime:vs,pidAlive:ws}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),y8(1);return}}l8(e,n,!0)}function d8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),y8(0);return}g8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(s8)}MB`),Tr();let r=e8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),r8.arm(),i8.arm(),m8().arm(),f8(e,n.identity)}function f8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>y8(e),log:M}).arm()}let p8=null;function m8(){if(p8===null)throw Error(`daemon: limits not yet established`);return p8}function h8(e){s8=nr(e),p8=ur(gr(O6.startedAt.getTime(),e=>y8(e),{limitBytes:s8}))}function g8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:a8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let _8=0,v8=!1;function y8(e){if(v8)return;v8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>X6.restoreAll()],[`gitService close`,()=>F6.close()],[`usageStore close`,()=>I6.close()],[`tmuxService close`,()=>L6.close()],[`runs close`,()=>q6.close()],[`managedStorage close`,()=>B6.close()],[`watcherRegistry close`,()=>N6.closeAll()],[`sessionState flush`,()=>V6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),o8!==null&&js(o8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function b8(e){let t=performance.now();_8++,O6.inFlight=_8;let n=!1,r=!0,i=()=>{r&&(r=!1,_8=Math.max(0,_8-1),O6.inFlight=_8)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>y8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,O6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,x8)},200),c=en(e=>{O8(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(T8(e),null,x8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,x8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=P4(e),o=Z6.subscribe(t,{lane:r,frame:(e,t)=>a($t(aW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const x8=()=>{},S8=e=>({resp:e,exitAfterFlush:null,delivered:x8}),C8=e=>({kind:`reply`,...e}),w8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},T8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),E8=(e,t)=>C8(S8({ok:!1,error:t,code:e,daemonV:3}));function D8(e){let t=oW(e.sessionId);if(!t.ok)return E8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return E8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Fv.join(`, `)}): it predates the lane toggles — update it`);let n=Hv(e.lane);return n===null?E8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function O8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?E8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?D8(e):typeof e.kind!=`string`||!Object.hasOwn(w8,e.kind)?E8(`BAD_REQUEST`,`unknown kind`):C8(await k8(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:x8})}async function k8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:x8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return S8(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:Z6.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return S8({ok:!0,stats:O6.snapshot({gitCache:F6.getStats(),usageCache:I6.getStats(),sources:{tmux:L6.getStats(),autocompact:R6.getStats(),cache:z6.getStats(),today:I6.scanStats(),pluginStorage:B6.stats()},runs:q6.stats(),transcriptReads:Ra(),renderCache:t8.stats,effectCache:W6.getStats(),menuIdle:G6.getStats(),sessionState:{sessions:V6.size(),observers:V6.observers(),revision:V6.latestRevision()},frameFeeds:Z6.getStats(),tmuxStatus:X6.stats(),watchersActive:N6.size(),nextRestartReason:m8().describeNextRestart(),handlerProbes:k6.list(),clients:A6.list(ik(new Date)),bundle:j6,daemon:m8().serving(),doctorStores:j1(M6)})});if(e.kind===`render`){let r=new Date,i=ik(r),a=performance.now(),o=Math.round(a-n),s=[],c=++O6.requestsTotal,l=V8(e),u=(e,t)=>A6.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Ya(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:dM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),Z6.note(l.req.sessionId,l.req,c));let d=l.ok?await Z8(l.req,c,i,(e=>{let t=C6(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?x8:()=>es(V6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:T8(e),delivered:x8})):H8(l.problems);d.outcome.kind!==`ok`&&O6.requestsErrored++,w6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=D6(s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`)return S8(F8(e.verb,e.value,{via:`link`,handler:Zt(e.clientVersion)}));if(e.kind===`debug`){if(!w4(e.what))return S8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${C4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=t8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?P8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):N8};return S8({ok:!0,debug:f4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function A8(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:HB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const j8={sessionState:V6,dlog:M,applyUpdate:()=>i8.act(),doctor:V1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];t8.reload(...t);let n=t8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:M6,probes:k6,clients:A6,bundle:j6,serving:()=>m8().serving(),claudeInput:G0(),history:H6,navigation:U6,configFor:e=>t8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>t8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>t8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:K6,runs:q6,lanes:{of:B8,clicked:e5},views:{follow:(e,t)=>t8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};j8.reloadConfig;const M8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},N8=new Map;function P8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...M8,colorCompatibility:t}));return n}function F8(e,t,n){if(e===`tmux-status-click`)return I8(t);let r=r4.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{let i=$2(e,t);return i!==null&&G6.clicked(i,ik(new Date)),r(t,{...j8,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof q?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function I8(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=X6.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=zo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):F8(e.verb,e.value,{via:`tmux-status`})}let i=D({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}function L8(e,t){let n=new Date,r=ik(n),i=[];try{try{var a=Aa();let n=a.u(G8(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=q8(n,{by:`feed`,fps:t}),u=e8.linkFor(e,Y8(o)),d=J8(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:n5(e,o,u,d,_6(l,Z6.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=D6(i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=T8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function R8(e,t){return kH(t.config,t=>V6.get(e,t),e=>t.authoredRoots.has(e))}function z8(e){try{var t=Aa();let n=t.u(t8.holdView(e));return n===null?null:EH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function B8(e,t){try{var n=Aa();return EH(R8(t,n.u(t8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function V8(e){let{report:t}=c4(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=oW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=S6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};let a=Vt(e),{configFile:o,refusedArgs:s}=A8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:uM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const H8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:x8});function U8(e,t,n){w6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return w6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function W8(e,t,n){let r=e.sessionId,i=U8(e,t,n),a=l2(e.requested,V6,r);return K8(t8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function G8(e,t,n){let r=t8.holdView(e);if(r===null){let t=t8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=U8(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return K8(r,i,a,t,n)}function K8(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...P6,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function q8(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=EH(u);w6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=vq(f),m=mb(f.termRows);w6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:Z6.feedsOf(a,r),today:Nq(P6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;w6(i,Oq(c.lanes().sources)),w6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:eq(h.git,mq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:O4(g.feeds)});let v=[],y=ZK(u,p),b=W6.of(a),ee=G6.since(a,r),x=nZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});G6.observe(a,r,x.menuRows>0,u.menuTimeout);let S=G6.since(a,r);w6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(V6,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
|
|
497
|
-
`),ae=
|
|
498
|
-
`)),se=
|
|
499
|
-
`}function
|
|
500
|
-
`);return}t.stdout.write(
|
|
501
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
492
|
+
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var J4=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${T(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:K4(t.stdout,G4(n.stdout)),status:q4(t.stdout,n.stdout)}:{kind:`unasked`,reason:n.reason}:{kind:`unasked`,reason:t.reason}]})),n=new Set;for(let[e,r]of t){let t=this.servers.get(e);this.servers.set(e,r),!Y4(t,r)&&(n.add(e),this.deps.log(r.kind===`asked`?`info`:`warn`,r.kind===`asked`?`visibility socket=${JSON.stringify(e)} shown=${[...r.shown].join(`,`)||`-`}`:`visibility socket=${JSON.stringify(e)} unasked: ${r.reason} — its panes count as shown`))}for(let[e,n]of t)n.kind===`asked`&&this.deps.onAnswer(e,n.status);n.size>0&&this.deps.onChange(n)}};function Y4(e,t){return e===void 0||e.kind!==t.kind?!1:e.kind===`unasked`||t.kind===`unasked`?!0:e.shown.size===t.shown.size&&[...e.shown].every(e=>t.shown.has(e))}const X4=`@cc-candybar-status-prior`,Z4=`@cc-candybar-status-wrote`,Q4=`@cc-candybar-binding-prior`,$4=[`-T`,`root`,`MouseDown1Status`],e3=Array.from({length:5},(e,t)=>t),t3=e=>`@cc-candybar-row-${e}`,n3=e=>`#[fill=terminal]#{${t3(e)}}`,r3=e=>`status-format[${e}]`;function i3(e){return e===0?`off`:e===1?`on`:String(e)}function a3(e){let t=e===`off`?0:e===`on`?1:/^[2-5]$/.test(e)?+e:NaN;if(Number.isNaN(t))throw Error(`tmux status is ${JSON.stringify(e)}`);return t}function o3(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function s3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function c3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function l3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function u3(e){return e.map(e=>e.map(l3).join(` `)).join(` ; `)}const d3=`ccb:separator`;function f3(e){return c3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,d3],e]))}function p3(e,t){let n=e.split(`${d3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const m3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],h3=e=>[`show-options`,`-g`,`-q`,`-v`,e],g3=e=>[[`show-options`,`-t`,e],m3(e,`status`),...e3.map(t=>m3(e,r3(t)))];function _3(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
493
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of e3)i.includes(r3(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function v3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,r3(Number(t)),s3(n)])]}const y3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...g3(e),...e3.map(e=>h3(r3(e))),m3(e,X4),m3(e,Z4)];function b3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:a3(t)}catch(e){return{kind:`theirs`,why:`${X4} does not read (${String(e)})`}}return r.owner===n?{kind:`ours`,prior:r,status:i}:{kind:`theirs`,why:`the daemon at ${JSON.stringify(r.owner)} draws it`}}function x3(e,t,n){let[r=``,...i]=t,a=_3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return b3(s,c,n);let l=a3(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,n3(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,X4,JSON.stringify(f)],...v3(e,d)]}}const S3=e=>[...g3(e),m3(e,Z4)];function C3(e,t,n){let r=_3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(o3(r.formats,t.wrote))a.push(...v3(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,r3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,s3(t.status)]):o.push(`status`)),a.push(...e3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,t3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,X4],[`set-option`,`-q`,`-u`,`-t`,e,Z4]),{commands:a,kept:o}}const w3=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,T3=[[`list-keys`,`-T`,`root`]];function E3(e){let t=w3.exec(e);return t===null?null:{line:t[0],command:t[1]}}const D3=`cc-candybar://tmux-status-click/`,O3=e=>`${D3}${ui([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,k3=e=>e?.command.includes(D3)??!1;function A3(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,Q4]};return k3(E3(t))?{steps:[e===null?{command:[`unbind-key`,...$4]}:{command:[`source-file`,`-`],stdin:`${e.line}\n`},n],said:`restored MouseDown1Status to ${e===null?`unbound`:JSON.stringify(e.line)}`}:{steps:[n],said:`left MouseDown1Status as it is: bound again since`}}var j3=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=uW(e),this.reconcile(a.socket)},refused:t=>{this.held.get(e)===a&&this.release(a,`refused: ${t.error}`)},drawing:()=>this.draws(a)})}answered(e,t){if(this.closed)return;let n=this.serverOf(e);n.view=t;for(let n of[...this.held.values()])if(n.socket===e)if(!t.sessionOf.has(n.pane))this.release(n,`pane gone`);else{let t=this.deps.sessionInPane(e,n.pane);t!==null&&t!==n.sessionId&&this.release(n,`pane taken by sid=${JSON.stringify(t)}`)}this.reconcile(e)}draws(e){let t=this.servers.get(e.socket),n=t?.view?.sessionOf.get(e.pane);return n!==void 0&&t.layouts.has(n)&&t.view.shownBy.get(n)===e.pane}restoreAll(){this.closed=!0;for(let e of this.held.values())e.unsubscribe?.();this.held.clear();for(let[e,t]of this.servers){for(let[n,r]of[...t.layouts]){t.layouts.delete(n);let i=this.askSync(e,S3(n));if(i===null)continue;let a=C3(n,r.prior,i);this.writeSync(e,a.commands),this.saidRestored(e,n,a.kept)}let n=t.binding;if(t.binding={kind:`none`},n.kind===`ours`||n.kind===`adopted`){let t=this.askSync(e,T3);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let[t,n,r,...i]=di(e);if(t===void 0||n===void 0||r===void 0||i.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let a=[...this.held.values()].find(e=>e.socket===t&&e.pane===`%${n}`)?.frame?.links[r];return a===void 0?{kind:`refused`,reason:`pane %${n}'s status line draws no link ${r} now`}:{kind:`link`,url:a}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${X4}}\t#{${Z4}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
494
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=b3(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[h3(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${Q4} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,y3(n));if(r===null||this.closed)return null;let i=x3(n,r,this.deps.owner);if(i.kind===`theirs`)return this.leave(e,t,n,i.why),null;let a={prior:i.prior,rows:[],status:i.kind===`ours`?i.status:i.prior.base};return t.layouts.set(n,a),i.kind===`lay-out`&&await this.write(e,i.commands),this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.kind===`ours`?`took over`:`laid out`} session ${n} base=${i.prior.base} own=${[i.prior.status===null?[]:[`status`],i.prior.formats===null?[]:[`status-format`]].flat().join(`,`)||`-`}`),a}async draw(e,t,n,r){let i=n.prior.base+r.length,a=[];if(r.forEach((e,r)=>{n.rows[r]!==e&&a.push([`set-option`,`-t`,t,t3(r),e])}),i!==n.status){let e=i3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,Z4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,u3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,S3(n));if(i===null)return;let a=C3(n,r.prior,i);await this.write(e,a.commands),this.saidRestored(e,n,a.kept)}saidRestored(e,t,n){this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} restored session ${t} kept=${n.join(`,`)||`-`}`)}async installBinding(e,t){let n=t.binding;if(n.kind===`ours`||n.kind===`left`)return;let r=await this.ask(e,T3);if(r===null||this.closed)return;let i=E3(r[0]??``);if(n.kind===`none`&&k3(i)){t.binding={kind:`left`,why:`another cc-candybar daemon's status-line clicks are bound to MouseDown1Status; left as it is, so this daemon's are off`},this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.binding.why}`);return}let a=n.kind===`adopted`&&k3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...$4,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${l3(`${this.deps.handler} ${O3(e)}`)}`,...a===null?[]:[a.command]],[`set-option`,`-g`,`@cc-candybar-binding-prior`,JSON.stringify(o)]])){t.binding=n;return}this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} bound MouseDown1Status (was ${a===null?`unbound`:JSON.stringify(a.line)})`)}async restoreBinding(e,t){let n=t.binding;if(t.binding={kind:`none`},n.kind!==`ours`&&n.kind!==`adopted`)return;let r=await this.ask(e,T3);if(r===null)return;let i=A3(n.prior,r[0]??``);for(let t of i.steps)await this.write(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${i.said}`)}writeBindingRestoreSync(e,t,n){let r=A3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,f3(t));return n.kind===`ok`?p3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,f3(t)));return n.kind===`ok`?p3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,c3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,c3(t),n)))}};const M3=`CC_CANDYBAR_CONFIG`;function N3(e,t){return JB(t,e[M3])}const $=e=>({arity:e,keep:!0}),P3=e=>({arity:e,keep:!1}),F3={"--add-dir":$(`variadic`),"--agent":$(`one`),"--agents":$(`one`),"--allow-dangerously-skip-permissions":$(`none`),"--allowedTools":$(`variadic`),"--allowed-tools":$(`variadic`),"--append-system-prompt":$(`one`),"--autocompact":$(`one`),"--ax-screen-reader":$(`none`),"--bg":P3(`none`),"--background":P3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":P3(`optional`),"-c":P3(`none`),"--continue":P3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":P3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":P3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":P3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":P3(`optional`),"-h":P3(`none`),"--help":P3(`none`),"--ide":$(`none`),"--include-hook-events":$(`none`),"--include-partial-messages":$(`none`),"--input-format":$(`one`),"--json-schema":$(`one`),"--max-budget-usd":$(`one`),"--mcp-config":$(`variadic`),"--model":$(`one`),"-n":$(`one`),"--name":$(`one`),"--no-chrome":$(`none`),"--no-session-persistence":$(`none`),"--output-format":$(`one`),"--permission-mode":$(`one`),"--permission-prompts":$(`one`),"--plugin-dir":$(`one`),"--plugin-url":$(`one`),"-p":P3(`none`),"--print":P3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":P3(`optional`),"--resume":P3(`optional`),"--safe-mode":$(`none`),"--session-id":P3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":P3(`optional`),"--tmux":P3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":P3(`none`),"--version":P3(`none`),"-w":P3(`optional`),"--worktree":P3(`optional`)},I3={resume:`--resume`,fresh:`--session-id`};function L3(e){return[I3[e.kind],e.sessionId]}const R3=e=>e.startsWith(`-`)&&e!==`-`;function z3(e,t){let n=H3(t);return n===null?{dir:e??t,args:[]}:e!==null&&B3(e,n.top)?{dir:e,args:[]}:{dir:e===null||H3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const B3=(e,t)=>e===t||e.startsWith(t+s.sep);function V3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!R3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=F3[a];if(o===void 0)return{kind:`refused`,reason:`Claude Code was started with ${a}, which cc-candybar does not know how to carry to a restart`};let s=i===-1?o.arity===`one`?n.slice(r,r+1):o.arity===`optional`?n.slice(r,r+1).filter(e=>!R3(e)):o.arity===`variadic`?U3(n.slice(r),e=>!R3(e)):[]:[];if(o.arity===`one`&&i===-1&&s.length===0)return{kind:`refused`,reason:`Claude Code was started with ${a} and no value after it`};r+=s.length,o.keep&&t.push(e,...s)}return{kind:`args`,args:t}}function H3(e){let t=e.split(s.sep),n=t.findLastIndex((e,n)=>e===`worktrees`&&t[n-1]===`.claude`&&n+1<t.length);return n===-1?null:{name:t[n+1].replaceAll(`+`,`/`),top:t.slice(0,n+2).join(s.sep),repo:t.slice(0,n-1).join(s.sep)||s.sep}}function U3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const W3=`candybar-band@cc-candybar`,G3=s.join(`bin`,`cc-candybar-native`),K3=`@cc-candybar-bar-pane`,q3=cP(`/reload-plugins`),J3=e=>({kind:`done`,said:e});function Y3(e){let t=q0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const X3={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Pv.band.label} runs the band mod from a cc-candybar source checkout, and this daemon runs ${t.bundle} — run the daemon from a checkout (mod/README.md)`);let i=s.join(r,G3);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${W3} from ${r}`,finished:Z3(e,r,n)}},off:()=>J3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=Y3(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Pv.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:e6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>J3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=Y3(e),i=n.barPanes(r);return i.length>0?J3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):J3(`opened bar pane ${n.openBarPane(r,[...t.node,t.bundle,`bar-pane`,r.pane],{CC_CANDYBAR_SOCKET:t.socket})} under ${r.pane}`)},off:(e,t,n)=>{let r=q0(e.hints.tmux);if(r.kind===`refused`)return J3(`no bar pane to close: ${r.reason}`);let i=r.hint,a=n.barPanes(i);for(let e of a)n.closePane(i,e);return J3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>J3(`the daemon draws ${Y3(e).pane}'s bar in its status line`),off:()=>J3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function Z3(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,W3],r);let i=J0(n.claudeInput,e.hints.tmux,q3);if(i.kind===`refused`)throw Error(`the band mod is installed, but /reload-plugins was not typed: ${i.reason} — or type /reload-plugins yourself`);return`installed ${W3} from ${t} and typed /reload-plugins into ${i.pane}`}const Q3=new Set([qa,M3]);function $3(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function e6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Pv.statusline.label} needs the native Claude Code install (\`claude install\`), so it was left running`);if((await r.paneClaude(t)).pid!==i.pid)throw Error(`Claude Code in ${t.pane} is no longer the process the restart read (pid ${i.pid}), so it was not restarted under the attach launcher`);let o=a6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Pv.statusline.label} off and on again`);let s=t6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=V3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=$3(i.env),u=l.get(`PATH`),d=r.launcherNode(u);if(d.kind===`refused`)throw Error(`Claude Code in ${t.pane} was left running, under the PATH it was started with: ${d.why}`);let f=r.onPath(`claude`,u)===i.executable?`claude`:i.executable,p=[...l].filter(([e])=>Q3.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...L3(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=n6(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(z3(null,i.cwd),_))}let y=m(z3(v,i.cwd),_);if(g.kind===`unchecked`)throw h(`whether session ${e.sessionId} has a conversation could not be seen (${g.error})`,y);try{r.typeShellLine(t,y)}catch(e){throw h(`the line could not be typed into its pane (${e.message})`,y)}if(!await r.followed(e.sessionId,`statusline`,3e4))throw Error(`Claude Code in ${t.pane} did not come back attached within ${3e4/1e3} s of \`${y}\` — the pane says why`);return`restarted Claude Code in ${t.pane} under the attach launcher with \`${y}\`, ${r6[g.kind](e.sessionId)}, and its statusline follows lane B`}function t6(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function n6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const r6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},i6={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function a6(e){let t=H0(e);return t.kind===`ready`?G0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:U0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:i6[t.kind]}var o6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Fv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),$o(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=X3[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function s6(e,t,n){for(let r of(t??``).split(s.delimiter)){if(!s.isAbsolute(r))continue;let t=s.join(r,e);if(n(t))return t}return null}function c6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function l6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function u6(e,t,n){let r=s6(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const d6=2e3;function f6(e,t,n){let r=NK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function p6(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function m6(e){try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`ok`in t&&t.ok===!1&&`reason`in t&&typeof t.reason==`string`)return`detail`in t&&typeof t.detail==`string`?`${t.reason}: ${t.detail}`:t.reason}catch{}return null}const h6=`#{pane_id} #{${K3}}`;function g6(e,t){return e.split(`
|
|
495
|
+
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const _6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function v6(e,t,n){for(let r of B$(z$(e),t)){if(r.command.split(` `).some(e=>_6.test(e)))return!0;if(r.pid===n)return!1}return!1}const y6=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
|
|
496
|
+
`);async function b6(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=p6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,y6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function x6(e,t){return p6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function S6(e){let t=await PK(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await x6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function C6(e){let{panePid:t,cwd:n,foreground:r}=await S6(e),i=await x6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await b6(r),o=z$(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:v6(i,r,t)}}function w6(e){return{claudeInput:$0(),barPanes:e=>g6(f6(e,[`list-panes`,`-a`,`-F`,h6]),e.pane),openBarPane:(e,t,n)=>{let r=f6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return f6(e,[`set-option`,`-p`,`-t`,r,K3,e.pane]),r},closePane:(e,t)=>void f6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void p6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:T$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:BV,paneClaude:C6,paneDir:async(e,t)=>{let n=Date.now()+d6;for(;;){let r=await S6(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${d6/1e3} s`);await be(100)}},launcherNode:e=>u6(e,e=>c6(e,p.constants.X_OK),l6),onPath:(e,t)=>{let n=s6(e,t,e=>c6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?m6(r.stdout):null;return i===null?(p6(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;ws(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void f6(e,Z0(e.pane,`cc-candybar-lane`,[]),t)}}function T6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function E6(e,t){let n=`the bar is drawn in ${t.map(e=>Pv[e].elsewhere).join(` and `)}`,r=pi([{verb:Qr,args:[e,...t.map(e=>Pv[e].setting)]}]);return{channels:[{severity:vb,message:n,lines:[[yb(n,pi([{verb:Br,args:[n]}])),yb(`[⟲ draw it here]`,r)]]}]}}const D6={order:-1/0,text:null,failure:null};var O6=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??D6;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??D6;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}},k6=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?qv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function A6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function j6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function M6(e,t){for(let n of Object.entries(t))e.push(n)}const N6={ok:`info`,"bad-request":`warn`,threw:`error`};function P6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function F6(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...P6(t)];return{level:N6[t.kind],line:`render${r.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const I6=new PZ,L6=new O0,R6=new xM,z6=i(import.meta.url),B6=R1(yt());dt(I6.launchStats);const V6=new ZW({counters:I6,logger:M}),H6=new jk(M),U6=aq({watchers:V6,logger:M,ledger:H6}),{gitProvider:W6,usageStore:G6,tmuxService:K6,hostService:q6,managedStorage:J6}=U6,Y6=new LZ,X6=new KQ(Y6,M),Z6=new h$,Q6=new eb,$6=new k6({now:()=>ik(new Date),close:(e,t)=>f4(e,t,B8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),e8=Yo(),t8=new ls({supersede:(e,t)=>J6.supersede(e,t),launch:pt,state:Y6,log:M,now:()=>ik(new Date)}),n8=[t.execPath,...t.execArgv],r8=new o6({edge:w6(e=>a8.following(e)),host:{bundle:z6,node:n8,socket:St(),preload:Do(z6)},state:Y6,log:M,now:()=>ik(new Date),defer:e=>void _e(e)}),i8=new j3({edge:{run:(e,t,n)=>PK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>NK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>a8.subscribe(e,t),sessionInPane:(e,t)=>a8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...n8,z6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),a8=new V4({render:(e,t)=>K8(e,t),watch:(e,t)=>(0,J.reaction)(()=>Y6.revision(e),t),lanes:e=>J8(e),pin:e=>l8.pin(e),shown:e=>o8.shown(e.hints.tmux),watching:()=>o8.follow(),refreshes:()=>H6.totals(),periods:P4,now:()=>performance.now(),log:M}),o8=new J4({listPanes:e=>PK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,U4]),listClients:e=>PK({socket:e},`frames.visibility`,[`list-clients`,`-F`,W4]),sockets:()=>new Set(a8.watched().flatMap(({req:e})=>s8(e))),onAnswer:(e,t)=>i8.answered(e,t),onChange:e=>a8.wakeWhere(`visibility`,t=>s8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function s8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const c8=new O6(Pt(),e=>a8.wake(e,`data`)),l8=new MZ({sessionState:Y6,watchers:V6,log:M,storage:J6,signer:e8,ledger:H6,declare:(e,t,n,r)=>Pq(U6,e,t,n,r),source:N4({providers:U6,sessionState:Y6,history:e=>X6.depth(e),navigation:(e,t)=>Z6.depth(e,Y6,_U(t))})},{budgetBytes:()=>(C8(),_Z(h8)),observers:{onReload:(e,t)=>{M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`);for(let e of t)a8.wake(e,`reload`)},onViewChanged:e=>a8.wake(e,`data`)}}),u8=60*1e3,d8=HU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:u8,stat:p.statSync,exit:()=>O8(0),log:M}),f8=zU({entryUrl:import.meta.url,intervalMs:u8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>d8.checkNow(),log:M});let p8=null,m8=null,h8=0;function g8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),O8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),O8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),O8(0)});try{w8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),O8(1);return}p8=bs(t.pid);let e=As(Ms(p8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),O8(1);return}m8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),Y6.useStorage(new zZ(Ot(),500,M)),X6.useStorage(p$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),O8(0)}}),v8(ue.createServer({allowHalfOpen:!1},e=>{k8(e)}),St(),!1)}function _8(){let e=W6.getStats(),t=K6.getStats(),n=G6.scanStats(),r=J6.stats(),i=l8.stats;return{records:H6.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:G6.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:q6.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function v8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),O8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}y8(e,n)}),e.listen(n,()=>b8(n))}function y8(e,n){let r=us(ds(Et(n)),(e,t)=>ys(e,t,{readStartTime:vs,pidAlive:ws}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),O8(1);return}}v8(e,n,!0)}function b8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),O8(0);return}T8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(h8)}MB`),Tr();let r=c8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),d8.arm(),f8.arm(),C8().arm(),x8(e,n.identity)}function x8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>O8(e),log:M}).arm()}let S8=null;function C8(){if(S8===null)throw Error(`daemon: limits not yet established`);return S8}function w8(e){h8=nr(e),S8=ur(gr(I6.startedAt.getTime(),e=>O8(e),{limitBytes:h8}))}function T8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:p8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let E8=0,D8=!1;function O8(e){if(D8)return;D8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>i8.restoreAll()],[`gitService close`,()=>W6.close()],[`usageStore close`,()=>G6.close()],[`tmuxService close`,()=>K6.close()],[`hostService close`,()=>q6.close()],[`runs close`,()=>t8.close()],[`managedStorage close`,()=>J6.close()],[`watcherRegistry close`,()=>V6.closeAll()],[`sessionState flush`,()=>Y6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),m8!==null&&js(m8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function k8(e){let t=performance.now();E8++,I6.inFlight=E8;let n=!1,r=!0,i=()=>{r&&(r=!1,E8=Math.max(0,E8-1),I6.inFlight=E8)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>O8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,I6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,A8)},200),c=en(e=>{L8(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(P8(e),null,A8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,A8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=H4(e),o=a8.subscribe(t,{lane:r,frame:(e,t)=>a($t(dW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const A8=()=>{},j8=e=>({resp:e,exitAfterFlush:null,delivered:A8}),M8=e=>({kind:`reply`,...e}),N8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},P8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),F8=(e,t)=>M8(j8({ok:!1,error:t,code:e,daemonV:3}));function I8(e){let t=fW(e.sessionId);if(!t.ok)return F8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return F8(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Fv.join(`, `)}): it predates the lane toggles — update it`);let n=Hv(e.lane);return n===null?F8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function L8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?F8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?I8(e):typeof e.kind!=`string`||!Object.hasOwn(N8,e.kind)?F8(`BAD_REQUEST`,`unknown kind`):M8(await R8(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:A8})}async function R8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:A8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return j8(typeof t!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:a8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return j8({ok:!0,stats:I6.snapshot({gitCache:W6.getStats(),usageCache:G6.getStats(),sources:_8(),runs:t8.stats(),transcriptReads:Ra(),renderCache:l8.stats,effectCache:Q6.getStats(),menuIdle:$6.getStats(),sessionState:{sessions:Y6.size(),observers:Y6.observers(),revision:Y6.latestRevision()},frameFeeds:a8.getStats(),tmuxStatus:i8.stats(),watchersActive:V6.size(),nextRestartReason:C8().describeNextRestart(),handlerProbes:L6.list(),clients:R6.list(ik(new Date)),bundle:z6,daemon:C8().serving(),doctorStores:z1(B6)})});if(e.kind===`render`){let r=new Date,i=ik(r),a=performance.now(),o=Math.round(a-n),s=[],c=++I6.requestsTotal,l=X8(e),u=(e,t)=>R6.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Ya(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:_M(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),a8.note(l.req.sessionId,l.req,c));let d=l.ok?await o5(l.req,c,i,(e=>{let t=j6(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?A8:()=>es(Y6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:P8(e),delivered:A8})):Z8(l.problems);d.outcome.kind!==`ok`&&I6.requestsErrored++,M6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=F6(s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`)return j8(W8(e.verb,e.value,{via:`link`,handler:Zt(e.clientVersion)}));if(e.kind===`debug`){if(!M4(e.what))return j8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${j4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=l8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?U8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):H8};return j8({ok:!0,debug:b4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function z8(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:JB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const B8={sessionState:Y6,dlog:M,applyUpdate:()=>f8.act(),doctor:Y1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];l8.reload(...t);let n=l8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:B6,probes:L6,clients:R6,bundle:z6,serving:()=>C8().serving(),claudeInput:$0(),history:X6,navigation:Z6,configFor:e=>l8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>l8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>l8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:e8,runs:t8,lanes:{of:Y8,clicked:l5},views:{follow:(e,t)=>l8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};B8.reloadConfig;const V8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},H8=new Map;function U8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...V8,colorCompatibility:t}));return n}function W8(e,t,n){if(e===`tmux-status-click`)return G8(t);let r=d4.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{let i=s4(e,t);return i!==null&&$6.clicked(i,ik(new Date)),r(t,{...B8,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof q?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function G8(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=i8.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=zo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):W8(e.verb,e.value,{via:`tmux-status`})}let i=D({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}function K8(e,t){let n=new Date,r=ik(n),i=[];try{try{var a=Aa();let n=a.u(e5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=n5(n,{by:`feed`,fps:t}),u=c8.linkFor(e,i5(o)),d=r5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:d5(e,o,u,d,T6(l,a8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=F6(i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=P8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function q8(e,t){return FH(t.config,t=>Y6.get(e,t),e=>t.authoredRoots.has(e))}function J8(e){try{var t=Aa();let n=t.u(l8.holdView(e));return n===null?null:MH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function Y8(e,t){try{var n=Aa();return MH(q8(t,n.u(l8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function X8(e){let{report:t}=g4(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=fW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=A6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};let a=Vt(e),{configFile:o,refusedArgs:s}=z8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:gM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const Z8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:A8});function Q8(e,t,n){M6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return M6(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function $8(e,t,n){let r=e.sessionId,i=Q8(e,t,n),a=_2(e.requested,Y6,r);return t5(l8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function e5(e,t,n){let r=l8.holdView(e);if(r===null){let t=l8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=Q8(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return t5(r,i,a,t,n)}function t5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...U6,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function n5(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=MH(u);M6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=Dq(f),m=mb(f.termRows);M6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:a8.feedsOf(a,r),today:Uq(U6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;M6(i,Rq(c.lanes().sources)),M6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:dq(h.git,Cq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:I4(g.feeds)});let v=[],y=cq(u,p),b=Q6.of(a),ee=$6.since(a,r),x=fZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});$6.observe(a,r,x.menuRows>0,u.menuTimeout);let S=$6.since(a,r);M6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(Y6,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
|
|
497
|
+
`),ae=f8.notice({sessionId:a,dismissed:Y6.get(a,CU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],oe=bb(ie,ae,w.map(e=>e.message).join(`
|
|
498
|
+
`)),se=W6.getStats(),T=G6.getStats(),ce=b.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=w.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return M6(i,{git:`${se.size}/${se.hits}h/${se.misses}m`,usage:`${T.size}/${T.hits}h/${T.misses}m`,effect:ce.effect,effectT:ce.t.toFixed(3),speed:`${ce.speed}x`,effectRows:`${ce.made}made/${ce.reused}reused`,effectOwn:le,fadeBasis:ce.basis,stateRev:String(ce.revision),fades:ue(ce.fades),leaves:ue(ce.leaves),motion:x.motion,evaluated:String(x.evaluated),pending:x.pending.join(`,`)||`-`,rules:[...x.rules].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ie?`Y`:`N`,clickError:te.kind===`none`?`-`:te.kind,upd:String(ae.length),warn:de}),{drawn:{body:x.text,diagnostics:oe,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function r5(e,t){return Cb(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
|
|
499
|
+
`}function i5(e){return e.diagnostics===null?null:Sb(e.diagnostics)}function a5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);Y6.get(t,`client-hints`)!==i&&Y6.set(t,K2,i);let a=v2(e.requested);Y6.get(t,`render-origin`)!==a&&Y6.set(t,g2,a)}async function o5(e,t,n,r,i){return a5(e),u5(e,t,n,r,i)}function s5(e,t){r8.noted(c5(e),t),i8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function c5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:_2(e.requested,Y6,t),transcript:e.hookData.transcript_path,answered:mM(e.hookData)}}function l5(e,t,n){let r=a8.latest(e);r8.clicked(e,r===null?null:c5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&i8.observe(e,r.hints.tmux,n.tmuxStatus)}async function u5(e,t,n,r,i){try{var a=Aa();let o=a.u($8(e,n,i));s5(e,MH(o.view.source.effective())),M6(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await cG(e=>Promise.all([Wq(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${T(e)}`)),u=performance.now();M6(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:kq(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=n5(o,Iv),{link:h,failure:g}=c8.sync(e.sessionId,t,i5(d));M6(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=r5(d,h),v=e.sessionId,y=T6(m,a8.following(v)),b=d5(v,d,h,_,y),ee=bM(e.hints.client??null)===`statusline`;return M6(i,{handoff:(ee?y:[]).join(`,`)||`-`,drew:`${Math.round(performance.now()-u)}ms`}),{answer:ee?b:_,motion:f,clickShown:p}}catch(e){a.e=e}finally{a.d()}}function d5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:r5({...t,body:wb(E6(e,[a,...o]),t.geometry)},n)}const f5={connectMs:200,budgetMs:500};async function p5(e,n){let r=n.includes(`--json`),i=await m5(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${un(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
500
|
+
`);return}t.stdout.write(h5(i.value))}function m5(e){return rn(()=>({kind:`debug`,what:e}),f5,e=>`debug`in e?e.debug:void 0)}function h5(e){switch(e.what){case`vars`:return g5(e.vars);case`segments`:return _5(e.segments);case`config`:return v5(e.config);default:return e}}function g5(e){if(e.length===0)return`no variables (DSL not active)
|
|
501
|
+
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${b5(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${y5(a.value)}${e}${o}`)}return t.join(`
|
|
502
502
|
`)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function _5(e){if(e.length===0)return`no segments (DSL not active)
|
|
504
504
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
505
505
|
`)+`
|
|
506
|
-
`}function
|
|
506
|
+
`}function v5(e){return e===null?`config: DSL not active
|
|
507
507
|
`:JSON.stringify(e,null,2)+`
|
|
508
|
-
`}function
|
|
508
|
+
`}function y5(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function b5(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function x5(){let e=C5();return e===null?null:p.readFileSync(e,`utf-8`)}function S5(){let e;try{e=x5()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function C5(){let e=s.join(`schema`,`cc-candybar.schema.json`),n=t.argv[1];if(n===void 0)return null;let r=s.dirname(s.resolve(n));for(;;){let t=s.join(r,e);if(p.existsSync(t))return t;let n=s.dirname(r);if(n===r)return null;r=n}}const w5=5e3;function T5(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:gP(4e5,1e6),...lq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:ky(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:sq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:zq(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>F)}}const E5={cost:12.5,tokens:34e5};function D5(e,t){let n=WV(e,e),r=qV(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function O5(e,n=t.cwd()){let r=[],i=JB(n,e)??null,a=i===null?D5(n,r):[i];if(i!==null){let e;try{e=p.statSync(i,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:i,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:i,message:`not a file`}}let o=YV(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await j5(a,n,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&a.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof Z_&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Z_||e instanceof Error?e.message:String(e),warnings:r})}}async function k5(e,t,n,r){let i=rH(e,EH,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:a}=i,o=new pS,s=new $k(o,a.globals.default_empty_value??``,new LZ);try{let c=JX(a,s,{cwd:t,signer:Yo()});n.push(...c.loadWarnings);let l=FH(a,()=>null,()=>!1);CX(c,o,s,UX({...T5(a,l,e.at(-1)??null,r),today:E5},l));let u=await s.settled(w5);return u.length>0&&n.push(`source${u.length===1?``:`s`} still running after ${w5} ms, rendered with fallback values: ${u.join(`, `)}`),{layers:e,droppedPlugins:[...i.installed.dropped,...i.layers.flatMap(e=>e.plugins.dropped)],config:a,compiled:c,store:o,registry:s}}catch(e){throw s.dispose(),e}}function A5({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u=e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}};return{rendered:dZ(t,n,r,i,{...T5(t,a,e.at(-1)??null,s),today:E5},s,cq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function j5(e,t,n){let r=ik(new Date),i=await k5(e,t,n,r),{config:a}=i;try{let e=RU();try{_U(a),qI(a)}finally{e()}let t=$b(null,a.globals.preset,a.presets),o=(e,t)=>{let n=FH(a,t=>t===`preset`?e:null,()=>t),o;try{o=A5(i,n,200,r)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Qb(a.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=i.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
509
509
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
510
|
-
`));return d}finally{i.registry.dispose()}}function
|
|
511
|
-
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${
|
|
512
|
-
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
513
|
-
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:
|
|
510
|
+
`));return d}finally{i.registry.dispose()}}function M5(e){return e.map(e=>`warning: ${e}\n`).join(``)}function N5(e,t=!1){switch(e.kind){case`clean`:return{stdout:`✓ ${e.layers.join(` < `)||`bundled default (no config file found)`}: config OK${e.warnings.length>0?` (${e.warnings.length} warning${e.warnings.length===1?``:`s`})`:``}\n`+(t?`${e.rendered}\n`:``),stderr:M5(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:M5(e.warnings)+`✗ ${e.layers.join(` < `)||`<default>`}\n${e.message}\n`,code:1};case`unreadable`:return{stdout:``,stderr:`check: cannot read ${e.path}: ${e.message}\n`,code:2}}}const P5=`--render`,F5=`Usage: cc-candybar check [${P5}] [config-file]\n`;function I5(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==P5);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${F5}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${F5}`}:{kind:`run`,target:n[0],render:t.includes(P5)}}async function L5(e){let n=I5(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:N5(await O5(n.target??N3(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const R5=/^[a-z][a-z0-9+.-]*:\/\//i,z5=/^[^@\s/]+@[^:\s/]+:/,B5=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function V5(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function H5(e,t,n){let r=qB(t,e);if(n(r))return{kind:`path`,dir:r};if(R5.test(e)||z5.test(e))return{kind:`git`,url:e,shown:V5(e)};let i=B5.exec(e);if(i){let e=`https://github.com/${i[1]}.git`;return{kind:`git`,url:e,shown:e}}return{error:`"${e}" is not a directory, a GitHub repo slug (owner/repo) or a git URL`}}function U5(e,t){let n=s.join(e,MV),r=FV(n);if(`error`in r)throw Error(`${t}: could not list ${MV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${MV}/<name>/${ZB}`);return r.folders.map(e=>s.join(n,e,ZB))}function W5(e,t,n){let r=(n,...r)=>{let i=D({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
|
|
511
|
+
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${MV}/`)}function G5(e,t){switch(e.kind){case`path`:return t(e.dir);case`git`:{let n=p.mkdtempSync(s.join(C.tmpdir(),`cc-candybar-plugin-`));try{return W5(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function K5(e){let t;try{t=p.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return`installed`;throw e}if(t.isDirectory())return`updated`;if(t.isSymbolicLink())return`replaced`;throw Error(`${e} is a file, not a plugin folder: move it, then install again`)}function q5(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,ZB),s.join(t,ZB));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function J5(e,t,n){let r=U5(e,n);p.mkdirSync(t,{recursive:!0});let i=p.mkdtempSync(s.join(t,`.install-`));try{let a=r.map(e=>{let t=s.join(i,s.basename(s.dirname(e)));p.mkdirSync(t);try{p.copyFileSync(e,s.join(t,ZB))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=tH(a.map(e=>s.join(e,ZB)),EH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(MV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,MV))}`).join(`
|
|
512
|
+
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:K5(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)q5(e,n,s.join(i,`.replaced-${t}`),r),l.push(t)}catch(e){throw Error(`${e.message} (placed before it: ${l.join(`, `)||`none`})`)}return c.map(({target:e,placed:t})=>({path:s.join(e,ZB),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function Y5(e){let[t,n,...r]=e;if(t!==`install`||n===void 0||r.length>0)return console.error(`Usage: cc-candybar plugin install <path | owner/repo | git URL>`),2;let i=H5(n,process.cwd(),Uk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=G5(i,t=>J5(t,jV(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function X5(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const Z5=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function Q5(e,t,n){return{termCols:X5(e.COLUMNS,n.columns),termRows:X5(e.LINES,n.rows),ssh:Z5.some(t=>(e[t]??``)!==``),tmux:fM(e),configEnv:N3(e,t),claudeConfigDir:Ja(e,t),terminalEnv:Lt(e)}}function $5(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function e7(e){let t=_0(e,[`bundle`,`clients`]);if(t!==null)return{kind:`failed`,reason:t};if(typeof e.bundle!=`string`)return{kind:`failed`,reason:`the running daemon (${e.version}) reported its bundle as ${JSON.stringify(e.bundle)}`};let n=$5(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:nn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const t7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},n7=e=>{let t=e??{};if(t.kind===`unmeasured`)return!0;let n=t.charge;return t.kind===`measured`&&typeof t.rss==`number`&&typeof t.heapTotal==`number`&&typeof n?.bytes==`number`&&(n.kind===`charged`&&(n.measure===`phys_footprint`||n.measure===`rss`)||n.kind===`stand-in`&&typeof n.unread==`string`&&Number.isFinite(n.gap))};function r7(e,t){let n=e;if(n?.kind===`failed`&&typeof n.reason==`string`)return{kind:`failed`,reason:n.reason};if(n?.kind!==`ok`)return{kind:`misshapen`,reason:`is not an answer`};let r=t(n.value);return r.kind===`ok`?r:{kind:`misshapen`,reason:r.reason}}function i7(e){let t=_0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=r7(n?.postMortems,e=>Array.isArray(e)&&e.every(t7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&n7(n.memory)&&typeof n.limit==`number`&&r.kind!==`misshapen`?{kind:`ok`,value:{...n,postMortems:r}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported itself as ${JSON.stringify(e.daemon)}`}}function a7(e,t,n){let r=_0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=$5(e);return i.every(t)?{kind:`ok`,value:i}:{kind:`failed`,reason:`the running daemon (${e.version}) reported its renders without ${n} — restart it on this build: ${JSON.stringify(e.clients)}`}}const o7=e=>yM.includes(e.role),s7=e=>a7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&hM.includes(e.rateLimits),`the rate-limit windows they carried`),c7=e=>a7(e,e=>{let t=e.transcript;return typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof t?.path==`string`&&typeof t.answered==`boolean`},`their transcripts`),l7=e=>a7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&o7(e)&&vM.includes(e.frame),`what they drew and from which project`),u7=e=>a7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&o7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function d7(e,t,n){let r=e.doctorStores?.[t],i=r7(r,n);return i.kind===`misshapen`?{kind:`failed`,reason:`the running daemon (${e.version}) reported its ${t} as ${JSON.stringify(r)}, which ${i.reason}`}:i}function f7(e){let t=_0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:d7(e,`marks`,O$),clicked:d7(e,`clicked`,j$),postMortemsRead:d7(e,`postMortemsRead`,N1)}}async function p7(){let e=await g0();if(e.kind!==`ok`){let t={kind:`failed`,reason:un(e).split(`
|
|
513
|
+
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:e7(e.value),rateLimits:s7(e.value),transcripts:c7(e.value),frames:l7(e.value),widths:u7(e.value),serving:i7(e.value),stores:f7(e.value)}}const m7=` (fix: click the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,h7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor`;function g7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:m7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${h7}\n`)}function _7(e){let t={sessionState:new LZ,storage:vZ,signer:Yo()},n=DZ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??OZ(e.cwd,e.projectDir,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function v7(e,t,n){return n.kind===`failed`?n:L1(e,n.value.bundle,I$(t,n.value.clients).map(({client:e})=>e))}function y7(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:I$(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function b7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:I$(e,t.value).map(e=>e.transcript)}}function x7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value)}}function S7(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:d0(e.sessionId,I$(e,t.value))}async function C7(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=Q5(r,i,a()),u=F$(r.CLAUDE_CODE_SESSION_ID);s={...f0(e,l,{projectDir:L$(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:JB(i,o)??N3(r,i)??null},()=>null,c.serving,y7(u,c.rateLimits,Ya(l.claudeConfigDir)),b7(u,c.transcripts),u,x7(u,c.frames),S7(u,c.widths,l.termCols??null),c.stores),urlHandler:await N0(t),install:v7(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=IN(s);return{stdout:c.map(g7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function w7(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new xe(e),{columns:r}=n;return n.destroy(),{columns:r}}async function T7(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
|
|
514
514
|
Usage: cc-candybar doctor [config-file]
|
|
515
|
-
`),t.exit(2));let n=t.cwd(),r=await
|
|
516
|
-
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const
|
|
517
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
515
|
+
`),t.exit(2));let n=t.cwd(),r=await C7(Y1(_7),L0(),p7,t.env,n,w7,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function E7(e){return!e.ok&&e.code!==`RENDER_FAILED`}function D7(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=ue.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Qt(c))),s.on(`data`,en(e=>{let t=e;E7(t)?o({kind:`refused`,resp:t}):r(t)},e=>o({kind:`failed`,error:e}))),s.on(`error`,e=>o({kind:`failed`,error:e})),s.on(`close`,()=>o({kind:`closed-there`})),{close:()=>o({kind:`closed-here`})}}function O7(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function k7(e){switch(e.kind){case`failed`:return{kind:`reconnect`,reason:`stream failed (${e.error.message})`,kick:!0};case`closed-there`:return{kind:`reconnect`,reason:`daemon closed the stream`,kick:!1};case`refused`:return e.resp.code===`SWITCHED_OFF`?{kind:`off`,resp:e.resp}:e.resp.code===`TIMEOUT`?{kind:`reconnect`,reason:`the daemon was too busy to open the stream (${e.resp.error})`,kick:!1}:e.resp.code===`BAD_REQUEST`?{kind:`reconnect`,reason:`the daemon does not take subscribe (${e.resp.error}); it restarts on the new build`,kick:!1}:e.resp.code===`VERSION_MISMATCH`&&e.resp.daemonV!==void 0&&e.resp.daemonV<3?{kind:`reconnect`,reason:`the daemon is older than this client (${e.resp.error})`,kick:!0}:{kind:`exit`,reason:`the daemon refused the stream: ${e.resp.code}: ${e.resp.error}`}}}function A7(e,t,n,r){let i=null,a=null,o=!1,s=250,c=(e,t)=>{a=setTimeout(()=>{a=null,((t?r.beforeReconnect?.():void 0)??Promise.resolve()).then(()=>{o||l()})},e)},l=()=>{i=D7(e,t,n,e=>{s=O7(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=k7(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&_r();let e=s;s=O7(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function j7(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function M7(e,n){let{values:r,tokens:i}=ce({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=Hv(r.lane);c===null&&(s(`--lane needs one of ${Fv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=H4(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{j7(p,e)&&t(),p=e},h=async e=>{let r=await hn(e,a,o,{...Q5(t.env,o,t.stderr),client:zt(`frames`,n)});r.kind!==`ok`&&(s(un(r)),r.kind===`transient`&&_r())},g=e=>{f?.close(),f=A7(St(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of Se({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function N7(e){let t=e.replace(/\n+$/,``).split(`
|
|
516
|
+
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const P7=5e3,F7=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function I7(e,t,n,r){let i=e.split(`
|
|
517
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?K4(e,G4(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function L7(e,t){let[n,r]=await Promise.all([PK(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,U4]),PK(e,`bar-pane.tmux`,[`list-clients`,`-F`,W4])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:I7(n.stdout,r.stdout,t,e.pane)}:r:n}function R7(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>P7)throw Error(`tmux has not answered for ${P7/1e3} s: ${t.reason}`)}}function z7(e){let{positionals:t}=(()=>{try{return ce({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${F7}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(F7);return{pane:n}}async function B7(e){try{return await V7(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function V7(e){let{pane:n}=z7(e),r=fM(t.env);if(r===null)throw Error(`cc-candybar bar-pane runs in a tmux pane`);if(!t.stdout.isTTY)throw Error(`cc-candybar bar-pane draws on its pane's terminal`);let i=await L7(r,n);if(i.kind!==`ok`)throw Error(i.reason);let a=i.placement;if(a.kind===`gone`)throw Error(`no pane ${n} on this tmux server (${r.socket})`);t.stdout.write(`\x1B[?25l\x1B[?7l`),t.on(`exit`,()=>t.stdout.write(`\x1B[?25h\x1B[?7h`));for(let[e,n]of[[`SIGINT`,130],[`SIGTERM`,143],[`SIGHUP`,129]])t.once(e,()=>t.exit(n));let o=e=>{t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),t.exit(1)},s=null,c=`waiting for pane ${n}'s bar`,l=()=>s?.said.latest??c,u=``,d=R7(),f=async()=>{if(a.kind!==`shown`)return;let e=N7(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await PK(r,`bar-pane.tmux`,[`resize-pane`,`-t`,r.pane,`-y`,String(e.rows)])),e.bytes!==u&&t.stdout.write(e.bytes),u=e.bytes},p=null,m=!1,h=()=>{m=!0,p??=(async()=>{try{for(;m;)m=!1,await f()}finally{p=null}})(),p.catch(o)};t.stdout.on(`resize`,()=>{u=``,h()});let g=e=>{if(s?.sessionId===e)return;if(s?.follower.close(),e===null){s=null;return}let t={latest:null},n=e=>{t.latest=e,h()};s={sessionId:e,said:t,follower:A7(St(),e,`pane`,{frame:e=>n(KU(mn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=R7();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await gn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${St()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(_r(),u=``),c=un(e))}h(),await be(500);let e=await L7(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const H7=i(import.meta.url),U7=e=>e.some(e=>t.argv.includes(e));function W7(){console.log(lM);let e=Do(H7),t=p.existsSync(e)?``:" (nothing is there yet: run `cc-candybar install` first — in a checkout, `pnpm build`)\n";console.log(`Starting Claude Code on ${Pv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${He(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const G7={install:async e=>{await Uo(e,H7),t.exit(0)},"install-url-handler":async()=>{Ro(H7),t.exit(0)},"url-handle":async e=>{await Bo(e[0])},daemon:async()=>{g8()},"daemon-stats":async e=>{await h0(e),t.exit(0)},frames:async()=>{await M7(t.argv,H7)},check:async e=>{await L5(e)},lint:async e=>{await L5(e)},plugin:async e=>{t.exit(Y5(e))},schema:async()=>{S5()},doctor:async e=>{await T7(e)},"bar-pane":async e=>{t.exit(await B7(e))},...Object.fromEntries(j4.map(e=>[e,async n=>{await p5(e,n),t.exit(0)}]))};async function K7(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(G7,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),U7(qj.help)&&(W7(),t.exit(0)),U7(qj.version)&&(console.log(`cc-candybar ${Ze}`),t.exit(0)),n!==null){await G7[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
518
518
|
|
|
519
519
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
520
520
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -530,4 +530,4 @@ Add to ~/.claude/settings.json:
|
|
|
530
530
|
Run with --help for more options.
|
|
531
531
|
|
|
532
532
|
To test output manually:
|
|
533
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
533
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),W7(),t.exit(1));let i=KU(await hn(r,t.argv.slice(1),t.cwd(),{...Q5(t.env,t.cwd(),t.stderr),client:zt(`node`,H7)}));i.debug!==null&&E(i.debug),i.kick&&_r(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}K7();export{};
|