@promptctl/cc-candybar 1.158.1 → 1.159.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/README.md +2 -0
- package/dist/index.mjs +64 -64
- 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.158.1`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`22eae4ca13e486d5381eb96b7a9f37cc1d5a430e6dd2f964d878fd5ac6c081c0`}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.159.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`ecd32a680979d751323e860dea79678ad23e0c19c188d0d1468d70bba7a630d4`}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?)
|
|
@@ -175,30 +175,30 @@ Config tooling:
|
|
|
175
175
|
running daemon; none spawn one.)
|
|
176
176
|
|
|
177
177
|
`,dM=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,fM={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function pM(e){let t=e[fM.socket]??``,n=e[fM.pane]??``;if(t===``||n===``)return null;let r=e[fM.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const mM=[`moves`,`can-move`,`still`];function hM(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const gM=[`carried`,`missing`,`unanswered`];function _M(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:hM(e)===`no`?`unanswered`:`missing`}function vM(e){return{path:e.transcript_path,answered:hM(e)===`yes`}}const yM=[...mM,`failed`,`drawing`],bM=[`statusline`,`frames`],xM=e=>e?.kind===`frames`?`frames`:`statusline`;var SM=class{seen=new Map;see(e,t,n,r){let i=xM(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 CM={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`}}},wM=e=>CM[e];function TM(e){return wM(e).glyphs.kind===`bundled`}function EM(e){return wM(e).glyphs.kind===`configured`}const DM=e=>wM(e).label,OM=[{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 kM(e,t){let n=t.codePointAt(0);return OM.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&MM(e,t)===!0)}const AM=Object.keys(CM);function jM(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function MM(e,t){let n=jM(e),r=jM(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 NM(e){for(let t of AM){let n=wM(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 PM(e){let t=AM.find(t=>wM(t).term===e);return t===void 0?null:{name:t,version:null}}function FM(e){let t=NM(e.termtype)??PM(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 IM(e){let t=e.TERM_PROGRAM,n=AM.find(e=>wM(e).program===t),r=n===void 0?PM(e.TERM):{name:n,version:wM(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 LM(e){switch(e.kind){case`known`:return DM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function RM(e){switch(e.kind){case`known`:return DM(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function zM({name:e,version:t}){let n=wM(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=MM(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const BM=AM.filter(e=>wM(e).links!==null).map(DM).join(`, `);function VM(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 HM(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 UM=[`managed`,`project`],WM=e=>!UM.includes(e.scope),GM={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})},KM=[`drawn`,`boxes`],qM=1024*1024,JM=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function YM(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 XM(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const ZM=fM.truecolor;function QM(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 $M={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>QM(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=HM(t.sources,ZM);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:`${ZM} 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`,ZM],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=GM[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 ${ZM} to "1" there`}:o(s)})},eN={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>QM(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"})},tN={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:`${JM(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 ${JM(e.value.of)} measured`}},nN={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},rN={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 XM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${nN[e]}`)])}}},iN="re-run `cc-candybar install`";function aN(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:// — ${iN}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${iN}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${iN}`)}const oN={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}) — ${iN}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${iN}`};case`lost`:return XM([...aN(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 sN({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 cN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?iN:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function lN(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 — ${cN(e,`native`)}`];let{bundle:i,source:a}=sN(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} — ${cN(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 — ${cN(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 uN=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)`},dN={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`:`${uN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:XM([...new Set(i.flatMap(e=>lN(n,r,e)))])}};function fN({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 pN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const mN={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`?pN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return XM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=fN(e.value,n),u=XM([...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}}}},hN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function gN(e,t){let n=LM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?zM(e.terminal):{kind:`unknown`}}function _N({identified:e,tmuxClient:t},n){let r=RM(e),i=gN(e,n),a=LM(e)===null?hN:`${hN}, 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: ${BM}`];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 vN={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 XM(_N(t,n))}}},yN=e=>e.filter(e=>e.role===`statusline`),bN={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})=>CN(e,xN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:SN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:uN(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}}},xN=e=>{let t=yN(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`}},SN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function CN(e,t){let n=VM(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 SN(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 WM(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 wN=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function TN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return RM(e);case`bundling`:case`unread`:case`configured`:return[DM(e.name),e.version].filter(e=>e!==null).join(` `)}}function EN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return LM(e);case`bundling`:case`unread`:return DM(e.name);case`configured`:{let t=DM(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 DN(e){let t=EN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${wN(e.glyphs)}`}}const ON={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=DN(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=TN(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 ${wN(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=CM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:MM(i.version,e);if(t===!0)return{ok:!0};let n=DM(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 ${wN(n)} — set a Nerd Font as its font`)}}}};function kN(e){return e.join(`, `)}function AN(e){return`or set missingData: "ignore" on ${kN(e)}`}function jN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${kN(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`?[`${kN(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${AN(t)}`]:[`${kN(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${AN(t)}`]}function MN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${kN(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${kN(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`:`${kN(n)}: ${uN(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`)?[`${kN(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${kN(n)}`]:[]}const NN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>XM([...jN(e.pullRequests),...MN(e.rateLimits,t)])};function PN({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 ${qM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const FN=[rN,dN,mN,oN,vN,$M,eN,tN,bN,ON,NN,{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`:`${uN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:XM(e.value.flatMap(PN))}],IN=FN.filter(e=>e.takesMark);function LN(e){return FN.map(t=>({check:t,verdict:t.probe(e)}))}function RN(e){return FN.find(t=>t.name===e)}const zN=`${X}doctor.`;function BN(e){let t=`${zN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function VN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?LM(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 HN(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 UN(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}=sN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const WN=e=>`${e>=0?`+`:``}${tr(e)}`;function GN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${pN(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`:`${fN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${WN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function KN(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 qN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>JN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=yN(r.flatMap(e=>e.bars));return`frames=${yM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function JN(e){let t=VM(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 YN(e){let t=HM(e,ZM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function XN(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 ZN(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=DN(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 QN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function $N(e){return e.flatMap(({check:e,verdict:t})=>{let n=BN(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:QN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const eP={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function tP(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(eP).map(([t,n])=>[`${e}${t}`,n]))}}const nP=`armed`,rP=`disarmed`,iP=`.armed`,aP=e=>e.endsWith(iP);function oP(e,t,n){let r=`${e}${iP}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${nP}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:nP},[a]:{set:r,to:rP},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:rP}},disarm:a}}const sP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function cP(e){return typeof e==`string`&&sP.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 lP(e){let t=cP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const uP=[`/compact`,`/model`],dP=`/clear`;function fP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=oP(`${e}clear`,{arm:dP,confirm:`${dP} ✓ confirm`},[n]);return{template:uP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${uA} }}`,actions:{...Object.fromEntries(uP.map(e=>[t(e),{slash:lP(e)}])),...r.actions,[n]:{slash:lP(dP)}},variables:r.variables,disarm:r.disarm}}const pP=Array.from({length:10},(e,t)=>(t+1)*1e5),mP=pP[0],hP=pP[pP.length-1];function gP(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>=mP&&n<=hP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${mP}–${hP} tokens)`)}function _P(e,t){let n=Math.min(t??hP,hP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:pP.filter(e=>e<r).at(-1)??0,higher:pP.find(e=>e>r&&e<=n)??0}}function vP(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${uA} }}{{ 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:lP(`/autocompact auto`)},...Object.fromEntries(pP.map(t=>[`${e}${t}`,{slash:lP(`/autocompact ${t}`)}]))}}}const yP=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 }}`,bP=`${X}edit`,xP=`${X}toolbar`,SP=tP(X),CP=`${X}commands`,wP=fP(`${CP}.`),TP=`${X}autocompact`,EP=vP(`${TP}.`,yP),DP=e=>({kind:`segment`,name:e}),OP=`${X}tab`,kP=e=>`${OP}.${e}`,AP=e=>`${kP(e)}.toggle`,jP=e=>({variable:OP,key:OP,member:e}),MP=`${X}save`,NP=`${X}preset.save`,PP=`${X}preset.delete`,FP=e=>`${X}${e}`,IP=e=>`${X}apply.${e}`,LP=e=>`${X}reset.${e}`,RP=`${X}themeDefault.save`,zP=`${X}themeDefault.differs`,BP=`${X}themeDefault.theme`,VP={when:`{{ .${zP} }}`,template:`{{ action "${RP}" (printf "⤓ default for %s" .${BP}) }} {{ swatch "${IP(`theme`)}" .${BP} }}`},HP=`${X}resetAll`,UP=`${Cj}.toggle`,WP=`${X}undo`,GP=`${X}back`,KP=`${GP}.step`,qP=`${X}navigation.back`,JP=GP,YP={template:`{{ if gt .${qP} 0 }}{{ action "${GP}" "◁" }}{{ else }}{{ fg (${dM}) "◁" }}{{ end }}`},XP=`${X}redo`,ZP=`${X}doctor`,QP=`${ZP}.run`,$P=e=>`${ZP}.fix.${e}`,eF=(e,t)=>`${ZP}.mark.${e}.${t}`,tF=e=>`${ZP}.${e}`,nF={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},rF=wA(`${X}pickers`),iF=e=>`${X}${e}`,aF=e=>`${iF(e)}.toggle`,oF=e=>eM(e)?wA(`${X}${e}Pickers`):rF,sF=e=>{let t=oF($j[Zj[e].beside]);return{variable:t,key:t,member:e}},cF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${PP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},lF=(e,t)=>`${X}list.${e}.${t}`,uF=e=>`${X}resettable.${e}`,dF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${uF(e)}`).join(` `)})`,fF=Fv.map(e=>[Pv[e].setting,e]),pF={variables:{},actions:{},segments:{}},mF=Object.fromEntries(fF.map(([e,t])=>[e,zj(`${X}help.${e}`,lM[t],[],pF)])),hF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],gF=e=>{let t=t=>`.${zv(e,t)}`,n=hF.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 }}`},_F=`{{ if eq .${Lv(`by`)} "feed" }} {{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ end }}`,vF=Object.fromEntries(fF.map(([e,t])=>[e,gF(t)])),yF=Object.keys(Sy).map(e=>{let t=Sy[e],n=zA(t.configKey),r=IA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,IP(e),oF($j[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>cF[e])}}),bF=e=>yF.filter(t=>$j[t.name]===e),xF=e=>yF.filter(t=>tM($j[t.name],e)),SF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${dF(xF(e).map(e=>e.name))}))`,CF=e=>Qj.filter(t=>Zj[t].beside===e),wF=e=>bF(e).flatMap(e=>[IF(e),...[mF[e.name]].filter(e=>e!==void 0),...CF(e.name).map(e=>wi(iF(e),sF(e),UF(e),`drop`))]);new Set(yF.flatMap(e=>[e.sessionKey,e.configKey]));const TF=oP(HP,{arm:`⟲`,confirm:`⟲ reset all?`},yF.map(e=>LP(e.name))),EF=[`unsaved`,`history.undo`,`history.redo`],DF=e=>`${X}${e}`,OF=DF(`unsaved`),kF=(e,t)=>({body:t,shown:`(gt .${DF(e)} 0)`}),AF=[kF(`unsaved`,`{{ action "${MP}" (printf "💾 save %d" .${OF}) }}`),kF(`history.undo`,`{{ action "${WP}" "↶" }}`),kF(`history.redo`,`{{ action "${XP}" "↷" }}`),{body:TF.template,shown:`(or ${dF(yF.map(e=>e.name))} ${TF.armed})`}],jF={when:`{{ or ${AF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+AF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},MF=[{step:TF,place:`door`},{step:wP,place:`session`}],NF=e=>e.map(e=>e.step.disarm),PF=NF(MF),FF=NF(MF.filter(e=>e.place!==`door`));function IF(e){let t=FP(e.name);return e.control.kind===`inline`?DP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>DP(lF(e.name,n)))},`drop`)}function LF(e){return e===Cj}function RF(e){let t=DP(Cj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[RF(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 zF(e){return BF(e)>0?e:RF(e)}function BF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&LF(n.name)&&(t+=1);return t}function VF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&LF(e.name)||e.opens!==void 0&&VF(e.opens.body,!0):e.children.some(e=>VF(e,n))}const HF={door:{direction:`horizontal`,content:[DP(JP)],after:[DP(bP),DP(MP)]},session:{direction:`vertical`,content:[DP(xP),{kind:`container`,direction:`horizontal`,children:[DP(CP),DP(TP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[DP(NP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[DP(ZP),...FN.map(e=>DP(tF(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[DP(RP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function UF(e){let{direction:t,content:n,after:r}=HF[e];return{kind:`container`,direction:t,children:[...n,...wF(e),...r]}}function WF(e){return e.kind===`segment`?LF(e.name)?wi(e.name,Tj,KF,`above`):e:qF(e)}function GF(){return{kind:`container`,direction:`vertical`,children:[UF(`door`),{kind:`container`,direction:`horizontal`,children:Yj.map(({member:e})=>wi(kP(e),jP(e),UF(e),`drop`))}]}}const KF=GF();function qF(e){return{...e,children:e.children.map(e=>WF(e))}}function JF(e){let t={variables:{[Cj]:Ai(Cj,yi)},actions:{[UP]:N(Cj,wj),[Cj]:{do:[UP,...PF]},[QP]:{doctor:`run`},...SP.actions,...wP.actions,...EP.actions,[MP]:{save:!0},[WP]:{undo:!0},[KP]:{back:!0},[GP]:{do:[KP,...PF]},[XP]:{redo:!0},[NP]:{preset:`save`},[RP]:{themeDefault:`save`},[PP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[Cj]:{template:`{{ $door := ${Oi(Cj,ki(e),ki(`✖`))} }}{{ if ${Ei(Tj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+_F},[xP]:{template:SP.template},[CP]:{template:wP.template,when:wP.when},[TP]:{template:EP.template,bg:EP.bg,when:EP.when},[JP]:YP,[MP]:jF,[RP]:VP,[NP]:{template:`{{ action "${NP}" "+ preset" }}`},[ZP]:{template:`{{ action "${QP}" "🩺 doctor" }}`},[bP]:{template:`{{ action "${Oj}" "✎ arrange" "✎ done" }}`}}};t.variables[zP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[BP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[qP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of EF)t.variables[DF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[OP]=Ai(OP,`session`);for(let{member:e,label:n}of Yj){t.actions[AP(e)]=N(OP,e),t.actions[kP(e)]={do:[AP(e),...FF]};let r=SF(e);t.segments[kP(e)]={template:`{{ ${Oi(kP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,wP.variables,TF.variables),XF(t),YF(t),t}function YF(e){for(let t of FN){let n=BN(t.name),r=$P(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?KM:[];for(let n of i)e.actions[eF(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${eF(t.name,e)}" "${nF[e]}" }}`).join(``);e.segments[tF(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 XF(e){for(let t of yF){Object.assign(e.actions,t.control.actions);let n=LP(t.name);e.actions[n]={reset:t.configKey},e.variables[uF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${uF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[FP(t.name)]={template:`${t.control.template}${vF[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[lF(t.name,r)]=n})}Object.assign(e.actions,TF.actions),Object.assign(e.variables,pF.variables),Object.assign(e.actions,pF.actions),Object.assign(e.segments,pF.segments);for(let t of Qj){let n=sF(t);e.actions[aF(t)]=N(n.key,n.member),e.segments[iF(t)]={template:`{{ action "${aF(t)}" ${SF(t)(Zj[t].trigger)} }}`}}}function ZF(e){let{variables:t,actions:n}=Lj();Object.assign(e.variables,t),Object.assign(e.actions,n)}function QF(e){let t=JF(e.globals.menuGlyph??`🍫`);ZF(t);let n={...e.presets},r=[];for(let t of $b(e.presets)){let{node:i}=nx(e,t),a=WF(zF(i));r.push(a),n[t]={...tx(e.presets,t),root:a}}let i=fA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const $F=`${_A}live`,eI=[`☐ live`,`☑ live`],tI=`${_A}done`,nI=`${_A}cancel`,rI=`${_A}rewind`,iI=`${_A}changes`,aI=`(gt .${iI} 0)`,oI=`(or ${aI} (gt .${OF} 0))`,sI={variable:$F,key:$F,member:`open`};function cI(e){return`${_A}configuring.p${e}`}function lI(e){return`and ${Ei(Mj)} (not ${Ei(sI)}) (ne .${cI(e)} "true")`}function uI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Dj} "${Ci(e)}")`).join(` `)} false }}`}}function dI(e,t,n){return`{{ if ${lI(e)} }}${t}{{ else }}${n}{{ end }}`}const fI=`{{ and ${Ei(Mj)} .preset.customized }}`,pI=yA;function mI(e){return new Map([...sx(e),...gI(e)])}const hI=`${_A}addable`;function gI(e){return new Map([[hI,{members:Object.keys(e.segments).filter(e=>!pI(e)),library:{groups:bj.map(e=>({id:e,label:xj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function _I(e,t,n){return n.segments[e]={template:t,when:Nj,bg:Vj},{kind:`segment`,name:e}}function vI(e,t,n){let r=`${_A}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function yI(e){return`{{ if ${Ei(Mj)} }}${e}{{ end }}`}function bI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(Mj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function xI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function SI(e,t,n){return`${Aj}${e}.${t}.${n}`}function CI(e,t,n,r){let i=S_(n),a=`${_A}${e.presetIdent}`,o=jj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=wA(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:Dj,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=SI(e.presetIdent,i,r),l=`${Aj}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=IA(PA(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}" "${qj}" }}`,ref:{variable:Dj,key:Dj,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const wI=`${_A}label:`;function TI(e){if(e.startsWith(wI)){let t=e.slice(wI.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function EI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${wI}${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`,bI([r.ref],`{{ ${lI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function DI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${_A}${i}.insert.${t}`,s=`${_A}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:hI,anchor:n,relation:r};let c=SA(o),l=CA(s,o,void 0),u=EA(l),d=TA(l,c);return a.variables[l]={...Ai(l,yi),within:[Mj]},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 OI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!pI(e.name)),i=e=>OI(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(pI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[DI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=DI(t,u,c,`after`),f=vI(t,u,c),p=t.segments[o.name],m=CI(t,u,o,V_(p)),h=yI(f),g=yI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>_I(e.host,e.template,t.artifacts)),{...EI(o,p,t,m),lead:h,trail:g},{...s,when:dI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},_I(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:bI(xI(n),dI(t.presetIdent,`true`,e.when))}}}function kI(e,t,n,r,i,a,o){let s=`${_A}${t}.resetLayout`,c=`${_A}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:fI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},AI(e,o)]}}function AI(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),AI(n,t)]}:{...e,children:[...e.children,t]}}function jI(e,t,n,r,i,a){let{node:o}=nx(e,t),s={presetIdent:pA(t),rootKey:pj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=OI(o,s);return n.variables[cI(s.presetIdent)]=uI(s.configured),kI(c,s.presetIdent,s.rootKey,n,r,i,a)}function MI(e){let t={variables:{},actions:{},segments:{}},n=zj(`${_A}help`,cM,[Mj],t);t.variables[$F]=Ai($F,yi),t.actions[$F]=N($F,sI.member),t.segments[$F]={template:Di($F,...eI),when:Nj};let r={kind:`segment`,name:$F},i=n;t.variables[iI]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[tI]={do:[MP,Oj]},t.segments[tI]={template:`{{ if ${oI} }}{{ action "${tI}" "✓ save" }}{{ else }}{{ action "${tI}" "✓ done" }}{{ end }}`,when:Nj},t.actions[rI]={rewind:!0},t.actions[nI]={do:[rI,Oj]},t.segments[nI]={template:`{{ action "${nI}" "↩ cancel" }}`,when:`{{ and ${Ei(Mj)} ${aI} }}`};let a=[{kind:`segment`,name:tI},{kind:`segment`,name:nI}],o={...e.presets},s=[];for(let n of $b(e.presets)){let c=jI(e,n,t,a,r,i);s.push(c),o[n]={...tx(e.presets,n),root:c}}let c=fA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function NI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function PI(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 FI(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 II=/^-?\d+$/;function LI(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 RI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!II.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 zI(e,t,n){return r=>r?II.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 BI(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=>!II.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 VI(e){return e===`config`?`set-config`:`set-state`}function HI(e,t,n){return t.kind===`int`?RI(`menu page "${e}"`):t.kind===`range`?zI(t.min,t.max,`${n} stepper "${e}"`):LI(t.allowed,`${n} "${e}"`,VI(n))}function UI(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:BI(e,n,t)}))}function WI(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 UI(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,HI(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 GI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};WI(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=WI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const KI=GI({},`config`,$I);function qI(e,t){return KI.register(e,t)}function JI(e){return KI.gateFor(e)}function YI(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:lx(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:[NI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[NI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:lx(e.insertSegmentFrom,t).members.map(t=>NI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function XI(e,t){let n=cj(e).get(t);return n===void 0?null:String(n)}function ZI(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?_j(n.persist):null;e?.scope===`preset-root`&&t.add(pj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function QI(e){let t=mI(e);return[...ZI(e),...Object.values(e.actions).flatMap(e=>YI(e,t))]}function $I(e){return UI(QI(e),`config`)}function eL(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:rL(t.segments,tL(t.segments,e.segments??{})),root:Yb(e.root??Hb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:rL(t.presets,nL(t.presets,e.presets??{})),themeDefaults:rL(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function tL(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 nL(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 rL(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function iL(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):sL(e,`${t}.cache`,n.cache)}function aL(e){return{required:!0,json:cL(),parse:(t,n,r,i)=>iL(t,n,i,e)??void 0}}const oL={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&uL(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 sL(e,t,n){return hv(e,oL,t,n)}function cL(){return Nv(oL)}const lL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function uL(e){return lL.test(e)}const dL=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 fL(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 pL(e){let t=dL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${fL(t)}`}function mL(e){let t=dL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${fL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const hL=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`]]),gL=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 _L(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 vL(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`?gL.get(e.field):void 0;if(n===void 0){let e=[...gL.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 ${_L(n.declare)} under a name of your own`}function yL(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,UL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function bL(){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 xL(){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 SL={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`?CL(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 CL(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 wL(){return{required:!1,json:Nv(SL),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,SL,`${t}.parse`,r.parse)??void 0)}}function TL(){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?EL(e,t,r.default):iv(e,t,r,`default`)}}function EL(e,t,n){if(n!==void 0)return DL(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 DL(e){return e!==null&&OL(e)}function OL(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(OL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(OL)}default:return!1}}const kL={value:bL(),default:bv()};function AL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:hL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const jL={path:AL(),type:Ov([`string`,`number`,`boolean`]),default:xL()},ML={name:Tv(),default:bv()},NL={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:wL(),cache:aL(`file`),default:TL()},PL={command:Tv(),parse:wL(),cache:aL(`shell`),default:TL()};function FL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const IL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:xL()},LL=FL(`a template variable recomputes whenever a variable it reads changes`),RL={layout:Tv(),default:bv()},zL=FL(`a time variable reads the instant its render is drawn at`),BL={key:Tv(),default:bv()},VL=`kind`;function HL(e,t,n={}){return{..._v(VL,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 UL={tag:VL,noun:`source kind`,memberNoun:`variable`,arms:{literal:HL(`literal`,kL),input:HL(`input`,jL),env:HL(`env`,ML),file:HL(`file`,NL),shell:HL(`shell`,PL),template:HL(`template`,IL,LL),time:HL(`time`,RL,zL),state:HL(`state`,BL)},retired:{git:vL}};function WL(){return Mv(UL)}function GL(){return{type:`object`,additionalProperties:WL()}}const KL=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 qL(e){let t=KL.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 JL=/^[A-Za-z_][A-Za-z0-9_]*$/,YL={pattern:JL.source},XL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},ZL={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`,...YL}}}]},default:XL}},QL=[`label`,`domain`,`default`],$L=[`min`,`max`,`step`,`atLeast`];function eR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function tR(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 eR(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 eR(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?eR(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=>!$L.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}}:eR(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 eR(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function nR(e,t,n){if(!sv(n))return eR(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))QL.includes(r)||eR(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${QL.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||eR(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=tR(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!rR(n.default)||!W_(o,n.default)?eR(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function rR(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const iR={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 aR(e){return B_.includes(e)}function oR(){return{required:!1,json:{type:`object`,propertyNames:{...YL,not:{enum:[...B_]}},additionalProperties:ZL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return eR(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(!JL.test(t)){eR(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(aR(t)){eR(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${iR[t]}`);continue}let r=nR(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const sR=vA.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function cR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${sR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!yA(i)?i:eR(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${vA.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function lR(){return{required:!1,json:{type:`object`,propertyNames:YL,additionalProperties:XL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return eR(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))rR(n)?o[t]=n:eR(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function uR(e){return new Set(Object.keys(e.segments).filter(e=>!yA(e)))}function dR(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)?_R:gR,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function fR(){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${qL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function pR(){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 mR(){return{required:!1,json:GL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return yL(e,`${t}.${n}`,i)}}}const hR={template:fR(),description:bv(),group:Ov(yj),width:pR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:mR(),settings:oR(),missingData:Ov(F_)},gR={noun:`segment key`,fields:hR},_R={noun:`segment key`,fields:{...hR,template:bv()}},vR=`#/definitions/LayoutNode`,yR={kind:`container`,direction:`vertical`,children:[]};function bR(e){return{required:!0,json:{const:e},parse:()=>e}}function xR(){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 SR(){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 CR(e){return{required:!0,json:{type:`array`,items:{$ref:vR}},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 wR={noun:`layout-node key`,fields:{kind:bR(`segment`),name:xR(),when:bv(),id:cR(),settings:lR()}},TR=()=>Ov(Eh),ER={noun:`layout-node key`,fields:{kind:bR(`container`),direction:SR(),children:CR(vv(()=>jR)),when:bv(),distribution:TR()}};function DR(){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 OR={noun:`layout-node key`,fields:{seg:DR(),when:bv(),id:cR(),settings:lR()}},kR={noun:`layout-node key`,fields:{h:CR(vv(()=>jR)),when:bv(),distribution:TR()}},AR={noun:`layout-node key`,fields:{v:CR(vv(()=>jR)),when:bv(),distribution:TR()}},jR=(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`])}),yR):{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`])}),yR;if(n.kind===`container`)return lv(e,ER,t,n)??yR;if(n.kind===`segment`)return lv(e,wR,t,n)??yR;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
178
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return XM([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${nN[e]}`)])}}},iN="re-run `cc-candybar install`";function aN(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:// — ${iN}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${iN}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${iN}`)}const oN={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}) — ${iN}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${iN}`};case`lost`:return XM([...aN(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 sN({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 cN(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${Fv.join(`|`)}>\``:e.checkout===null?iN:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function lN(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 — ${cN(e,`native`)}`];let{bundle:i,source:a}=sN(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} — ${cN(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 — ${cN(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 uN=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)`},dN={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`:`${uN(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:XM([...new Set(i.flatMap(e=>lN(n,r,e)))])}};function fN({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 pN(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const mN={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`?pN(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return XM([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=fN(e.value,n),u=XM([...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}}}},hN=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function gN(e,t){let n=LM(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?zM(e.terminal):{kind:`unknown`}}function _N({identified:e,tmuxClient:t},n){let r=RM(e),i=gN(e,n),a=LM(e)===null?hN:`${hN}, 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: ${BM}`];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 vN={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 XM(_N(t,n))}}},yN=e=>e.filter(e=>e.role===`statusline`),bN={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})=>CN(e,xN(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:SN(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:uN(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}}},xN=e=>{let t=yN(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`}},SN=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function CN(e,t){let n=VM(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 SN(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 WM(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 wN=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function TN(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return RM(e);case`bundling`:case`unread`:case`configured`:return[DM(e.name),e.version].filter(e=>e!==null).join(` `)}}function EN(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return LM(e);case`bundling`:case`unread`:return DM(e.name);case`configured`:{let t=DM(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 DN(e){let t=EN(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${wN(e.glyphs)}`}}const ON={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=DN(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=TN(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 ${wN(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=CM[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:MM(i.version,e);if(t===!0)return{ok:!0};let n=DM(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 ${wN(n)} — set a Nerd Font as its font`)}}}};function kN(e){return e.join(`, `)}function AN(e){return`or set missingData: "ignore" on ${kN(e)}`}function jN(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${kN(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`?[`${kN(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${AN(t)}`]:[`${kN(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${AN(t)}`]}function MN(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${kN(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${kN(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`:`${kN(n)}: ${uN(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`)?[`${kN(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${kN(n)}`]:[]}const NN={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>XM([...jN(e.pullRequests),...MN(e.rateLimits,t)])};function PN({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 ${qM/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const FN=[rN,dN,mN,oN,vN,$M,eN,tN,bN,ON,NN,{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`:`${uN(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:XM(e.value.flatMap(PN))}],IN=FN.filter(e=>e.takesMark);function LN(e){return FN.map(t=>({check:t,verdict:t.probe(e)}))}function RN(e){return FN.find(t=>t.name===e)}const zN=`${X}doctor.`;function BN(e){let t=`${zN}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function VN(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?LM(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 HN(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 UN(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}=sN(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const WN=e=>`${e>=0?`+`:``}${tr(e)}`;function GN({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${pN(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`:`${fN(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${fr(i.charge)}${i.charge.kind===`stand-in`?`(${WN(-i.charge.gap)})`:``}:${tr(i.charge.bytes)}`}/${tr(a)} postMortems=${s}`}function KN(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 qN(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>JN(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${as(i)}`;let a=yN(r.flatMap(e=>e.bars));return`frames=${yM.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${as(i)}`}function JN(e){let t=VM(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 YN(e){let t=HM(e,ZM);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${as(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function XN(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 ZN(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=DN(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 QN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function $N(e){return e.flatMap(({check:e,verdict:t})=>{let n=BN(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:QN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?h_:m_},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const eP={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function tP(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(eP).map(([t,n])=>[`${e}${t}`,n]))}}const nP=`armed`,rP=`disarmed`,iP=`.armed`,aP=e=>e.endsWith(iP);function oP(e,t,n){let r=`${e}${iP}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${nP}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:nP},[a]:{set:r,to:rP},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:rP}},disarm:a}}const sP=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function cP(e){return typeof e==`string`&&sP.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 lP(e){let t=cP(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const uP=[`/compact`,`/model`],dP=`/clear`;function fP(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=oP(`${e}clear`,{arm:dP,confirm:`${dP} ✓ confirm`},[n]);return{template:uP.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${uA} }}`,actions:{...Object.fromEntries(uP.map(e=>[t(e),{slash:lP(e)}])),...r.actions,[n]:{slash:lP(dP)}},variables:r.variables,disarm:r.disarm}}const pP=Array.from({length:10},(e,t)=>(t+1)*1e5),mP=pP[0],hP=pP[pP.length-1];function gP(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>=mP&&n<=hP?P(n):I(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${mP}–${hP} tokens)`)}function _P(e,t){let n=Math.min(t??hP,hP),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:pP.filter(e=>e<r).at(-1)??0,higher:pP.find(e=>e>r&&e<=n)??0}}function vP(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${uA} }}{{ 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:lP(`/autocompact auto`)},...Object.fromEntries(pP.map(t=>[`${e}${t}`,{slash:lP(`/autocompact ${t}`)}]))}}}const yP=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 }}`,bP=`${X}edit`,xP=`${X}toolbar`,SP=tP(X),CP=`${X}commands`,wP=fP(`${CP}.`),TP=`${X}autocompact`,EP=vP(`${TP}.`,yP),DP=e=>({kind:`segment`,name:e}),OP=`${X}tab`,kP=e=>`${OP}.${e}`,AP=e=>`${kP(e)}.toggle`,jP=e=>({variable:OP,key:OP,member:e}),MP=`${X}save`,NP=`${X}preset.save`,PP=`${X}preset.delete`,FP=e=>`${X}${e}`,IP=e=>`${X}apply.${e}`,LP=e=>`${X}reset.${e}`,RP=`${X}themeDefault.save`,zP=`${X}themeDefault.differs`,BP=`${X}themeDefault.theme`,VP={when:`{{ .${zP} }}`,template:`{{ action "${RP}" (printf "⤓ default for %s" .${BP}) }} {{ swatch "${IP(`theme`)}" .${BP} }}`},HP=`${X}resetAll`,UP=`${Cj}.toggle`,WP=`${X}undo`,GP=`${X}back`,KP=`${GP}.step`,qP=`${X}navigation.back`,JP=GP,YP={template:`{{ if gt .${qP} 0 }}{{ action "${GP}" "◁" }}{{ else }}{{ fg (${dM}) "◁" }}{{ end }}`},XP=`${X}redo`,ZP=`${X}doctor`,QP=`${ZP}.run`,$P=e=>`${ZP}.fix.${e}`,eF=(e,t)=>`${ZP}.mark.${e}.${t}`,tF=e=>`${ZP}.${e}`,nF={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},rF=wA(`${X}pickers`),iF=e=>`${X}${e}`,aF=e=>`${iF(e)}.toggle`,oF=e=>eM(e)?wA(`${X}${e}Pickers`):rF,sF=e=>{let t=oF($j[Zj[e].beside]);return{variable:t,key:t,member:e}},cF={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${PP}" (printf "🚮 delete %s" .${Sy.preset.effectiveVar}) }}`}},lF=(e,t)=>`${X}list.${e}.${t}`,uF=e=>`${X}resettable.${e}`,dF=e=>e.length===0?`false`:`(or ${e.map(e=>`.${uF(e)}`).join(` `)})`,fF=Fv.map(e=>[Pv[e].setting,e]),pF={variables:{},actions:{},segments:{}},mF=Object.fromEntries(fF.map(([e,t])=>[e,zj(`${X}help.${e}`,lM[t],[],pF)])),hF=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],gF=e=>{let t=t=>`.${zv(e,t)}`,n=hF.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 }}`},_F=`${X}fps`,vF=`{{ if eq .${Lv(`by`)} "feed" }}{{ printf "%2d" (int .${Lv(`fps`)}) }} fps{{ else }}${`polled`.padStart(6)}{{ end }}`,yF=Object.fromEntries(fF.map(([e,t])=>[e,gF(t)])),bF=Object.keys(Sy).map(e=>{let t=Sy[e],n=zA(t.configKey),r=IA({label:t.label,domain:n},t.sessionKey,t.effectiveVar,IP(e),oF($j[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>cF[e])}}),xF=e=>bF.filter(t=>$j[t.name]===e),SF=e=>bF.filter(t=>tM($j[t.name],e)),CF=e=>t=>`(print ${ki(t)} (ternary ${ki(` •`)} "" ${dF(SF(e).map(e=>e.name))}))`,wF=e=>Qj.filter(t=>Zj[t].beside===e),TF=e=>xF(e).flatMap(e=>[LF(e),...[mF[e.name]].filter(e=>e!==void 0),...wF(e.name).map(e=>wi(iF(e),sF(e),WF(e),`drop`))]);new Set(bF.flatMap(e=>[e.sessionKey,e.configKey]));const EF=oP(HP,{arm:`⟲`,confirm:`⟲ reset all?`},bF.map(e=>LP(e.name))),DF=[`unsaved`,`history.undo`,`history.redo`],OF=e=>`${X}${e}`,kF=OF(`unsaved`),AF=(e,t)=>({body:t,shown:`(gt .${OF(e)} 0)`}),jF=[AF(`unsaved`,`{{ action "${MP}" (printf "💾 save %d" .${kF}) }}`),AF(`history.undo`,`{{ action "${WP}" "↶" }}`),AF(`history.redo`,`{{ action "${XP}" "↷" }}`),{body:EF.template,shown:`(or ${dF(bF.map(e=>e.name))} ${EF.armed})`}],MF={when:`{{ or ${jF.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+jF.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},NF=[{step:EF,place:`door`},{step:wP,place:`session`}],PF=e=>e.map(e=>e.step.disarm),FF=PF(NF),IF=PF(NF.filter(e=>e.place!==`door`));function LF(e){let t=FP(e.name);return e.control.kind===`inline`?DP(t):wi(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>DP(lF(e.name,n)))},`drop`)}function RF(e){return e===Cj}function zF(e){let t=DP(Cj);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[zF(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 BF(e){return VF(e)>0?e:zF(e)}function VF(e){let t=0;for(let n of E_(e))n.kind===`segment`&&RF(n.name)&&(t+=1);return t}function HF(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&RF(e.name)||e.opens!==void 0&&HF(e.opens.body,!0):e.children.some(e=>HF(e,n))}const UF={door:{direction:`horizontal`,content:[DP(JP)],after:[DP(bP),DP(MP)]},session:{direction:`vertical`,content:[DP(xP),{kind:`container`,direction:`horizontal`,children:[DP(CP),DP(TP)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[DP(NP)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[DP(ZP),...FN.map(e=>DP(tF(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[DP(RP)]},toggles:{direction:`horizontal`,content:[],after:[]}};function WF(e){let{direction:t,content:n,after:r}=UF[e];return{kind:`container`,direction:t,children:[...n,...TF(e),...r]}}function GF(e){return e.kind===`segment`?RF(e.name)?{kind:`container`,direction:`horizontal`,children:[wi(e.name,Tj,qF,`above`),DP(_F)]}:e:JF(e)}function KF(){return{kind:`container`,direction:`vertical`,children:[WF(`door`),{kind:`container`,direction:`horizontal`,children:Yj.map(({member:e})=>wi(kP(e),jP(e),WF(e),`drop`))}]}}const qF=KF();function JF(e){return{...e,children:e.children.map(e=>GF(e))}}function YF(e){let t={variables:{[Cj]:Ai(Cj,yi)},actions:{[UP]:N(Cj,wj),[Cj]:{do:[UP,...FF]},[QP]:{doctor:`run`},...SP.actions,...wP.actions,...EP.actions,[MP]:{save:!0},[WP]:{undo:!0},[KP]:{back:!0},[GP]:{do:[KP,...FF]},[XP]:{redo:!0},[NP]:{preset:`save`},[RP]:{themeDefault:`save`},[PP]:{preset:`delete`,name:`{{ .${Sy.preset.effectiveVar} }}`}},segments:{[Cj]:{template:`{{ $door := ${Oi(Cj,ki(e),ki(`✖`))} }}{{ if ${Ei(Tj)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`},[_F]:{template:vF},[xP]:{template:SP.template},[CP]:{template:wP.template,when:wP.when},[TP]:{template:EP.template,bg:EP.bg,when:EP.when},[JP]:YP,[MP]:MF,[RP]:VP,[NP]:{template:`{{ action "${NP}" "+ preset" }}`},[ZP]:{template:`{{ action "${QP}" "🩺 doctor" }}`},[bP]:{template:`{{ action "${Oj}" "✎ arrange" "✎ done" }}`}}};t.variables[zP]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[BP]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[qP]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of DF)t.variables[OF(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[OP]=Ai(OP,`session`);for(let{member:e,label:n}of Yj){t.actions[AP(e)]=N(OP,e),t.actions[kP(e)]={do:[AP(e),...IF]};let r=CF(e);t.segments[kP(e)]={template:`{{ ${Oi(kP(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,wP.variables,EF.variables),ZF(t),XF(t),t}function XF(e){for(let t of FN){let n=BN(t.name),r=$P(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?KM:[];for(let n of i)e.actions[eF(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${eF(t.name,e)}" "${nF[e]}" }}`).join(``);e.segments[tF(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 ZF(e){for(let t of bF){Object.assign(e.actions,t.control.actions);let n=LP(t.name);e.actions[n]={reset:t.configKey},e.variables[uF(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${uF(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[FP(t.name)]={template:`${t.control.template}${yF[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[lF(t.name,r)]=n})}Object.assign(e.actions,EF.actions),Object.assign(e.variables,pF.variables),Object.assign(e.actions,pF.actions),Object.assign(e.segments,pF.segments);for(let t of Qj){let n=sF(t);e.actions[aF(t)]=N(n.key,n.member),e.segments[iF(t)]={template:`{{ action "${aF(t)}" ${CF(t)(Zj[t].trigger)} }}`}}}function QF(e){let{variables:t,actions:n}=Lj();Object.assign(e.variables,t),Object.assign(e.actions,n)}function $F(e){let t=YF(e.globals.menuGlyph??`🍫`);QF(t);let n={...e.presets},r=[];for(let t of $b(e.presets)){let{node:i}=nx(e,t),a=GF(BF(i));r.push(a),n[t]={...tx(e.presets,t),root:a}}let i=fA(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const eI=`${_A}live`,tI=[`☐ live`,`☑ live`],nI=`${_A}done`,rI=`${_A}cancel`,iI=`${_A}rewind`,aI=`${_A}changes`,oI=`(gt .${aI} 0)`,sI=`(or ${oI} (gt .${kF} 0))`,cI={variable:eI,key:eI,member:`open`};function lI(e){return`${_A}configuring.p${e}`}function uI(e){return`and ${Ei(Mj)} (not ${Ei(cI)}) (ne .${lI(e)} "true")`}function dI(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${Dj} "${Ci(e)}")`).join(` `)} false }}`}}function fI(e,t,n){return`{{ if ${uI(e)} }}${t}{{ else }}${n}{{ end }}`}const pI=`{{ and ${Ei(Mj)} .preset.customized }}`,mI=yA;function hI(e){return new Map([...sx(e),..._I(e)])}const gI=`${_A}addable`;function _I(e){return new Map([[gI,{members:Object.keys(e.segments).filter(e=>!mI(e)),library:{groups:bj.map(e=>({id:e,label:xj[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function vI(e,t,n){return n.segments[e]={template:t,when:Nj,bg:Vj},{kind:`segment`,name:e}}function yI(e,t,n){let r=`${_A}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${Yh}`}) (action "${r}" "✖") }}`}function bI(e){return`{{ if ${Ei(Mj)} }}${e}{{ end }}`}function xI(e,t){return e.reduce((e,t)=>`{{ if and ${Ei(Mj)} ${Ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function SI(e){return e.flatMap(e=>[...E_(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function CI(e,t,n){return`${Aj}${e}.${t}.${n}`}function wI(e,t,n,r){let i=S_(n),a=`${_A}${e.presetIdent}`,o=jj(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=wA(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:Dj,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=CI(e.presetIdent,i,r),l=`${Aj}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=IA(PA(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}" "${qj}" }}`,ref:{variable:Dj,key:Dj,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const TI=`${_A}label:`;function EI(e){if(e.startsWith(TI)){let t=e.slice(TI.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function DI(e,t,n,r){let{artifacts:i}=n,a=S_(e),o=`${TI}${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`,xI([r.ref],`{{ ${uI(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(B_.map(e=>[e,r.drafts[e]]))}}function OI(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${_A}${i}.insert.${t}`,s=`${_A}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:gI,anchor:n,relation:r};let c=SA(o),l=CA(s,o,void 0),u=EA(l),d=TA(l,c);return a.variables[l]={...Ai(l,yi),within:[Mj]},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 kI(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!mI(e.name)),i=e=>kI(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(mI(o.name)){n.push(s);continue}let c=S_(o),l=a===r?[OI(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=OI(t,u,c,`after`),f=yI(t,u,c),p=t.segments[o.name],m=wI(t,u,o,V_(p)),h=bI(f),g=bI(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>vI(e.host,e.template,t.artifacts)),{...DI(o,p,t,m),lead:h,trail:g},{...s,when:fI(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},vI(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:xI(SI(n),fI(t.presetIdent,`true`,e.when))}}}function AI(e,t,n,r,i,a,o){let s=`${_A}${t}.resetLayout`,c=`${_A}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:pI},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},jI(e,o)]}}function jI(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),jI(n,t)]}:{...e,children:[...e.children,t]}}function MI(e,t,n,r,i,a){let{node:o}=nx(e,t),s={presetIdent:pA(t),rootKey:pj(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=kI(o,s);return n.variables[lI(s.presetIdent)]=dI(s.configured),AI(c,s.presetIdent,s.rootKey,n,r,i,a)}function NI(e){let t={variables:{},actions:{},segments:{}},n=zj(`${_A}help`,cM,[Mj],t);t.variables[eI]=Ai(eI,yi),t.actions[eI]=N(eI,cI.member),t.segments[eI]={template:Di(eI,...tI),when:Nj};let r={kind:`segment`,name:eI},i=n;t.variables[aI]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[nI]={do:[MP,Oj]},t.segments[nI]={template:`{{ if ${sI} }}{{ action "${nI}" "✓ save" }}{{ else }}{{ action "${nI}" "✓ done" }}{{ end }}`,when:Nj},t.actions[iI]={rewind:!0},t.actions[rI]={do:[iI,Oj]},t.segments[rI]={template:`{{ action "${rI}" "↩ cancel" }}`,when:`{{ and ${Ei(Mj)} ${oI} }}`};let a=[{kind:`segment`,name:nI},{kind:`segment`,name:rI}],o={...e.presets},s=[];for(let n of $b(e.presets)){let c=MI(e,n,t,a,r,i);s.push(c),o[n]={...tx(e.presets,n),root:c}}let c=fA(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function PI(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function FI(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 II(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 LI=/^-?\d+$/;function RI(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 zI(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!LI.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 BI(e,t,n){return r=>r?LI.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 VI(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=>!LI.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 HI(e){return e===`config`?`set-config`:`set-state`}function UI(e,t,n){return t.kind===`int`?zI(`menu page "${e}"`):t.kind===`range`?BI(t.min,t.max,`${n} stepper "${e}"`):RI(t.allowed,`${n} "${e}"`,HI(n))}function WI(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:VI(e,n,t)}))}function GI(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 WI(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,UI(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 KI(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};GI(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=GI(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const qI=KI({},`config`,eL);function JI(e,t){return qI.register(e,t)}function YI(e){return qI.gateFor(e)}function XI(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:lx(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:[PI({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[PI({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:lx(e.insertSegmentFrom,t).members.map(t=>PI({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function ZI(e,t){let n=cj(e).get(t);return n===void 0?null:String(n)}function QI(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?_j(n.persist):null;e?.scope===`preset-root`&&t.add(pj(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function $I(e){let t=hI(e);return[...QI(e),...Object.values(e.actions).flatMap(e=>XI(e,t))]}function eL(e){return WI($I(e),`config`)}function tL(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:iL(t.segments,nL(t.segments,e.segments??{})),root:Yb(e.root??Hb,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:iL(t.presets,rL(t.presets,e.presets??{})),themeDefaults:iL(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function nL(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 rL(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 iL(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function aL(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):cL(e,`${t}.cache`,n.cache)}function oL(e){return{required:!0,json:lL(),parse:(t,n,r,i)=>aL(t,n,i,e)??void 0}}const sL={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&dL(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 cL(e,t,n){return hv(e,sL,t,n)}function lL(){return Nv(sL)}const uL=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function dL(e){return uL.test(e)}const fL=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 pL(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 mL(e){let t=fL.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${pL(t)}`}function hL(e){let t=fL.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${pL(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const gL=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`]]),_L=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 vL(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 yL(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`?_L.get(e.field):void 0;if(n===void 0){let e=[..._L.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 ${vL(n.declare)} under a name of your own`}function bL(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,WL,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function xL(){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 SL(){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 CL={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`?wL(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 wL(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 TL(){return{required:!1,json:Nv(CL),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,CL,`${t}.parse`,r.parse)??void 0)}}function EL(){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?DL(e,t,r.default):iv(e,t,r,`default`)}}function DL(e,t,n){if(n!==void 0)return OL(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 OL(e){return e!==null&&kL(e)}function kL(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(kL);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(kL)}default:return!1}}const AL={value:xL(),default:bv()};function jL(){let e=Tv();return{...e,parse:(t,n,r,i)=>{let a=e.parse(t,n,r,i),o=a===void 0?void 0:gL.get(a);return o===void 0?a:mv(t,`${n}.${r}`,`${n}.${r} "${a}" is no longer in the payload: ${o}`)??void 0}}}const ML={path:jL(),type:Ov([`string`,`number`,`boolean`]),default:SL()},NL={name:Tv(),default:bv()},PL={path:Dv(),readMode:Ov([`whole`,`first-line`]),parse:TL(),cache:oL(`file`),default:EL()},FL={command:Tv(),parse:TL(),cache:oL(`shell`),default:EL()};function IL(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const LL={template:Tv(),type:Ov([`string`,`number`,`boolean`]),default:SL()},RL=IL(`a template variable recomputes whenever a variable it reads changes`),zL={layout:Tv(),default:bv()},BL=IL(`a time variable reads the instant its render is drawn at`),VL={key:Tv(),default:bv()},HL=`kind`;function UL(e,t,n={}){return{..._v(HL,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 WL={tag:HL,noun:`source kind`,memberNoun:`variable`,arms:{literal:UL(`literal`,AL),input:UL(`input`,ML),env:UL(`env`,NL),file:UL(`file`,PL),shell:UL(`shell`,FL),template:UL(`template`,LL,RL),time:UL(`time`,zL,BL),state:UL(`state`,VL)},retired:{git:yL}};function GL(){return Mv(WL)}function KL(){return{type:`object`,additionalProperties:GL()}}const qL=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 JL(e){let t=qL.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 YL=/^[A-Za-z_][A-Za-z0-9_]*$/,XL={pattern:YL.source},ZL={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},QL={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`,...XL}}}]},default:ZL}},$L=[`label`,`domain`,`default`],eR=[`min`,`max`,`step`,`atLeast`];function tR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,t.split(`.`))})}function nR(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 tR(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 tR(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?tR(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=>!eR.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}}:tR(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 tR(e,t,`domain must be "bool", a list of words, or { min, max }, got ${K(n)}`)}function rR(e,t,n){if(!sv(n))return tR(e,t,`${t} must be { label, domain, default }, got ${cv(n)}`);for(let r of Object.keys(n))$L.includes(r)||tR(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${$L.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||tR(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=nR(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!iR(n.default)||!W_(o,n.default)?tR(e,`${t}.default`,`default must be ${J_(o)}, got ${K(n.default)}`):o}function iR(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const aR={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 oR(e){return B_.includes(e)}function sR(){return{required:!1,json:{type:`object`,propertyNames:{...XL,not:{enum:[...B_]}},additionalProperties:QL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return tR(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(!YL.test(t)){tR(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(oR(t)){tR(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${aR[t]}`);continue}let r=rR(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const cR=vA.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function lR(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${cR})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!yA(i)?i:tR(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${vA.map(e=>`"${e}"`).join(`, `)} namespaces, got ${K(i)}`)}}}function uR(){return{required:!1,json:{type:`object`,propertyNames:XL,additionalProperties:ZL},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!sv(i))return tR(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))iR(n)?o[t]=n:tR(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${cv(n)}`);return o}}}function dR(e){return new Set(Object.keys(e.segments).filter(e=>!yA(e)))}function fR(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)?vR:_R,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function pR(){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${JL(t.slice(9))}`)??void 0:nv(e,t,r,n)??void 0}}function mR(){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 hR(){return{required:!1,json:KL(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return bL(e,`${t}.${n}`,i)}}}const gR={template:pR(),description:bv(),group:Ov(yj),width:mR(),justify:Ov(Y_),truncate:Ov(X_),bg:bv(),fg:bv(),when:bv(),palette:wv(),vars:hR(),settings:sR(),missingData:Ov(F_)},_R={noun:`segment key`,fields:gR},vR={noun:`segment key`,fields:{...gR,template:bv()}},yR=`#/definitions/LayoutNode`,bR={kind:`container`,direction:`vertical`,children:[]};function xR(e){return{required:!0,json:{const:e},parse:()=>e}}function SR(){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 CR(){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 wR(e){return{required:!0,json:{type:`array`,items:{$ref:yR}},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 TR={noun:`layout-node key`,fields:{kind:xR(`segment`),name:SR(),when:bv(),id:lR(),settings:uR()}},ER=()=>Ov(Eh),DR={noun:`layout-node key`,fields:{kind:xR(`container`),direction:CR(),children:wR(vv(()=>MR)),when:bv(),distribution:ER()}};function OR(){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 kR={noun:`layout-node key`,fields:{seg:OR(),when:bv(),id:lR(),settings:uR()}},AR={noun:`layout-node key`,fields:{h:wR(vv(()=>MR)),when:bv(),distribution:ER()}},jR={noun:`layout-node key`,fields:{v:wR(vv(()=>MR)),when:bv(),distribution:ER()}},MR=(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`])}),bR):{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`])}),bR;if(n.kind===`container`)return lv(e,DR,t,n)??bR;if(n.kind===`segment`)return lv(e,TR,t,n)??bR;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`])}),yR;if(n.kind===`group`){let r=lv(e,RR,t,n);return r===null?yR:(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}),BR(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`])}),yR}if(a){let r=lv(e,OR,t,n);return r===null?yR:{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,kR,t,n);return r===null?yR:{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,AR,t,n);return r===null?yR:{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`])}),yR};function MR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Bb.source},additionalProperties:{$ref:vR}},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(!Bb.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]=jR(e,`${t}.${n}.${r}`,o)}return a}}}const NR={noun:`root key`,fields:{rows:MR(),when:bv(),distribution:TR()}};function PR(e,t,n){return sv(n)&&`rows`in n?lv(e,NR,t,n)??{rows:{}}:jR(e,t,n)}function FR(){return{required:!0,json:{type:`string`,pattern:Bb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Bb.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 IR(){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 LR(){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 RR={noun:`layout-node key`,fields:{kind:bR(`group`),name:FR(),label:LR(),open:xv(),direction:Ov(b_),key:IR(),bg:bv(),fg:bv(),when:bv(),distribution:TR(),children:CR(vv(()=>jR))}};function zR(e){return e.key??`groups.`+e.name}function BR(e){let t=mA+e.name;return wi(t,{variable:t,key:zR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function VR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function HR(e,t){xA(e,t,mA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&VR(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}.`)&&zR(t)===zR(r)&&VR(e,t.path,`group "${t.name}" shares key "${zR(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=zR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&VR(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=mA+e.name,r=zR(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 UR=`menu`,WR=`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`,GR=e=>e.kind===`call`&&e.name===`dict`,KR=e=>e.kind===`literal`&&typeof e.value!=`object`,qR=e=>xi(``,e,2)===void 0;function JR(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&&GR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(GR))return t(`whose options (dict …) is not its last argument — ${WR}`);if(i!==void 0&&a===void 0&&!KR(i)&&qR(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} — ${WR}`);let c=a===void 0?{}:QT(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=AA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=bA(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 "${wA(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 YR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===UR).map(JR)}catch{return`parse-failed`}}function XR(e,t){let n=YR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:CA(t,e.apply,e.options.key),member:SA(e.apply)}]:[])}function ZR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(UR)}catch{return!1}}function QR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function $R(e,t){xA(e,t,hA,`{{ menu }} helpers`),xA(e,t,gA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))ZR(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`&&ZR(i)&&QR(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_(qb(t.root)))typeof n.when==`string`&&ZR(n.when)&&QR(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||!ZR(r))continue;let n=YR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:ez(r.apply);n!==void 0&&QR(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function ez(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(SA(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 tz(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 $b(e.presets)){let a=new Map,s=new Map;for(let c of E_(nx(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,YR(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`||ez(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=SA(i),f=CA(u,i,l.key),p=EA(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=TA(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 nz(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=rz(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 rz(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=fx.filter(e=>e in n);return i.length===1?az(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${fx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function iz(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const az=e=>({set:(e,t,n)=>Vz(e,t,n,`set`,Lz),persist:(e,t,n)=>Vz(e,t,n,`persist`,Rz),copy:oz(`copy`),open:oz(`open`),reset:sz,undo:lz(`undo`),redo:lz(`redo`),back:lz(`back`),rewind:lz(`rewind`),save:lz(`save`),preset:uz,themeDefault:dz,doctor:pz,slash:mz,run:_z(e),do:vz});function oz(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 sz(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=yz(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 cz={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 lz(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 — ${cz[e]}), got ${K(r[e])}`),null)}}function uz(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 dz(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 fz={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function pz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(fz,r),a=i?fz[r]:[...new Set(Object.values(fz).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(fz).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?IN:FN;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 KM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${KM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function mz(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=cP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const hz=[`run`,`env`,`refreshes`],gz=/^[A-Za-z_][A-Za-z0-9_]*$/;function _z(e){return(t,n,r)=>{for(let e of Object.keys(r))hz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${hz.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])=>!gz.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}}}gz.source;function vz(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 yz(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 bz={set:`the SessionState key to write`,persist:`the config globals field to write`};function xz(e,t,n,r){let i=bz[r],a=yz(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 Sz(e){return e===`set`?`set-state`:`set-config`}const Cz={to:Hz(`set`)},wz={to:Hz(`persist`)},Tz={from:Uz(`set`)},Ez={from:Uz(`persist`)},Dz={min:Jz(),max:Jz(),by:Jz()},Oz={int:Gz()},kz={cycle:Wz(`set`)},Az={cycle:Wz(`persist`)},jz={removeSegment:Kz(`removeSegment`)},Mz={insertSegment:Kz(`insertSegment`),anchor:Kz(`anchor`),relation:qz()},Nz={insertSegmentFrom:Uz(`persist`),anchor:Kz(`anchor`),relation:qz()},Pz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Fz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Iz(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 Lz=[Iz(`set`,Cz),Iz(`set`,Tz),Iz(`set`,Dz,[Pz,Fz]),Iz(`set`,Oz),Iz(`set`,kz)],Rz=[Iz(`persist`,wz),Iz(`persist`,Ez),Iz(`persist`,Dz,[Pz,Fz]),Iz(`persist`,Az),Iz(`persist`,jz),Iz(`persist`,Mz,[],[`insertSegment`]),Iz(`persist`,Nz,[],[`insertSegmentFrom`])];function zz(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 Bz(e){let t=zz(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 Vz(e,t,n,r,i){let a=xz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${Bz(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 Hz(e){let t=Sz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>yz(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 Uz(e){let t=Sz(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 Wz(e){let t=Sz(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 Gz(){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 Kz(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 qz(){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 Jz(){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 Yz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Xz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Zz(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:Yz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Xz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const Qz={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:PR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:tj(),parse:(e,t,n,r)=>r[n]===void 0?void 0:ej(e,`${t}.${n}`,r[n])}}};function $z(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,Qz,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function eB(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 tB({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),[...[...mx(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Px(e,t)?Object.keys(n):Mx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=rB(n=>i(n).flatMap(n=>[...Ox(n,t).keys()].map(t=>({path:t,reaches:Vx(t,e)}))));return{ofTemplate:a,calls:rB(e=>new Set(i(e).flatMap(e=>[...Ix(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 nB(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function rB(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const iB=new WeakMap;function aB(e){let t=iB.get(e);return t===void 0&&(t=tB({names:new Set([...Bx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),iB.set(e,t)),t}function oB(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 sB=new WeakMap;function cB(e){let t=sB.get(e);return t===void 0&&(t=uB(e),sB.set(e,t)),t}function lB(e){return cB(e).projections}function uB(e){let t=new Map(Bx(e)),n=new Map,r={reads:aB(e),projections:n,clock:gk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=nB(e,r),i=t===void 0?null:sA(t);i&&n.set(e,`reads the draw's "${i}" (${oA[i]})`)}let i=fB(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=oB(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=oB(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=nB(r,i);if(t===void 0||n.has(r))continue;let o=lA(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 dB(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 fB(e){let t=dB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function pB(e,t){return oB(e,cB(t))}function mB(e){return t=>oB(t,e)!==null}const hB={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 gB(e,t){let n=new Map;for(let e of Object.keys(t)){let t=pA(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 _B(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)?Yz(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`])}),gB(e,t.presets);let i=Ux(t);for(let t of i.names)t!==`settings`&&!t.startsWith(bB)||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)=>{BF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" ${BF(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}),VF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" 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:hB[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=qb(n),o=Ub(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:hB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of Jb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(IB(e,`${o}.when`,a.when,i,{line:n}),PB(e,`${o}.when`,a.when,n),FB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(LF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Cj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Cj}"`,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${qL(a.name)}`,line:n}),OB(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`,Kb(t.root)]]);for(let e of $b(t.presets)){let{node:n,path:r}=nx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));UB(e,t,i,()=>!0)}const vB=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function yB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!$b(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${$b(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(`, `)})${qL(i)}`,line:c})},p=new Set(C_(nx(t,a).node)),m=(r,i)=>{!KL.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${qL(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 bB=`settings.`;function xB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>bB+e)])}}function SB(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=TB(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,wB(n)))i(e,`the defaults do not stand together: ${t}`)}function CB(e){return TB(e).length>0||U_(e,wB(e)).length>0}function wB(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function TB(e){let t=t=>H_(EB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(EB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${DB(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 EB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function DB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function OB(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))||CB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function kB(e,t,n,r,i){for(let[a,o]of P_(n))IB(e,`${t}.${a}`,o,r,{segCtx:i})}function AB(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 jB=`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 MB(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=pB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${jB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=lB(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}: ${jB}`,line:i(`depends_on`)})})}}function NB(e,t){let n=new Map(Bx(t)),r=aB(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>cA[e]===n||cA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${cA[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=nB(e,a),s=o===void 0?void 0:lA(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 dB(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 PB(e,t,n,r){try{Sj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function FB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of Mx(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){LB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function IB(e,t,n,r,i){for(let[a,o]of Ox(n,r.helpers)){if(Hx(a,r))continue;if(a.startsWith(bB)){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){LB(e,o,`Template references unknown variable ".${a}"${mL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Hx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:mL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function LB(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 RB(e,t,n,r,i){let a=n.set,o=zA(Sy[r].configKey),s=`${a} takes ${NA(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=VB(n,i);if(c===BB){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=>!MA(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:Yz(`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<=zB?r.join(`, `):`${r.slice(0,zB).join(`, `)} and ${r.length-zB} 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 zB=3,BB=Symbol(`any integer`);function VB(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?lx(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)}]:BB}function HB(e,t){return Object.entries(e).filter(([e])=>t(e))}function UB(e,t,n,r){let i=mI(t),a=cx(i);for(let[n,o]of HB(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 ${dx(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&&RB(e,n,o,s,i)}for(let[n,i]of HB(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&&hx(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 HB(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 HB(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=_j(r);if(o===null){let t=aj(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${oj().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=vB.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`){yB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!$b(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: ${$b(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(`, `)})${qL(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 HB(t.variables,r)){kB(e,`variables.${i}`,a,n);let t=pL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of HB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))kB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);SB(e,i,r);let o=xB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(IB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),FB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of HB(t.variables,r))AB(e,`variables.${i}`,a,n),MB(e,`variables.${i}`,a,t);NB(e,t);for(let[i,a]of HB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))AB(e,`segments.${i}.vars.${r}`,o,n,i),MB(e,`segments.${i}.vars.${r}`,o,t)}function WB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=GB(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 GB(e){let t=new Map,n=new Map,r=aB(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 KB(e,t,n){let r=new Map([...zx(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 qB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function JB(e,t){return s.resolve(e,qB(t))}function YB(e,t){return typeof t==`string`&&t!==``?JB(e,t):void 0}function XB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const ZB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),QB=`plugin.json5`,$B=/^[a-z][a-z0-9_]*$/;function eV(e){let t=s.basename(s.dirname(e));return $B.test(t)?t:void 0}const tV=`plugins.`;function nV(e){return`${tV}${e}.data`}function rV(e){return`${e}.json`}function iV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:aV(e)}}}function aV(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 oV(e,t){return e.map(e=>JB(s.dirname(t),e))}function sV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=eV(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 ${QB}, and the folder's name is the plugin's: move this file to <dir>/<name>/${QB} and list that`;return o(t,a===void 0?e.config:dV(uV(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 ${$B}: 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=uV(e.config,a),u=iV(()=>{let i=p.readFileSync(n,`utf-8`),o=eL(_V(n,a,{source:i,json:Ii.default.parse(i)},t),l);return DV(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,dV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function cV(e){let t=lV(e);return e=>e===t||e.startsWith(`${t}.`)}function lV(e){return`${tV}${e}`}function uV(e,t){let n=cV(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 dV(e,t,n){return{...e,variables:{...e.variables,[lV(t)]:{kind:`dropped`,reason:XB(n),definition:n.path}}}}function fV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function pV(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(fV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:XB(e)}));return t=>{let i=fV(t);if(i===void 0)return[];let a=e.config.variables[lV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function mV(e,t){let n=$b(e.presets).flatMap(t=>[...E_(nx(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,hV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=fV(t),r=n===void 0?void 0:e.variables[lV(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=>Mx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Rx(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:`{{ .${lV(fV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function hV(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,gV(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function gV(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 _V(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))ZB.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: ${[...ZB].join(`, `)}`});let c=r.data===void 0?void 0:AV(r.data,e,i,a),l=r.sources===void 0?{}:EV(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?{}:yL(u,`data`,{[nV(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=yL(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 (.${nV(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 (.${tV}${t}.${e}): give one of them another name`});let m={variables:{...d,...yV(t,l),...yV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,xV(t,n)])))},segments:yV(t,SV(t,dR(u,r.segments,new Set))),helpers:yV(t,eB(u,r.helpers)),actions:yV(t,CV(t,nz(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of vV(m))try{Sj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*vV(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 mx(n))yield[`actions.${t}.${e}`,r]}function yV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${tV}${e}.${t}`,n]))}function bV(e,t){return`${tV}${e}.${t}`}function xV(e,t){return t.kind===`state`?{...t,key:bV(e,t.key)}:t}function SV(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,xV(e,n)]))}]))}function CV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:bV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>bV(e,t))}:n]))}const wV=$B,TV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function EV(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(TV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!wV.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${wV}: it is the last segment of .${tV}<plugin>.${t})`});continue}let s=kV(o,TV,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 DV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=OV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=cV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${tV}${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 OV(e){return s.join(e.storage,rV(`<session id>`))}function kV(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)?kV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function AV(e,t,n,r){if(typeof e==`string`&&e!==``)return JB(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 jV(e){let t=[...[...(process.env.XDG_DATA_DIRS||PV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),MV(),...e===null?[]:[s.join(e,NV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function MV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const NV=s.join(`.cc-candybar`,`plugins`);function PV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function FV(e){let t=jV(e),n=new Map,r=[],i=[];for(let e of t){let t=IV(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,QB));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${QB}: move this file to ${s.join(e,`<name>`,QB)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function IV(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()||LV(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 LV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function RV(e){return p.existsSync(s.join(e,`.git`))}function zV(e){let t=s.resolve(e);for(;;){if(RV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function BV(e){let t=zV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function VV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const HV=[`json5`,`json`];function UV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?HV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...HV.map(e=>s.join(r,`.cc-candybar.${e}`)),...HV.map(e=>`${WV()}.${e}`)])]}function WV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function GV(e,t,n){let r=[],i=new Map;for(let a of UV(e,t,n)){let e=VV(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:KV(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 KV(e){let t=WV();return e.find(e=>HV.some(n=>e===`${t}.${n}`))??`${t}.${HV[0]}`}function qV(e,t,n){let r=GV(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 JV(e){return YV(e).join(`
|
|
181
|
-
`)||null}function
|
|
180
|
+
New: { h: ["seg1", "seg2"] }`,line:G(e.source,[`root`])}),bR;if(n.kind===`group`){let r=lv(e,zR,t,n);return r===null?bR:(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}),VR(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`])}),bR}if(a){let r=lv(e,kR,t,n);return r===null?bR:{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,AR,t,n);return r===null?bR:{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,jR,t,n);return r===null?bR:{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`])}),bR};function NR(){return{required:!0,json:{type:`object`,propertyNames:{pattern:Bb.source},additionalProperties:{$ref:yR}},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(!Bb.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]=MR(e,`${t}.${n}.${r}`,o)}return a}}}const PR={noun:`root key`,fields:{rows:NR(),when:bv(),distribution:ER()}};function FR(e,t,n){return sv(n)&&`rows`in n?lv(e,PR,t,n)??{rows:{}}:MR(e,t,n)}function IR(){return{required:!0,json:{type:`string`,pattern:Bb.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!Bb.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 LR(){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 RR(){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 zR={noun:`layout-node key`,fields:{kind:xR(`group`),name:IR(),label:RR(),open:xv(),direction:Ov(b_),key:LR(),bg:bv(),fg:bv(),when:bv(),distribution:ER(),children:wR(vv(()=>MR))}};function BR(e){return e.key??`groups.`+e.name}function VR(e){let t=mA+e.name;return wi(t,{variable:t,key:BR(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function HR(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function UR(e,t){xA(e,t,mA,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&HR(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}.`)&&BR(t)===BR(r)&&HR(e,t.path,`group "${t.name}" shares key "${BR(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=BR(t);if(i.has(n)||i.set(n,yi),t.open===!0){let r=i.get(n);r!==`closed`&&HR(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=mA+e.name,r=BR(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 WR=`menu`,GR=`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`,KR=e=>e.kind===`call`&&e.name===`dict`,qR=e=>e.kind===`literal`&&typeof e.value!=`object`,JR=e=>xi(``,e,2)===void 0;function YR(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&&KR(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(KR))return t(`whose options (dict …) is not its last argument — ${GR}`);if(i!==void 0&&a===void 0&&!qR(i)&&JR(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} — ${GR}`);let c=a===void 0?{}:QT(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=AA(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=bA(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 "${wA(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 XR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===WR).map(YR)}catch{return`parse-failed`}}function ZR(e,t){let n=XR(e);return n===`parse-failed`?[]:n.flatMap(e=>e.kind===`ok`?[{key:CA(t,e.apply,e.options.key),member:SA(e.apply)}]:[])}function QR(e){let t=sw({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(WR)}catch{return!1}}function $R(e,t,n){e.issues.push({path:t,message:n,line:G(e.source,[`root`])})}function ez(e,t){xA(e,t,hA,`{{ menu }} helpers`),xA(e,t,gA,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))QR(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`&&QR(i)&&$R(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_(qb(t.root)))typeof n.when==`string`&&QR(n.when)&&$R(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||!QR(r))continue;let n=XR(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:tz(r.apply);n!==void 0&&$R(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function tz(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(SA(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 nz(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 $b(e.presets)){let a=new Map,s=new Map;for(let c of E_(nx(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,XR(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`||tz(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=SA(i),f=CA(u,i,l.key),p=EA(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=TA(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 rz(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=iz(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 iz(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=fx.filter(e=>e in n);return i.length===1?oz(r)[i[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${fx.join(`, `)}${i.length>1?` (found: ${i.join(`, `)})`:``}`),null)}function az(e){return s.isAbsolute(e)?{dir:s.dirname(e)}:{text:e}}const oz=e=>({set:(e,t,n)=>Hz(e,t,n,`set`,Rz),persist:(e,t,n)=>Hz(e,t,n,`persist`,zz),copy:sz(`copy`),open:sz(`open`),reset:cz,undo:uz(`undo`),redo:uz(`redo`),back:uz(`back`),rewind:uz(`rewind`),save:uz(`save`),preset:dz,themeDefault:fz,doctor:mz,slash:hz,run:vz(e),do:yz});function sz(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 cz(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=bz(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 lz={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 uz(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 — ${lz[e]}), got ${K(r[e])}`),null)}}function dz(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 fz(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 pz={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function mz(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(pz,r),a=i?pz[r]:[...new Set(Object.values(pz).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(pz).map(e=>`"${e}"`).join(`, `)}, got ${K(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?IN:FN;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 KM.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${KM.map(e=>`"${e}"`).join(` or `)}, got ${K(c)}`),null)}function hz(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=cP(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}const gz=[`run`,`env`,`refreshes`],_z=/^[A-Za-z_][A-Za-z0-9_]*$/;function vz(e){return(t,n,r)=>{for(let e of Object.keys(r))gz.includes(e)||Z(t,`${n}.${e}`,`Unknown key "${e}" on a run action. Expected only: ${gz.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])=>!_z.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}}}_z.source;function yz(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 bz(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 xz={set:`the SessionState key to write`,persist:`the config globals field to write`};function Sz(e,t,n,r){let i=xz[r],a=bz(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 Cz(e){return e===`set`?`set-state`:`set-config`}const wz={to:Uz(`set`)},Tz={to:Uz(`persist`)},Ez={from:Wz(`set`)},Dz={from:Wz(`persist`)},Oz={min:Yz(),max:Yz(),by:Yz()},kz={int:Kz()},Az={cycle:Gz(`set`)},jz={cycle:Gz(`persist`)},Mz={removeSegment:qz(`removeSegment`)},Nz={insertSegment:qz(`insertSegment`),anchor:qz(`anchor`),relation:Jz()},Pz={insertSegmentFrom:Wz(`persist`),anchor:qz(`anchor`),relation:Jz()},Fz={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},Iz={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function Lz(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 Rz=[Lz(`set`,wz),Lz(`set`,Ez),Lz(`set`,Oz,[Fz,Iz]),Lz(`set`,kz),Lz(`set`,Az)],zz=[Lz(`persist`,Tz),Lz(`persist`,Dz),Lz(`persist`,Oz,[Fz,Iz]),Lz(`persist`,jz),Lz(`persist`,Mz),Lz(`persist`,Nz,[],[`insertSegment`]),Lz(`persist`,Pz,[],[`insertSegmentFrom`])];function Bz(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 Vz(e){let t=Bz(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 Hz(e,t,n,r,i){let a=Sz(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${Vz(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 Uz(e){let t=Cz(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>bz(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 Wz(e){let t=Cz(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 Gz(e){let t=Cz(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 Kz(){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 qz(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 Jz(){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 Yz(){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 Xz(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const Zz={noun:`style key`,fields:{hueShift:Cv(),chromaScale:Cv({min:0}),lightnessScale:Cv(),lightnessShift:Cv()}};function Qz(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:Xz(`styles.${r}`,r,`globals.endcaps`),line:G(e.source,[`styles`,r])});continue}let t=lv(e,Zz,`styles.${r}`,i);t!==null&&(n[r]={...ml,...t})}return n}const $z={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:FR(e,`${t}.${n}`,r[n])},globals:{required:!1,json:tj(),parse:(e,t,n,r)=>r[n]===void 0?void 0:ej(e,`${t}.${n}`,r[n])}}};function eB(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,$z,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function tB(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 nB({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),[...[...mx(i)].map(([,e])=>e),...`do`in i?i.do.flatMap(e=>r(e,t)):[]])},i=e=>{let i=Px(e,t)?Object.keys(n):Mx(e,t).map(e=>e.name),a=new Set;return[e,...i.flatMap(e=>r(e,a))]},a=iB(n=>i(n).flatMap(n=>[...Ox(n,t).keys()].map(t=>({path:t,reaches:Vx(t,e)}))));return{ofTemplate:a,calls:iB(e=>new Set(i(e).flatMap(e=>[...Ix(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 rB(e,t){switch(t.kind){case`input`:return t.path;case`source`:return e;default:return}}function iB(e){let t=new Map;return n=>(t.has(n)||t.set(n,e(n)),t.get(n))}const aB=new WeakMap;function oB(e){let t=aB.get(e);return t===void 0&&(t=nB({names:new Set([...Bx(e)].map(([e])=>e)),helpers:e.helpers,actions:e.actions}),aB.set(e,t)),t}function sB(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 cB=new WeakMap;function lB(e){let t=cB.get(e);return t===void 0&&(t=dB(e),cB.set(e,t)),t}function uB(e){return lB(e).projections}function dB(e){let t=new Map(Bx(e)),n=new Map,r={reads:oB(e),projections:n,clock:gk};for(let[e,r]of t){r.kind===`time`&&n.set(e,`is a time variable`);let t=rB(e,r),i=t===void 0?null:sA(t);i&&n.set(e,`reads the draw's "${i}" (${oA[i]})`)}let i=pB(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=sB(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=sB(n,r);if(i!==null){a.set(t,i),e=!0;break}}for(let[r,i]of t){let t=rB(r,i);if(t===void 0||n.has(r))continue;let o=lA(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 fB(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 pB(e){let t=fB(e),n=e=>t.flatMap(t=>t.slot===e?[t.rule]:[]);return{style:n(`style`),palette:n(`palette`),effect:n(`effect`)}}function mB(e,t){return sB(e,lB(t))}function hB(e){return t=>sB(t,e)!==null}const gB={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 _B(e,t){let n=new Map;for(let e of Object.keys(t)){let t=pA(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 vB(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)?Xz(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`])}),_B(e,t.presets);let i=Ux(t);for(let t of i.names)t!==`settings`&&!t.startsWith(xB)||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)=>{VF(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" ${VF(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}),HF(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${Cj}" 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:gB[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=qb(n),o=Ub(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:gB[t](n),line:G(e.source,n.split(`.`))});for(let[a,o]of Jb(n,r)){let n=G(e.source,o.split(`.`));if(a.when!==void 0&&(LB(e,`${o}.when`,a.when,i,{line:n}),FB(e,`${o}.when`,a.when,n),IB(e,t,`${o}.when`,a.when,n)),a.kind===`segment`){if(RF(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${Cj}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${Cj}"`,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${JL(a.name)}`,line:n}),kB(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`,Kb(t.root)]]);for(let e of $b(t.presets)){let{node:n,path:r}=nx(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,G(e.source,t.split(`.`)));WB(e,t,i,()=>!0)}const yB=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function bB(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=G(e.source,[`actions`,n,r]);if(!$b(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${$b(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(`, `)})${JL(i)}`,line:c})},p=new Set(C_(nx(t,a).node)),m=(r,i)=>{!qL.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${JL(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 xB=`settings.`;function SB(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>xB+e)])}}function CB(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=EB(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,TB(n)))i(e,`the defaults do not stand together: ${t}`)}function wB(e){return EB(e).length>0||U_(e,TB(e)).length>0}function TB(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function EB(e){let t=t=>H_(DB(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||H_(DB(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${OB(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 DB(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function OB(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&H_(n)!==void 0).map(([e])=>e)}function kB(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))||wB(o)))for(let{message:t}of U_(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function AB(e,t,n,r,i){for(let[a,o]of P_(n))LB(e,`${t}.${a}`,o,r,{segCtx:i})}function jB(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 MB=`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 NB(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=mB(n.cache.key,r);a!==null&&e.issues.push({path:`${t}.cache.key`,message:`cache.key ${a}: ${MB}`,line:i(`key`)})}if(`depends_on`in n.cache){let a=uB(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}: ${MB}`,line:i(`depends_on`)})})}}function PB(e,t){let n=new Map(Bx(t)),r=oB(t),i=(e,t)=>{for(let{path:n,reaches:r}of e){let e=Ug.find(e=>cA[e]===n||cA[e].startsWith(`${n}.`));if(e!==void 0)return`reads "${cA[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=rB(e,a),s=o===void 0?void 0:lA(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 fB(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 FB(e,t,n,r){try{Sj.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function IB(e,t,n,r,i){let a=n.slice(n.lastIndexOf(`.`)+1);for(let{name:o,site:s,via:c}of Mx(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){RB(e,c,`Template references unknown action "${o}"${r}`);continue}e.issues.push({path:n,message:`${a} references unknown action "${o}"${r}`,line:i})}}function LB(e,t,n,r,i){for(let[a,o]of Ox(n,r.helpers)){if(Hx(a,r))continue;if(a.startsWith(xB)){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){RB(e,o,`Template references unknown variable ".${a}"${hL(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&Hx(n,r)?` (segment-local vars are namespaced — write ".${n}")`:hL(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??G(e.source,t.split(`.`))})}}function RB(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 zB(e,t,n,r,i){let a=n.set,o=zA(Sy[r].configKey),s=`${a} takes ${NA(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=HB(n,i);if(c===VB){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=>!MA(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:Xz(`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<=BB?r.join(`, `):`${r.slice(0,BB).join(`, `)} and ${r.length-BB} 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 BB=3,VB=Symbol(`any integer`);function HB(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?lx(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)}]:VB}function UB(e,t){return Object.entries(e).filter(([e])=>t(e))}function WB(e,t,n,r){let i=hI(t),a=cx(i);for(let[n,o]of UB(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 ${dx(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&&zB(e,n,o,s,i)}for(let[n,i]of UB(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&&hx(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 UB(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 UB(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=_j(r);if(o===null){let t=aj(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${oj().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=yB.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`){bB(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!$b(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: ${$b(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(`, `)})${JL(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 UB(t.variables,r)){AB(e,`variables.${i}`,a,n);let t=mL(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:G(e.source,[`variables`,i])})}for(let[i,a]of UB(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))AB(e,`segments.${i}.vars.${t}`,r,n,i);let r=V_(a);CB(e,i,r);let o=SB(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];typeof s==`string`&&(LB(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r}),IB(e,t,`segments.${i}.${n}`,s,G(e.source,[`segments`,i,n])))}}for(let[i,a]of UB(t.variables,r))jB(e,`variables.${i}`,a,n),NB(e,`variables.${i}`,a,t);PB(e,t);for(let[i,a]of UB(t.segments,r))if(a.vars)for(let[r,o]of Object.entries(a.vars))jB(e,`segments.${i}.vars.${r}`,o,n,i),NB(e,`segments.${i}.vars.${r}`,o,t)}function GB(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=KB(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 KB(e){let t=new Map,n=new Map,r=oB(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 qB(e,t,n){let r=new Map([...zx(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 JB(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function YB(e,t){return s.resolve(e,JB(t))}function XB(e,t){return typeof t==`string`&&t!==``?YB(e,t):void 0}function ZB(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const QB=new Set([`data`,`sources`,`variables`,`segments`,`helpers`,`actions`]),$B=`plugin.json5`,eV=/^[a-z][a-z0-9_]*$/;function tV(e){let t=s.basename(s.dirname(e));return eV.test(t)?t:void 0}const nV=`plugins.`;function rV(e){return`${nV}${e}.data`}function iV(e){return`${e}.json`}function aV(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:oV(e)}}}function oV(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 sV(e,t){return e.map(e=>YB(s.dirname(t),e))}function cV(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=tV(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 ${$B}, and the folder's name is the plugin's: move this file to <dir>/<name>/${$B} and list that`;return o(t,a===void 0?e.config:fV(dV(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 ${eV}: 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=dV(e.config,a),u=aV(()=>{let i=p.readFileSync(n,`utf-8`),o=tL(vV(n,a,{source:i,json:Ii.default.parse(i)},t),l);return OV(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,fV(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function lV(e){let t=uV(e);return e=>e===t||e.startsWith(`${t}.`)}function uV(e){return`${nV}${e}`}function dV(e,t){let n=lV(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 fV(e,t,n){return{...e,variables:{...e.variables,[uV(t)]:{kind:`dropped`,reason:ZB(n),definition:n.path}}}}function pV(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function mV(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(pV)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:ZB(e)}));return t=>{let i=pV(t);if(i===void 0)return[];let a=e.config.variables[uV(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function hV(e,t){let n=$b(e.presets).flatMap(t=>[...E_(nx(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,gV(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=pV(t),r=n===void 0?void 0:e.variables[uV(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=>Mx(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...Rx(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:`{{ .${uV(pV(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:p}}function gV(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,_V(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function _V(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 vV(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))QB.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: ${[...QB].join(`, `)}`});let c=r.data===void 0?void 0:jV(r.data,e,i,a),l=r.sources===void 0?{}:DV(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?{}:bL(u,`data`,{[rV(t)]:{kind:`file`,path:c,parse:{json:!0},cache:{watch_file:c},default:{}}}),f=bL(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 (.${rV(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 (.${nV}${t}.${e}): give one of them another name`});let m={variables:{...d,...bV(t,l),...bV(t,Object.fromEntries(Object.entries(f).map(([e,n])=>[e,SV(t,n)])))},segments:bV(t,CV(t,fR(u,r.segments,new Set))),helpers:bV(t,tB(u,r.helpers)),actions:bV(t,wV(t,rz(u,r.actions,{dir:p.realpathSync(s.dirname(e))})))};for(let[e,t]of yV(m))try{Sj.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),m}function*yV(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 mx(n))yield[`actions.${t}.${e}`,r]}function bV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${nV}${e}.${t}`,n]))}function xV(e,t){return`${nV}${e}.${t}`}function SV(e,t){return t.kind===`state`?{...t,key:xV(e,t.key)}:t}function CV(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,SV(e,n)]))}]))}function wV(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:xV(e,n.set)}:`run`in n?{...n,refreshes:n.refreshes.map(t=>xV(e,t))}:n]))}const TV=eV,EV={scope:`session`,refresh:{watch:!0},read:{file:{json:!0}}};function DV(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(EV),a={};for(let[t,o]of Object.entries(e)){let e=`sources.${t}`;if(!TV.test(t)){n.push({path:e,message:`source name "${t}" is not one identifier (one matching ${TV}: it is the last segment of .${nV}<plugin>.${t})`});continue}let s=AV(o,EV,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 OV(e,t,n){let r=Object.entries(n.variables).reduce((e,[t,n])=>{if(n.kind!==`source`)return e;let r=kV(n);return e.set(r,[...e.get(r)??[],t])},new Map),i=lV(t),a=[...r].filter(([,e])=>e.length>1&&e.some(i)).map(([e,n])=>({path:`sources.${n.find(i).slice(`${nV}${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 kV(e){return s.join(e.storage,iV(`<session id>`))}function AV(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)?AV(e[r],t[r],i):[{field:i,is:`is missing`}]:[{field:i,is:`is not built`}]})}function jV(e,t,n,r){if(typeof e==`string`&&e!==``)return YB(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 MV(e){let t=[...[...(process.env.XDG_DATA_DIRS||FV()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),NV(),...e===null?[]:[s.join(e,PV)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function NV(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const PV=s.join(`.cc-candybar`,`plugins`);function FV(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function IV(e){let t=MV(e),n=new Map,r=[],i=[];for(let e of t){let t=LV(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,$B));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${$B}: move this file to ${s.join(e,`<name>`,$B)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function LV(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()||RV(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 RV(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function zV(e){return p.existsSync(s.join(e,`.git`))}function BV(e){let t=s.resolve(e);for(;;){if(zV(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function VV(e){let t=BV(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function HV(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const UV=[`json5`,`json`];function WV(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?UV.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...UV.map(e=>s.join(r,`.cc-candybar.${e}`)),...UV.map(e=>`${GV()}.${e}`)])]}function GV(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function KV(e,t,n){let r=[],i=new Map;for(let a of WV(e,t,n)){let e=HV(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:qV(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 qV(e){let t=GV();return e.find(e=>UV.some(n=>e===`${t}.${n}`))??`${t}.${UV[0]}`}function JV(e,t,n){let r=KV(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 YV(e){return XV(e).join(`
|
|
181
|
+
`)||null}function XV(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 ZV(e,t){let n=WV(e,t).filter(e=>HV(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 QV(e,t,n,r){return e===null?{...cH,config:tL(cH.raw,t)}:eH(e,p.readFileSync(e,`utf-8`),t,n,r)}const $V={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function eH(e,t,n,r,i){let a=dH(e,t,i,(t,a)=>{let o=cV(sV(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>oH(t,n,r,e,i)),s=mV(o,r.beneath.dropped);return{inherited:new Set([...dR(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=hV(tL(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(ZB)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const tH=new WeakMap;function nH(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,iH(e)])]),a=tH.get(n)??new Map;tH.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=cV(e,t,{config:n,rendering:new Map},(e,t,n)=>oH(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function rH(e,t,n){return cV(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>oH(e,t,n,`<plugin install>`,void 0)).dropped}function iH(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function aH(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:VV(r.cwd)},s=IV(o.projectDir),c=nH(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=eH(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(ZB));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:lH(QV(null,u,$V),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:lH(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),lH(e,e.path,a);throw n.entered(v.path),e}}function oH(e,t,n,r,i){if(n){lH(sH(e),r,i);return}let a=lV(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(WB(s,e,Ux(e),a),GB(s,e,a),qB(s,e,{checked:a,authored:a}),o.length>0)throw new Z_(r,o)}function sH(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const cH={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function lH({config:e,raw:t,source:n},r=`<config>`,i=new Set(Rg())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(vB(o,e,t),GB(o,e),a.length>0)throw new Z_(r,a);let s=nz(e,a);if(a.length>0)throw new Z_(r,a);let c=NI($F(s)),l=new Set([...zx({variables:t.variables??{},segments:t.segments??{}})].map(([e])=>e));if(qB(o,c,{checked:()=>!0,authored:e=>l.has(e)}),a.length>0)throw new Z_(r,a);return c}function uH(e,t,n=new Set(Rg()),r=fH){return dH(e,t,n,()=>({inherited:r,layer:null})).raw}function dH(e,t,n,r){let i=pH(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?[]:gH({...c,issues:[]},i.plugins)??[],sv(i.segments)?Object.keys(i.segments):[]),d=mH(c,i,l,az(e));if(s.length>0)throw new Z_(e,s,o);return{raw:d,warnings:o,layer:u}}const fH=new Set;function pH(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 mH(e,t,n,r){for(let n of Object.keys(t))hH.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...hH].join(`, `)}`,line:G(e.source,[n])});let i={};return t.globals!==void 0&&(i.globals=$A(e,`globals`,t.globals)),t.variables!==void 0&&(i.variables=bL(e,`variables`,t.variables)),t.segments!==void 0&&(i.segments=fR(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=PR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=nz(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=Zz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=QA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=$z(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=nj(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=eB(e,t.helpers)),t.plugins!==void 0&&(i.plugins=hH(e,t.plugins)),HR(e,i),$R(e,i),Ij(e,i),xA(e,i,X,`the global settings menu`),i}const mH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function hH(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 gH={},_H=fP(`commands.`),vH=vP(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),yH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,bH=`{{ \$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 (${yH}) (basename .project_dir) (ne (${yH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,xH=`{{ ${dM} }}`,SH={min:0,max:100,step:5},CH={warnAt:{label:`warning at %`,domain:SH,default:50},errorAt:{label:`error at %`,domain:{...SH,atLeast:`warnAt`},default:80}};function wH(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:SH,default:80}}}const TH={globals:{palette:`tokyo-night`},variables:{..._H.variables,...aA,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:bH},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:xH,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:tP(``).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:_H.template,when:_H.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:wH(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:wH(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:CH,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:CH,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:vH.template,bg:vH.bg,when:vH.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:{...tP(``).actions,..._H.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...vH.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:gH,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 (${dM}) 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:yP(`.`),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 .)) }}`}},EH=new Set([TH.globals.palette,...Object.keys(TH.themeDefaults),...Object.values(TH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),DH=eL(lH(`<default>`,JSON.stringify(TH),EH),TH),OH=$b(DH.presets);function kH(e){return OH.includes(e)}const AH=Object.freeze({});function jH(e,t){return e.kind===`decided`?t[e.name]??AH:AH}function MH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const NH=e=>Bv(t=>e[Pv[t].setting]);function PH(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 FH(e,t){return ex(t(`preset`),e.globals.preset,e.presets)}function IH(e,t,n){let r=FH(e,t),i=rx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Rb(a.palette,t(`theme`),i.palette),s=MH(i,jH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,PH(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 LH(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 RH=Object.entries(Sy),zH=new Set(wy.map(e=>e.sessionKey)),BH=()=>!1;function VH(e,t){return IH(e,e=>zH.has(e)?t(e):null,BH)}const HH=[`preset`,`theme`];function UH(e,t,n){let r=new Set(HH.slice(0,n).map(e=>Sy[e].sessionKey));return IH(e,e=>r.has(e)?t(e):null,BH)}function WH(e,t){let n=Array.from({length:HH.length+1},(n,r)=>UH(e,t,r));return e=>{let t=HH.indexOf(e);return n[t===-1?HH.length:t]}}function GH(e,t,n,r){return e.flatMap(([e,i])=>{let a=LH(t,e);return a===null||a===LH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function KH(e,t,n){return LH(VH(e,t),n)}function qH(e,t){let n=VH(e,t);return GH(RH,n,WH(e,t),t=>JH(e,n.preset,t.configKey))}function JH(e,t,n){return n in(tx(e.presets,t).globals??{})?gj(t,n):n}function YH(e,t,n){let r=ex(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=_j(n);return{key:i?.scope===`globals`?JH(e,r,i.field):n,globals:rx(e,r)}}function XH(e,t){let{preset:n}=VH(e,t);return $H(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 ZH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return $b(e.presets).flatMap(n=>{let i=$H(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 QH=new WeakMap;function $H(e,t){let n=QH.get(e)??new Map;QH.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(nx(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 eU(e,t){let n=VH(e,t);return{from:n.preset,globals:tx(e.presets,n.preset).globals??{},picks:GH(RH.filter(([e])=>e!==`preset`),n,WH(e,t),e=>e.configKey),placements:XH(e,t)}}function tU(e,t){return IH({...e,globals:{palette:t},presets:{}},()=>null,BH)}function nU(e,t){let n=VH(e,t),r=LH(n,`theme`);if(r===null)return{kind:`rule`};let i=tU(e,r),a=rx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,LH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==LH(i,e))}}function rU(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...JA(e)?OH.map(t=>gj(t,e)):[],...hj(e)?Rg().map(t=>mj(t,e)):[]]}}function iU(e){return new Set(wy.map(e=>e.configKey).filter(t=>rU(t).fileKeys.some(t=>sU(e,oU(t)))))}function aU(e,t,n){let r=qH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=nU(e,n);return{unsaved:r.length+XH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function oU(e){let t=_j(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return vj(t)}function sU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&sU(e[n],r)}const cU=Rg(),lU=new Set(cU),uU=new Set(o_),dU=e=>e?lU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${cU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},fU=e=>e?uU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},pU=new Set([`1`,`true`]),mU=new Set([`0`,`false`]),hU={endcaps:fU,theme:dU,"toolbar-expanded":e=>pU.has(e)?{ok:!0,value:`1`}:mU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},gU=GI(hU,`state`,CU);function _U(e,t){return gU.register(e,t)}function vU(e){return gU.gateFor(e)}function yU(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:lx(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 bU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(hU,e.key))}function xU(e,t,n){let r=Ay.get(n);if(r!==void 0)return KH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function SU(e){let t=mI(e);return bU(Object.values(e.actions).flatMap(e=>yU(e,t)))}function CU(e){return UI(SU(e))}const wU=`update.dismissed`,TU=`updateNotice`,EU=Sy.updateNotice.sessionKey;function DU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const OU=e=>`${e.version} [${Xe(e.digest)}]`;function kU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:OU(e.newer),running:OU(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 AU={kind:`idle`},jU={kind:`running`};function MU(e,t,n){if(e===null)return[];let r=DU(e);if(!n.enabled||n.dismissed===r)return[];let i=kU(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=qW(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 NW(await this.execGitAsync(MW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=LW(e);return(n===null?null:zW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=RW(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=jW(t);return n===`github`?HW(`gh pr view`,await this.execForgeAsync(EW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,GW):n===`gitlab`?HW(`glab mr view`,await this.execForgeAsync(EW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,KW):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=xW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(WW(t.value)):t}};const YW=(e,t)=>E(t);function XW(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 ZW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var QW=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??YW}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=XW(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(ZW(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(ZW(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 $W(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var eG=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 tG(){return J.observable.box(nG(`unread`),{deep:!1})}function nG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function rG(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 iG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(nG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function aG(e,t){e.reading.get().kind===`pending`&&rG(e,t)}function oG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function sG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function cG(e){for(;;){let t=e();if(!oG(t))return t;await t.landed}}function lG(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 uG(e){return{current:()=>e}}function dG(e){return cG(()=>e.current())}const fG=`pass`,pG={okMs:5*6e4,failedMs:45e3};function mG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function hG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function gG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function _G(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 vG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function yG(e){e.missed=!0,iG(e,`unread`)}function bG(e,t){return e.missed&&e.reading.get().kind===`pending`&&rG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function xG(e,t){let n=sG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:sG(t)})}function SG(e){return t=>I(`${e} threw: ${String(t)}`)}var CG=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 JW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new Mk(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 QW({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 uG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>xG(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 Ak,watcher:this.watchers.acquire(`git:${e}`,_G(n),()=>this.changed(e)),period:new eG(()=>{r.refresh.share(fG,()=>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(fG,()=>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&&yG(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(fG,()=>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:tG(),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=gG(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(hG(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(SG(`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,rG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of bW(n.value))s.add(e)});let c=vG(a),l=i===null||r.length===0?`-`:c===void 0?bG(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}`,mG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new eG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:tG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(SG(`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?(yG(t),`owed`):(iG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,rG(t,a.outcome),t.period.landed($W(pG,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(SG(`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||(rG(t,i),t.period.landed($W(pG,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())aG(n,t);e.pr!==null&&aG(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()}},wG=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 TG={"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 EG=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 wG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await wG.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(TG).length} models`),this.executionCache=TG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(TG).length} models`),TG)}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 DG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function OG(e){if(typeof e==`string`)return DG.exec(e)?.[1]}function kG(e){let t=e?.todos;if(!Array.isArray(t))return;let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let{content:t,activeForm:r,status:i}=e,a=i===`in_progress`,o=a&&typeof r==`string`?r:t;typeof o==`string`&&n.push({text:o,active:a,done:i===`completed`})}return n}function AG(e){return typeof e==`string`?e:Array.isArray(e)?e.find(e=>typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`)?.text??``:``}function jG(e,t){let n=e.message?.content,r=[],i=[],a;if(Array.isArray(n))for(let e of n){if(typeof e!=`object`||!e)continue;let t=e;switch(t.type){case`tool_use`:{let{id:e,name:n}=t;if(typeof e!=`string`||typeof n!=`string`)break;r.push({id:e,name:n}),n===`TodoWrite`&&(a=kG(t.input)??a);break}case`tool_result`:{let e=t.tool_use_id;typeof e==`string`&&i.push(e);break}default:break}}let o=t===`prompt`?OG(AG(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 MG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function NG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await PG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function PG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function FG(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=UG(i,t,s.value);let c=BG(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 IG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(RG(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=AG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||LG.test(r)?`claude-code`:`prompt`}const LG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function RG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function zG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=IG(e);return{timestamp:new Date(e.timestamp),type:typeof e.type==`string`?e.type:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n,role:typeof t.role==`string`?t.role:void 0,type:typeof t.type==`string`?t.type:void 0}:void 0,costUSD:typeof e.costUSD==`number`?e.costUSD:void 0,isSidechain:e.isSidechain===!0,userEntry:r,activity:jG(e,r),raw:{model:typeof e.model==`string`?e.model:void 0,message:t?{id:typeof t.id==`string`?t.id:void 0,model:typeof t.model==`string`?t.model:void 0,usage:n}:void 0,requestId:typeof e.requestId==`string`?e.requestId:void 0}}}function BG(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 VG(e){let t=BG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return zG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function HG(e){let t=[];for(let n of e.split(`
|
|
191
|
-
`)){let e=VG(n);e&&t.push(e)}return t}function UG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function WG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function GG(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=UG(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=>HG(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 KG=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}},qG=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:()=>sG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,iG(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:tG(),holders:0,flight:null,changed:!1,superseding:0,revisit:JG(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();XG(()=>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{rG(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(),aG(e,I(`${this.spec.name} entry dropped`))}};function JG(e,t){if(e===null)return new YG(t.holdReturned);let n=new eG(t.period);return{landed:t=>n.landed($W(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var YG=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 XG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function ZG(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 QG={okMs:60*1e3,failedMs:10*1e3},$G={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},eK={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function tK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function nK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function rK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const iK={entries:0,cost:0,breakdown:rK(),days:new Map};async function aK(e,t){let n=tK(new Date(nK())),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 EG.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=tK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...$G};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 oK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function sK(e){let t=0,n=0,r=rK(),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)??{...$G};oK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:eK,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 cK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function lK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!cK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...$G};oK(r,t),n.set(e,r)}return n}async function uK(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 dK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function fK(e,t){(0,J.runInAction)(()=>e.set(t))}var pK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new KG;scans;daySets=new Map;speedFlight=new KG;requestFlight=new KG;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 Mk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new qG({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??QG,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(dK(t.kind===`ok`?t.value.sessionInfo:eK,e))},speed:t=>this.observed(e,r,t),today:async e=>{await dG(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(dK(n.record?.sessionInfo??eK,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),fK(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=MG(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=tK(ok(n)),o={...$G},s=e.sums.get(a);s!==void 0&&oK(o,s);let c=cK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&oK(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 fK(this.hold(e).speed,t),t;let r=ZG(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 fK(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 iS(`today over ${e.join(`,`)}`,()=>lK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await FG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of WG(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 GG(e,r,iK,aK);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 WG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...sK(i),mainStamp:a})}async scan(e){try{let t=nK(),n=await NG(e),r=[];for(let e of n){let n=await PG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await PG(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 uK(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=tK(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()}},mK=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)}})}},hK=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 mK(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 GG(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 WG(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 gK(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 _K=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new hK(void 0,gK,(e.ledger??new Mk(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,vK(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,vK(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 vK(e){return e.context_window?.context_window_size??2e5}const yK={messageCount:0,nonPrompts:0,recent:[]},bK=new Set([`turn`,`interrupt`,`claude-code`]);function xK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!bK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function SK(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 CK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new hK(yK,xK,(e.ledger??new Mk(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?wK(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:wK(e,n,r)}};function wK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:SK(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 TK={command:null,todos:[],pending:[],done:[]};function EK(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 DK(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 OK(e,t){if(t.isSidechain)return e;let n=DK(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=EK(a,i[t].name),i=[...i.slice(0,t),...i.slice(t+1)])}return{...n,pending:i,done:a,todos:r.todos??n.todos}}function kK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>EK(e,t.name),[]),done:e.done}}var AK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new hK(TK,OK,(e.ledger??new Mk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return jK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:jK(e,t)}};function jK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(kK(t.value))}function MK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function NK(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 PK(e,t,n,r){return NK(D(MK(e,t,n,r)),n)}async function FK(e,t,n,r){return NK(await pt(MK(e,t,n,r)),n)}const IK=3e4;var LK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new qG({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:RK,every:{okMs:IK,failedMs:IK},maxEntries:64,logger:t,ledger:e.ledger??new Mk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function RK(e){let t=await FK(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 zK=6e4,BK={okMs:zK,failedMs:zK};function VK(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function HK(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var UK=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:BK,maxEntries:1,logger:t,ledger:e.ledger??new Mk(t)};this.name=new qG({...n,name:`host.name`,read:()=>HK(`name`,()=>VK(C.hostname()))}),this.user=new qG({...n,name:`host.user`,read:()=>HK(`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()}},WK=class{known=new mK(64);refreshes;constructor(e=Me,t=new Mk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=GK(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=gP(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 GK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const KK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function qK(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 JK=class{known=new mK(256);refreshes;constructor(e=Me,t=new Mk(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 YK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function YK(e){let t=await XK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function XK(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||!KK.test(t))continue;let r=qK(t);if(r!=null)return r}return null}var QK=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 $K=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}},eq=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,tq=e=>rV(e),nq=e=>s.join(e.storage.folder,tq(e.sessionId)),rq=e=>JSON.stringify([e.folder,e.generation]),iq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var aq=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??$K,this.sessions=new qG({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(nq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Mk(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`||!eq(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(rq(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:${rq(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(rq(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=rq(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=>iq(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(tq(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`&&eq(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=>iq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(rq(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=>iq(e.storage,r))}async read(e){let t=this.faults.get(rq(e.storage));if(t!==void 0)return I(t);let n=nq(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=kk(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&&tq(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 oq(e){let{logger:t,ledger:n}=e;return{hostService:new UK({logger:t,ledger:n}),gitProvider:new CG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new pK({logger:t,ledger:n}),contextProvider:new _K({logger:t,ledger:n}),metricsProvider:new CK({logger:t,ledger:n}),activityProvider:new AK({logger:t,ledger:n}),tmuxService:new LK({logger:t,ledger:n}),autoCompact:new WK(t,n),cacheExpiry:new JK(t,n),managedStorage:new aq({watchers:e.watchers,logger:t,ledger:n}),faults:new QK,log:e.logger}}function sq(e){return Math.max(1,e-2)}function cq(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 lq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function uq(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:kH(e.preset)}}}const dq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function fq(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 pq=10*1e3;function mq(e,t){if(!(t<60))return e*3600/t}function hq(e,t,n,r){let i=r-t;if(i<50||i>pq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function gq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=hq(t.input,t.atMs,n.input,n.atMs),i=hq(t.output,t.atMs,n.output,n.atMs),a=hq(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 _q(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>pq)continue;let o=hq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function vq(e,t){let n=rx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(nx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...yq(e,n.name));return xq(e,r)}function yq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function bq(e,t,n){return xq(e,[...yq(e,t),...n])}function xq(e,t){let n=aB(e),r=new Map(Bx(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=nB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Sq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=vq(e,n);return t.set(n,i),i}}function Cq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function wq(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(dq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Tq=new WeakMap;function Eq(e){let t=Tq.get(e);return t===void 0&&(t=Dq(e),Tq.set(e,t)),t}function Dq(e){let t=t=>Cq(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 Oq(e){return sq(e.termCols??120)}function kq(e){return Xa(Ya(e.claudeConfigDir))}function Aq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function jq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Eq(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(ok(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(kq(a)))])}function Mq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Nq(e,t){let n=uG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Pq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,wq(n),t.workspace?.project_dir]}function Fq(e,t,n,r,i){let a=Eq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return uG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),uG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Pq(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(Mq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Iq(e){let{hookData:t,deps:n}=e,r=Eq(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(kq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Lq(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 Rq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Eq(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:Zq(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:Kq(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:Vq(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,Hq),x=u(n.usage,e=>Yq({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>Yq({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,qq),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=Xq(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:Xq(r.workspace.current_dir)??``,project_dir:Xq(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>Xq(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}},...uq(a),history:t.history,navigation:{back:t.back},term:{cols:Oq(i)},...c,...s!==null&&{configPath:s},resumeCommand:cq(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:Bq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})}}function zq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function Bq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Vq(e,t){let n=e!=null&&t!=null?mq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Hq(e){let t=gq(e),n=_q(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Uq(e,t){return Rq(e,t,Iq(e))}function Wq({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 Gq(e,t,n){await jq(e,t,n),await cG(()=>{let t=Lq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function Kq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return _P(e.value,t)}}function qq(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=Jq(e.running),i=Jq(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 Jq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Yq(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 Xq(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function Zq(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(mW(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:hW(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 Qq(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const $q={kind:`hidden`},eJ={kind:`shown`};function tJ(e,t){try{return Qq(e,t)?eJ:$q}catch(e){let t=tS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function nJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function rJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function iJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function aJ({text:e,placement:t,lead:n,trail:r}){return{text:oJ(e),placement:t,...n!==void 0&&{lead:oJ(n)},...r!==void 0&&{trail:oJ(r)}}}function oJ(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 sJ(e){let t=iJ(e);if(t.length===1)return e.text;let n=nJ(t);return n.style=e.text.style,n}function cJ(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=nJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:nJ([d,...c],a)},...l.length>0&&{trail:nJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(rJ(u,n,p),[{text:u,...f}])}const lJ=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function uJ(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-uJ(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];rJ(c,c.cellLength+a,n)}),n()}function fJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=pJ(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=pJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function pJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>mJ(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 mJ(e,t){let n=e.copy();return n.style=t,n}function hJ(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 gJ(e,t){let{look:n}=hJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function _J(e,t){let{layout:n}=hJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function vJ(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 yJ(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,bJ(e,t,o,n,r,i));return i}function bJ(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=lx(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=lx(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=lx(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:CJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:CJ(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:px(n),argv:n.run.map(n=>CJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,CJ(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:CJ(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 xJ(e){return e.kind===`do`?xJ(e.head):e}function SJ(e){switch(xJ(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 CJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function wJ(e,t){return e.has(t)?Zx(e.read(t)):``}function TJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function EJ(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 DJ(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 OJ(e,t){return Math.max(e.members.indexOf(wJ(t,e.stateVar)),0)}function kJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=wJ(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=wJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=wJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(OJ(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:[TJ(e.text,xk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[TJ(e.target,xk(r))]}],active:!1};case`persist-literal`:{let t=wJ(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=wJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(OJ(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,TJ(e.name,xk(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=xk(r),n=JSON.stringify({run:e.argv.map(e=>TJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,TJ(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,NI(e.op)]}],active:!1};case`do`:{let o=kJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>kJ(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,NI(r)]}],active:!1}}}}function AJ(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,OJ(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 jJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=hJ(n,`action "${e}"`).store,{display:a,boundValue:o}=AJ(e,xJ(r),t,i),s=wJ(i,`session.id`),{effects:c,active:l}=kJ(r,a.plain,o,i,s,n.signer);return DJ(a,pi(c),l)}function MJ(e){return{action:{fn:(t,...n)=>jJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function NJ(e,t){return EJ(`✕`,pi([{verb:Rr,args:[wJ(e,`session.id`),t,yi]}]),!1)}function PJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function FJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function IJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function LJ(e,t,n){return V.combine([PJ(e,t,n),IJ(e,t,n)])}function RJ(e,t,n){return PJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function zJ(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 BJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},VJ=e=>new V({bold:e});function HJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>BJ(a,V.combine([RJ(e,{...n,distribution:t},i),VJ(o)]));let o=PJ(e.palette,a,i);return(e,t,i,a)=>UJ(i,V.combine([o,VJ(a)]),r(t,n))}const UJ=(e,t,n)=>BJ(W.fromFragments([BJ(e,t),BJ(` `,t),zJ(n)]));function WJ(e,t){return t===void 0?(e,t,n)=>BJ(n):(n,r,i)=>UJ(i,void 0,t(r,e))}function GJ(e,t,n,r,i){let a=PJ(e.palette,i,r);return(e,r,i,o)=>BJ(W.fromFragments([BJ(o?`[`:` `,a),zJ(n(r,t)),BJ(o?`]`:` `,a)]))}function KJ(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=>qJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function qJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function JJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function YJ(e){return{current:null,drawnAt:e}}function XJ(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 ZJ(e,t,n){return $J(e,()=>n(XJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function QJ(e,t){return $J(e,()=>(e.current=null,t()))}function $J(e,t){let n=e.current;try{return t()}finally{e.current=n}}function eY(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 tY(e){return new W(e).cellLength}function nY(e){let{width:t,chromeCols:n,padding:r}=hJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function rY(e){let{padding:t,seamCols:n}=hJ(e,`a row fit`);return Math.max(1,nY(e)-(tY(`✕`)+2*t+n))}function iY(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 aY(e,t,n){let r=tY(`←`)+1+tY(`→`)+1,i=iY(e,t,n);return(i.length>1?iY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function oY(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 sY(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 cY(e,t,n){let r=e.compiled.get(t),i=r&&xJ(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 lY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=hJ(a,`picker`).store,d=wJ(u,`session.id`),f=`stateVar`in t?wJ(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`?rY(a):nY(a):1/0,h=(r.kind===`led`?0:tY(`✕`)+1)+c.reduce((e,t)=>e+tY(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?aY(_.map(e=>e.cellLength),m,h):KJ(g.entries,g.groups,i),y=parseInt(wJ(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([...kJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>DJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[EJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>EJ(e,pi([...kJ(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(EJ(`←`,te(x-1),!1));let w=x<v.length-1?[EJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[oY([...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=[oY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(oY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>tY(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-tY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(oY([ae(p(r,JJ(c,m)),r)],i))}}return ce}function uY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{QO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=sY(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=cY(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=eY(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]=lY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,HJ(u,kh(void 0),gJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),IJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function dY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function fY(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 pY(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=hJ(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=wJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return oY([],!0);let d=wJ(o,t.stateVar),f=dY(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(kJ(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=DJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):DJ(WJ(gJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(kJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=fY(e=>v(e).cellLength,u,tY(`◀`)+1+y.cellLength+1+tY(`▶`),rY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return oY([...ee(-1).reverse(),EJ(`◀`,h(-1),!1),y,EJ(`▶`,h(1),!1),...ee(1)],!0)}function mY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(QO(`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&&SJ(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=cY(e,n,`carousel`),l=eY(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 pY(n,c,e,HJ(l,kh(void 0),gJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function hY(e,t,n){let r=cY(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 gY(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 _Y(e,t,n,r){let i=hY(e,t,n),a=r??wJ(hJ(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,gJ(e,`{{ ${n} }}`))}function vY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(QO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return zJ(_Y(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function yY(e,t,n){return{swatches:{fn:(r,i)=>{let a=hY(e,r,`swatches`),o=sY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=eY(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]=lY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,GJ(s,gJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),IJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=dY(l,wJ(hJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[gY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const bY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function xY(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:bY[i%bY.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 SY(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:FJ({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 CY(e,t,n,r,i){let a=xY(e,t,n,r).map(e=>SY(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=FR(e,`root`,t.root)),t.actions!==void 0&&(i.actions=rz(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=Qz(e,t.styles)),t.themeDefaults!==void 0&&(i.themeDefaults=QA(e,t.themeDefaults)),t.presets!==void 0&&(i.presets=eB(e,t.presets)),t.editGlobals!==void 0&&(i.editGlobals=nj(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(i.helpers=tB(e,t.helpers)),t.plugins!==void 0&&(i.plugins=gH(e,t.plugins)),UR(e,i),ez(e,i),Ij(e,i),xA(e,i,X,`the global settings menu`),i}const hH=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function gH(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 _H={},vH=fP(`commands.`),yH=vP(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),bH=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,xH=`{{ \$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 (${bH}) (basename .project_dir) (ne (${bH}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,SH=`{{ ${dM} }}`,CH={min:0,max:100,step:5},wH={warnAt:{label:`warning at %`,domain:CH,default:50},errorAt:{label:`error at %`,domain:{...CH,atLeast:`warnAt`},default:80}};function TH(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:CH,default:80}}}const EH={globals:{palette:`tokyo-night`},variables:{...vH.variables,...aA,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:xH},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:SH,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:tP(``).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:vH.template,when:vH.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:TH(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:TH(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:wH,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:wH,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:yH.template,bg:yH.bg,when:yH.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:{...tP(``).actions,...vH.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},...yH.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:_H,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 (${dM}) 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:yP(`.`),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 .)) }}`}},DH=new Set([EH.globals.palette,...Object.keys(EH.themeDefaults),...Object.values(EH.segments).map(e=>e.palette)].filter(e=>e!==void 0)),OH=tL(uH(`<default>`,JSON.stringify(EH),DH),EH),kH=$b(OH.presets);function AH(e){return kH.includes(e)}const jH=Object.freeze({});function MH(e,t){return e.kind===`decided`?t[e.name]??jH:jH}function NH(e,t){return{...e,...Object.fromEntries(hy.map(n=>[n,e[n]??t[n]]))}}const PH=e=>Bv(t=>e[Pv[t].setting]);function FH(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 IH(e,t){return ex(t(`preset`),e.globals.preset,e.presets)}function LH(e,t,n){let r=IH(e,t),i=rx(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Rb(a.palette,t(`theme`),i.palette),s=NH(i,MH(o,e.themeDefaults));return{...Object.fromEntries(py.map(e=>[e,FH(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 RH(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 zH=Object.entries(Sy),BH=new Set(wy.map(e=>e.sessionKey)),VH=()=>!1;function HH(e,t){return LH(e,e=>BH.has(e)?t(e):null,VH)}const UH=[`preset`,`theme`];function WH(e,t,n){let r=new Set(UH.slice(0,n).map(e=>Sy[e].sessionKey));return LH(e,e=>r.has(e)?t(e):null,VH)}function GH(e,t){let n=Array.from({length:UH.length+1},(n,r)=>WH(e,t,r));return e=>{let t=UH.indexOf(e);return n[t===-1?UH.length:t]}}function KH(e,t,n,r){return e.flatMap(([e,i])=>{let a=RH(t,e);return a===null||a===RH(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function qH(e,t,n){return RH(HH(e,t),n)}function JH(e,t){let n=HH(e,t);return KH(zH,n,GH(e,t),t=>YH(e,n.preset,t.configKey))}function YH(e,t,n){return n in(tx(e.presets,t).globals??{})?gj(t,n):n}function XH(e,t,n){let r=ex(t(Sy.preset.sessionKey),e.globals.preset,e.presets),i=_j(n);return{key:i?.scope===`globals`?YH(e,r,i.field):n,globals:rx(e,r)}}function ZH(e,t){let{preset:n}=HH(e,t);return eU(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 QH(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return $b(e.presets).flatMap(n=>{let i=eU(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 $H=new WeakMap;function eU(e,t){let n=$H.get(e)??new Map;$H.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...E_(nx(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 tU(e,t){let n=HH(e,t);return{from:n.preset,globals:tx(e.presets,n.preset).globals??{},picks:KH(zH.filter(([e])=>e!==`preset`),n,GH(e,t),e=>e.configKey),placements:ZH(e,t)}}function nU(e,t){return LH({...e,globals:{palette:t},presets:{}},()=>null,VH)}function rU(e,t){let n=HH(e,t),r=RH(n,`theme`);if(r===null)return{kind:`rule`};let i=nU(e,r),a=rx(e,n.preset),o=Object.fromEntries(hy.map(e=>[e,RH(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:hy.some(e=>o[e]!==RH(i,e))}}function iU(e){return{sessionKeys:wy.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...JA(e)?kH.map(t=>gj(t,e)):[],...hj(e)?Rg().map(t=>mj(t,e)):[]]}}function aU(e){return new Set(wy.map(e=>e.configKey).filter(t=>iU(t).fileKeys.some(t=>cU(e,sU(t)))))}function oU(e,t,n){let r=JH(e,n),i=new Set(r.map(e=>e.configKey)),a=ky(e=>i.has(Sy[e].configKey)||t.has(Sy[e].configKey)),o=rU(e,n);return{unsaved:r.length+ZH(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function sU(e){let t=_j(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return vj(t)}function cU(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&cU(e[n],r)}const lU=Rg(),uU=new Set(lU),dU=new Set(o_),fU=e=>e?uU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${lU.join(`, `)})`}:{ok:!1,reason:`theme name is required`},pU=e=>e?dU.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${o_.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},mU=new Set([`1`,`true`]),hU=new Set([`0`,`false`]),gU={endcaps:pU,theme:fU,"toolbar-expanded":e=>mU.has(e)?{ok:!0,value:`1`}:hU.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},_U=KI(gU,`state`,wU);function vU(e,t){return _U.register(e,t)}function yU(e){return _U.gateFor(e)}function bU(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:lx(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 xU(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(gU,e.key))}function SU(e,t,n){let r=Ay.get(n);if(r!==void 0)return qH(e,t,r);for(let[,t]of L_(e))if(t.key===n)return t.default??null;return null}function CU(e){let t=hI(e);return xU(Object.values(e.actions).flatMap(e=>bU(e,t)))}function wU(e){return WI(CU(e))}const TU=`update.dismissed`,EU=`updateNotice`,DU=Sy.updateNotice.sessionKey;function OU(e){return e.kind===`source`?e.newer.digest:uo(e.newer)}const kU=e=>`${e.version} [${Xe(e.digest)}]`;function AU(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:kU(e.newer),running:kU(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 jU={kind:`idle`},MU={kind:`running`};function NU(e,t,n){if(e===null)return[];let r=OU(e);if(!n.enabled||n.dismissed===r)return[];let i=AU(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,TU,r]}])),yb(`[disable]`,pi([{verb:Kr,args:[n.sessionId,EU,`false`]},{verb:Rr,args:[n.sessionId,DU,`false`]}]))],...o.map(e=>[yb(e,c)])]}]}function PU(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 FU(e){switch(e.kind){case`current`:return[`info`,`build: current ${kU(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${kU(e.source)}, running ${kU(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function IU(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 LU(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const RU=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function zU(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=RU(e.stderr)??e.error??RU(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function BU(){let e=[JI(EU,[`false`]),vU(DU,[`false`]),vU(TU,[])];return()=>e.forEach(e=>e())}function VU(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=jU,d=null,f=LU(s),p=LU(s),m=()=>PU(c,l);function h(){let e=m(),t=e===null?null:OU(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:vU(TU,[t])})}function g(){c=nt(t,$e),f(FU(c)),h()}async function _(){l=ho(Ze,await mo(po,a,i)),p(IU(l)),h()}return{arm(){BU(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>NU(m(),u,e),act(){let e=m();if(e===null)throw new q(`apply-update: nothing newer is known to apply`);let t=AU(e);if(u.kind===`running`)throw new q(`apply-update: already ${t.busy}`);u=MU,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=jU,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=zU(n);u={kind:`failed`,identity:OU(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function HU(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function UU(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function WU(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:HU(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=HU(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!UU(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 GU=`${Iy}${Fy}`;function KU(e){return`${GU}⚠ cc-candybar: ${qU(e)}${Ly}\n`}function qU(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 JU(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:KU(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const YU=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function XU(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?YU[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const ZU={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},QU=Object.keys(ZU);function $U(e,t){let n=XU(t.color),r=XU(t.bgcolor),i={};for(let e of QU){if(t[e]!==!0)continue;let n=ZU[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 eW=new V;function tW(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($U(t.slice(r,i.start),eW)),n.push($U(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push($U(t.slice(r),eW)),n})}}function nW(e){let t=JU(mn(e)).output;try{return tW(t)}catch(e){return tW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}function rW(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const iW=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function aW(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case R.STANDARD:{let t=e.number===void 0?void 0:iW[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 oW={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},sW=Object.keys(oW);function cW(e){return e.replaceAll(`#`,`##`)}function lW(e){let t=sW.filter(t=>e[t]===!0).map(e=>{let t=oW[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${aW(e.color)}`,`bg=${aW(e.bgcolor)}`,...t].join(`,`)}]`}const uW=new V;function dW(e){let t={},n=(e,n)=>{let r=lW(n)+cW(e);if(n.link===void 0)return r;let i=rW(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),uW)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),uW)),r.join(``)}),links:t}}function fW(e){let t=JU(mn(e)).output;try{return dW(t)}catch(e){return dW(`${Iy}${Fy}⚠ cc-candybar ${Ny(e instanceof Error?e.message:String(e))}${Ly}\n`)}}const pW={band:e=>JSON.stringify(nW(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:fW(e)})};function mW(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 hW(e,t){return e.kind===`absent`?P(`none`):e.kind===`failed`?e:t.kind===`failed`?t:P(t.kind===`ok`?`tracked`:`gone`)}function gW(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 _W={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},vW={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function yW(e,t,n){return Object.hasOwn(t,n)?P(t[n]):I(`${e}: unknown state ${JSON.stringify(n)}`)}const bW={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`committedAt`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function xW(e){return Object.keys(bW).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${bW[t]}: ${n.reason}`]:[]})}function SW(e,t,n){return t.ok?P(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?F:I(CW(e,t))}function CW(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??wW(t.stderr)].filter(Boolean).join(`, `)}`}function wW(e){return e.trim().split(`
|
|
187
|
+
`,1)[0]??``}function TW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?F:P(n)}function EW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?P(t):F}const DW={github:`gh`,gitlab:`glab`};function OW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const kW=/^[A-Za-z]:[\\/]/;function AW(e){let t=e.trim();if(kW.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 jW(e){return AW(e)?.host||null}function MW(e){let t=jW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const NW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function PW(e){let t=SW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?FW(t.value):[]}}function FW(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 IW(e){return e.urls.find(e=>VW(e)!==null)??e.urls[0]??null}function LW(e){return e.find(e=>e.name===`origin`)??e[0]??null}function RW(e){let t=LW(e);return t?IW(t):null}function zW(e){let t=LW(e);return t?t.urls.find(e=>MW(e)!==null)??IW(t):null}function BW(e){let t=(AW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function VW(e){let t=AW(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 HW(e){let t=RW(e);return t===null?null:VW(t)}function UW(e,t,n,r){return t.ok?r(t.stdout):OW(t)||t.reason===`non-zero`&&n.test(t.stderr)?F:I(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??wW(t.stderr)].filter(Boolean).join(`, `)}`)}function WW(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function GW(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 KW(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(!WW(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=yW(`gh pr view`,_W,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function qW(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(!WW(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=yW(`glab mr view`,vW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function JW(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var YW=class{isGitRepo(e){return zV(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=BV(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=TW(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=TW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=TW(s,HW)),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 EW(SW(`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=EW(SW(`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=JW(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 PW(await this.execGitAsync(NW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=RW(e);return(n===null?null:BW(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=zW(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=MW(t);return n===`github`?UW(`gh pr view`,await this.execForgeAsync(DW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,KW):n===`gitlab`?UW(`glab mr view`,await this.execForgeAsync(DW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,qW):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=SW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(GW(t.value)):t}};const XW=(e,t)=>E(t);function ZW(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 QW=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var $W=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??XW}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=ZW(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(QW(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(QW(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 eG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var tG=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 nG(){return J.observable.box(rG(`unread`),{deep:!1})}function rG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function iG(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 aG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(rG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function oG(e,t){e.reading.get().kind===`pending`&&iG(e,t)}function sG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function cG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function lG(e){for(;;){let t=e();if(!sG(t))return t;await t.landed}}function uG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function dG(e){return{current:()=>e}}function fG(e){return lG(()=>e.current())}const pG=`pass`,mG={okMs:5*6e4,failedMs:45e3};function hG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function gG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function _G(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function vG(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 yG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function bG(e){e.missed=!0,aG(e,`unread`)}function xG(e,t){return e.missed&&e.reading.get().kind===`pending`&&iG(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function SG(e,t){let n=cG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:cG(t)})}function CG(e){return t=>I(`${e} threw: ${String(t)}`)}var wG=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 YW,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new Mk(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 $W({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return dG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>SG(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 Ak,watcher:this.watchers.acquire(`git:${e}`,vG(n),()=>this.changed(e)),period:new tG(()=>{r.refresh.share(pG,()=>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(pG,()=>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&&bG(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(pG,()=>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:nG(),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=_G(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(gG(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(CG(`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,iG(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of xW(n.value))s.add(e)});let c=yG(a),l=i===null||r.length===0?`-`:c===void 0?xG(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}`,hG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new tG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:nG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(CG(`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?(bG(t),`owed`):(aG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,iG(t,a.outcome),t.period.landed(eG(mG,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(CG(`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||(iG(t,i),t.period.landed(eG(mG,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())oG(n,t);e.pr!==null&&oG(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()}},TG=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 EG={"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 DG=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 TG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await TG.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(EG).length} models`),this.executionCache=EG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(EG).length} models`),EG)}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 OG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function kG(e){if(typeof e==`string`)return OG.exec(e)?.[1]}function AG(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 jG(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 MG(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=AG(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`?kG(jG(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 NG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function PG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await FG(Fa(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function FG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function IG(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=WG(i,t,s.value);let c=VG(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 LG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(zG(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=jG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||RG.test(r)?`claude-code`:`prompt`}const RG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function zG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function BG(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=LG(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:MG(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 VG(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 HG(e){let t=VG(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return BG(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function UG(e){let t=[];for(let n of e.split(`
|
|
191
|
+
`)){let e=HG(n);e&&t.push(e)}return t}function WG(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function GG(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function KG(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=WG(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=>UG(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 qG=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}},JG=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:()=>cG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,aG(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:nG(),holders:0,flight:null,changed:!1,superseding:0,revisit:YG(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();ZG(()=>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{iG(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(),oG(e,I(`${this.spec.name} entry dropped`))}};function YG(e,t){if(e===null)return new XG(t.holdReturned);let n=new tG(t.period);return{landed:t=>n.landed(eG(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var XG=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 ZG(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function QG(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 $G={okMs:60*1e3,failedMs:10*1e3},eK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},tK={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function nK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function rK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function iK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const aK={entries:0,cost:0,breakdown:iK(),days:new Map};async function oK(e,t){let n=nK(new Date(rK())),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 DG.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=nK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...eK};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 sK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function cK(e){let t=0,n=0,r=iK(),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)??{...eK};sK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:tK,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 lK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function uK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!lK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...eK};sK(r,t),n.set(e,r)}return n}async function dK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function fK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function pK(e,t){(0,J.runInAction)(()=>e.set(t))}var mK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new qG;scans;daySets=new Map;speedFlight=new qG;requestFlight=new qG;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 Mk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new JG({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${as(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??$G,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(fK(t.kind===`ok`?t.value.sessionInfo:tK,e))},speed:t=>this.observed(e,r,t),today:async e=>{await fG(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(fK(n.record?.sessionInfo??tK,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),pK(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=NG(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=nK(ok(n)),o={...eK},s=e.sums.get(a);s!==void 0&&sK(o,s);let c=lK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&sK(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 pK(this.hold(e).speed,t),t;let r=QG(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 pK(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 iS(`today over ${e.join(`,`)}`,()=>uK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await IG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of GG(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 KG(e,r,aK,oK);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 GG(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...cK(i),mainStamp:a})}async scan(e){try{let t=rK(),n=await PG(e),r=[];for(let e of n){let n=await FG(Fa(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await FG(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 dK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${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=nK(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()}},hK=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)}})}},gK=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 hK(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 KG(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 GG(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 _K(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 vK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(void 0,_K,(e.ledger??new Mk(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,yK(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,yK(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 yK(e){return e.context_window?.context_window_size??2e5}const bK={messageCount:0,nonPrompts:0,recent:[]},xK=new Set([`turn`,`interrupt`,`claude-code`]);function SK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!xK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function CK(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 wK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(bK,SK,(e.ledger??new Mk(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?TK(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:TK(e,n,r)}};function TK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:CK(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 EK={command:null,todos:[],pending:[],done:[]};function DK(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 OK(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 kK(e,t){if(t.isSidechain)return e;let n=OK(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=DK(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 AK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>DK(e,t.name),[]),done:e.done}}var jK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new gK(EK,kK,(e.ledger??new Mk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return MK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:MK(e,t)}};function MK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(AK(t.value))}function NK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function PK(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 FK(e,t,n,r){return PK(D(NK(e,t,n,r)),n)}async function IK(e,t,n,r){return PK(await pt(NK(e,t,n,r)),n)}const LK=3e4;var RK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new JG({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${as(e.pane)} socket=${as(e.socket)}`,read:zK,every:{okMs:LK,failedMs:LK},maxEntries:64,logger:t,ledger:e.ledger??new Mk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function zK(e){let t=await IK(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 BK=6e4,VK={okMs:BK,failedMs:BK};function HK(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function UK(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var WK=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:VK,maxEntries:1,logger:t,ledger:e.ledger??new Mk(t)};this.name=new JG({...n,name:`host.name`,read:()=>UK(`name`,()=>HK(C.hostname()))}),this.user=new JG({...n,name:`host.user`,read:()=>UK(`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()}},GK=class{known=new hK(64);refreshes;constructor(e=Me,t=new Mk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=KK(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=gP(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 KK(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Ma(t)}catch(e){return`unread:${e.code??`error`}`}}const qK=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function JK(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 YK=class{known=new hK(256);refreshes;constructor(e=Me,t=new Mk(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 XK(t);return this.refreshes.recorded(`sid=${as(e)} stamp=${as(n)}`,`request`,i,Date.now()-r),i}};async function XK(e){let t=await ZK(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function ZK(e){for(let t of[65536,1048576]){let n=await Ga(e,t);if(n.kind!==`ok`)return n;let r=QK(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function QK(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||!qK.test(t))continue;let r=JK(t);if(r!=null)return r}return null}var $K=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 eq=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}},tq=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,nq=e=>iV(e),rq=e=>s.join(e.storage.folder,nq(e.sessionId)),iq=e=>JSON.stringify([e.folder,e.generation]),aq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var oq=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??eq,this.sessions=new JG({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${as(rq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Mk(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`||!tq(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(iq(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:${iq(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(iq(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=iq(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=>aq(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(nq(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`&&tq(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=>aq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(iq(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=>aq(e.storage,r))}async read(e){let t=this.faults.get(iq(e.storage));if(t!==void 0)return I(t);let n=rq(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=kk(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&&nq(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 sq(e){let{logger:t,ledger:n}=e;return{hostService:new WK({logger:t,ledger:n}),gitProvider:new wG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new mK({logger:t,ledger:n}),contextProvider:new vK({logger:t,ledger:n}),metricsProvider:new wK({logger:t,ledger:n}),activityProvider:new jK({logger:t,ledger:n}),tmuxService:new RK({logger:t,ledger:n}),autoCompact:new GK(t,n),cacheExpiry:new YK(t,n),managedStorage:new oq({watchers:e.watchers,logger:t,ledger:n}),faults:new $K,log:e.logger}}function cq(e){return Math.max(1,e-2)}function lq(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 uq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function dq(e){return{...Object.fromEntries(py.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:AH(e.preset)}}}const fq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function pq(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 mq=10*1e3;function hq(e,t){if(!(t<60))return e*3600/t}function gq(e,t,n,r){let i=r-t;if(i<50||i>mq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function _q(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=gq(t.input,t.atMs,n.input,n.atMs),i=gq(t.output,t.atMs,n.output,n.atMs),a=gq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function vq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>mq)continue;let o=gq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function yq(e,t){let n=rx(e,t),r=[...Ug.flatMap(e=>{let t=n[e];return Wg(t)?[t]:[]})];for(let n of E_(nx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...bq(e,n.name));return Sq(e,r)}function bq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function xq(e,t,n){return Sq(e,[...bq(e,t),...n])}function Sq(e,t){let n=oB(e),r=new Map(Bx(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=rB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Cq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=yq(e,n);return t.set(n,i),i}}function wq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Tq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(fq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Eq=new WeakMap;function Dq(e){let t=Eq.get(e);return t===void 0&&(t=Oq(e),Eq.set(e,t)),t}function Oq(e){let t=t=>wq(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 kq(e){return cq(e.termCols??120)}function Aq(e){return Xa(Ya(e.claudeConfigDir))}function jq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Mq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Dq(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(ok(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Aq(a)))])}function Nq(e,t){return[...t.keys()].filter(t=>e.has(t))}function Pq(e,t){let n=dG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function Fq({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Tq(n),t.workspace?.project_dir]}function Iq(e,t,n,r,i){let a=Dq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return dG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),dG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...Fq(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(Nq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function Lq(e){let{hookData:t,deps:n}=e,r=Dq(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(Aq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function Rq(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 zq(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Dq(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:Qq(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:qq(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:Hq(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,Uq),x=u(n.usage,e=>Xq({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>Xq({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,Jq),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(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{...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}},...dq(a),history:t.history,navigation:{back:t.back},term:{cols:kq(i)},...c,...s!==null&&{configPath:s},resumeCommand:lq(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:Vq(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?Oa:t})}}function Bq(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function Vq(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function Hq(e,t){let n=e!=null&&t!=null?hq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function Uq(e){let t=_q(e),n=vq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function Wq(e,t){return zq(e,t,Lq(e))}function Gq({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 Kq(e,t,n){await Mq(e,t,n),await lG(()=>{let t=Rq(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function qq(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return _P(e.value,t)}}function Jq(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=Yq(e.running),i=Yq(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 Yq(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function Xq(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 Qq(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(hW(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:gW(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 $q(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const eJ={kind:`hidden`},tJ={kind:`shown`};function nJ(e,t){try{return $q(e,t)?tJ:eJ}catch(e){let t=tS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function rJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function iJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function aJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function oJ({text:e,placement:t,lead:n,trail:r}){return{text:sJ(e),placement:t,...n!==void 0&&{lead:sJ(n)},...r!==void 0&&{trail:sJ(r)}}}function sJ(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 cJ(e){let t=aJ(e);if(t.length===1)return e.text;let n=rJ(t);return n.style=e.text.style,n}function lJ(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=rJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:rJ([d,...c],a)},...l.length>0&&{trail:rJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(iJ(u,n,p),[{text:u,...f}])}const uJ=RegExp(`\\x1b\\[[0-9;]*m|${Zd.source}`,`g`);function dJ(e){return Math.max(0,...e.split(`
|
|
193
|
+
`).map(e=>Us(e.replace(uJ,``))))}function fJ(e,t){let n=()=>e.map(e=>({owner:cJ(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(cJ),t).split(`
|
|
194
|
+
`);if(i.length>1)return n();let a=Math.max(0,t.width-dJ(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];iJ(c,c.cellLength+a,n)}),n()}function pJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=mJ(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=mJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function mJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>hJ(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 hJ(e,t){let n=e.copy();return n.style=t,n}function gJ(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 _J(e,t){let{look:n}=gJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function vJ(e,t){let{layout:n}=gJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function yJ(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 bJ(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,xJ(e,t,o,n,r,i));return i}function xJ(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=lx(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=lx(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=lx(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:wJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:wJ(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:px(n),argv:n.run.map(n=>wJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,wJ(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:wJ(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 SJ(e){return e.kind===`do`?SJ(e.head):e}function CJ(e){switch(SJ(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 wJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function TJ(e,t){return e.has(t)?Zx(e.read(t)):``}function EJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function DJ(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 OJ(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 kJ(e,t){return Math.max(e.members.indexOf(TJ(t,e.stateVar)),0)}function AJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=TJ(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=TJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=TJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(kJ(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:[EJ(e.text,xk(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[EJ(e.target,xk(r))]}],active:!1};case`persist-literal`:{let t=TJ(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=TJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(kJ(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,EJ(e.name,xk(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=xk(r),n=JSON.stringify({run:e.argv.map(e=>EJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,EJ(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,PI(e.op)]}],active:!1};case`do`:{let o=AJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>AJ(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,PI(r)]}],active:!1}}}}function jJ(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,kJ(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 MJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=gJ(n,`action "${e}"`).store,{display:a,boundValue:o}=jJ(e,SJ(r),t,i),s=TJ(i,`session.id`),{effects:c,active:l}=AJ(r,a.plain,o,i,s,n.signer);return OJ(a,pi(c),l)}function NJ(e){return{action:{fn:(t,...n)=>MJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function PJ(e,t){return DJ(`✕`,pi([{verb:Rr,args:[TJ(e,`session.id`),t,yi]}]),!1)}function FJ(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Xh(e,t,n))})}function IJ({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function LJ(e,t,n){return new V({color:z.fromRgba(Fl(Bh(e,`warning`),t,Yh,n))})}function RJ(e,t,n){return V.combine([FJ(e,t,n),LJ(e,t,n)])}function zJ(e,t,n){return FJ(e.palette,Cg(e.palette,e.disclosure,t,n),n)}function BJ(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 VJ=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},HJ=e=>new V({bold:e});function UJ(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>VJ(a,V.combine([zJ(e,{...n,distribution:t},i),HJ(o)]));let o=FJ(e.palette,a,i);return(e,t,i,a)=>WJ(i,V.combine([o,HJ(a)]),r(t,n))}const WJ=(e,t,n)=>VJ(W.fromFragments([VJ(e,t),VJ(` `,t),BJ(n)]));function GJ(e,t){return t===void 0?(e,t,n)=>VJ(n):(n,r,i)=>WJ(i,void 0,t(r,e))}function KJ(e,t,n,r,i){let a=FJ(e.palette,i,r);return(e,r,i,o)=>VJ(W.fromFragments([VJ(o?`[`:` `,a),BJ(n(r,t)),VJ(o?`]`:` `,a)]))}function qJ(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=>JJ(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function JJ(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function YJ(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function XJ(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 QJ(e,t,n){return eY(e,()=>n(ZJ(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function $J(e,t){return eY(e,()=>(e.current=null,t()))}function eY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function tY(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 nY(e){return new W(e).cellLength}function rY(e){let{width:t,chromeCols:n,padding:r}=gJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function iY(e){let{padding:t,seamCols:n}=gJ(e,`a row fit`);return Math.max(1,rY(e)-(nY(`✕`)+2*t+n))}function aY(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 oY(e,t,n){let r=nY(`←`)+1+nY(`→`)+1,i=aY(e,t,n);return(i.length>1?aY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function sY(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 cY(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 lY(e,t,n){let r=e.compiled.get(t),i=r&&SJ(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 uY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=gJ(a,`picker`).store,d=TJ(u,`session.id`),f=`stateVar`in t?TJ(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`?iY(a):rY(a):1/0,h=(r.kind===`led`?0:nY(`✕`)+1)+c.reduce((e,t)=>e+nY(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?oY(_.map(e=>e.cellLength),m,h):qJ(g.entries,g.groups,i),y=parseInt(TJ(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([...AJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>OJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[DJ(`✕`,pi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>DJ(e,pi([...AJ(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(DJ(`←`,te(x-1),!1));let w=x<v.length-1?[DJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[sY([...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=[sY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(sY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>nY(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-nY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(sY([ae(p(r,YJ(c,m)),r)],i))}}return ce}function dY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{QO(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=cY(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=lY(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=tY(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]=uY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,UJ(u,kh(void 0),_J(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),LJ(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function fY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function pY(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 mY(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=gJ(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=TJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return sY([],!0);let d=TJ(o,t.stateVar),f=fY(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(AJ(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=OJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):OJ(GJ(_J(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),pi(AJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=pY(e=>v(e).cellLength,u,nY(`◀`)+1+y.cellLength+1+nY(`▶`),iY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return sY([...ee(-1).reverse(),DJ(`◀`,h(-1),!1),y,DJ(`▶`,h(1),!1),...ee(1)],!0)}function hY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(QO(`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&&CJ(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=lY(e,n,`carousel`),l=tY(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 mY(n,c,e,UJ(l,kh(void 0),_J(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function gY(e,t,n){let r=lY(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 _Y(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 vY(e,t,n,r){let i=gY(e,t,n),a=r??TJ(gJ(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,_J(e,`{{ ${n} }}`))}function yY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(QO(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return BJ(vY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function bY(e,t,n){return{swatches:{fn:(r,i)=>{let a=gY(e,r,`swatches`),o=cY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=tY(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]=uY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,KJ(s,_J(e,`{{ swatches }}`),a.paletteOf,c,s.bg),LJ(s.palette,s.bg,c),u===0?[]:(()=>{let t=fY(l,TJ(gJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[_Y(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const xY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function SY(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:xY[i%xY.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 CY(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:IJ({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 wY(e,t,n,r,i){let a=SY(e,t,n,r).map(e=>CY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
195
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function TY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(QO(`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}=_J(e,`{{ themePreview }}`);return wY(r===void 0?a:vY(e,r,`themePreview`),o,{...tY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),iY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const EY=e=>e.slice(e.lastIndexOf(`.`)+1),DY=(e,t)=>{let n=new W(EY(e));return n.truncate(t,{marker:`…`}),n.plain};function OY(e,t){let n=e.map(e=>e.map(({name:e})=>nY(EY(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 kY(e,t,n,r){let i=OY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${DY(s,i)} `,{style:IJ(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 AY=`layoutPreview`;function jY(e,t){return{[AY]:{fn:()=>kY(vJ(e,`{{ layoutPreview }}`),_J(e,`{{ layoutPreview }}`).decor,t.drawnAt(),iY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function MY(e,t,n,r){let i=tY(r.activeSegment,`{{ menu }}`),a=r.action,o=CA(i.placementId,e,n.key),s=EA(o),c=SA(e),l=gJ(a,`menu`).store,u=TJ(l,o)===c,d=TJ(l,`session.id`),f=u?yi:c,p=DJ(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=lY(a,e,`menu`);return uY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,yi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,UJ(i,n.distribution,_J(a,`{{ menu }}`),l.paletteOf,t,c),LJ(i.palette,c,t))})():[]),p}const NY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function PY(e,t){let n=t[t.length-1],r=NY(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:AA(r??{})}}function FY(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=PY(t,n);return MY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function IY(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=LY(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 LY(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 RY(e){let t={fn:(()=>{let t=tY(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:(()=>tY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=tY(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=IO(()=>tY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...zY(s)];return IY({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 zY(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 BY(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>yk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const VY={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},HY=new WeakMap;function UY(e){let t=HY.get(e);return t===void 0&&(t=WY(e),HY.set(e,t)),t}function WY(e){let t=new Map(Bx(e)),n=oB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:VY[t.kind]])),i=new Map([...t].map(([e,t])=>[e,BY(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 GY(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 GY(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 KY=e=>e.kind===`failed`?$q:e;function qY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function JY(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 YY(e){return{...e,cells:e.cells.map(aJ)}}function XY(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,...ZY(e,r)]}function ZY(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 QY(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:XY(e.direction,e.children.map((t,i)=>n(t,[...r,$Y(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function $Y(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const eX={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(),XY(e.direction,e.children.map((n,r)=>t.renderChild(n,KY(t.gate),$Y(e,r))))}},tX={drop:e=>e.place,above:()=>`above`},nX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},rX={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,iX(e,t))};function iX(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=Ck(t.scope,e.settings);if(t.gate.kind===`failed`)return uX(e,r,t,t.gate.message);try{let i=t.placement(e),a=qY(t.gate,i.gate());if(a.kind===`failed`)return uX(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 uX(e,r,t,s.message);let c=Mb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Hj(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`?aX(f.variable):oX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?sX(p.segment,u):cX(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:$q,h.disclosure).map(e=>({...e,place:tX[v.placement](e)})),b=(e,t,n)=>cJ(fJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?nX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(lX(iJ(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(iJ)),[...ie,...re]}catch(n){return uX(e,r,t,n.message??String(n))}}const aX=e=>({kind:`waiting`,variable:e});function oX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=tS(e);if(t===void 0)throw e;return aX(t.variable)}}function sX(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:WY(fJ(r,c)).map((e,t)=>({cells:cJ(e,{...l,lead:t===0?fJ(i,c):[],trail:t===0?fJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:cJ(fJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function cX(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=fJ(dX(e.lead,e,t,n),l),d=fJ(dX(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 cJ(fJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function lX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function uX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:cJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Hj(n.palette)},lead:dX(e.lead,e,t,n),trail:dX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function dX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=tS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const fX={container:eX,segment:rX};function pX(e){return fX[e]}var mX=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?hX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const hX={kind:`hidden`},gX={palette:`theme`,style:`style`,effect:`effect`},_X=Dy.get(`colorCompatibility`),vX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function yX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function bX(e){if(e.ok)return e.value;throw e.error}const xX=e=>({read:()=>e}),SX=fh({basePalette:dh,palette:dh,decor:Eg});var CX=class{evaluated=0;memory=new mX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&SX(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=xk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(_X);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(vX,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 QY(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=TI(e);return i===void 0?[]:[{name:i,address:n,palette:Mb(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=lA(e);return t===void 0?sA(e)===void 0?Xk(this.view.get().payload(),e):Xk(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()[gX[e]];if(t.kind===`decided`)return EX(t.name,null,null);let r=OX(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=kX(this.source,e,i.name,r.where,e=>{t=e}),EX(n,t,null)}case`pending`:return EX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],EX(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||!DX(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 tJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>QJ(this.source.activeSegment,()=>tJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new AX(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:vJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=tS(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:yX(e)}),bX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:TI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function wX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new CX(t,n,e,r);return e.views.set(t,a),a}function TX(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 EX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),DX=(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 OX(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 kX(e,t,n,r,i){switch(t){case`palette`:return Lb(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var AX=class{where=jX(fh({palette:dh,region:wg}));ground=jX(fh({colours:NX,bodyOpen:dh}));opened=jX(fh({colours:NX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ck(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?xX(eJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>QJ(r,()=>tJ(a,i))),this.open=d===void 0?xX($q):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>QJ(r,()=>tJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return IX(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 LX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?xX(zX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return RX(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}),VX(n,r,this.affixes.read())}};function jX(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 MX=(e,t)=>e.hex===t.hex,NX=fh({palette:dh,drawnAt:dh,tint:MX,text:MX,bg:MX,disclosure:Dg});function PX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const FX=e=>ug(e.palette,e.disclosure,e.drawnAt);function IX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return ZJ(e,PX(t,c),e=>{let t=Wj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function LX(e,t,n,r,i,a){return ZJ(e,PX(t,n),e=>(e.bg=i?FX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function RX(e,t,n,r,i,a,o){return ZJ(e,PX(t,n),e=>(e.bg=r?FX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const zX={lead:[],trail:[],drops:[]};function BX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return PJ(t,FX(e).state,n)},get band(){return PJ(t,FX(e).plane,n)},get close(){return LJ(t,FX(e).state,n)},disclosure:r}}function VX(e,t,n){return{styles:BX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?FX(e).shortfalls:[]}}function HX(e,t,n,r,i,a,o){let s=IX(e,t,n,r,i,void 0,void 0,o);return VX(s,LX(e,t,s,a,!1,o),zX)}function UX(e,t,n,r,i){return BX(IX(e,t,n,r,i,void 0,void 0,{}))}function WX(e,t){return{payload:()=>e,selections:()=>t}}function GX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Ik(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 KX(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 qX(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:GX(n.cache),parse:KX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:GX(n.cache),parse:KX(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 JX(e,t){let n=US.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 YX(e,t,n){let{compiled:r,loadWarnings:i}=ZX(e,t,n.cwd,XX(n.signer),tZ);return{...r,loadWarnings:i}}const XX=e=>(t,n)=>nZ(n,e);function ZX(e,t,n,r,i=tZ){let a=QX(e),o=$X(a);return{compiled:r(o,a),compileKey:o,loadWarnings:eZ(e,t,n,i)}}function QX(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:[...lB(e)].sort(([e],[t])=>e<t?-1:1)}}function $X(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function eZ(e,t,n,r){let i=HY(e),a=lB(e),o=[];for(let[s,c]of Bx(e))if(r.has(i.get(s)))try{qX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const tZ=new Set([`directory`,`view`]);function nZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>hJ(i,`drawnAt`).registry.drawnAt(),o=YJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=$b(e.presets),u=mI(e),d=[e=>yY(i,o,e.now)],f=bk({extraFuncs:{...MJ(i),...vY(i),...uY(i,o),...mY(i,o),...wY(i,o),...AY(i,o),...PY(s),...LY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=JX(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=yJ(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(hJ(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 pX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=nx(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 dB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:aZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:tB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:_k(d)},re=mB(ne),ie=[...S.values()].flatMap(iZ(y)).some(e=>re(m.get(e))),ae=ie?mB({...ne,clock:new Set([...ne.clock,kY])}):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 rZ(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 iZ=e=>t=>{let n=[];return QY(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 aZ(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 oZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function sZ(e,t,n,r,i){let a=cZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function cZ(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 lZ(e){return uZ(e).filter(e=>!e.name.startsWith(_A)).map(e=>e.id)}function uZ(e){return e.kind===`container`?e.children.flatMap(uZ):[e,...e.opens===void 0?[]:uZ(e.opens.body)]}function dZ(e,t,n,r,i,a,o,s,c=IH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return wX(t,n,r,WX(l,c)),pZ(e,t,n,r,l,a,o,s,c)}function fZ(...e){return dZ(...e).text}function pZ(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(ck(a,g.anim));let _=TX(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(vJ(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,JY),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=kX(t,e,sZ(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:Lb(C(`palette`),``,oZ),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Pb(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:JY,hold:YY},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:qY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${lZ(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(HX(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=>NJ(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)=>UX(t.activeSegment,e,n,a,r.drawnAt())};return pX(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 "${Zb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=GY(ye(be,eJ,Ag(x))).map(({line:e,row:t})=>{let n=dJ(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||uZ(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 EZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=iH(t.layers,DH,{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??DH,l=a.find(e=>e.path===t.home)?.raw??{},u=new mS,d=new eA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=ZX(o,d,e,r.compile??XX(r.signer),AZ),n.push(...f.loadWarnings);let t=d.view();n.push(...eZ(o,t,e,jZ)),t.dispose(),vU(o),JI(o),p=DZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Sq(o),authoredRoots:CZ(c,l),fileHeldSettings:iU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>gZ(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 DZ(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 OZ(e,t,n,r){let i=GV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[XV(e,t),JV(i)],s,c=null;try{s=EZ(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:TZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:TZ(o),state:s,error:null}}function kZ(e,t,n){return EZ(e,{layers:[],home:``,projectDir:t},[],n)}const AZ=new Set([`directory`]),jZ=new Set([`view`]);function MZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new _Z;eZ(e.config,l,t,jZ);let d=()=>FH(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)}`),Nq(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});wX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var NZ=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)??nZ(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=SZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,bZ(a.layers,a.state));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??kZ(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(SZ(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=MZ(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 OZ(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`,xZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,bZ(n.layers,n.state));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=wZ(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 PZ=16384;var FZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<PZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%PZ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function IZ(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 LZ={load:()=>({}),save:()=>{},flush:()=>{}};var RZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=LZ,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 zZ(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 BZ=class{timer=null;pending=null;writing=!1;generation=0;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return zZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=`${this.filePath}.writing`;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}if(t!==this.generation){await p.promises.rm(i,{force:!0});return}let c=performance.now();p.renameSync(i,this.filePath),this.saved(r,e,n,a+performance.now()-c),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.generation++,this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.renameSync(n,this.filePath),this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const VZ=new Set([`1`,`true`]),HZ=new Set([`0`,`false`,``]);function UZ(e,t){let n=mQ(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(VZ.has(t))return`true`;if(HZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function WZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function GZ(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 KZ(e){return/^\s*$/.test(e)?null:Ui(e)}function qZ(e,t){return e!==null&&Gi(e,t)!==void 0}function JZ(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(JZ),...i}}return e}function YZ(e){if(!Ub(e))return JZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,JZ(t)])),...n}}const XZ=TH,ZZ=XZ.segments,QZ=XZ.presets,$Z=XZ.root;function eQ(e,t,n,r){if(!qZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function tQ(e,t){let n=vj(t);return t.scope===`segment-palette`&&eQ(e,[`segments`,t.segment],ZZ[t.segment],n.join(`.`)),n}function nQ(e){return Ui($i(e))}function rQ(){return Object.entries($Z.rows).map(([e,t])=>{let n=JZ(t);return{path:[`root`],fragment:nQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function iQ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function aQ(e,t){if(t===void 0)return null;let n=YZ(t);return{path:e,fragment:nQ(n),unit:{path:e,value:n}}}function oQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=QZ[t];eQ(e,n,i,r.join(`.`));let a=iQ(e,r)??aQ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function sQ(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 cQ(e,t){return[...rQ(),iQ(e,[`root`]),oQ(e,t)].filter(e=>e!==null).reduce(sQ,new Map)}function lQ(e,t,n){for(let{node:r,...i}of cQ(e,t).values())if(Sa(r,n))return i;throw new q(`${uQ(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 uQ(e,t){return oQ(e,t)?.path??[`root`]}function dQ(e,t){return t.scope===`preset-root`?uQ(e,t.preset):vj(t)}function fQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function pQ(e){let t=_j(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function mQ(e){let t=pQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function hQ(e,t,n,r,i){i(t,n,EQ(t,r)),GZ(t.path,r,e.logger),e.record(t.path,n,r)}function gQ(e,t,n){let r=yQ(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 _Q=()=>{};function vQ(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 yQ(e,t,n){let r=bQ(e,t);if(r===null)return[];let i=new Set(wQ(CQ(r),CQ(n)));return wQ(SQ(e,r),SQ(e,n)).filter(e=>!i.has(e))}function bQ(e,t){try{return xQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function xQ(e,t){return iH(t===null?e.above:[e.path,...e.above],DH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function SQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function CQ(e){return e.layers.at(-1)?.config??e.base}function wQ(e,t,n=``){return!TQ(e)||!TQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>wQ(e[r],t[r],n===``?r:`${n}.${r}`))}function TQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function EQ(e,t){try{return xQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function DQ(e,t){let n=mQ(t),r=KZ(WZ(e)??``),i=r===null?void 0:Gi(r,vj(n));return i!==void 0&&`value`in i?i.value:void 0}function OQ(e,t,n){kQ(e,t,n,[])}function kQ(e,t,n,r){let i=WZ(t.path),a=n.reduce((e,[t,n])=>pa(e,tQ(KZ(e),mQ(t)),UZ(t,n),Zi),i??``);hQ(e,t,i,vQ(t,()=>AQ(a,t.path,r,e=>e)),gQ)}function AQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=lQ(KZ(s),n,i),l=Ea(fQ(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 jQ(e,t,n){let r=KZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of cQ(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(oQ(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 MQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!kH(t[1])?2:0)}function NQ(e,t,n){let r=n.map(pQ),i=WZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>MQ(e,dQ(KZ(e),t)),i);a!==i&&hQ(e,t,i,a,_Q)}function PQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function FQ(e,t){let n=new Set([...OH,...PQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(pA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(pA(e)))}function IQ(e,t,n,r,i,a){let o=WZ(t.path),s=KZ(o??``),c=FQ(s,t),l=[`presets`,c],u=vQ(t,()=>oQ(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=gj(c,e);return[tQ(s,mQ(n)),UZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return hQ(e,t,o,vQ(t,()=>AQ(p,t.path,a.map(e=>({...e,preset:c})),jQ)),gQ),c}function LQ(e,t,n,r){let i=WZ(t.path);hQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),gQ)}function RQ(e,t,n){if(kH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=WZ(t.path),a=KZ(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`]);hQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>MQ(e,t),i),_Q)}function zQ(e,t,n,r){let i=pQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=WZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=vQ(t,()=>lQ(KZ(a??``),i.preset,o)),c=fQ(a??``,s),{after:l,placed:u}=BQ(c,s.path,r,()=>{let e=EQ(t,c).config;return $b(e.presets).map(t=>nx(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 hQ(e,t,a,l,gQ),u}function BQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=FI(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const VQ={load:()=>({}),save:()=>{}},HQ=new Set(wy.map(e=>e.sessionKey)),UQ=e=>HQ.has(e)||e.startsWith(Aj),WQ=8*1024*1024,GQ={past:[],future:[]},KQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var qQ=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=VQ){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)??GQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??GQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(KQ(n));r.set(KQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:IZ(this.sessionState,e=>UQ(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:t$(i,n),o=r.get(e),s=o===void 0?a:a$(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`,r$(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(KQ)),a=n.net.filter(e=>!i.has(KQ(e))),o=XQ(o$(i$(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(c$).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=XQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...QQ(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(KQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:o$(n,t),future:o$(i,t),...a!==void 0&&{savepoint:{at:o$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(KQ(e))),below:o$(a.below,t)}}}),new q(`${r}: ${o.map(c$).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):WZ(t.file)}write(e,t,n){t.kind===`file`?GZ(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||JQ(n)>WQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,YQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${WQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function JQ(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 YQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...QQ(n,1,[])}:{past:e,future:t.slice(1),...QQ(n,0,[])}}function XQ(e){return e.slice(-50)}const ZQ=e=>e===Mj.member;function QQ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:$Q(e.net,n),below:e.below}}}function $Q(e,t){let n=new Map(e.map(e=>[KQ(e),e]));for(let e of t){let t=n.get(KQ(e));n.set(KQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const e$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function t$(e,t){let n=[...e.past,t],r=XQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...QQ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...n$(e.future,a),...i.below]},n.length-r.length,t)}}function n$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function r$(e,t){return{past:e.past.slice(0,-1),future:XQ([...e.future,t]),...QQ(e.savepoint,0,e$(t))}}function i$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...n$(r,t.at-i.length),...t.below]}function a$(e,t){if(ZQ(t.after)&&!ZQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!ZQ(t.after)&&ZQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function o$(e,t){return e.map(e=>e.filter(e=>!t.has(KQ(e)))).filter(e=>e.length>0)}function s$(e){return e.map(c$).join(`, `)}function c$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function l$(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 u$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(l$))}function d$(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(l$)&&u$(t.below)}function f$(e){if(typeof e!=`object`||!e)return!1;let t=e;return u$(t.past)&&u$(t.future)&&(t.savepoint===void 0||d$(t.savepoint))}function p$(e,t){let n=e=>e.kind===`file`||UQ(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 m$(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(f$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,p$(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),gt(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const h$=e=>!UQ(e)&&!aP(e)&&e!==`update.dismissed`;var g$=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:IZ(e,h$,(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 _$={inside:()=>[],defaultOf:()=>yi,menus:[]},v$=e=>`${e.key}\0${e.member}`;function y$(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?[]:XR(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(v$(e))??new Map;n.set(v$(t),t),o.set(v$(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(v$(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 $b(e.presets))d(nx(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(v$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(v$(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(v$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const b$=new WeakMap;function x$(e){let t=b$.get(e);if(t!==void 0)return t;let n=y$(e);return b$.set(e,n),n}function S$(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 C$(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 w$(e,t,n){let r=(r,i,a)=>{let o=S$(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 T$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function E$(e,t){let n={...e};for(let e of T$)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 D$(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 O$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function k$(e){let t=e=>({kind:`failed`,reason:e});if(!O$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!O$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!KM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${KM.join(` or `)}`)}return{kind:`ok`,value:e}}function A$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const j$=e=>D$(e,`doctor-marks.json`,{},k$),M$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},N$=(e,t)=>e.includes(t)?e:[...e,t],P$=e=>D$(e,`doctor-clicked-terminals.json`,[],M$);var F$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const I$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},L$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),R$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=L$(e,t);return r===void 0?n:r.projectDir},z$=(e,t)=>L$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function B$(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 KY(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 qY=e=>e.kind===`failed`?eJ:e;function JY(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function YY(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 XY(e){return{...e,cells:e.cells.map(oJ)}}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,...QY(e,r)]}function QY(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 $Y(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,eX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function eX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:x_[e.direction]}}const tX={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,qY(t.gate),eX(e,r))))}},nX={drop:e=>e.place,above:()=>`above`},rX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},iX={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,aX(e,t))};function aX(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=Ck(t.scope,e.settings);if(t.gate.kind===`failed`)return dX(e,r,t,t.gate.message);try{let i=t.placement(e),a=JY(t.gate,i.gate());if(a.kind===`failed`)return dX(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 dX(e,r,t,s.message);let c=Mb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Hj(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`?oX(f.variable):sX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?cX(p.segment,u):lX(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:eJ,h.disclosure).map(e=>({...e,place:nX[v.placement](e)})),b=(e,t,n)=>lJ(pJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?rX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(uX(aJ(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(aJ)),[...ie,...re]}catch(n){return dX(e,r,t,n.message??String(n))}}const oX=e=>({kind:`waiting`,variable:e});function sX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=tS(e);if(t===void 0)throw e;return oX(t.variable)}}function cX(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:GY(pJ(r,c)).map((e,t)=>({cells:lJ(e,{...l,lead:t===0?pJ(i,c):[],trail:t===0?pJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:lJ(pJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function lX(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=pJ(fX(e.lead,e,t,n),l),d=pJ(fX(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 lJ(pJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function uX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function dX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:lJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Hj(n.palette)},lead:fX(e.lead,e,t,n),trail:fX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function fX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=tS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const pX={container:tX,segment:iX};function mX(e){return pX[e]}var hX=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?gX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const gX={kind:`hidden`},_X={palette:`theme`,style:`style`,effect:`effect`},vX=Dy.get(`colorCompatibility`),yX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function bX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function xX(e){if(e.ok)return e.value;throw e.error}const SX=e=>({read:()=>e}),CX=fh({basePalette:dh,palette:dh,decor:Eg});var wX=class{evaluated=0;memory=new hX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&CX(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=xk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(vX);return typeof e==`string`&&u_(e)?e:`truecolor`});let i=(0,J.observable)(yX,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 $Y(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=EI(e);return i===void 0?[]:[{name:i,address:n,palette:Mb(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=lA(e);return t===void 0?sA(e)===void 0?Xk(this.view.get().payload(),e):Xk(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()[_X[e]];if(t.kind===`decided`)return DX(t.name,null,null);let r=kX(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=AX(this.source,e,i.name,r.where,e=>{t=e}),DX(n,t,null)}case`pending`:return DX(n??Zg[e],null,i.variable);case`failed`:return n=Zg[e],DX(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||!OX(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 nJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>$J(this.source.activeSegment,()=>nJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new jX(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:yJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=tS(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:bX(e)}),xX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:EI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function TX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new wX(t,n,e,r);return e.views.set(t,a),a}function EX(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 DX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),OX=(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 kX(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 AX(e,t,n,r,i){switch(t){case`palette`:return Lb(n,r,i).name;case`style`:return Jg(n,e.styles).name;case`effect`:return i_(n).name}}var jX=class{where=MX(fh({palette:dh,region:wg}));ground=MX(fh({colours:PX,bodyOpen:dh}));opened=MX(fh({colours:PX,open:dh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ck(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?SX(tJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>$J(r,()=>nJ(a,i))),this.open=d===void 0?SX(eJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>$J(r,()=>nJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return LX(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 RX(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?SX(BX):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return zX(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}),HX(n,r,this.affixes.read())}};function MX(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 NX=(e,t)=>e.hex===t.hex,PX=fh({palette:dh,drawnAt:dh,tint:NX,text:NX,bg:NX,disclosure:Dg});function FX(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const IX=e=>ug(e.palette,e.disclosure,e.drawnAt);function LX(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Ng(n,r,i)};return QJ(e,FX(t,c),e=>{let t=Wj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function RX(e,t,n,r,i,a){return QJ(e,FX(t,n),e=>(e.bg=i?IX(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function zX(e,t,n,r,i,a,o){return QJ(e,FX(t,n),e=>(e.bg=r?IX(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const BX={lead:[],trail:[],drops:[]};function VX(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return FJ(t,IX(e).state,n)},get band(){return FJ(t,IX(e).plane,n)},get close(){return RJ(t,IX(e).state,n)},disclosure:r}}function HX(e,t,n){return{styles:VX(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?IX(e).shortfalls:[]}}function UX(e,t,n,r,i,a,o){let s=LX(e,t,n,r,i,void 0,void 0,o);return HX(s,RX(e,t,s,a,!1,o),BX)}function WX(e,t,n,r,i){return VX(LX(e,t,n,r,i,void 0,void 0,{}))}function GX(e,t){return{payload:()=>e,selections:()=>t}}function KX(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Ik(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 qX(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 JX(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:KX(n.cache),parse:qX(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:KX(n.cache),parse:qX(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 YX(e,t){let n=US.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 XX(e,t,n){let{compiled:r,loadWarnings:i}=QX(e,t,n.cwd,ZX(n.signer),nZ);return{...r,loadWarnings:i}}const ZX=e=>(t,n)=>rZ(n,e);function QX(e,t,n,r,i=nZ){let a=$X(e),o=eZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:tZ(e,t,n,i)}}function $X(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:[...uB(e)].sort(([e],[t])=>e<t?-1:1)}}function eZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function tZ(e,t,n,r){let i=UY(e),a=uB(e),o=[];for(let[s,c]of Bx(e))if(r.has(i.get(s)))try{JX(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const nZ=new Set([`directory`,`view`]);function rZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>gJ(i,`drawnAt`).registry.drawnAt(),o=XJ(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=$b(e.presets),u=hI(e),d=[e=>bY(i,o,e.now)],f=bk({extraFuncs:{...NJ(i),...yY(i),...dY(i,o),...hY(i,o),...TY(i,o),...jY(i,o),...FY(s),...RY(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=YX(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=bJ(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(gJ(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 mX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=nx(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 fB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:oZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:nB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:_k(d)},re=hB(ne),ie=[...S.values()].flatMap(aZ(y)).some(e=>re(m.get(e))),ae=ie?hB({...ne,clock:new Set([...ne.clock,AY])}):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 iZ(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 aZ=e=>t=>{let n=[];return $Y(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 oZ(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 sZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function cZ(e,t,n,r,i){let a=lZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function lZ(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 uZ(e){return dZ(e).filter(e=>!e.name.startsWith(_A)).map(e=>e.id)}function dZ(e){return e.kind===`container`?e.children.flatMap(dZ):[e,...e.opens===void 0?[]:dZ(e.opens.body)]}function fZ(e,t,n,r,i,a,o,s,c=LH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return TX(t,n,r,GX(l,c)),mZ(e,t,n,r,l,a,o,s,c)}function pZ(...e){return fZ(...e).text}function mZ(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(ck(a,g.anim));let _=EX(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(yJ(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,YY),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=AX(t,e,cZ(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:Lb(C(`palette`),``,sZ),ce=oe.kind===`decided`?oe:Jg(C(`style`),e.styles),le=se.kind===`decided`?se:i_(C(`effect`)),ue=T.value,de=Pb(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:YY,hold:XY},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:JY(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${uZ(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(UX(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=>PJ(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)=>WX(t.activeSegment,e,n,a,r.drawnAt())};return mX(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 "${Zb}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=KY(ye(be,tJ,Ag(x))).map(({line:e,row:t})=>{let n=fJ(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||dZ(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*hZ(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*gZ(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 $b(e.presets)){for(let n of E_(nx(e,t).node))n.when!==void 0&&(yield n.when);let n=rx(e,t);for(let e of Ug){let t=n[e];Wg(t)&&(yield t)}}for(let[,t]of hZ(e))for(let[,e]of P_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of mx(t))yield e}function _Z(e,t){let n=oB(t),r=new Set,i=new Set,a=new Set;for(let e of gZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Mx(e,t.helpers))i.add(n);for(let n of Lx(e,t.helpers))a.add(n)}for(let[,e]of hZ(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 $b(t.presets))for(let n of E_(nx(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=>!yA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(hZ(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 vZ=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 yZ(e){return Math.floor(Math.max(e/4,e*or-67108864))}const bZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function xZ(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=tV(e),r=t===void 0?void 0:n.variables[rV(t)];return r?.kind===`file`?r.path:`none`},u=a.flatMap(e=>{let t=tV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>lV(e)(t)&&t!==rV(e))),d=u.filter(([,e])=>e.kind===`source`).length,f=u.length-d;return`config load ${e.join(` < `)||`<default>`}: projections=${[...uB(n).keys()].join(`,`)||`-`} instantSegments=${iZ(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 SZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function CZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function wZ(e,t){return new Set($b(e.presets).filter(n=>nx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function TZ(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...WV(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}=Gx(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}=Gx(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 EZ(e){return e.filter(Boolean).join(`
|
|
200
|
+
`)||null}function DZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=aH(t.layers,OH,{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??OH,l=a.find(e=>e.path===t.home)?.raw??{},u=new mS,d=new eA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=QX(o,d,e,r.compile??ZX(r.signer),jZ),n.push(...f.loadWarnings);let t=d.view();n.push(...tZ(o,t,e,MZ)),t.dispose(),yU(o),YI(o),p=OZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Cq(o),authoredRoots:wZ(c,l),fileHeldSettings:aU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>_Z(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 OZ(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 kZ(e,t,n,r){let i=KV(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[ZV(e,t),YV(i)],s,c=null;try{s=DZ(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:EZ(o),state:null,error:e instanceof Z_||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:EZ(o),state:s,error:null}}function AZ(e,t,n){return DZ(e,{layers:[],home:``,projectDir:t},[],n)}const jZ=new Set([`directory`]),MZ=new Set([`view`]);function NZ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new vZ;tZ(e.config,l,t,MZ);let d=()=>IH(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)}`),Pq(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()});TX(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 PZ=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)??rZ(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=CZ(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`,xZ(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??AZ(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(CZ(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=NZ(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 kZ(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`,SZ(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`,xZ(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=TZ(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 FZ=16384;var IZ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<FZ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%FZ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function LZ(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 RZ={load:()=>({}),save:()=>{},flush:()=>{}};var zZ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=RZ,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 BZ(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 VZ=class{timer=null;pending=null;writing=!1;generation=0;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return BZ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=`${this.filePath}.writing`;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}if(t!==this.generation){await p.promises.rm(i,{force:!0});return}let c=performance.now();p.renameSync(i,this.filePath),this.saved(r,e,n,a+performance.now()-c),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.generation++,this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.renameSync(n,this.filePath),this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const HZ=new Set([`1`,`true`]),UZ=new Set([`0`,`false`,``]);function WZ(e,t){let n=hQ(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(HZ.has(t))return`true`;if(UZ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function GZ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function KZ(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 qZ(e){return/^\s*$/.test(e)?null:Ui(e)}function JZ(e,t){return e!==null&&Gi(e,t)!==void 0}function YZ(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(YZ),...i}}return e}function XZ(e){if(!Ub(e))return YZ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,YZ(t)])),...n}}const ZZ=EH,QZ=ZZ.segments,$Z=ZZ.presets,eQ=ZZ.root;function tQ(e,t,n,r){if(!JZ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function nQ(e,t){let n=vj(t);return t.scope===`segment-palette`&&tQ(e,[`segments`,t.segment],QZ[t.segment],n.join(`.`)),n}function rQ(e){return Ui($i(e))}function iQ(){return Object.entries(eQ.rows).map(([e,t])=>{let n=YZ(t);return{path:[`root`],fragment:rQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function aQ(e,t){let n=e===null?void 0:Gi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function oQ(e,t){if(t===void 0)return null;let n=XZ(t);return{path:e,fragment:rQ(n),unit:{path:e,value:n}}}function sQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=$Z[t];tQ(e,n,i,r.join(`.`));let a=aQ(e,r)??oQ(r,i?.root);return a!==null&&ba(a.fragment)?a:null}function cQ(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 lQ(e,t){return[...iQ(),aQ(e,[`root`]),sQ(e,t)].filter(e=>e!==null).reduce(cQ,new Map)}function uQ(e,t,n){for(let{node:r,...i}of lQ(e,t).values())if(Sa(r,n))return i;throw new q(`${dQ(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 dQ(e,t){return sQ(e,t)?.path??[`root`]}function fQ(e,t){return t.scope===`preset-root`?dQ(e,t.preset):vj(t)}function pQ(e,{unit:t}){return t===null?e:pa(e,t.path,$i(t.value),Zi)}function mQ(e){let t=_j(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function hQ(e){let t=mQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function gQ(e,t,n,r,i){i(t,n,DQ(t,r)),KZ(t.path,r,e.logger),e.record(t.path,n,r)}function _Q(e,t,n){let r=bQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const vQ=()=>{};function yQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function bQ(e,t,n){let r=xQ(e,t);if(r===null)return[];let i=new Set(TQ(wQ(r),wQ(n)));return TQ(CQ(e,r),CQ(e,n)).filter(e=>!i.has(e))}function xQ(e,t){try{return SQ(e,t)}catch(e){if(e instanceof Z_)return null;throw e}}function SQ(e,t){return aH(t===null?e.above:[e.path,...e.above],OH,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function CQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function wQ(e){return e.layers.at(-1)?.config??e.base}function TQ(e,t,n=``){return!EQ(e)||!EQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>TQ(e[r],t[r],n===``?r:`${n}.${r}`))}function EQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function DQ(e,t){try{return SQ(e,t)}catch(e){throw e instanceof Z_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function OQ(e,t){let n=hQ(t),r=qZ(GZ(e)??``),i=r===null?void 0:Gi(r,vj(n));return i!==void 0&&`value`in i?i.value:void 0}function kQ(e,t,n){AQ(e,t,n,[])}function AQ(e,t,n,r){let i=GZ(t.path),a=n.reduce((e,[t,n])=>pa(e,nQ(qZ(e),hQ(t)),WZ(t,n),Zi),i??``);gQ(e,t,i,yQ(t,()=>jQ(a,t.path,r,e=>e)),_Q)}function jQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=uQ(qZ(s),n,i),l=Ea(pQ(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 MQ(e,t,n){let r=qZ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of lQ(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(sQ(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 NQ(e,t){return ha(e,t,t[0]===`presets`&&t.length>2&&!AH(t[1])?2:0)}function PQ(e,t,n){let r=n.map(mQ),i=GZ(t.path);if(i===null)return;let a=r.reduce((e,t)=>NQ(e,fQ(qZ(e),t)),i);a!==i&&gQ(e,t,i,a,vQ)}function FQ(e){let t=e===null?void 0:Gi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function IQ(e,t){let n=new Set([...kH,...FQ(e),...t.above.flatMap(e=>Object.keys(Ii.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(pA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(pA(e)))}function LQ(e,t,n,r,i,a){let o=GZ(t.path),s=qZ(o??``),c=IQ(s,t),l=[`presets`,c],u=yQ(t,()=>sQ(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=gj(c,e);return[nQ(s,hQ(n)),WZ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>pa(e,t,n,Zi),pa(o??``,l,`{}`,Zi));return gQ(e,t,o,yQ(t,()=>jQ(p,t.path,a.map(e=>({...e,preset:c})),MQ)),_Q),c}function RQ(e,t,n,r){let i=GZ(t.path);gQ(e,t,i,pa(i??``,[`themeDefaults`,n],$i(r),Zi),_Q)}function zQ(e,t,n){if(AH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=GZ(t.path),a=qZ(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`]);gQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>NQ(e,t),i),vQ)}function BQ(e,t,n,r){let i=mQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=GZ(t.path),o=r.op===`remove`?r.target:r.anchor,s=yQ(t,()=>uQ(qZ(a??``),i.preset,o)),c=pQ(a??``,s),{after:l,placed:u}=VQ(c,s.path,r,()=>{let e=DQ(t,c).config;return $b(e.presets).map(t=>nx(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 gQ(e,t,a,l,_Q),u}function VQ(e,t,n,r){switch(n.op){case`remove`:return{after:wa(e,t,n.target),placed:null};case`insert`:{let i=II(n.segment,n.anchor,r());return{after:Ta(e,t,i,n.anchor,n.relation),placed:i}}}}const HQ={load:()=>({}),save:()=>{}},UQ=new Set(wy.map(e=>e.sessionKey)),WQ=e=>UQ.has(e)||e.startsWith(Aj),GQ=8*1024*1024,KQ={past:[],future:[]},qQ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var JQ=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=HQ){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)??KQ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??KQ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(qQ(n));r.set(qQ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:LZ(this.sessionState,e=>WQ(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:n$(i,n),o=r.get(e),s=o===void 0?a:o$(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`,i$(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(qQ)),a=n.net.filter(e=>!i.has(qQ(e))),o=ZQ(s$(a$(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(l$).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=ZQ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...$Q(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(qQ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:s$(n,t),future:s$(i,t),...a!==void 0&&{savepoint:{at:s$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(qQ(e))),below:s$(a.below,t)}}}),new q(`${r}: ${o.map(l$).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):GZ(t.file)}write(e,t,n){t.kind===`file`?KZ(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||YQ(n)>GQ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,XQ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${GQ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function YQ(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 XQ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...$Q(n,1,[])}:{past:e,future:t.slice(1),...$Q(n,0,[])}}function ZQ(e){return e.slice(-50)}const QQ=e=>e===Mj.member;function $Q(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:e$(e.net,n),below:e.below}}}function e$(e,t){let n=new Map(e.map(e=>[qQ(e),e]));for(let e of t){let t=n.get(qQ(e));n.set(qQ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const t$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function n$(e,t){let n=[...e.past,t],r=ZQ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...$Q(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...r$(e.future,a),...i.below]},n.length-r.length,t)}}function r$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function i$(e,t){return{past:e.past.slice(0,-1),future:ZQ([...e.future,t]),...$Q(e.savepoint,0,t$(t))}}function a$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...r$(r,t.at-i.length),...t.below]}function o$(e,t){if(QQ(t.after)&&!QQ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!QQ(t.after)&&QQ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function s$(e,t){return e.map(e=>e.filter(e=>!t.has(qQ(e)))).filter(e=>e.length>0)}function c$(e){return e.map(l$).join(`, `)}function l$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function u$(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 d$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(u$))}function f$(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(u$)&&d$(t.below)}function p$(e){if(typeof e!=`object`||!e)return!1;let t=e;return d$(t.past)&&d$(t.future)&&(t.savepoint===void 0||f$(t.savepoint))}function m$(e,t){let n=e=>e.kind===`file`||WQ(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 h$(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(p$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,m$(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 g$=e=>!WQ(e)&&!aP(e)&&e!==`update.dismissed`;var _$=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:LZ(e,g$,(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 v$={inside:()=>[],defaultOf:()=>yi,menus:[]},y$=e=>`${e.key}\0${e.member}`;function b$(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?[]:ZR(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(y$(e))??new Map;n.set(y$(t),t),o.set(y$(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(y$(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 $b(e.presets))d(nx(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(y$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(y$(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(y$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const x$=new WeakMap;function S$(e){let t=x$.get(e);if(t!==void 0)return t;let n=b$(e);return x$.set(e,n),n}function C$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function w$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function T$(e,t,n){let r=(r,i,a)=>{let o=C$(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 E$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function D$(e,t){let n={...e};for(let e of E$)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 O$(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 k$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function A$(e){let t=e=>({kind:`failed`,reason:e});if(!k$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!k$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!KM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${KM.join(` or `)}`)}return{kind:`ok`,value:e}}function j$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const M$=e=>O$(e,`doctor-marks.json`,{},A$),N$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},P$=(e,t)=>e.includes(t)?e:[...e,t],F$=e=>O$(e,`doctor-clicked-terminals.json`,[],N$);var I$=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const L$=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},R$=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),z$=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=R$(e,t);return r===void 0?n:r.projectDir},B$=(e,t)=>R$(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function V$(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*H$(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 U$={pullRequests:e=>Tq(e).showPullRequest===!0,rateLimits:e=>wq(e,`block`)||wq(e,`weekly`)};function W$(e,t){let n=new Map;for(let r of E_(nx(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,xq(e,t,n.get(t))])),a=e=>r.filter(t=>U$[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 G$(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function K$(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]=G$(t.toml,t.ptr),i=K$(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 W$(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 q$(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 K$(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 J$=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var Y$=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(J$);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 q$=/^(\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 X$(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function Z$(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function Q$(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?l1(e):c1(e);return e.d++,t}return r===34||r===39?q$(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?$$(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?n1(e,r,t):e.s.charCodeAt(e.p+2)===58?r1(e,r,t):$$(e,e.p,r,0,t)}function $$(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||Z$(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return e1(e,t,16,i);if(a===98)return e1(e,t,2,i);if(a===111)return e1(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else X$(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!Z$(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:X$(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):t1(e,c,10,t)}function e1(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!Z$(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):X$(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(`_`,``)),t1(e,o,n,t)}function t1(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 n1(e,t,n){let r=e.p++,i;if(!X$(t)||!X$(e.s.charCodeAt(e.p++))||!X$(e.s.charCodeAt(e.p++))||!X$(e.s.charCodeAt(e.p++)))return $$(e,e.p=r,t,0,n);if(e.p+=5,X$(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,!X$(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return i1(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(;X$(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return i1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return i1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return i1(e,e.s.slice(r,e.p),2,i,r)}function r1(e,t,n){let r=e.p;if(!X$(t)||!X$(e.s.charCodeAt(++e.p)))return $$(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;X$(e.s.charCodeAt(++e.p)););return i1(e,e.s.slice(r,e.p),4,!1,r)}function i1(e,t,n,r,i,a){if(e.ld){let a=new Y$(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 Y$(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 a1(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 o1(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;a1(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 i1(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 s1(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(q$(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 c1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(o1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=s1(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),o1(e,!0,!0);let l=Q$(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),o1(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 l1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(o1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(Q$(e,93)),o1(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 o1(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 u1(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 d1(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 f1(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++,o1(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=s1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=u1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(d1(n,u,a),o=!0)}else{a=n.p;let e=u1(n,s1(n),s,c,0);!e&&!o&&d1(n,e,a),o1(n,!0,!0);let t=Q$(n,void 0);e&&!o&&(e[1][e[0]]=t)}o1(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),o1(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 l1(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 p1=e=>e.codePointAt(0).toString(16).toUpperCase(),m1=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 h1(e){let t=D({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,m1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new I$(`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 g1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),_1=e=>[...e].map(p1).join(`,`);function v1(e,t){let n=h1([`font`,e.kind,e.name,_1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:g1(r)}}}function y1(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=>!kM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const b1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function x1(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=>y1(e,n));if(t!==null)return r[0];let i=r.find(e=>!b1(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 S1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=h1([`iterm`,r??``,_1(n)]);return i.kind===`failed`?i:x1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:g1(e.lacks)})),r,e)}function C1(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 w1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function T1(e,t){let n=D({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
477
|
+
`,`:family=${w1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new I$(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return C1(n.stdout,t)}function E1(e,t){return process.platform===`darwin`?v1(e,t):T1(e.name,t)}function D1(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 O1(e){return e===`darwin`?`Menlo`:`monospace`}const k1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function A1(e){let t=k1(e.font)?e.font:{},n=k1(t.normal)?t.normal:{},r=(k1(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 j1(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=f1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=A1(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=j1(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function M1(e,t){let n=C.homedir(),r=D1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:j1(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??O1(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=E1({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 N1={iterm2:S1,alacritty:(e,t,n)=>M1(t,n)};function P1(e,t,n){return N1[e.name](e.version,t,n)}function F1(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 I1=e=>O$(e,`doctor-post-mortems-read.json`,{through:null},F1);function L1(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const R1={realpath:e=>L1(()=>p.realpathSync(e)),checkoutOf:Qe,digest:e=>L1(()=>Ye(e)),nativeShipped:vo(process.platform,process.arch)};function z1(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 B1=e=>({marks:M$(e),clicked:F$(e),postMortemsRead:I1(e)}),V1=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function H1(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 U1=/^(sshd|mosh-server)\b/;function W1(e,t){let n=V$(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of H$(n,t))if(U1.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function G1(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 I$(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return W1(t.stdout,e)}const K1=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function q1(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 J1(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=K1.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function Y1(){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:q1(e.stdout,J1)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function X1(e){let t=FK(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 I$(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:H1(t.stdout)}function Z1(e){return{probeTmux:X1,remoteLogin:G1,fontInUse:P1,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??no(process.platform),install:R1,daemons:Y1,forge:n0,transcript:$1}}function Q1(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=VG(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function $1(e){let t=Ka(e,qM+1);return t.kind===`ok`?P(Q1(t.value.buf,t.value.fromStart)):t}function e0(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 t0={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function n0(e){if(BV(e)===void 0)return{kind:`ok`,value:null};let t=PW(D({bin:`git`,args:[...NW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=zW(t.value);if(n===null)return{kind:`ok`,value:null};let r=MW(n);if(r===null)return{kind:`ok`,value:null};let i=DW[r],a=t0[r],o=a.loginHost(jW(n)),s=D({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return r0(i,o,a.nonZero,s)}function r0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):OW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:wW(r.stderr)}):{kind:`failed`,reason:CW(e,r)}}function i0(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 a0=e=>L1(()=>io(e));function o0(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:a0(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 s0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function c0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:IM(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:FM(t),tmuxClient:t}}}}function l0(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(TM(s))return{kind:`bundling`,name:s,version:c};if(!EM(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 u0(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 d0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function f0(e,t,n,r){return{pullRequests:d0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:d0(t.rateLimits,()=>r)}}function p0(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 m0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=LH(d.config,r,()=>!1),p=s0(e,t.tmux),m=c0(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:l0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:i0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:f0(e,W$(d.config,f.preset),n,a),transcripts:e0(e,o),claudeSettings:o0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Xa(Ya(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function h0(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:a0(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 g0={connectMs:200,budgetMs:500};async function _0(e){let n=e.includes(`--json`),r=await v0();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=y0(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(D0(r.value))}function v0(){return rn(()=>({kind:`stats`}),g0,e=>`stats`in e?e.stats:void 0)}function y0(e,t=b0){let n=IZ.referenceSnapshot(),r=x0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=C0(e.version,e.sourceDigest??null),a=C0(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 b0=Object.keys(IZ.referenceSnapshot());function x0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!S0(e))return[];if(!S0(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(...x0(e[i],t[i],a)):r.push(a)}return r}function S0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function C0(e,t){return`${e} [${t===null?`no digest`:Xe(t)}]`}function w0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function T0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function E0(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 D0(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${C0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${E0(e.uptimeSec)}`),t.push(` rss ${w0(e.rssBytes)}`),t.push(` heapUsed ${w0(e.heapUsedBytes)}`),t.push(` heapTotal ${w0(e.heapTotalBytes)}`),t.push(` external ${w0(e.externalBytes)}`),t.push(` arrayBuffers ${w0(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(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${T0(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 ${T0(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 ${w0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${w0(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 ${w0(e.renderCache.accountedBytes)} / ${w0(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 Q0(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 $0(e,t){let n=X0(e,`claude-input.type`,Q0(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 e2(){return{read:Z0,type:$0}}function t2(e){let t=pW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function n2(e){return kb(()=>decodeURIComponent(e))}function r2(e,t,n){let r=D(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function i2(e,t){r2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const a2=(e,t)=>i2(n2(e),t),o2=(e,t)=>r2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,n2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),s2=(e,t)=>i2(n2(e),t),c2=(e,t)=>i2(n2(e),t),l2=(e,t)=>{let n=t2(n2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},u2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=t2(n),a=vU(T2(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})}m2(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})`)},d2=/^-?\d+$/;function f2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const p2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=t2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!d2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=T2(t,a),c=vU(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&&d2.test(u)?h2(l,parseInt(u,10)):g2(`step-state`,r,l,xU(s,e=>t.sessionState.get(a,e),r)),f=f2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);m2(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 m2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Aj));if(i.length===0)return;let a=ZH(T2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function h2(e,t){return Math.max(e.min,Math.min(e.max,t))}function g2(e,t,n,r){if(r===null)return n.min;if(!d2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return h2(n,parseInt(r,10))}const _2=`render-origin`;function v2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function y2(e){return JSON.stringify(e)}function b2(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 x2(e,t){let n=C2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function S2(e,t){let n=e.sessionState.get(t,_2);return n===null?null:b2(n)}function C2(e,t){let n=S2(e,t);return n===null?null:v2(n,e.sessionState,t)}function w2(e,t,n){let r=C2(e,t);if(r===null)return;let{path:i}=O2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function T2(e,t){return e.configFor(x2(e,t))}function E2(e,t){let n=S2(e,t);if(n===null)return null;let r=()=>e.lanes.of(v2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function D2(e,t){let n=C2(e,t);return n===null?_$:x$(e.configFor(n))}function O2(e){return qV(e.projectDir,e.cwd,e.configFile??void 0)}function k2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const A2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=t2(n),o=x2(t,a),s=t.configFor(o),c=JI(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=O2(o),d=YH(s,e=>t.sessionState.get(a,e),r);OQ(k2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},j2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=t2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!d2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=x2(t,a),c=t.configFor(s),l=JI(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=O2(s),f=YH(c,e=>t.sessionState.get(a,e),r),p=DQ(d.path,f.key),m=typeof p==`number`?h2(u,p):g2(`step-config`,r,u,XI(f.globals,r)),h=f2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);OQ(k2(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})`)},M2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=t2(n),i=x2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=qH(a,o),c=XH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=vU(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]});P2(`save`,l,c);let d=O2(i);kQ(k2(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(N2)].join(` `)} → ${d.path} (session=${r})`)},N2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function P2(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 F2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=t2(n),i=x2(t,r),a=t.configFor(i),o=eU(a,e=>t.sessionState.get(r,e)),s=vU(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]});P2(`save-preset`,s,o.placements);let l=O2(i),u=IQ(k2(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(N2)].join(` `)} → ${l.path} (session=${r})`)},I2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=t2(n),i=x2(t,r),a=nU(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=O2(i);LQ(k2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(qH(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})`)},L2=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=t2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=x2(t,i),o=O2(a);RQ(k2(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})`)},R2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=t2(n),a=x2(t,i),o=JI(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=O2(a),l=r.map(rU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);NQ(k2(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 z2(e,t){let n=(e,t)=>[...E_(nx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set($b(t.presets).flatMap(e=>n(t,e).map(t=>jj(pA(e),S_(t)))));return $b(e.presets).flatMap(t=>n(e,t).map(e=>({member:jj(pA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function B2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Dj]:[]])}const V2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=t2(n),o=x2(t,a),s=t.configFor(o),c=JI(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=PI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=O2(o),f=zQ(k2(t,a),d,r,u);t.reloadConfig(o);let p=B2(z2(s,t.configFor(o)),t.sessionState.get(a,Dj)).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})`)},H2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=t2(n);t.journal.commit();let i=t.history.undo(r);w2(t,r,i),t.dlog(`info`,`undo: restored ${s$(i)} (session=${r})`)},U2=(e,t)=>{let n=t2(n2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,vU(T2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},W2=(e,t)=>{let n=t2(n2(e));t.journal.commit();let r=t.history.rewind(n);w2(t,n,r),t.dlog(`info`,`rewind: put back ${s$(r)||`nothing`} as edit mode found it (session=${n})`)},G2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=t2(n);t.journal.commit();let i=t.history.redo(r);w2(t,r,i),t.dlog(`info`,`redo: re-applied ${s$(i)} (session=${r})`)},K2=(e,t)=>{t2(n2(e)),t.applyUpdate()},q2=`client-hints`;function J2(e,t){let n=e.sessionState.get(t,q2);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 Y2(e,t,n){let r=LN(n);e.sessionState.setBatch(t,$N(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${ZN(n.nerdFont,n.marks)} ${VN(n.terminal,n.clicked)} ${HN(n.terminal,n.width)} ${UN(n.install)} ${GN(n.daemon)} ${KN(n.data)} ${XN(n.transcripts)} ${qN(n.frames,n.claudeSettings)} ${YN(n.claudeSettings.origin.sources)} (session=${t})`)}function X2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ak(new Date)),i;try{i=p0(e.doctor,J2(e,t),x2(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:z$(n,r)},f0(t,r),B1(e.doctorStores))}catch(e){throw e instanceof F$?new q(e.message):e}return{...i,urlHandler:l0(e.arrival),install:R1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:Z2(e,i)}}function Z2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?LM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>N$(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 Q2=(e,t)=>{let n=t2(n2(e));Y2(t,n,X2(t,n))},$2=(e,t)=>{let n=j0(n2(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`}`)},e4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=t2(n),a=RN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=X2(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=m0(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} → ${YM(s.fix)} (session=${i})`),Y2(t,i,c.value)},t4=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=t2(n),o=RN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!KM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${KM.join(` or `)}`);let s=X2(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=>A$(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})`),Y2(t,a,{...s,marks:u})},n4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=t2(n),a=Object.values(t.configFor(x2(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=Y0(t.claudeInput,J2(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 r4([e=``,t=``,n=``,r=``],i){let a=t2(e),o=x2(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=px(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:{...E$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:J2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const i4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=kb(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=r4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},a4=`config-override`,o4=new Map([[Br,a2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=t2(kb(()=>decodeURIComponent(e.slice(0,n)))),i=kb(()=>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,a4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,a4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,o2],[Rr,u2],[zr,p2],[Kr,A2],[qr,j2],[Qr,R2],[Jr,M2],[Yr,F2],[Xr,I2],[Zr,L2],[$r,V2],[ei,H2],[ti,G2],[ni,U2],[ri,W2],[Ur,s2],[Wr,c2],[Hr,l2],[ii,K2],[ai,Q2],[oi,e4],[si,t4],[ci,$2],[li,n4],[`run`,i4]]),s4=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 c4(e,t){return l4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function l4(e){let t=e.find(e=>s4.has(e.verb)),n=t===void 0?``:kb(()=>fi(t.value));return n===``?null:pW(n)}const u4=(e,t)=>{let n=[],r=!1,i=mi(e),a=l4(i);for(let{verb:e,value:a}of gi(i)){let i=o4.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?.ok&&$o(t.sessionState,a.id,n.join(`
|
|
488
|
-
`),ak(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function d4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:E2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>w$(e,e=>D2(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=C2(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 f4=new Map([...o4,[Lr,u4]].map(([e,t])=>[e,d4(t,t=>{let n=c4(e,t);return n?.ok?n.id:null})]));Object.freeze([...f4.keys()]);function p4(e,t,n){d4((n,r)=>{let i=C$(D2(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 m4=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`]),h4=[[`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`]],g4=[[`workspace.added_dirs`,`string-list`]];function _4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of h4){let i=b4(n,e);if(i==null)t.missingRequired.push(e);else{let n=v4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of g4){let i=b4(n,e),a=i===void 0?r:y4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))m4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function v4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function y4(e){return Array.isArray(e)&&e.every(e=>v4(e)===`string`)?`string-list`:v4(e)}function b4(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 x4(e,t){switch(e){case`vars`:return{what:e,vars:S4(t)};case`segments`:return{what:e,segments:D4(t)};case`config`:return{what:e,config:j4(t)}}}function S4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=T4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=C4(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:w4(r.lastUpdatedMs())})}return o}function C4(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 w4(e){return e===null?null:Math.max(0,Date.now()-e)}function T4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,E4(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}`,E4(i));return t}function E4(e){return e.kind}function D4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=k4(n),o=O4(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:A4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function O4(e){let t=new Map;for(let n of $b(e.presets))for(let r of E_(nx(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 k4(e){let t=[],n=new Set;for(let r of E_(Kb(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 A4(e,t,n){let r=new Set([...Ox(e,t).keys()].flatMap(e=>Vx(e,n)));return Array.from(r).sort()}function j4(e){return e===null?null:e.config}const M4=[`vars`,`segments`,`config`];function N4(e){return typeof e==`string`&&M4.includes(e)}function P4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>IH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Uq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...aU(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 F4={moving:1e3/30,still:1e3},I4=[`data`,`state`,`reload`,`visibility`];function L4(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 R4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const z4=e=>({resp:e,bytes:JSON.stringify(e)}),B4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,V4=e=>Math.round(1e3/e);var H4=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:V4(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=V4(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:z4(t.resp),statusline:z4(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||B4(i,n).bytes!==B4(r,n).bytes)&&R4(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}=B4(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:aM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=jk.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(i)}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 achieved=${a} evaluated=${e.evaluated} woke=${I4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function U4(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 W4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,G4=`#{session_id} #{client_control_mode} #{pane_id}`;function K4(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 O0=e=>({kind:`ok`,value:e}),k0=e=>({kind:`failed`,reason:e});var A0=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const j0=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function M0(e){return j0.test(e)?e:null}function N0(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return O0(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return O0({app:n,missing:k0(`its script could not be read (${r.reason})`)});let i=ko(r.value);return O0({app:n,missing:i===null?k0("its script is not one `cc-candybar install` wrote"):O0([i.node,i.script].filter(t=>!e.exists(t)))})}async function P0(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 F0(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 P0(e,n):null)??{kind:`lost`,unopened:r,opener:N0(e)}}function I0(e,t,n){let r=D({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?O0(r.stdout):k0(r.stderr.trim()||r.error||r.reason)}const L0=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ir}://probe"));u.isNil() ? "" : u.path.js`;async function R0(){let e=await v0();if(e.kind!==`ok`)return k0(un(e).split(`
|
|
486
|
+
`).join(` — `));let t=y0(e.value,[`handlerProbes`]);if(t!==null)return k0(t);let{version:n,handlerProbes:r}=e.value;return O0({version:n,arrivals:r})}function z0(){return{platform:process.platform,sockets:{own:St(),handler:Ct()},now:Date.now,nonce:ie,daemon:R0,open:e=>{let t=I0(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=I0(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,L0]);if(e.kind===`failed`)return e;let t=e.value.trim();return O0(t===``?null:t)},script:e=>I0(`doctor.osadecompile`,`/usr/bin/osadecompile`,[Ao(e)]),exists:p.existsSync}}const B0=/^─{20,}/,V0=/^❯(\s|$)/,H0=/›\s*stashed$/;function U0(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>B0.test(e)?[t]:[]).at(-2);return n===void 0||!V0.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function W0(e){if(e.inMode)return{kind:`in-mode`};let t=U0(e);return t===null?{kind:`no-prompt`}:H0.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function G0(e){return/^❯\s*\S/u.test(U0(e)?.prompt??``)}const K0=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function q0(e){return e.screen.some(e=>K0.test(e))}const J0={"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 Y0(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 X0(e,t,n){let r=Y0(t);if(r.kind===`refused`)return r;let i=r.hint,a=W0(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:J0[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function Z0(e,t,n,r){let i=FK(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function Q0(e){let t=Z0(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 $0(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 e2(e,t){let n=Z0(e,`claude-input.type`,$0(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 t2(){return{read:Q0,type:e2}}function n2(e){let t=mW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function r2(e){return kb(()=>decodeURIComponent(e))}function i2(e,t,n){let r=D(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function a2(e,t){i2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const o2=(e,t)=>a2(r2(e),t),s2=(e,t)=>i2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,r2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),c2=(e,t)=>a2(r2(e),t),l2=(e,t)=>a2(r2(e),t),u2=(e,t)=>{let n=n2(r2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},d2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=n2(n),a=yU(E2(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})}h2(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})`)},f2=/^-?\d+$/;function p2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const m2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!f2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=E2(t,a),c=yU(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&&f2.test(u)?g2(l,parseInt(u,10)):_2(`step-state`,r,l,SU(s,e=>t.sessionState.get(a,e),r)),f=p2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);h2(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 h2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Aj));if(i.length===0)return;let a=QH(E2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function g2(e,t){return Math.max(e.min,Math.min(e.max,t))}function _2(e,t,n,r){if(r===null)return n.min;if(!f2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return g2(n,parseInt(r,10))}const v2=`render-origin`;function y2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function b2(e){return JSON.stringify(e)}function x2(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 S2(e,t){let n=w2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function C2(e,t){let n=e.sessionState.get(t,v2);return n===null?null:x2(n)}function w2(e,t){let n=C2(e,t);return n===null?null:y2(n,e.sessionState,t)}function T2(e,t,n){let r=w2(e,t);if(r===null)return;let{path:i}=k2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function E2(e,t){return e.configFor(S2(e,t))}function D2(e,t){let n=C2(e,t);if(n===null)return null;let r=()=>e.lanes.of(y2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function O2(e,t){let n=w2(e,t);return n===null?v$:S$(e.configFor(n))}function k2(e){return JV(e.projectDir,e.cwd,e.configFile??void 0)}function A2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const j2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=S2(t,a),s=t.configFor(o),c=YI(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=k2(o),d=XH(s,e=>t.sessionState.get(a,e),r);kQ(A2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},M2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!f2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=S2(t,a),c=t.configFor(s),l=YI(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=k2(s),f=XH(c,e=>t.sessionState.get(a,e),r),p=OQ(d.path,f.key),m=typeof p==`number`?g2(u,p):_2(`step-config`,r,u,ZI(f.globals,r)),h=p2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);kQ(A2(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})`)},N2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=JH(a,o),c=ZH(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=yU(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]});F2(`save`,l,c);let d=k2(i);AQ(A2(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(P2)].join(` `)} → ${d.path} (session=${r})`)},P2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${G_(e.value)}`;function F2(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 I2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=t.configFor(i),o=tU(a,e=>t.sessionState.get(r,e)),s=yU(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]});F2(`save-preset`,s,o.placements);let l=k2(i),u=LQ(A2(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(P2)].join(` `)} → ${l.path} (session=${r})`)},L2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n),i=S2(t,r),a=rU(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=k2(i);RQ(A2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(JH(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})`)},R2=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=S2(t,i),o=k2(a);zQ(A2(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})`)},z2=(e,t)=>{let[n=``,...r]=kb(()=>di(e)),i=n2(n),a=S2(t,i),o=YI(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=k2(a),l=r.map(iU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);PQ(A2(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 B2(e,t){let n=(e,t)=>[...E_(nx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set($b(t.presets).flatMap(e=>n(t,e).map(t=>jj(pA(e),S_(t)))));return $b(e.presets).flatMap(t=>n(e,t).map(e=>({member:jj(pA(t),S_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function V2(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Dj]:[]])}const H2=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=S2(t,a),s=t.configFor(o),c=YI(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=FI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=k2(o),f=BQ(A2(t,a),d,r,u);t.reloadConfig(o);let p=V2(B2(s,t.configFor(o)),t.sessionState.get(a,Dj)).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})`)},U2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n);t.journal.commit();let i=t.history.undo(r);T2(t,r,i),t.dlog(`info`,`undo: restored ${c$(i)} (session=${r})`)},W2=(e,t)=>{let n=n2(r2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,yU(E2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},G2=(e,t)=>{let n=n2(r2(e));t.journal.commit();let r=t.history.rewind(n);T2(t,n,r),t.dlog(`info`,`rewind: put back ${c$(r)||`nothing`} as edit mode found it (session=${n})`)},K2=(e,t)=>{let[n=``]=kb(()=>di(e)),r=n2(n);t.journal.commit();let i=t.history.redo(r);T2(t,r,i),t.dlog(`info`,`redo: re-applied ${c$(i)} (session=${r})`)},q2=(e,t)=>{n2(r2(e)),t.applyUpdate()},J2=`client-hints`;function Y2(e,t){let n=e.sessionState.get(t,J2);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 X2(e,t,n){let r=LN(n);e.sessionState.setBatch(t,$N(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${ZN(n.nerdFont,n.marks)} ${VN(n.terminal,n.clicked)} ${HN(n.terminal,n.width)} ${UN(n.install)} ${GN(n.daemon)} ${KN(n.data)} ${XN(n.transcripts)} ${qN(n.frames,n.claudeSettings)} ${YN(n.claudeSettings.origin.sources)} (session=${t})`)}function Z2(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,ak(new Date)),i;try{i=m0(e.doctor,Y2(e,t),S2(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:B$(n,r)},p0(t,r),V1(e.doctorStores))}catch(e){throw e instanceof I$?new q(e.message):e}return{...i,urlHandler:u0(e.arrival),install:z1(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:Q2(e,i)}}function Q2(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?LM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>P$(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 $2=(e,t)=>{let n=n2(r2(e));X2(t,n,Z2(t,n))},e4=(e,t)=>{let n=M0(r2(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`}`)},t4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n),a=RN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=Z2(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=h0(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} → ${YM(s.fix)} (session=${i})`),X2(t,i,c.value)},n4=(e,t)=>{let[n=``,r=``,i=``]=kb(()=>di(e)),a=n2(n),o=RN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!KM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${KM.join(` or `)}`);let s=Z2(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=>j$(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})`),X2(t,a,{...s,marks:u})},r4=(e,t)=>{let[n=``,r=``]=kb(()=>di(e)),i=n2(n),a=Object.values(t.configFor(S2(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=X0(t.claudeInput,Y2(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 i4([e=``,t=``,n=``,r=``],i){let a=n2(e),o=S2(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=px(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:{...D$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:Y2(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const a4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=kb(()=>di(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=i4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},o4=`config-override`,s4=new Map([[Br,o2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=n2(kb(()=>decodeURIComponent(e.slice(0,n)))),i=kb(()=>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,o4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,o4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,s2],[Rr,d2],[zr,m2],[Kr,j2],[qr,M2],[Qr,z2],[Jr,N2],[Yr,I2],[Xr,L2],[Zr,R2],[$r,H2],[ei,U2],[ti,K2],[ni,W2],[ri,G2],[Ur,c2],[Wr,l2],[Hr,u2],[ii,q2],[ai,$2],[oi,t4],[si,n4],[ci,e4],[li,r4],[`run`,a4]]),c4=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 l4(e,t){return u4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function u4(e){let t=e.find(e=>c4.has(e.verb)),n=t===void 0?``:kb(()=>fi(t.value));return n===``?null:mW(n)}const d4=(e,t)=>{let n=[],r=!1,i=mi(e),a=u4(i);for(let{verb:e,value:a}of gi(i)){let i=s4.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?.ok&&$o(t.sessionState,a.id,n.join(`
|
|
488
|
+
`),ak(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function f4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:D2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>T$(e,e=>O2(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=w2(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 p4=new Map([...s4,[Lr,d4]].map(([e,t])=>[e,f4(t,t=>{let n=l4(e,t);return n?.ok?n.id:null})]));Object.freeze([...p4.keys()]);function m4(e,t,n){f4((n,r)=>{let i=w$(O2(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 h4=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`]),g4=[[`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`]],_4=[[`workspace.added_dirs`,`string-list`]];function v4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of g4){let i=x4(n,e);if(i==null)t.missingRequired.push(e);else{let n=y4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of _4){let i=x4(n,e),a=i===void 0?r:b4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))h4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function y4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function b4(e){return Array.isArray(e)&&e.every(e=>y4(e)===`string`)?`string-list`:y4(e)}function x4(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 S4(e,t){switch(e){case`vars`:return{what:e,vars:C4(t)};case`segments`:return{what:e,segments:O4(t)};case`config`:return{what:e,config:M4(t)}}}function C4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=E4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=w4(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:T4(r.lastUpdatedMs())})}return o}function w4(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 T4(e){return e===null?null:Math.max(0,Date.now()-e)}function E4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,D4(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}`,D4(i));return t}function D4(e){return e.kind}function O4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=A4(n),o=k4(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:j4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function k4(e){let t=new Map;for(let n of $b(e.presets))for(let r of E_(nx(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 A4(e){let t=[],n=new Set;for(let r of E_(Kb(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 j4(e,t,n){let r=new Set([...Ox(e,t).keys()].flatMap(e=>Vx(e,n)));return Array.from(r).sort()}function M4(e){return e===null?null:e.config}const N4=[`vars`,`segments`,`config`];function P4(e){return typeof e==`string`&&N4.includes(e)}function F4(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>LH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return Wq({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...oU(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 I4={moving:1e3/30,still:1e3},L4=[`data`,`state`,`reload`,`visibility`];function R4(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 z4(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const B4=e=>({resp:e,bytes:JSON.stringify(e)}),V4=(e,t)=>Pv[t].elsewhere===null?e.statusline:e.bar,H4=e=>Math.round(1e3/e);var U4=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:H4(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=H4(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:B4(t.resp),statusline:B4(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||V4(i,n).bytes!==V4(r,n).bytes)&&z4(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}=V4(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:aM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=jk.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(i)}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 achieved=${a} evaluated=${e.evaluated} woke=${L4.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function W4(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 G4=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,K4=`#{session_id} #{client_control_mode} #{pane_id}`;function q4(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 J4(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 Y4(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=x3(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,[g3(`@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)} ${$4} 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,b3(n));if(r===null||this.closed)return null;let i=S3(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,n3(r),e])}),i!==n.status){let e=a3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,Q4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,d3(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,C3(n));if(i===null)return;let a=w3(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,E3);if(r===null||this.closed)return;let i=D3(r[0]??``);if(n.kind===`none`&&A3(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`&&A3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...e3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${u3(`${this.deps.handler} ${k3(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,E3);if(r===null)return;let i=j3(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=j3(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,p3(t));return n.kind===`ok`?m3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,p3(t)));return n.kind===`ok`?m3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,l3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,l3(t),n)))}};function N3(e){try{return di(e)}catch(e){if(e instanceof URIError)return null;throw e}}const P3=`CC_CANDYBAR_CONFIG`;function F3(e,t){return YB(t,e[P3])}const $=e=>({arity:e,keep:!0}),I3=e=>({arity:e,keep:!1}),L3={"--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":I3(`none`),"--background":I3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":I3(`optional`),"-c":I3(`none`),"--continue":I3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":I3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":I3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":I3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":I3(`optional`),"-h":I3(`none`),"--help":I3(`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":I3(`none`),"--print":I3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":I3(`optional`),"--resume":I3(`optional`),"--safe-mode":$(`none`),"--session-id":I3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":I3(`optional`),"--tmux":I3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":I3(`none`),"--version":I3(`none`),"-w":I3(`optional`),"--worktree":I3(`optional`)},R3={resume:`--resume`,fresh:`--session-id`};function z3(e){return[R3[e.kind],e.sessionId]}const B3=e=>e.startsWith(`-`)&&e!==`-`;function V3(e,t){let n=W3(t);return n===null?{dir:e??t,args:[]}:e!==null&&H3(e,n.top)?{dir:e,args:[]}:{dir:e===null||W3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const H3=(e,t)=>e===t||e.startsWith(t+s.sep);function U3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!B3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=L3[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=>!B3(e)):o.arity===`variadic`?G3(n.slice(r),e=>!B3(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 W3(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 G3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const K3=`candybar-band@cc-candybar`,q3=s.join(`bin`,`cc-candybar-native`),J3=`@cc-candybar-bar-pane`,Y3=lP(`/reload-plugins`),X3=e=>({kind:`done`,said:e});function Z3(e){let t=J0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const Q3={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,q3);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 ${K3} from ${r}`,finished:$3(e,r,n)}},off:()=>X3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=Z3(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:n6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>X3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=Z3(e),i=n.barPanes(r);return i.length>0?X3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):X3(`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=J0(e.hints.tmux);if(r.kind===`refused`)return X3(`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 X3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>X3(`the daemon draws ${Z3(e).pane}'s bar in its status line`),off:()=>X3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function $3(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`,K3],r);let i=Y0(n.claudeInput,e.hints.tmux,Y3);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 ${K3} from ${t} and typed /reload-plugins into ${i.pane}`}const e6=new Set([qa,P3]);function t6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function n6(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=s6(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=r6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=U3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=t6(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])=>e6.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...z3(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=i6(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(V3(null,i.cwd),_))}let y=m(V3(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}\`, ${a6[g.kind](e.sessionId)}, and its statusline follows lane B`}function r6(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 i6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const a6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},o6={"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 s6(e){let t=U0(e);return t.kind===`ready`?K0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:W0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:o6[t.kind]}var c6=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=Q3[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 l6(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 u6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function d6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function f6(e,t,n){let r=l6(`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 p6=2e3;function m6(e,t,n){let r=PK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function h6(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 g6(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 _6=`#{pane_id} #{${J3}}`;function v6(e,t){return e.split(`
|
|
495
|
-
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const
|
|
496
|
-
`);async function S6(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=h6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,x6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function C6(e,t){return h6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function w6(e){let t=await FK(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 C6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function T6(e){let{panePid:t,cwd:n,foreground:r}=await w6(e),i=await C6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await S6(r),o=B$(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:b6(i,r,t)}}function E6(e){return{claudeInput:e2(),barPanes:e=>v6(m6(e,[`list-panes`,`-a`,`-F`,_6]),e.pane),openBarPane:(e,t,n)=>{let r=m6(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 m6(e,[`set-option`,`-p`,`-t`,r,J3,e.pane]),r},closePane:(e,t)=>void m6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void h6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:E$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:VV,paneClaude:T6,paneDir:async(e,t)=>{let n=Date.now()+p6;for(;;){let r=await w6(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 ${p6/1e3} s`);await be(100)}},launcherNode:e=>f6(e,e=>u6(e,p.constants.X_OK),d6),onPath:(e,t)=>{let n=l6(e,t,e=>u6(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`?g6(r.stdout):null;return i===null?(h6(`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 m6(e,Q0(e.pane,`cc-candybar-lane`,[]),t)}}function D6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function O6(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 k6={order:-1/0,text:null,failure:null};var A6=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)??k6;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)??k6;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}`}}},j6=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 M6(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 N6(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 P6(e,t){for(let n of Object.entries(t))e.push(n)}const F6={ok:`info`,"bad-request":`warn`,threw:`error`};function I6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function L6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...I6(n)];return{level:F6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const R6=new FZ,z6=new k0,B6=new SM,V6=i(import.meta.url),H6=z1(yt());dt(R6.launchStats);const U6=new QW({counters:R6,logger:M}),W6=new Mk(M),G6=oq({watchers:U6,logger:M,ledger:W6}),{gitProvider:K6,usageStore:q6,tmuxService:J6,hostService:Y6,managedStorage:X6}=G6,Z6=new RZ,Q6=new qQ(Z6,M),$6=new g$,e8=new eb,t8=new j6({now:()=>ak(new Date),close:(e,t)=>p4(e,t,H8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),n8=Yo(),r8=new ls({supersede:(e,t)=>X6.supersede(e,t),launch:pt,state:Z6,log:M,now:()=>ak(new Date)}),i8=[t.execPath,...t.execArgv],a8=new c6({edge:E6(e=>s8.following(e)),host:{bundle:V6,node:i8,socket:St(),preload:Do(V6)},state:Z6,log:M,now:()=>ak(new Date),defer:e=>void _e(e)}),o8=new M3({edge:{run:(e,t,n)=>FK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>PK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>s8.subscribe(e,t),sessionInPane:(e,t)=>s8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...i8,V6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),s8=new H4({render:(e,t)=>Z8(e,t),watch:(e,t)=>(0,J.reaction)(()=>Z6.revision(e),t),lanes:e=>$8(e),pin:e=>d8.pin(e),shown:e=>c8.shown(e.hints.tmux),watching:()=>c8.follow(),refreshes:()=>W6.totals(),periods:F4,now:()=>performance.now(),log:M}),c8=new Y4({listPanes:e=>FK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,W4]),listClients:e=>FK({socket:e},`frames.visibility`,[`list-clients`,`-F`,G4]),sockets:()=>new Set(s8.watched().flatMap(({req:e})=>l8(e))),onAnswer:(e,t)=>o8.answered(e,t),onChange:e=>s8.wakeWhere(`visibility`,t=>l8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function l8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const u8=new A6(Pt(),e=>s8.wake(e,`data`)),d8=new NZ({sessionState:Z6,watchers:U6,log:M,storage:X6,signer:n8,ledger:W6,declare:(e,t,n,r)=>Fq(G6,e,t,n,r),source:P4({providers:G6,sessionState:Z6,history:e=>Q6.depth(e),navigation:(e,t)=>$6.depth(e,Z6,vU(t))})},{budgetBytes:()=>(T8(),vZ(_8)),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)s8.wake(e,`reload`)},onViewChanged:e=>s8.wake(e,`data`)}}),f8=60*1e3,p8=UU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:f8,stat:p.statSync,exit:()=>A8(0),log:M}),m8=BU({entryUrl:import.meta.url,intervalMs:f8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>p8.checkNow(),log:M});let h8=null,g8=null,_8=0;function v8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),A8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),A8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),A8(0)});try{E8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),A8(1);return}h8=bs(t.pid);let e=As(Ms(h8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),A8(1);return}g8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),Z6.useStorage(new BZ(Ot(),500,M)),Q6.useStorage(m$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),A8(0)}}),b8(ue.createServer({allowHalfOpen:!1},e=>{j8(e)}),St(),!1)}function y8(){let e=K6.getStats(),t=J6.getStats(),n=q6.scanStats(),r=X6.stats(),i=d8.stats;return{records:W6.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:q6.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:Y6.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function b8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),A8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}x8(e,n)}),e.listen(n,()=>S8(n))}function x8(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}`),A8(1);return}}b8(e,n,!0)}function S8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),A8(0);return}D8(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(_8)}MB`),Tr();let r=u8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),p8.arm(),m8.arm(),T8().arm(),C8(e,n.identity)}function C8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>A8(e),log:M}).arm()}let w8=null;function T8(){if(w8===null)throw Error(`daemon: limits not yet established`);return w8}function E8(e){_8=nr(e),w8=ur(gr(R6.startedAt.getTime(),e=>A8(e),{limitBytes:_8}))}function D8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:h8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let O8=0,k8=!1;function A8(e){if(k8)return;k8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>o8.restoreAll()],[`gitService close`,()=>K6.close()],[`usageStore close`,()=>q6.close()],[`tmuxService close`,()=>J6.close()],[`hostService close`,()=>Y6.close()],[`runs close`,()=>r8.close()],[`managedStorage close`,()=>X6.close()],[`watcherRegistry close`,()=>U6.closeAll()],[`sessionState flush`,()=>Z6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),g8!==null&&js(g8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function j8(e){let t=performance.now();O8++,R6.inFlight=O8;let n=!1,r=!0,i=()=>{r&&(r=!1,O8=Math.max(0,O8-1),R6.inFlight=O8)},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:()=>A8(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,R6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,M8)},200),c=en(e=>{z8(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(I8(e),null,M8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,M8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=U4(e),o=s8.subscribe(t,{lane:r,frame:(e,t)=>a($t(fW[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 M8=()=>{},N8=e=>({resp:e,exitAfterFlush:null,delivered:M8}),P8=e=>({kind:`reply`,...e}),F8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},I8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),L8=(e,t)=>P8(N8({ok:!1,error:t,code:e,daemonV:3}));function R8(e){let t=pW(e.sessionId);if(!t.ok)return L8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return L8(`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?L8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function z8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?L8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?R8(e):typeof e.kind!=`string`||!Object.hasOwn(F8,e.kind)?L8(`BAD_REQUEST`,`unknown kind`):P8(await B8(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:M8})}async function B8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:M8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return N8(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:s8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return N8({ok:!0,stats:R6.snapshot({gitCache:K6.getStats(),usageCache:q6.getStats(),sources:y8(),runs:r8.stats(),transcriptReads:Ra(),renderCache:d8.stats,effectCache:e8.getStats(),menuIdle:t8.getStats(),sessionState:{sessions:Z6.size(),observers:Z6.observers(),revision:Z6.latestRevision()},frameFeeds:s8.getStats(),tmuxStatus:o8.stats(),watchersActive:U6.size(),nextRestartReason:T8().describeNextRestart(),handlerProbes:z6.list(),clients:B6.list(ak(new Date)),bundle:V6,daemon:T8().serving(),doctorStores:B1(H6)})});if(e.kind===`render`){let r=new Date,i=ak(r),a=performance.now(),o=Math.round(a-n),s=[],c=++R6.requestsTotal,l=t5(e),u=(e,t)=>B6.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:vM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),s8.note(l.req.sessionId,l.req,c));let d=l.ok?await d5(l.req,c,i,(e=>{let t=N6(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?M8:()=>es(Z6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:I8(e),delivered:M8})):n5(l.problems);d.outcome.kind!==`ok`&&R6.requestsErrored++,P6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=L6(`render`,s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`){let r=performance.now(),i=[[`queued`,`${Math.round(r-n)}ms`]],a=K8(e,i);P6(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=L6(`click`,i,a,Math.round(performance.now()-r));return M(o,s),N8(Y8(a))}if(e.kind===`debug`){if(!N4(e.what))return N8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${M4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=d8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?G8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):W8};return N8({ok:!0,debug:x4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function V8(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:YB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const H8={sessionState:Z6,dlog:M,applyUpdate:()=>m8.act(),doctor:X1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];d8.reload(...t);let n=d8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:H6,probes:z6,clients:B6,bundle:V6,serving:()=>T8().serving(),claudeInput:e2(),history:Q6,navigation:$6,configFor:e=>d8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>d8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>d8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:n8,runs:r8,lanes:{of:e5,clicked:m5},views:{follow:(e,t)=>d8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};H8.reloadConfig;const U8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},W8=new Map;function G8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...U8,colorCompatibility:t}));return n}function K8(e,t){let{verb:n,value:r}=e;if(typeof n!=`string`||typeof r!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof n} and ${typeof r}`]};try{return J8(n,r,{via:`link`,handler:Zt(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const q8={link:`verb`,"tmux-status":`linkVerb`};function J8(e,t,n,r){if(e===`tmux-status-click`)return P6(r,{verb:e}),X8(t,r);let i=f4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};P6(r,{[q8[n.via]]:e});let a=c4(e,t);return a===null?P6(r,{sid:`-`}):a.ok&&(P6(r,{sid:a.id}),t8.clicked(a.id,ak(new Date))),i(t,{...H8,arrival:n}),{kind:`ok`}}function Y8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:return I8(e.error)}}function X8(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=o8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(P6(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=kb(()=>zo(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):J8(e.verb,e.value,{via:`tmux-status`},n)}return r2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function Z8(e,t){let n=new Date,r=ak(n),i=[];try{try{var a=Aa();let n=a.u(a5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=s5(n,{by:`feed`,fps:t}),u=u8.linkFor(e,l5(o)),d=c5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:g5(e,o,u,d,D6(l,s8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=L6(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=I8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function Q8(e,t){return IH(t.config,t=>Z6.get(e,t),e=>t.authoredRoots.has(e))}function $8(e){try{var t=Aa();let n=t.u(d8.holdView(e));return n===null?null:NH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function e5(e,t){try{var n=Aa();return NH(Q8(t,n.u(d8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function t5(e){let{report:t}=_4(e.hookData),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=pW(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=M6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};for(let e of t.unknownTopLevelFields)R6.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Vt(e),{configFile:o,refusedArgs:s}=V8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:_M(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const n5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:M8});function r5(e,t,n){P6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return P6(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 i5(e,t,n){let r=e.sessionId,i=r5(e,t,n),a=v2(e.requested,Z6,r);return o5(d8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function a5(e,t,n){let r=d8.holdView(e);if(r===null){let t=d8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=r5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return o5(r,i,a,t,n)}function o5(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:{...G6,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 s5(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=NH(u);P6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=Oq(f),m=mb(f.termRows);P6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:s8.feedsOf(a,r),today:Wq(G6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;P6(i,zq(c.lanes().sources)),P6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:fq(h.git,wq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:L4(g.feeds)});let v=[],y=lq(u,p),b=e8.of(a),ee=t8.since(a,r),x=pZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});t8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=t8.since(a,r);P6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(Z6,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 X4=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:J4(t.stdout,q4(n.stdout)),status:Y4(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),!Z4(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 Z4(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 Q4=`@cc-candybar-status-prior`,$4=`@cc-candybar-status-wrote`,e3=`@cc-candybar-binding-prior`,t3=[`-T`,`root`,`MouseDown1Status`],n3=Array.from({length:5},(e,t)=>t),r3=e=>`@cc-candybar-row-${e}`,i3=e=>`#[fill=terminal]#{${r3(e)}}`,a3=e=>`status-format[${e}]`;function o3(e){return e===0?`off`:e===1?`on`:String(e)}function s3(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 c3(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 l3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function u3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function d3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function f3(e){return e.map(e=>e.map(d3).join(` `)).join(` ; `)}const p3=`ccb:separator`;function m3(e){return u3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,p3],e]))}function h3(e,t){let n=e.split(`${p3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const g3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],_3=e=>[`show-options`,`-g`,`-q`,`-v`,e],v3=e=>[[`show-options`,`-t`,e],g3(e,`status`),...n3.map(t=>g3(e,a3(t)))];function y3(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
493
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of n3)i.includes(a3(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 b3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,a3(Number(t)),l3(n)])]}const x3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...v3(e),...n3.map(e=>_3(a3(e))),g3(e,Q4),g3(e,$4)];function S3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:s3(t)}catch(e){return{kind:`theirs`,why:`${Q4} 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 C3(e,t,n){let[r=``,...i]=t,a=y3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return S3(s,c,n);let l=s3(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,i3(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,Q4,JSON.stringify(f)],...b3(e,d)]}}const w3=e=>[...v3(e),g3(e,$4)];function T3(e,t,n){let r=y3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(c3(r.formats,t.wrote))a.push(...b3(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,a3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,l3(t.status)]):o.push(`status`)),a.push(...n3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,r3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,Q4],[`set-option`,`-q`,`-u`,`-t`,e,$4]),{commands:a,kept:o}}const E3=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,D3=[[`list-keys`,`-T`,`root`]];function O3(e){let t=E3.exec(e);return t===null?null:{line:t[0],command:t[1]}}const k3=`cc-candybar://tmux-status-click/`,A3=e=>`${k3}${ui([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,j3=e=>e?.command.includes(k3)??!1;function M3(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,e3]};return j3(O3(t))?{steps:[e===null?{command:[`unbind-key`,...t3]}:{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 N3=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=fW(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,w3(n));if(i===null)continue;let a=T3(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,D3);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let t=P3(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}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#{${Q4}}\t#{${$4}}`]);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=S3(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,[_3(`@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)} ${e3} 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,x3(n));if(r===null||this.closed)return null;let i=C3(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,r3(r),e])}),i!==n.status){let e=o3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,$4,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,f3(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,w3(n));if(i===null)return;let a=T3(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,D3);if(r===null||this.closed)return;let i=O3(r[0]??``);if(n.kind===`none`&&j3(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`&&j3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...t3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${d3(`${this.deps.handler} ${A3(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,D3);if(r===null)return;let i=M3(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=M3(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,m3(t));return n.kind===`ok`?h3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,m3(t)));return n.kind===`ok`?h3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,u3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,u3(t),n)))}};function P3(e){try{return di(e)}catch(e){if(e instanceof URIError)return null;throw e}}const F3=`CC_CANDYBAR_CONFIG`;function I3(e,t){return XB(t,e[F3])}const $=e=>({arity:e,keep:!0}),L3=e=>({arity:e,keep:!1}),R3={"--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":L3(`none`),"--background":L3(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":L3(`optional`),"-c":L3(`none`),"--continue":L3(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":L3(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":L3(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":L3(`none`),"--forward-subagent-text":$(`none`),"--from-pr":L3(`optional`),"-h":L3(`none`),"--help":L3(`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":L3(`none`),"--print":L3(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":L3(`optional`),"--resume":L3(`optional`),"--safe-mode":$(`none`),"--session-id":L3(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":L3(`optional`),"--tmux":L3(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":L3(`none`),"--version":L3(`none`),"-w":L3(`optional`),"--worktree":L3(`optional`)},z3={resume:`--resume`,fresh:`--session-id`};function B3(e){return[z3[e.kind],e.sessionId]}const V3=e=>e.startsWith(`-`)&&e!==`-`;function H3(e,t){let n=G3(t);return n===null?{dir:e??t,args:[]}:e!==null&&U3(e,n.top)?{dir:e,args:[]}:{dir:e===null||G3(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const U3=(e,t)=>e===t||e.startsWith(t+s.sep);function W3(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!V3(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=R3[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=>!V3(e)):o.arity===`variadic`?K3(n.slice(r),e=>!V3(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 G3(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 K3(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const q3=`candybar-band@cc-candybar`,J3=s.join(`bin`,`cc-candybar-native`),Y3=`@cc-candybar-bar-pane`,X3=lP(`/reload-plugins`),Z3=e=>({kind:`done`,said:e});function Q3(e){let t=Y0(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const $3={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,J3);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 ${q3} from ${r}`,finished:e6(e,r,n)}},off:()=>Z3(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=Q3(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:r6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>Z3(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=Q3(e),i=n.barPanes(r);return i.length>0?Z3(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):Z3(`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=Y0(e.hints.tmux);if(r.kind===`refused`)return Z3(`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 Z3(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>Z3(`the daemon draws ${Q3(e).pane}'s bar in its status line`),off:()=>Z3(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function e6(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`,q3],r);let i=X0(n.claudeInput,e.hints.tmux,X3);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 ${q3} from ${t} and typed /reload-plugins into ${i.pane}`}const t6=new Set([qa,F3]);function n6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function r6(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=c6(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=i6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=W3(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=n6(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])=>t6.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...B3(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=a6(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(H3(null,i.cwd),_))}let y=m(H3(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}\`, ${o6[g.kind](e.sessionId)}, and its statusline follows lane B`}function i6(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 a6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const o6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},s6={"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 c6(e){let t=W0(e);return t.kind===`ready`?q0(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:G0(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:s6[t.kind]}var l6=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=$3[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 u6(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 d6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function f6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function p6(e,t,n){let r=u6(`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 m6=2e3;function h6(e,t,n){let r=FK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function g6(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 _6(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 v6=`#{pane_id} #{${Y3}}`;function y6(e,t){return e.split(`
|
|
495
|
+
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const b6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function x6(e,t,n){for(let r of H$(V$(e),t)){if(r.command.split(` `).some(e=>b6.test(e)))return!0;if(r.pid===n)return!1}return!1}const S6=[`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 C6(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=g6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,S6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function w6(e,t){return g6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function T6(e){let t=await IK(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 w6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function E6(e){let{panePid:t,cwd:n,foreground:r}=await T6(e),i=await w6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await C6(r),o=V$(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:x6(i,r,t)}}function D6(e){return{claudeInput:t2(),barPanes:e=>y6(h6(e,[`list-panes`,`-a`,`-F`,v6]),e.pane),openBarPane:(e,t,n)=>{let r=h6(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 h6(e,[`set-option`,`-p`,`-t`,r,Y3,e.pane]),r},closePane:(e,t)=>void h6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void g6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:D$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:HV,paneClaude:E6,paneDir:async(e,t)=>{let n=Date.now()+m6;for(;;){let r=await T6(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 ${m6/1e3} s`);await be(100)}},launcherNode:e=>p6(e,e=>d6(e,p.constants.X_OK),f6),onPath:(e,t)=>{let n=u6(e,t,e=>d6(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`?_6(r.stdout):null;return i===null?(g6(`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 h6(e,$0(e.pane,`cc-candybar-lane`,[]),t)}}function O6(e,t){return Fv.filter(n=>e[n]&&Pv[n].elsewhere!==null&&t.has(n))}function k6(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 A6={order:-1/0,text:null,failure:null};var j6=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)??A6;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)??A6;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}`}}},M6=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 N6(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 P6(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 F6(e,t){for(let n of Object.entries(t))e.push(n)}const I6={ok:`info`,"bad-request":`warn`,threw:`error`};function L6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function R6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...L6(n)];return{level:I6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${as(t)}`).join(``)}`}}const z6=new IZ,B6=new A0,V6=new SM,H6=i(import.meta.url),U6=B1(yt());dt(z6.launchStats);const W6=new $W({counters:z6,logger:M}),G6=new Mk(M),K6=sq({watchers:W6,logger:M,ledger:G6}),{gitProvider:q6,usageStore:J6,tmuxService:Y6,hostService:X6,managedStorage:Z6}=K6,Q6=new zZ,$6=new JQ(Q6,M),e8=new _$,t8=new eb,n8=new M6({now:()=>ak(new Date),close:(e,t)=>m4(e,t,U8),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),r8=Yo(),i8=new ls({supersede:(e,t)=>Z6.supersede(e,t),launch:pt,state:Q6,log:M,now:()=>ak(new Date)}),a8=[t.execPath,...t.execArgv],o8=new l6({edge:D6(e=>c8.following(e)),host:{bundle:H6,node:a8,socket:St(),preload:Do(H6)},state:Q6,log:M,now:()=>ak(new Date),defer:e=>void _e(e)}),s8=new N3({edge:{run:(e,t,n)=>IK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>FK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>c8.subscribe(e,t),sessionInPane:(e,t)=>c8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...a8,H6].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),c8=new U4({render:(e,t)=>Q8(e,t),watch:(e,t)=>(0,J.reaction)(()=>Q6.revision(e),t),lanes:e=>e5(e),pin:e=>f8.pin(e),shown:e=>l8.shown(e.hints.tmux),watching:()=>l8.follow(),refreshes:()=>G6.totals(),periods:I4,now:()=>performance.now(),log:M}),l8=new X4({listPanes:e=>IK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,G4]),listClients:e=>IK({socket:e},`frames.visibility`,[`list-clients`,`-F`,K4]),sockets:()=>new Set(c8.watched().flatMap(({req:e})=>u8(e))),onAnswer:(e,t)=>s8.answered(e,t),onChange:e=>c8.wakeWhere(`visibility`,t=>u8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function u8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const d8=new j6(Pt(),e=>c8.wake(e,`data`)),f8=new PZ({sessionState:Q6,watchers:W6,log:M,storage:Z6,signer:r8,ledger:G6,declare:(e,t,n,r)=>Iq(K6,e,t,n,r),source:F4({providers:K6,sessionState:Q6,history:e=>$6.depth(e),navigation:(e,t)=>e8.depth(e,Q6,yU(t))})},{budgetBytes:()=>(E8(),yZ(v8)),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)c8.wake(e,`reload`)},onViewChanged:e=>c8.wake(e,`data`)}}),p8=60*1e3,m8=WU({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:p8,stat:p.statSync,exit:()=>j8(0),log:M}),h8=VU({entryUrl:import.meta.url,intervalMs:p8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>m8.checkNow(),log:M});let g8=null,_8=null,v8=0;function y8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),j8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),j8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),j8(0)});try{D8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),j8(1);return}g8=bs(t.pid);let e=As(Ms(g8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),j8(1);return}_8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),Q6.useStorage(new VZ(Ot(),500,M)),$6.useStorage(h$(kt(),M)),Cs({anchor:Ss(t.env),isAlive:ws,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),j8(0)}}),x8(ue.createServer({allowHalfOpen:!1},e=>{M8(e)}),St(),!1)}function b8(){let e=q6.getStats(),t=Y6.getStats(),n=J6.scanStats(),r=Z6.stats(),i=f8.stats;return{records:G6.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:J6.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:X6.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function x8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),j8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}S8(e,n)}),e.listen(n,()=>C8(n))}function S8(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}`),j8(1);return}}x8(e,n,!0)}function C8(e){let n=ms(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),j8(0);return}O8(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(v8)}MB`),Tr();let r=d8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),m8.arm(),h8.arm(),E8().arm(),w8(e,n.identity)}function w8(e,n){_s({bound:n,myPid:t.pid,readIdentity:()=>ms(e),readLease:()=>ds(Et(e)),shutdown:e=>j8(e),log:M}).arm()}let T8=null;function E8(){if(T8===null)throw Error(`daemon: limits not yet established`);return T8}function D8(e){v8=nr(e),T8=ur(gr(z6.startedAt.getTime(),e=>j8(e),{limitBytes:v8}))}function O8(e){let n=fs(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:g8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let k8=0,A8=!1;function j8(e){if(A8)return;A8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>s8.restoreAll()],[`gitService close`,()=>q6.close()],[`usageStore close`,()=>J6.close()],[`tmuxService close`,()=>Y6.close()],[`hostService close`,()=>X6.close()],[`runs close`,()=>i8.close()],[`managedStorage close`,()=>Z6.close()],[`watcherRegistry close`,()=>W6.closeAll()],[`sessionState flush`,()=>Q6.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ps(Dt(),t.pid),_8!==null&&js(_8,t.pid,Os,e=>p.unlinkSync(e)),t.exit(e)}function M8(e){let t=performance.now();k8++,z6.inFlight=k8;let n=!1,r=!0,i=()=>{r&&(r=!1,k8=Math.max(0,k8-1),z6.inFlight=k8)},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:()=>j8(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,z6.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,N8)},200),c=en(e=>{B8(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(L8(e),null,N8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,N8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=W4(e),o=c8.subscribe(t,{lane:r,frame:(e,t)=>a($t(pW[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 N8=()=>{},P8=e=>({resp:e,exitAfterFlush:null,delivered:N8}),F8=e=>({kind:`reply`,...e}),I8={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},L8=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),R8=(e,t)=>F8(P8({ok:!1,error:t,code:e,daemonV:3}));function z8(e){let t=mW(e.sessionId);if(!t.ok)return R8(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return R8(`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?R8(`BAD_REQUEST`,`subscribe needs a lane, one of ${Fv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function B8(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?R8(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?z8(e):typeof e.kind!=`string`||!Object.hasOwn(I8,e.kind)?R8(`BAD_REQUEST`,`unknown kind`):F8(await V8(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:N8})}async function V8(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:N8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return P8(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:c8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return P8({ok:!0,stats:z6.snapshot({gitCache:q6.getStats(),usageCache:J6.getStats(),sources:b8(),runs:i8.stats(),transcriptReads:Ra(),renderCache:f8.stats,effectCache:t8.getStats(),menuIdle:n8.getStats(),sessionState:{sessions:Q6.size(),observers:Q6.observers(),revision:Q6.latestRevision()},frameFeeds:c8.getStats(),tmuxStatus:s8.stats(),watchersActive:W6.size(),nextRestartReason:E8().describeNextRestart(),handlerProbes:B6.list(),clients:V6.list(ak(new Date)),bundle:H6,daemon:E8().serving(),doctorStores:V1(U6)})});if(e.kind===`render`){let r=new Date,i=ak(r),a=performance.now(),o=Math.round(a-n),s=[],c=++z6.requestsTotal,l=n5(e),u=(e,t)=>V6.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:vM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),c8.note(l.req.sessionId,l.req,c));let d=l.ok?await f5(l.req,c,i,(e=>{let t=P6(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?N8:()=>es(Q6,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:L8(e),delivered:N8})):r5(l.problems);d.outcome.kind!==`ok`&&z6.requestsErrored++,F6(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=R6(`render`,s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`){let r=performance.now(),i=[[`queued`,`${Math.round(r-n)}ms`]],a=q8(e,i);F6(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=R6(`click`,i,a,Math.round(performance.now()-r));return M(o,s),P8(X8(a))}if(e.kind===`debug`){if(!P4(e.what))return P8({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${N4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=f8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?K8(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??vy(`colorCompatibility`)):G8};return P8({ok:!0,debug:S4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function H8(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:XB(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const U8={sessionState:Q6,dlog:M,applyUpdate:()=>h8.act(),doctor:Z1(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];f8.reload(...t);let n=f8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:U6,probes:B6,clients:V6,bundle:H6,serving:()=>E8().serving(),claudeInput:t2(),history:$6,navigation:e8,configFor:e=>f8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>f8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>f8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:r8,runs:i8,lanes:{of:t5,clicked:h5},views:{follow:(e,t)=>f8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};U8.reloadConfig;const W8={endcaps:vy(`endcaps`),colorCompatibility:vy(`colorCompatibility`),wrap:vy(`autoWrap`),padding:vy(`padding`),width:1/0},G8=new Map;function K8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,pb(i,{...W8,colorCompatibility:t}));return n}function q8(e,t){let{verb:n,value:r}=e;if(typeof n!=`string`||typeof r!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof n} and ${typeof r}`]};try{return Y8(n,r,{via:`link`,handler:Zt(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const J8={link:`verb`,"tmux-status":`linkVerb`};function Y8(e,t,n,r){if(e===`tmux-status-click`)return F6(r,{verb:e}),Z8(t,r);let i=p4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};F6(r,{[J8[n.via]]:e});let a=l4(e,t);return a===null?F6(r,{sid:`-`}):a.ok&&(F6(r,{sid:a.id}),n8.clicked(a.id,ak(new Date))),i(t,{...U8,arrival:n}),{kind:`ok`}}function X8(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:return L8(e.error)}}function Z8(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=s8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(F6(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=kb(()=>zo(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):Y8(e.verb,e.value,{via:`tmux-status`},n)}return i2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function Q8(e,t){let n=new Date,r=ak(n),i=[];try{try{var a=Aa();let n=a.u(o5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=c5(n,{by:`feed`,fps:t}),u=d8.linkFor(e,u5(o)),d=l5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:_5(e,o,u,d,O6(l,c8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=R6(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=L8(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function $8(e,t){return LH(t.config,t=>Q6.get(e,t),e=>t.authoredRoots.has(e))}function e5(e){try{var t=Aa();let n=t.u(f8.holdView(e));return n===null?null:PH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function t5(e,t){try{var n=Aa();return PH($8(t,n.u(f8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function n5(e){let{report:t}=v4(e.hookData),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=mW(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=N6(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};for(let e of t.unknownTopLevelFields)z6.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Vt(e),{configFile:o,refusedArgs:s}=H8(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:_M(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const r5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:N8});function i5(e,t,n){F6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return F6(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 a5(e,t,n){let r=e.sessionId,i=i5(e,t,n),a=y2(e.requested,Q6,r);return s5(f8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function o5(e,t,n){let r=f8.holdView(e);if(r===null){let t=f8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=i5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return s5(r,i,a,t,n)}function s5(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:{...K6,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 c5(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=PH(u);F6(i,{lanes:Fv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=kq(f),m=mb(f.termRows);F6(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:c8.feedsOf(a,r),today:Gq(K6,c.lanes().today,c.facts().hookData,r)},_=ka(h.metrics)?void 0:h.metrics;F6(i,Bq(c.lanes().sources)),F6(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:pq(h.git,Tq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:R4(g.feeds)});let v=[],y=uq(u,p),b=t8.of(a),ee=n8.since(a,r),x=mZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});n8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=n8.since(a,r);F6(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=ns(Q6,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=h8.notice({sessionId:a,dismissed:Q6.get(a,TU),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=q6.getStats(),T=J6.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 F6(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 l5(e,t){return Cb(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
|
|
499
|
+
`}function u5(e){return e.diagnostics===null?null:Sb(e.diagnostics)}function d5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);Q6.get(t,`client-hints`)!==i&&Q6.set(t,J2,i);let a=b2(e.requested);Q6.get(t,`render-origin`)!==a&&Q6.set(t,v2,a)}async function f5(e,t,n,r,i){return d5(e),g5(e,t,n,r,i)}function p5(e,t){o8.noted(m5(e),t),s8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function m5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:y2(e.requested,Q6,t),transcript:e.hookData.transcript_path,answered:hM(e.hookData)}}function h5(e,t,n){let r=c8.latest(e);o8.clicked(e,r===null?null:m5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&s8.observe(e,r.hints.tmux,n.tmuxStatus)}async function g5(e,t,n,r,i){try{var a=Aa();let o=a.u(a5(e,n,i));p5(e,PH(o.view.source.effective())),F6(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await uG(e=>Promise.all([Kq(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();F6(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:jq(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=c5(o,Iv),{link:h,failure:g}=d8.sync(e.sessionId,t,u5(d));F6(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=l5(d,h),v=e.sessionId,y=O6(m,c8.following(v)),b=_5(v,d,h,_,y),ee=xM(e.hints.client??null)===`statusline`;return F6(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 _5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:l5({...t,body:wb(k6(e,[a,...o]),t.geometry)},n)}const v5={connectMs:200,budgetMs:500};async function y5(e,n){let r=n.includes(`--json`),i=await b5(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(x5(i.value))}function b5(e){return rn(()=>({kind:`debug`,what:e}),v5,e=>`debug`in e?e.debug:void 0)}function x5(e){switch(e.what){case`vars`:return S5(e.vars);case`segments`:return C5(e.segments);case`config`:return w5(e.config);default:return e}}function S5(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?``:` ${E5(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${T5(a.value)}${e}${o}`)}return t.join(`
|
|
502
502
|
`)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function C5(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 w5(e){return e===null?`config: DSL not active
|
|
507
507
|
`:JSON.stringify(e,null,2)+`
|
|
508
|
-
`}function
|
|
508
|
+
`}function T5(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function E5(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function D5(){let e=k5();return e===null?null:p.readFileSync(e,`utf-8`)}function O5(){let e;try{e=D5()}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 k5(){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 A5=5e3;function j5(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:_P(4e5,1e6),...dq(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:lq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:Vq(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>F)}}const M5={cost:12.5,tokens:34e5};function N5(e,t){let n=KV(e,e),r=YV(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function P5(e,n=t.cwd()){let r=[],i=XB(n,e)??null,a=i===null?N5(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=ZV(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await L5(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 F5(e,t,n,r){let i=aH(e,OH,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:a}=i,o=new mS,s=new eA(o,a.globals.default_empty_value??``,new zZ);try{let c=XX(a,s,{cwd:t,signer:Yo()});n.push(...c.loadWarnings);let l=LH(a,()=>null,()=>!1);TX(c,o,s,GX({...j5(a,l,e.at(-1)??null,r),today:M5},l));let u=await s.settled(A5);return u.length>0&&n.push(`source${u.length===1?``:`s`} still running after ${A5} 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 I5({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:pZ(t,n,r,i,{...j5(t,a,e.at(-1)??null,s),today:M5},s,uq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function L5(e,t,n){let r=ak(new Date),i=await F5(e,t,n,r),{config:a}=i;try{let e=BU();try{yU(a),YI(a)}finally{e()}let t=ex(null,a.globals.preset,a.presets),o=(e,t)=>{let n=LH(a,t=>t===`preset`?e:null,()=>t),o;try{o=I5(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),...$b(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 R5(e){return e.map(e=>`warning: ${e}\n`).join(``)}function z5(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:R5(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:R5(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 B5=`--render`,V5=`Usage: cc-candybar check [${B5}] [config-file]\n`;function H5(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==B5);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${V5}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${V5}`}:{kind:`run`,target:n[0],render:t.includes(B5)}}async function U5(e){let n=H5(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:z5(await P5(n.target??I3(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const W5=/^[a-z][a-z0-9+.-]*:\/\//i,G5=/^[^@\s/]+@[^:\s/]+:/,K5=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function q5(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function J5(e,t,n){let r=YB(t,e);if(n(r))return{kind:`path`,dir:r};if(W5.test(e)||G5.test(e))return{kind:`git`,url:e,shown:q5(e)};let i=K5.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 Y5(e,t){let n=s.join(e,PV),r=LV(n);if(`error`in r)throw Error(`${t}: could not list ${PV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${PV}/<name>/${$B}`);return r.folders.map(e=>s.join(n,e,$B))}function X5(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`,`/${PV}/`)}function Z5(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 X5(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function Q5(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 $5(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,$B),s.join(t,$B));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function e7(e,t,n){let r=Y5(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,$B))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=rH(a.map(e=>s.join(e,$B)),OH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(PV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,PV))}`).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:Q5(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)$5(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,$B),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function t7(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=J5(n,process.cwd(),Wk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=Z5(i,t=>e7(t,NV(),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 n7(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 r7=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function i7(e,t,n){return{termCols:n7(e.COLUMNS,n.columns),termRows:n7(e.LINES,n.rows),ssh:r7.some(t=>(e[t]??``)!==``),tmux:pM(e),configEnv:I3(e,t),claudeConfigDir:Ja(e,t),terminalEnv:Lt(e)}}function a7(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function o7(e){let t=y0(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=a7(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 s7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},c7=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 l7(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 u7(e){let t=y0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=l7(n?.postMortems,e=>Array.isArray(e)&&e.every(s7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&c7(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 d7(e,t,n){let r=y0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=a7(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 f7=e=>bM.includes(e.role),p7=e=>d7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&gM.includes(e.rateLimits),`the rate-limit windows they carried`),m7=e=>d7(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`),h7=e=>d7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&f7(e)&&yM.includes(e.frame),`what they drew and from which project`),g7=e=>d7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&f7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function _7(e,t,n){let r=e.doctorStores?.[t],i=l7(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 v7(e){let t=y0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:_7(e,`marks`,A$),clicked:_7(e,`clicked`,N$),postMortemsRead:_7(e,`postMortemsRead`,F1)}}async function y7(){let e=await v0();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:o7(e.value),rateLimits:p7(e.value),transcripts:m7(e.value),frames:h7(e.value),widths:g7(e.value),serving:u7(e.value),stores:v7(e.value)}}const b7=` (fix: click the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,x7=`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 S7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:b7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${x7}\n`)}function C7(e){let t={sessionState:new zZ,storage:bZ,signer:Yo()},n=kZ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??AZ(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 w7(e,t,n){return n.kind===`failed`?n:z1(e,n.value.bundle,R$(t,n.value.clients).map(({client:e})=>e))}function T7(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function E7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:R$(e,t.value).map(e=>e.transcript)}}function D7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:B$(e,t.value)}}function O7(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:p0(e.sessionId,R$(e,t.value))}async function k7(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=i7(r,i,a()),u=L$(r.CLAUDE_CODE_SESSION_ID);s={...m0(e,l,{projectDir:z$(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:XB(i,o)??I3(r,i)??null},()=>null,c.serving,T7(u,c.rateLimits,Ya(l.claudeConfigDir)),E7(u,c.transcripts),u,D7(u,c.frames),O7(u,c.widths,l.termCols??null),c.stores),urlHandler:await F0(t),install:w7(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=LN(s);return{stdout:c.map(S7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function A7(){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 j7(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 k7(Z1(C7),z0(),y7,t.env,n,A7,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function M7(e){return!e.ok&&e.code!==`RENDER_FAILED`}function N7(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;M7(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 P7(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function F7(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 I7(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=N7(e,t,n,e=>{s=P7(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=F7(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=P7(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function L7(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function R7(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=W4(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{L7(p,e)&&t(),p=e},h=async e=>{let r=await hn(e,a,o,{...i7(t.env,o,t.stderr),client:zt(`frames`,n)});r.kind!==`ok`&&(s(un(r)),r.kind===`transient`&&_r())},g=e=>{f?.close(),f=I7(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 z7(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 B7=5e3,V7=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function H7(e,t,n,r){let i=e.split(`
|
|
517
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?J4(e,q4(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function U7(e,t){let[n,r]=await Promise.all([IK(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,G4]),IK(e,`bar-pane.tmux`,[`list-clients`,`-F`,K4])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:H7(n.stdout,r.stdout,t,e.pane)}:r:n}function W7(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>B7)throw Error(`tmux has not answered for ${B7/1e3} s: ${t.reason}`)}}function G7(e){let{positionals:t}=(()=>{try{return ce({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${V7}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(V7);return{pane:n}}async function K7(e){try{return await q7(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function q7(e){let{pane:n}=G7(e),r=pM(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 U7(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=W7(),f=async()=>{if(a.kind!==`shown`)return;let e=z7(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await IK(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:I7(St(),e,`pane`,{frame:e=>n(JU(mn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=W7();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 U7(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const J7=i(import.meta.url),Y7=e=>e.some(e=>t.argv.includes(e));function X7(){console.log(uM);let e=Do(J7),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 Z7={install:async e=>{await Uo(e,J7),t.exit(0)},"install-url-handler":async()=>{Ro(J7),t.exit(0)},"url-handle":async e=>{await Bo(e[0])},daemon:async()=>{y8()},"daemon-stats":async e=>{await _0(e),t.exit(0)},frames:async()=>{await R7(t.argv,J7)},check:async e=>{await U5(e)},lint:async e=>{await U5(e)},plugin:async e=>{t.exit(t7(e))},schema:async()=>{O5()},doctor:async e=>{await j7(e)},"bar-pane":async e=>{t.exit(await K7(e))},...Object.fromEntries(N4.map(e=>[e,async n=>{await y5(e,n),t.exit(0)}]))};async function Q7(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(Z7,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),Y7(Jj.help)&&(X7(),t.exit(0)),Y7(Jj.version)&&(console.log(`cc-candybar ${Ze}`),t.exit(0)),n!==null){await Z7[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`),X7(),t.exit(1));let i=JU(await hn(r,t.argv.slice(1),t.cwd(),{...i7(t.env,t.cwd(),t.stderr),client:zt(`node`,J7)}));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)}}Q7();export{};
|