@promptctl/cc-candybar 1.156.2 → 1.156.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +78 -78
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.156.2`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`bb5bee22ef7474a7052967a8afef6457eceba4f2745c1733136de53ae4634055`}function Ze(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:$e(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:$e(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function O(e,t,n){let r=pt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
2
|
+
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,randomUUID as ne}from"node:crypto";import C,{homedir as re}from"node:os";import{spawn as ie,spawnSync as ae}from"node:child_process";import{inspect as w,parseArgs as T,types as oe}from"node:util";import E from"node:net";import se from"node:v8";import{open as ce,readFile as le,readdir as ue,stat as de}from"node:fs/promises";import{clearInterval as fe,setImmediate as pe,setInterval as me}from"node:timers";import{get as he}from"node:https";import{setTimeout as ge}from"node:timers/promises";import{WriteStream as _e}from"node:tty";import{createInterface as ve}from"node:readline";var ye=Object.create,be=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Se=Object.getOwnPropertyNames,Ce=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty,Te=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ee=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Se(t),a=0,o=i.length,s;a<o;a++)s=i[a],!we.call(e,s)&&s!==n&&be(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=xe(t,s))||r.enumerable});return e},De=(e,t,n)=>(n=e==null?{}:ye(Ce(e)),Ee(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e));function D(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Oe=(e,t)=>D(t),ke=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ae(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function je(e){return ke.test(e)?e:Ae(e)}function Me(e){return`${e.dir===void 0?``:`cd ${je(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${je(t)} `).join(``)}${[e.program,...e.args].map(je).join(` `)}`}const Ne=`cc-extra`;function Pe(e){return s.join(s.dirname(e),Ne,`src`,`bun-attach.js`)}function Fe(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ie=`attach-preload.cjs`;function Le(e){return s.join(s.dirname(e),Ie)}function Re(e,t){return Me({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const ze=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Be(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ve(e,t,n=ze){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ve(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Be(r,i)]]})}function He(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ue(e){return He(Ve(e,e))}const We=[`Cargo.toml`,`Cargo.lock`,`src`];function Ge(e){return He(Ve(e,e,e=>We.includes(e)))}const Ke=e=>e.slice(0,7),qe=`1.156.3`;function Je(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function Ye(){let e=Xe();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:qe,digest:e}}function Xe(){return`6765990c6b0374a5e28d9a1bf3ff0629b3513e7a8769cc3ab8f6d50893f7b732`}function Ze(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function Qe(e,t){try{let n=Je(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ue(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:Ze(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function $e(e,t){return oe.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const et={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},tt=new Map;function nt(e){let t=et[e];if(t===void 0)return{allowed:!0};let n=tt.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function rt(e){tt.set(e,Date.now())}function it(e){return e.env??process.env}function at(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ot=null;function st(e){ot=e}function ct(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function lt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();return ot?.onStart(e.category),new Promise(t=>{let r;try{r=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ot?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ot?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ct(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:$e(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function ut(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=ae(e.bin,e.args??[],{cwd:e.cwd,env:it(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ot?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:$e(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ot?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}}function dt(e){let t=nt(e.category);if(!t.allowed)return at(e.category,t.minIntervalMs,t.sinceLastMs);rt(e.category);let n=Date.now();ot?.onStart(e.category);let r=ft(e);return ot?.onEnd(e.category,Date.now()-n),r}function ft(e){let t;try{t=ie(e.bin,e.args??[],{cwd:e.cwd,env:it(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:$e(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function O(e,t,n){let r=pt(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function pt(e){let t=e;for(let e=0;e<mt;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${mt} symbolic links`)}const mt=40;function ht(e,t){let n=e[t];return n&&n.length>0?n:void 0}function gt(e=process.env){let t=ht(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function k(){let e=ht(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function _t(){return gt()}function vt(){return process.env.CC_CANDYBAR_SOCKET||yt()}function yt(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function bt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function xt(e){bt(s.dirname(e));for(let t of[e,St(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function St(e){return`${e}.lease`}function Ct(){return St(vt())}function wt(){return s.join(gt(),`session-state.json`)}function Tt(){return s.join(gt(),`settings-history.json`)}function Et(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function Dt(){return s.join(gt(),`spawn.lock`)}function Ot(){return s.join(gt(),`spawn.cooldown`)}function kt(){return s.join(gt(),`spawn.backoff`)}function At(){return s.join(gt(),`diagnostics`)}function jt(e=process.env){return s.join(gt(e),`daemon.log`)}const Mt=[`MEMENTO_CONFIG_HOME`,`XDG_CONFIG_HOME`];function Nt(e,t){return Object.fromEntries(Mt.flatMap(n=>{let r=e[n]??``;return r===``?[]:[[n,s.resolve(t,r)]]}))}const Pt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Ft(e){return Object.fromEntries(Pt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const It=[`native`,`node`,`frames`];function Lt(e,t){return{kind:e,bundle:t,source:null}}const Rt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,mementoEnv:!0,terminalEnv:!0,client:!0});function zt(e){let t=Jt(e.termCols),n=Jt(e.termRows),r=Yt(e.ssh),i=Kt(e.tmux),a=Gt(e.configEnv),o=Gt(e.claudeConfigDir),s=Wt(e.mementoEnv),c=A(e.terminalEnv),l=tn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{mementoEnv:s},...c!==void 0&&{terminalEnv:c},...l!==void 0&&{client:l}}}function Bt(e,t){return Rt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Vt(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Ht={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Ut(e){let t=Object.keys(Ht).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Ht[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
3
3
|
`)}function Wt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Mt.filter(e=>t[e]!==void 0);return n.every(e=>Gt(t[e])!==void 0)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function A(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=Pt.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function Gt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Kt(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const qt=1e4;function Jt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>qt?qt:t}function Yt(e){return typeof e==`boolean`?e:void 0}function Xt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var j=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Zt(e){return Qt(JSON.stringify(e))}function Qt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function $t(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new j(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new j(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function en(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n),c=$t(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(Zt(t))})}function tn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Gt(n);return It.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function nn(e,t,n){let r=null;try{r=await cn(vt(),t.connectMs);let i=await en(r,{v:3,...e},t.budgetMs);return on(e.kind,i,n)}catch(e){return sn(e)}finally{r&&r.destroy()}}function rn(e,t){return typeof e==`string`?e:t}function an(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function on(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=rn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:an(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function sn(e){if(e instanceof j||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function cn(e,t){return new Promise((n,r)=>{let i=E.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function ln(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const un={connectMs:50,budgetMs:150},dn={connectMs:50,budgetMs:200};function fn(e){let t=e.output;return typeof t==`string`?t:void 0}function pn(e){return on(`render`,e,fn)}function mn(e,t,n,r){return nn({kind:`render`,hookData:e,args:t,cwd:n,...r},un,fn)}function hn(e,t){return nn({kind:`pane-session`,socket:e,pane:t},dn,e=>`paneSession`in e?e.paneSession:void 0)}function gn(e,t){return nn({kind:`click`,verb:e,value:t,clientVersion:qe},dn,fn)}let _n=null;function vn(e){if(_n!==null)return _n;p.mkdirSync(s.dirname(e),{recursive:!0});try{_n=p.statSync(e).size}catch{_n=0}return _n}function yn(e){for(let t=2;t>=1;t--){let n=`${e}.${t}`,r=`${e}.${t+1}`;try{p.renameSync(n,r)}catch{}}try{p.renameSync(e,`${e}.1`)}catch{}_n=0}function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;try{let e=jt(),t=vn(e);p.appendFileSync(e,n),_n=t+Buffer.byteLength(n,`utf8`),_n>=5242880&&yn(e)}catch(e){_n=null;try{process.stderr.write(`${n}cc-candybar: daemon.log unwritable: ${e.message}\n`)}catch{}}}const bn=5e3;function xn(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
4
4
|
`)}const Sn=`/usr/bin/footprint`;function Cn(e,t){return e===`darwin`?[En(Sn,[`-p`,String(t)]),En(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Dn(`/proc/self/smaps_rollup`),Dn(`/proc/self/status`)]:[]}function wn(e,t){return e===`darwin`?Tn(t,e=>lt({bin:Sn,args:e,timeoutMs:bn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Tn(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${On(r.stderr)}`};let i=N(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function N(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function En(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=ut({bin:e,args:[...t],timeoutMs:bn,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${On(n.stderr)}`}}}}function Dn(e){return{name:e,read:()=>{try{let t=p.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function On(e){let t=e.split(`
|
|
5
5
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const kn=`CC_CANDYBAR_RSS_LIMIT_MB`;function An(e){let t=e[kn];if(t===void 0)return 512;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${kn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function jn(e){return An(e)*2}const Mn=1024*1024,Nn=e=>Math.round(e/Mn);function Pn(e){return An(e)*Mn}const Fn={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function In(e,t){return e>t}function Ln(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}function Rn(e,t){return e>t*.75}function zn(e,t,n){let{prefix:r,suffix:i}=Fn[t];return s.join(e,`${r}${n}${i}`)}function Bn(e){for(let t of Object.keys(Fn)){let{prefix:n,suffix:r}=Fn[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function Vn(e){let t=e.limitBytes??512*Mn,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null;function o(){return a??=s().finally(()=>{a=null}),a}async function s(){if(r)return!0;let{rss:a,heapTotal:o}=e.memoryBytes(),s=Ln(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${Wn(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${Hn(s)} > limit ${Nn(t)} MB (rss ${Nn(a)} MB, v8 heap ${Nn(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return Gn(e.log,`memory report`,()=>{let t=zn(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),Gn(e.log,`heap snapshot`,()=>{let t=zn(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),Gn(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of Kn(e.listArtifacts()).slice(n))for(let n of Object.values(t))Gn(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&Rn(i.charge.bytes,t)?`${Hn(i.charge)} approaching limit ${Nn(t)} MB (v8 heap ${Nn(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:Kn(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function u(t=6e4){let n,r=!0,i=async()=>{try{if(await o())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}r&&(n=setTimeout(()=>void i(),t),n.unref())};return i(),{disarm:()=>{r=!1,clearTimeout(n)}}}return{check:o,describeNextRestart:c,serving:l,arm:u}}function Hn(e){return e.kind===`charged`?`${e.measure} ${Nn(e.bytes)} MB`:`rss ${Nn(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${Nn(e.gap)} MB gap`} (standing in: ${e.unread})`}function Un(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function Wn({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${Nn(e.gap)}MB`:``;return`measure=${Un(e)} charge=${Nn(e.bytes)}MB rss=${Nn(t)}MB heap=${Nn(n)}MB limit=${Nn(r)}MB${i}`}function Gn(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function Kn(e){let t=new Map;for(let n of e){let e=s.basename(n),r=Bn(e);if(r===null)continue;let{prefix:i,suffix:a}=Fn[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(Fn);return[...t].sort(([e],[t])=>In(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function qn(e,t,n={}){let r=_t();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:wn(process.platform,process.pid),captureMemoryReport:()=>xn(Cn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>se.writeHeapSnapshot(e),listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>Bn(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function Jn(e={}){if(ur()!==null)return;let n=e.spawn??dr,r=sr();if(r.kind===`contended`){let e=Xn();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),Yn(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),Yn(n);return}try{Yn(n)}finally{lr()}}function Yn(e){rr()&&Zn(e)}function Xn(){try{let e=p.statSync(Dt());return Date.now()-e.mtimeMs}catch{return null}}function Zn(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -69,18 +69,18 @@ import{createRequire as e}from"node:module";import t from"node:process";import{U
|
|
|
69
69
|
`).map(e=>n+e).join(`
|
|
70
70
|
`)}function ZT(e){let t=new TextEncoder;return e.split(/\s+/).filter(e=>e.length>0).map(e=>String.fromCharCode(...t.encode(e).slice(0,1))).join(``)}function QT(e,t){let n=[];for(let e of t){if(typeof e==`object`&&e)throw Bw(`join`,2,`list of strings/primitives`,`list element of type ${$T(e)}`);n.push(String(e))}return n.join(e)}function $T(e){return Array.isArray(e)?`array`:e instanceof Map?`Map`:e instanceof Set?`Set`:`object`}function eE(e){return UT(e,`-`)}function tE(e){return e.toLowerCase()}function nE(e,t){return`\n${XT(e,t)}`}function rE(e){return e.replace(/\s+/g,``)}function iE(e,t,n){return n===1?e:t}function aE(...e){return e.map(e=>`"${e}"`).join(` `)}function oE(e){return e.replace(/[\\.+*?()|[\]{}^$]/g,`\\$&`)}function sE(e,t){return t.repeat(Math.max(0,e))}function cE(e,t,n){return OT(e,n).join(t)}function lE(e){return UT(e,`_`)}function uE(e,t){let n=OT(e,t),r={};for(let e=0;e<n.length;e++)r[`_${e}`]=n[e];return r}function dE(e,t){return OT(e,t)}function fE(e,t,n){let r=pE(n,e,t),i={};for(let e=0;e<r.length;e++)i[`_${e}`]=r[e]??``;return i}function pE(e,t,n){if(n===0)return[];let r=OT(t,e);if(n<0||r.length<=n)return r;let i=r.slice(0,n-1),a=r.slice(n-1).join(t);return[...i,a]}function mE(...e){return e.map(e=>`'${e}'`).join(` `)}function hE(e,t,n){let r=DT(n),i=t<0||t>r.length?r.length:t,a=Math.min(Math.max(0,e),i);return r.slice(a,i).join(``)}function gE(e){let t=``;for(let n of e)_E(n)?t+=n.toLowerCase():vE(n)?t+=n.toUpperCase():t+=n;return t}function _E(e){return e!==e.toLowerCase()&&e===e.toUpperCase()}function vE(e){return e!==e.toUpperCase()&&e===e.toLowerCase()}function yE(e){return e.replace(/\b([a-zA-Z])/g,e=>e.toUpperCase())}function bE(e){return e.trim()}function xE(e,t){if(e.length===0)return t;let n=new Set(DT(e)),r=DT(t),i=0;for(;i<r.length&&n.has(r[i]);)i+=1;let a=r.length;for(;a>i&&n.has(r[a-1]);)--a;return r.slice(i,a).join(``)}function SE(e,t){return t.startsWith(e)?t.slice(e.length):t}function CE(e,t){return t.endsWith(e)?t.slice(0,t.length-e.length):t}function wE(e,t){let n=DT(t);if(e<0){let r=-e;return r>=n.length?t:n.slice(n.length-r).join(``)}return e>=n.length?t:n.slice(0,e).join(``)}function TE(e){return e.replace(/\b([A-Z])/g,e=>e.toLowerCase())}function EE(e){return e.toUpperCase()}function DE(e,t){return OE(e,`
|
|
71
71
|
`,t)}function OE(e,t,n){if(e<=0)return n;let r=[];for(let t of n.split(`
|
|
72
|
-
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function kE(e,t,n){return OE(e,t,n)}function AE(){return{abbrev:{fn:(e,t)=>kT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>AT(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>GT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>KT(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>qT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>JT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>YT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>XT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>ZT(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>QT(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>eE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>tE(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>nE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>rE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>iE(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>aE(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>oE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>sE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>cE(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>lE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>uE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>dE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>fE(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>mE(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>hE(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>gE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>yE(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>bE(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>xE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>SE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>CE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>wE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>TE(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>EE(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>DE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>kE(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function jE(e,t){let n=ME(e),r=n.copy();return r.style=Su(n.style,t),r}function ME(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function NE(e){return{fn:(t=>jE(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function PE(e){return{fn:((t,n)=>jE(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function FE(e,t){return new H({[e]:t})}function IE(){let e={};for(let t of gu)e[t]=NE(FE(t,!0)),e[`not_${t}`]=NE(FE(t,!1));for(let[t,n]of Object.entries(vu))e[t]=NE(FE(n,!0));return e}const LE={fn:((e,t)=>jE(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},RE={fn:((e,t)=>jE(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function zE(){return{fg:PE(`color`),bg:PE(`bgcolor`),...IE(),link:RE,style:LE}}function BE(e,t){let n;try{n=rc(e.trim())}catch(n){throw n instanceof zs?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return VE(n,t,JSON.stringify(e))}function VE(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function HE(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function UE(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const WE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`darken`),t).hex)),GE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`lighten`),-t).hex)),KE={min:0,max:100,note:`0 = from, 100 = toward`},qE=HE([`string`,`string`,`float`],((e,t,n)=>ic(BE(e,`mix`),BE(t,`mix`),UE(n,`mix`,`percentage`,KE)/100).hex)),JE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},YE=HE([`string`],(e=>Hc(BE(e,`contrastOn`)).hex)),XE={depth:z.TRUECOLOR},ZE=e=>HE([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uc(BE(t,`readableOn`),BE(n,`readableOn`),UE(r,`readableOn`,`ratio`,JE),i,void 0,a).hex})),QE={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function $E(){let e={};for(let[t,n]of Object.entries(QE)){let r=t;e[n]=HE([`string`,`float`],((e,t)=>{let i={...Sc,[r]:UE(t,n,`amount`)};return V.fromRgba(BE(e,n)).applyKey(i).toRgba().hex}))}return e}function eD(e=()=>XE){return{darken:WE,lighten:GE,mix:qE,contrastOn:YE,readableOn:ZE(e),...$E()}}function tD(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:VE(Pc(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function nD(e){return{color:{fn:(t=>Pc(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new su(Jl(n),tD(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function rD(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function iD(e){return{frames:{fn:((...t)=>dm(new um(rD(`frame`,t,ME).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=rD(`color`,t,e=>BE(e,`stepped`));return n[ru(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function aD(e){return{...zE(),...eD(e)}}new H({color:`red`,dim:!0});const oD=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,sD=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function cD(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(oD);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(sD);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function lD(e){let t=e.match(sD);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function uD(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function dD(e){return e.toLocaleString()}function fD(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function pD(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const mD=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hD=mD.length;function gD(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(hD-1));o+=mD[t]}return o}function _D(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function vD(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const yD=Lh(),bD=[...ig];function xD(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>uD(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(jb(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Ab(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Mb(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>yD,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>bD,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(vD(`sparkline`,[`width`],n),gD(_D(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>pD(e,fD(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function SD(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>dD(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>cD(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>lD(e),argTypes:[`string`],arity:{kind:`exact`}}}}function CD(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return DS({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...gw(),...AE(),...iT(),...ET(),...cw(t),...QS(),...Mw(),...Aw(),...aD(n&&(()=>({depth:n()}))),...iD(()=>t().getTime()/1e3),...xD(),...SD(t),...r??{}}})}function wD(e){return TD(e,new Set(e.names()),``)}function TD(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?DD(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return TD(e,t,a)}})}function ED(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function DD(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new Nb(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function OD(e){return p.existsSync(s.join(e,`.git`))}function kD(e){let t=s.resolve(e);for(;;){if(OD(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function AD(e){let t=kD(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function jD(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function MD(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const ND={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},PD={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function FD(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}function ID(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(LD(e,t))}function LD(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??RD(t.stderr)].filter(Boolean).join(`, `)}`}function RD(e){return e.trim().split(`
|
|
73
|
-
`,1)[0]??``}function
|
|
74
|
-
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function
|
|
75
|
-
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function
|
|
76
|
-
`).length:0)}async getRemotesAsync(e){let t=cO(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 JD(await this.execGitAsync(qD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=QD(e);return(n===null?null:eO(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=$D(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=KD(t);return n===`github`?rO(`gh pr view`,await this.execForgeAsync(VD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,oO):n===`gitlab`?rO(`glab mr view`,await this.execForgeAsync(VD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,sO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=ID(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(aO(t.value)):t}};const uO=(e,t)=>D(t);var dO=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??uO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},fO=class{running=new Set;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:(this.running.add(e),{kind:`started`,done:this.loop(e,t)})}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}};const pO={showSha:!0,showStashCount:!0};function mO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function hO(e){let t=t=>{try{return p.statSync(s.join(e,t)).mtimeMs}catch{return 0}};return{head:t(`HEAD`),index:t(`index`)}}function gO(e,t){return e.head!==t.head||e.index!==t.index}function _O(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}var vO=class extends lO{entries=new Map;subscribersByRepo=new Map;fetchInFlight=new Map;resolutions=new Map;prCache=new Map;prFetchInFlight=new Map;refreshes=new fO;hits=0;misses=0;invalidations=0;inner;ttlMs;maxEntries;watchers;ownsWatchers;logger;sanityTimer=null;constructor(e={}){super(),this.inner=e.inner??new lO,this.ttlMs=e.ttlMs??3e4,this.maxEntries=e.maxEntries??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new dO({logger:this.logger}),this.ownsWatchers=!0);let t=e.sanityIntervalMs??3e5;t>0&&(this.sanityTimer=setInterval(()=>this.runSanityCheck(),t),this.sanityTimer.unref())}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.entries.values())t.value.kind===`expired`&&e++;return{size:this.entries.size,expired:e,hits:this.hits,misses:this.misses,invalidations:this.invalidations,watchers:this.watchers.size()}}resolveEffectiveGitDir(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<this.ttlMs)return this.resolutions.delete(n),this.resolutions.set(n,i),i.dir;let a=this.inner.resolveEffectiveGitDir(e,t);return this.resolutions.set(n,{dir:a,computedAt:r}),a.catch(()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)}),this.evictResolutionsIfNeeded(),a}evictResolutionsIfNeeded(){for(;this.resolutions.size>this.maxEntries;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}}async getGitInfo(e,t={},n){let r=await this.resolveEffectiveGitDir(e,n);return r.kind===`ok`?this.getGitInfoForRoot(r.value,t):r}getGitInfoForRoot(e,t){let n=`${e}|${mO(t)}`,r=Date.now(),i=this.entries.get(n);if(i?.value.kind===`fresh`&&r-i.value.computedAt<this.ttlMs)return this.entries.delete(n),this.entries.set(n,i),this.hits++,Promise.resolve(F(i.value.info));let a=this.fetchInFlight.get(n);if(a)return a;let o=this.doFetch(e,n,t,r).finally(()=>{this.fetchInFlight.delete(n)});return this.fetchInFlight.set(n,o),o}async doFetch(e,t,n,r){this.misses++;let i=this.inner.resolveGitDir(e),a=hO(i),o=await this.inner.getGitInfo(e,n);if(o.kind===`absent`&&this.dropRepo(e),o.kind!==`ok`)return o;let s=o.value;n.showPullRequest&&(s.pullRequest=await this.getPullRequestCached(e,s.branch));let c={kind:`fresh`,info:s,computedAt:r,mtime:a},l=this.entries.get(t)??{value:c,watcher:this.watchers.acquire(`git:${e}`,_O(i),()=>this.invalidateRepo(e)),repoRoot:e};return l.value=c,this.entries.delete(t),this.entries.set(t,l),this.evictIfNeeded(),o}async getPullRequestCached(e,t){let n=await this.inner.getRepoRemoteUrl(e);if(n.kind===`failed`)return n;if(n.kind===`absent`)return I;let r=n.value,i=`${e}|${t}|${r}`,a=Date.now(),o=this.prCache.get(i);if(o){let e=o.pr.kind===`failed`?45e3:3e5;if(a-o.computedAt<e)return this.prCache.delete(i),this.prCache.set(i,o),o.pr}let s=this.prFetchInFlight.get(i);if(s)return s;let c=this.inner.resolvePullRequest(e,r).then(e=>(this.prCache.set(i,{pr:e,computedAt:Date.now()}),this.evictPrIfNeeded(),e)).finally(()=>{this.prFetchInFlight.delete(i)});return this.prFetchInFlight.set(i,c),c}evictPrIfNeeded(){for(;this.prCache.size>this.maxEntries;){let e=this.prCache.keys().next().value;if(e===void 0)break;this.prCache.delete(e)}}deliverable(e,t){return e.kind===`failed`?(this.logger(`warn`,`git fetch failed (${t}): ${e.reason}`),null):e.kind===`ok`?e.value:null}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){i.kind===`failed`&&this.logger(`warn`,`git resolve failed (subscribe ${e}): ${i.reason}`),this.safeInvoke(t,null);return}let a=i.value,o=this.subscribersByRepo.get(a);if(!o){let t=this.inner.resolveGitDir(a),n=this.watchers.acquire(`git:${a}`,_O(t),()=>this.invalidateRepo(a));o={workingDir:e,repoRoot:a,callbacks:new Set,watcher:n},this.subscribersByRepo.set(a,o)}o.callbacks.add(t),r={repoRoot:a,entry:o};let s=await this.getGitInfoForRoot(a,{...pO});n||this.safeInvoke(t,this.deliverable(s,a))})(),unsubscribe:()=>{if(n=!0,!r)return;let{repoRoot:e,entry:i}=r;i.callbacks.delete(t),i.callbacks.size===0&&(i.watcher.release(),this.subscribersByRepo.delete(e))}}}invalidateRepo(e){let t=0;for(let n of this.entries.values())n.repoRoot===e&&n.value.kind===`fresh`&&(n.value={kind:`expired`},t++);t>0&&(this.invalidations+=t,this.logger(`info`,`gitCache invalidate ${e} expired=${t}`)),this.refreshSubscribers(e)}refreshSubscribers(e){let t=this.subscribersByRepo.get(e);!t||t.callbacks.size===0||this.refreshes.run(e,()=>this.refreshOnce(e))}async refreshOnce(e){let t=this.subscribersByRepo.get(e);if(!t||t.callbacks.size===0)return;let n=await this.getGitInfoForRoot(e,{...pO}),r=this.deliverable(n,e),i=this.subscribersByRepo.get(e);if(!(!i||i.callbacks.size===0))for(let e of[...i.callbacks])i.callbacks.has(e)&&this.safeInvoke(e,r)}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}dropEntry(e){let t=this.entries.get(e);t&&(t.watcher.release(),this.entries.delete(e))}dropRepo(e){let t=0;for(let[n,r]of this.entries)r.repoRoot===e&&(this.dropEntry(n),t++);t>0&&this.logger(`info`,`gitCache drop ${e} entries=${t}`)}evictIfNeeded(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.dropEntry(e),this.logger(`info`,`gitCache evict ${e}`)}}runSanityCheck(){let e=new Map;for(let t of this.entries.values()){if(t.value.kind===`expired`)continue;let n=e.get(t.repoRoot);n||(n=hO(this.inner.resolveGitDir(t.repoRoot)),e.set(t.repoRoot,n)),gO(t.value.mtime,n)&&this.invalidateRepo(t.repoRoot)}}runSanityCheckNow(){this.runSanityCheck()}close(){this.sanityTimer&&=(clearInterval(this.sanityTimer),null);for(let e of this.entries.values())e.watcher.release();this.entries.clear();for(let e of this.subscribersByRepo.values())e.callbacks.clear(),e.watcher.release();this.subscribersByRepo.clear(),this.refreshes.clear(),this.fetchInFlight.clear(),this.prCache.clear(),this.prFetchInFlight.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}};const yO=/\r\n|\r|\n/g,bO=e=>F(e.replace(yO,` `).trim());function xO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(yO,` `))}}const SO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}},CO=e=>e.getTime()/1e3,wO=e=>new Date(e*1e3);function TO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function EO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const DO=`session.id`;function OO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function kO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function AO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const jO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],MO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],NO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],PO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function FO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>jO[e.getMonth()]],[`Monday`,e=>NO[e.getDay()]],[`Jan`,e=>MO[e.getMonth()]],[`Mon`,e=>PO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const IO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function LO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=IO[t];try{return GO(r,e)}catch{return KO(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function RO(e){try{return b(e)}catch{return e}}function zO(e){try{return ee(e).isDirectory()}catch{return!1}}function BO(e){let t=RO(e);return zO(t)?{dir:t,name:null,leaf:!0}:Cb(t)}const VO=e=>`${e.dir}\0${e.name??``}`;var HO=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:BO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=BO(e);if(t.watcher!==null&&VO(n)===VO(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},UO=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function WO(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function GO(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Ab(e):t===`number`?jb(e):Mb(e)}function KO(e){return e===`number`?0:e===`boolean`?!1:``}var qO=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new HO;ttlMgr=new UO;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new fO;abort=new AbortController;drawn=Db.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=Db.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return wO(e)};engine=CD({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new vO({sanityIntervalMs:0}),this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,kb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,OO(t,n.cwd,this.abort.signal),TO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,kO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,bO,t.default,n);case`regex`:return this.scalarPublisher(e,xO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=AO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=AO(s,SO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(wD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>FO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Pb(t)?new Nb(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=IO[t.field],r=t.varDefault===void 0?KO(n):GO(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,LO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(DO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(DO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=WO(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,GO(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(wD(this.store)).map(e=>e.plain).join(``))}catch(e){return Pb(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,Db.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,Db.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,GO(this.defaultEmptyValue,t))}catch{this.store.setBox(e,KO(t))}}defaultFor(e){try{return GO(this.defaultEmptyValue,e)}catch{return KO(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function JO(e,t){let n=nv[e],r=uv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const YO=Object.fromEntries([...vv].map(([e,t])=>[t,JO(e,t)])),XO={subscribers:`number`,fps:`number`,shown:`boolean`},ZO=Object.keys(XO),QO={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[DO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...YO,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(M_.flatMap(e=>ZO.map(t=>[I_(e,t),{kind:`input`,path:I_(e,t),type:XO[t],default:F_[t]}]))),[P_(`by`)]:{kind:`input`,path:P_(`by`),default:N_.by},[P_(`fps`)]:{kind:`input`,path:P_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},$O=`ne .tmux.pane ""`;function ek(e,t,n){let r=new Set,i=e=>{for(let t of pb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of Cg(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(DO);for(let t of Object.values(e.actions)){r.add(DO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?yv.get(t.set):void 0,n=`persist`in t?vv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function tk(e,t,n){let r=xb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of ek(e,t,n.helpers)){if(bb(a,r))continue;let e=QO[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function nk(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const rk=`groups.`,ik=`menus.`,ak=`edit.`,X=`candybar.`,ok=[rk,ik,ak,X];function sk(e){return ok.some(t=>e.startsWith(t))}function ck(e){let t=nk(e);return ok.find(e=>t.startsWith(nk(e)))}function lk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function uk(e){return e}function dk(e,t,n){return n===void 0?ik+nk(e)+`.`+nk(t):fk(n)}function fk(e){return ik+nk(e)}function pk(e,t){return e+`.`+t}function mk(e){return e+`.page`}const hk=[`closeOnPick`,`paged`,`key`,`distribution`],gk=e=>hk.includes(e),_k=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${jm.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function vk(e){for(let t of Object.keys(e))if(!gk(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${_k}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Mm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${jm.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Pm(r)}}const yk=e=>`from`in e?e.from:e.themes;function bk(e,t,n){return e===`bool`?hg(t)!==null:`min`in e?gg(t,e)!==null:Qy(yk(e),n).members.includes(t)}function xk(e,t){if(e===`bool`)return pg.join(` or `);if(!(`min`in e)){let n=yk(e),{members:r}=Qy(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function Sk(e){return{label:e.label,domain:Ck(e.domain)}}function Ck(e){return e===`theme`?{themes:Yy}:e===`bool`||`min`in e?e:{from:e}}function wk(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...pg]}},variables:{}};if(`from`in o)return Tk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return Tk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function Tk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=pk(n,t),s=`${t}.open`,c=mk(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const Ek=Object.fromEntries(Object.entries(nv).map(([e,t])=>[e,t.spec]));function Dk(e){return nv[e].domain}function Ok(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function kk(e){return Ok(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function Ak(e){return Ok(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function jk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Uh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Mk={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Nk={noun:`globals key`,fields:Ek,removed:Mk},Pk={preset:kk(`a preset`),menuGlyph:Ak(`a preset`)},Fk={noun:`preset globals key`,fields:{...Ek,...Pk},removed:Mk};function Ik(e){return Kk(e)&&!(e in Pk)}const Lk=`is decided later than any rule could be settled`,Rk={noun:`editGlobals key`,removed:Mk,fields:{...Ek,preset:kk(`the editGlobals fragment`),menuGlyph:Ak(`the editGlobals fragment`),palette:jk(Ek.palette,`the editGlobals fragment`,Lk),style:jk(Ek.style,`the editGlobals fragment`,Lk),effect:jk(Ek.effect,`the editGlobals fragment`,Lk)}},zk={noun:`theme default key`,fields:{...Object.fromEntries(ov.map(e=>[e,Ek[e]])),style:jk(Ek.style,`a theme's default`,`is the look that theme wears by name`)}};function Bk(e,t){if(!i_(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${a_(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Ph(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=o_(e,zk,t,i);a!==null&&(n[r]=a)}return n}function Vk(e,t,n){return n===void 0?{}:o_(e,Nk,t,n)??{}}function Hk(e,t,n){return o_(e,Fk,t,n)??{}}function Uk(){return D_(Fk)}function Wk(e,t,n){return o_(e,Rk,t,n)??{}}const Gk=new Set(Object.keys(Ek));function Kk(e){return Gk.has(e)}function qk(e){return Object.hasOwn(Mk,e)?Mk[e]:void 0}function Jk(){return[...Gk]}const Yk=new Map(Object.entries(nv).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function Xk(e){let t=new Map;for(let[n,r]of Yk){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const Zk=/^segments\.([^.]+)\.palette$/,Qk=/^presets\.(.+)\.root$/,$k=/^presets\.(.+)\.globals\.([^.]+)$/,eA=/^themeDefaults\.(.+)\.([^.]+)$/;function tA(e){return`presets.${e}.root`}function nA(e,t){return`themeDefaults.${e}.${t}`}const rA=e=>ov.includes(e);function iA(e,t){return`presets.${e}.globals.${t}`}function aA(e){if(Kk(e))return{scope:`globals`,field:e};let t=Zk.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=$k.exec(e);if(n&&Ik(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=eA.exec(e);if(r&&rA(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=Qk.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function oA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const sA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],cA=[...sA,`other`],lA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},uA=DS({fromString:e=>e}),dA=`edit.mode`,fA=`edit.configure`,pA=`edit.toggle`,mA=`edit.unconfigure`,hA=[pA,mA],gA=`arrange`,_A=`${ak}draft.`;function vA(e,t){return`${e}:${t}`}const yA={variable:dA,key:dA,member:gA},bA=$r(yA);function xA(e){try{return uA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function SA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&xA(e))return!0;return!1}function CA(e,t){if(lk(e,t,ak,`edit mode`),!SA(t))return;let{variables:n,actions:r}=wA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function wA(){return{variables:{[dA]:ii(dA,P),[fA]:ii(fA,P)},actions:{[pA]:ai(dA,gA),[mA]:{set:fA,to:P}}}}const TA=`open`;function EA(e,t,n,r){let i={variable:e,key:e,member:TA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,TA),r.segments[e]={template:ti(e,`(?)`,`✕`),...DA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function DA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const OA=`none`;function kA(e){return Pc(e,`background`)}var AA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function jA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=MA(n,i),l=c!==OA,u=l?c===void 0?o:NA(a,c,`bg`):kA(a);e.bg=u;let d=MA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:NA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function MA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function NA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new AA(t,n,e.message):e}}const PA=`🔧`,FA={help:[`-h`,`--help`],version:[`-V`,`--version`]},IA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],LA=Object.fromEntries(IA.map(e=>[e.member,e.label])),RA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},zA=Object.keys(RA),BA=bv(e=>pv[e].place),VA=e=>Object.hasOwn(RA,e),HA=(e,t)=>e===t||VA(e)&&HA(BA[RA[e].beside],t),UA=e=>VA(e)?`${UA(BA[RA[e].beside])} › ${RA[e].trigger}`:e===`door`?`first line`:LA[e],WA=e=>UA(BA[e]),GA=()=>[`door`,...IA.map(e=>e.member)].flatMap(e=>[e,...zA.filter(t=>HA(t,e))]).map(e=>({path:UA(e),names:mv.filter(t=>BA[t]===e)})).filter(({names:e})=>e.length>0),KA=e=>`${j_[e].label} is off — turn it on in the settings menu's ${WA(j_[e].setting)}, or set globals.${j_[e].setting}: true`,qA=[...new Set(Object.values(j_).map(e=>WA(e.setting)))].join(` or `),JA=Math.max(...Object.values(pv).map(e=>e.configKey.length))+2,YA=[`✚ inserts`,`✖ removes`,`${PA} configures`,`↺ resets layout`],XA={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},ZA=`
|
|
72
|
+
`)){let n=``;for(let i of t.split(/\s+/))i.length!==0&&(n.length===0?n=i:n.length+1+i.length<=e?n+=` ${i}`:(r.push(n),n=i));n.length>0&&r.push(n)}return r.join(t)}function kE(e,t,n){return OE(e,t,n)}function AE(){return{abbrev:{fn:(e,t)=>kT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},abbrevboth:{fn:(e,t,n)=>AT(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},camelcase:{fn:e=>GT(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},cat:{fn:(...e)=>KT(...e),argTypes:[`string`],arity:{kind:`variadic`}},contains:{fn:(e,t)=>qT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasPrefix:{fn:(e,t)=>JT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},hasSuffix:{fn:(e,t)=>YT(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},indent:{fn:(e,t)=>XT(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},initials:{fn:e=>ZT(e),argTypes:[`string`],arity:{kind:`exact`}},join:{fn:(e,t)=>QT(e,t),argTypes:[`string`,`list`],arity:{kind:`exact`}},kebabcase:{fn:e=>eE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},lower:{fn:e=>tE(e),argTypes:[`string`],arity:{kind:`exact`}},nindent:{fn:(e,t)=>nE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},nospace:{fn:e=>rE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},plural:{fn:(e,t,n)=>iE(e,t,n),argTypes:[`string`,`string`,`int`],arity:{kind:`exact`},returnType:`string`},quote:{fn:(...e)=>aE(...e),argTypes:[`string`],arity:{kind:`variadic`}},regexQuoteMeta:{fn:e=>oE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},repeat:{fn:(e,t)=>sE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},replace:{fn:(e,t,n)=>cE(e,t,n),argTypes:[`string`,`string`,`string`],arity:{kind:`exact`}},snakecase:{fn:e=>lE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},split:{fn:(e,t)=>uE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitList:{fn:(e,t)=>dE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},splitn:{fn:(e,t,n)=>fE(e,t,n),argTypes:[`string`,`int`,`string`],arity:{kind:`exact`},returnType:`dict`},squote:{fn:(...e)=>mE(...e),argTypes:[`string`],arity:{kind:`variadic`}},substr:{fn:(e,t,n)=>hE(e,t,n),argTypes:[`int`,`int`,`string`],arity:{kind:`exact`}},swapcase:{fn:e=>gE(e),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},title:{fn:e=>yE(e),argTypes:[`string`],arity:{kind:`exact`}},trim:{fn:e=>bE(e),argTypes:[`string`],arity:{kind:`exact`}},trimAll:{fn:(e,t)=>xE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimPrefix:{fn:(e,t)=>SE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trimSuffix:{fn:(e,t)=>CE(e,t),argTypes:[`string`,`string`],arity:{kind:`exact`}},trunc:{fn:(e,t)=>wE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},untitle:{fn:e=>TE(e),argTypes:[`string`],arity:{kind:`exact`}},upper:{fn:e=>EE(e),argTypes:[`string`],arity:{kind:`exact`}},wrap:{fn:(e,t)=>DE(e,t),argTypes:[`int`,`string`],arity:{kind:`exact`}},wrapWith:{fn:(e,t,n)=>kE(e,t,n),argTypes:[`int`,`string`,`string`],arity:{kind:`exact`}}}}function jE(e,t){let n=ME(e),r=n.copy();return r.style=Su(n.style,t),r}function ME(e){if(!(e instanceof G))throw TypeError(`template function expected a RichText fragment, got ${typeof e==`object`?Object.prototype.toString.call(e):typeof e}`);return e}function NE(e){return{fn:(t=>jE(t,e)),argTypes:[`liftable`],arity:{kind:`exact`},returnType:`T`}}function PE(e){return{fn:((t,n)=>jE(n,new H({[e]:B.parse(t)}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`}}function FE(e,t){return new H({[e]:t})}function IE(){let e={};for(let t of gu)e[t]=NE(FE(t,!0)),e[`not_${t}`]=NE(FE(t,!1));for(let[t,n]of Object.entries(vu))e[t]=NE(FE(n,!0));return e}const LE={fn:((e,t)=>jE(t,H.parse(e))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`},RE={fn:((e,t)=>jE(t,new H({link:e}))),argTypes:[`string`,`liftable`],arity:{kind:`exact`},returnType:`T`};function zE(){return{fg:PE(`color`),bg:PE(`bgcolor`),...IE(),link:RE,style:LE}}function BE(e,t){let n;try{n=rc(e.trim())}catch(n){throw n instanceof zs?TypeError(`${t} expected a color (#RRGGBB or #RRGGBBAA), got ${JSON.stringify(e)} — to use a palette name here, wrap it: ${t} (color ${JSON.stringify(e)}) …`,{cause:n}):n}return VE(n,t,JSON.stringify(e))}function VE(e,t,n){if(e.alpha===0)throw RangeError(`${t} got ${n}, which is fully transparent: it draws no colour of its own, so there is nothing to compute with — use the colour of the surface it sits on, e.g. (color "background")`);return e}function HE(e,t){return{fn:t,argTypes:e,arity:{kind:`exact`},returnType:`string`}}function UE(e,t,n,r){let i=r===void 0||e>=r.min&&e<=r.max;if(!Number.isFinite(e)||!i){let i=r===void 0?`a finite number`:`within ${r.min}..${r.max} (${r.note})`;throw RangeError(`${t}'s ${n} must be ${i}, got ${e}`)}return e}const WE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`darken`),t).hex)),GE=HE([`string`,`int`],((e,t)=>Bc(BE(e,`lighten`),-t).hex)),KE={min:0,max:100,note:`0 = from, 100 = toward`},qE=HE([`string`,`string`,`float`],((e,t,n)=>ic(BE(e,`mix`),BE(t,`mix`),UE(n,`mix`,`percentage`,KE)/100).hex)),JE={min:1,max:21,note:`4.5 = AA body text, 3 = AA large text`},YE=HE([`string`],(e=>Hc(BE(e,`contrastOn`)).hex)),XE={depth:z.TRUECOLOR},ZE=e=>HE([`string`,`string`,`float`],((t,n,r)=>{let{depth:i,terminal:a}=e();return Uc(BE(t,`readableOn`),BE(n,`readableOn`),UE(r,`readableOn`,`ratio`,JE),i,void 0,a).hex})),QE={hueShift:`shiftHue`,chromaScale:`scaleChroma`,lightnessScale:`scaleLightness`,lightnessShift:`shiftLightness`};function $E(){let e={};for(let[t,n]of Object.entries(QE)){let r=t;e[n]=HE([`string`,`float`],((e,t)=>{let i={...Sc,[r]:UE(t,n,`amount`)};return V.fromRgba(BE(e,n)).applyKey(i).toRgba().hex}))}return e}function eD(e=()=>XE){return{darken:WE,lighten:GE,mix:qE,contrastOn:YE,readableOn:ZE(e),...$E()}}function tD(e,t){if(e.length%2!=0)throw RangeError(`ramp's last stop (position ${String(e[e.length-1])}) has no color — stops are <position> <color> pairs`);let n=[];for(let r=0;r<e.length;r+=2)n.push({at:e[r],color:VE(Pc(t,e[r+1]),`ramp`,JSON.stringify(e[r+1]))});return n}function nD(e){return{color:{fn:(t=>Pc(e(),t).hex),argTypes:[`string`],arity:{kind:`exact`},returnType:`string`},ramp:{fn:((t,n,...r)=>new su(Jl(n),tD(r,e())).at(t).hex),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:4},returnType:`string`}}}function rD(e,t,n){if(t.length%2!=0)throw RangeError(`last hold (${String(t[t.length-1])} s) has no ${e} — the arguments are <seconds> <${e}> pairs`);let r=[];for(let e=0;e<t.length;e+=2){let i=t[e];if(!Number.isFinite(i)||i<=0)throw RangeError(`hold ${e/2} must be a positive number of seconds, got ${i}`);r.push({seconds:i,value:n(t[e+1])})}return r}function iD(e){return{frames:{fn:((...t)=>dm(new um(rD(`frame`,t,ME).map(({seconds:e,value:t})=>({seconds:e,text:t}))),e())),argTypes:[`float`,`liftable`],arity:{kind:`alternating`,minimum:2},returnType:`T`},stepped:{fn:((...t)=>{let n=rD(`color`,t,e=>BE(e,`stepped`));return n[ru(n.map(e=>e.seconds)).at(e())].value.hex}),argTypes:[`float`,`string`],arity:{kind:`alternating`,minimum:2},returnType:`string`}}}function aD(e){return{...zE(),...eD(e)}}new H({color:`red`,dim:!0});const oD=/^(?:(?:global|apac|au|eu|us|us-east-\d|us-west-\d|eu-west-\d|eu-central-\d)\.)?(?:anthropic\.|azure_ai\/|bedrock\/|vertex_ai\/)?claude-(?:(?<family>opus|sonnet|haiku)-(?<newMajor>\d+)(?:-(?<newMinor>\d))?|(?<oldMajor>\d+)(?:-(?<oldMinor>\d))?-(?<oldFamily>opus|sonnet|haiku))(?:[-@]\d{8})?(?:-v\d+:\d+)?(?:-latest)?$/i,sD=/^(?<family>opus|sonnet|haiku)\s+(?<major>\d+)(?:\.(?<minor>\d))?$/i;function cD(e){if(!e)return`Claude`;let t=e.trim().replace(/\s*\([^)]*\)\s*$/,``).replace(/\s*\[[^\]]*\]\s*$/,``).trim(),n=t.match(oD);if(n?.groups){let{family:e,newMajor:t,newMinor:r,oldMajor:i,oldMinor:a,oldFamily:o}=n.groups,s=e||o,c=t||i,l=r||a;if(s&&c)return`${s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()} ${l?`${c}.${l}`:c}`}let r=t.match(sD);if(r?.groups){let e=r.groups.family,t=r.groups.major,n=r.groups.minor;return`${e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()} ${n?`${t}.${n}`:t}`}return t||e}function lD(e){let t=e.match(sD);if(!t?.groups)return e;let n=t.groups.family,r=t.groups.major,i=t.groups.minor;return`${n.charAt(0).toUpperCase()}${i?`${r}.${i}`:r}`}function uD(e){let t=e.split(`/`),n=t.length-1;return t.map((e,t)=>{if(t===n)return e;let r=e.match(/^\.*./);return r?r[0]:e}).join(`/`)}function dD(e){return e.toLocaleString()}function fD(e){if(e.length===0)throw Error(`a cascade needs at least one stop, e.g. "0:calm"`);let t=[];for(let[n,r]of e.entries()){let e=r.indexOf(`:`),i=e<0?NaN:Number(r.slice(0,e));if(!Number.isFinite(i))throw Error(`cascade stop ${n} ("${r}") must be "<position>:<result>", e.g. "80:hot" — the position must be a number`);let a=t[n-1];if(a!==void 0&&i<a.at)throw Error(`cascade stops must be in ascending position order; stop ${n} at ${i} follows stop ${n-1} at ${a.at}`);t.push({at:i,text:r.slice(e+1)})}return t}function pD(e,t){if(!Number.isFinite(e))throw Error(`a cascade needs a finite value, got ${e}`);let n=-1;for(;n+1<t.length&&t[n+1].at<=e;)n++;return(n<0?t[0]:t[n]).text}const mD=[`▁`,`▂`,`▃`,`▄`,`▅`,`▆`,`▇`,`█`],hD=mD.length;function gD(e,t){let n=t===void 0?e:t<=0?[]:e.slice(-t);if(n.length===0)return``;let r=n[0],i=n[0];for(let e of n)e<r&&(r=e),e>i&&(i=e);let a=i-r,o=``;for(let e of n){let t=a===0?0:Math.round((e-r)/a*(hD-1));o+=mD[t]}return o}function _D(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(e===``)continue;let r=Number(e);if(!Number.isFinite(r))throw TypeError(`sparkline: non-numeric series element ${JSON.stringify(n)}`);t.push(r)}return t}function vD(e,t,n){if(n.length!==0)throw Error(`${e}: takes at most ${t.length} optional argument${t.length===1?``:`s`} (${t.join(`, `)}), got ${t.length+n.length}`)}const yD=Lh(),bD=[...ig];function xD(){return{basename:{fn:e=>c(e),argTypes:[`string`],arity:{kind:`exact`}},dirname:{fn:e=>l(e),argTypes:[`string`],arity:{kind:`exact`}},abbreviatePath:{fn:e=>uD(e),argTypes:[`string`],arity:{kind:`exact`}},int:{fn:e=>Math.trunc(jb(e)),argTypes:[`value`],arity:{kind:`exact`}},string:{fn:e=>Ab(e),argTypes:[`value`],arity:{kind:`exact`}},bool:{fn:e=>Mb(e),argTypes:[`value`],arity:{kind:`exact`}},urlEncode:{fn:e=>encodeURIComponent(e),argTypes:[`string`],arity:{kind:`exact`}},themes:{fn:()=>yD,argTypes:[],arity:{kind:`exact`}},endcaps:{fn:()=>bD,argTypes:[],arity:{kind:`exact`}},sparkline:{fn:(e,t,...n)=>(vD(`sparkline`,[`width`],n),gD(_D(e),t)),argTypes:[`string`,`int`],arity:{kind:`variadic`}},cascade:{fn:(e,...t)=>pD(e,fD(t)),argTypes:[`float`,`string`],arity:{kind:`variadic`}}}}function SD(e){return{minutesUntilReset:{fn:t=>Math.round(Math.max(0,t*1e3-e().getTime())/6e4),argTypes:[`int`],arity:{kind:`exact`}},formatInteger:{fn:e=>dD(e),argTypes:[`int`],arity:{kind:`exact`}},round:{fn:e=>Math.round(e),argTypes:[`float`],arity:{kind:`exact`}},formatModelName:{fn:e=>cD(e),argTypes:[`string`],arity:{kind:`exact`}},shortenModelName:{fn:e=>lD(e),argTypes:[`string`],arity:{kind:`exact`}}}}function CD(e){let{clock:t,drawnAt:n,extraFuncs:r}=e;return DS({fromString:e=>new G(e),toString:e=>e.plain,isT:e=>e instanceof G,clock:t,missingKey:`error`,funcs:{...gw(),...AE(),...iT(),...ET(),...cw(t),...QS(),...Mw(),...Aw(),...aD(n&&(()=>({depth:n()}))),...iD(()=>t().getTime()/1e3),...xD(),...SD(t),...r??{}}})}function wD(e){return TD(e,new Set(e.names()),``)}function TD(e,t,n){return new Proxy(Object.create(null),{has(e,r){if(typeof r!=`string`)return!1;let i=n?`${n}.${r}`:r;if(t.has(i))return!0;let a=`${i}.`;for(let e of t)if(e.startsWith(a))return!0;return!1},get(r,i){if(typeof i!=`string`)return;let a=n?`${n}.${i}`:i;if(t.has(a))return e.getKind(a)===`document`?DD(a,e.readDocument(a)):e.read(a);let o=`${a}.`;for(let n of t)if(n.startsWith(o))return TD(e,t,a)}})}function ED(e,t){return new Proxy(e,{has:(e,t)=>t===`settings`||Reflect.has(e,t),get:(e,n)=>n===`settings`?t:Reflect.get(e,n)})}function DD(e,t){switch(t.kind){case`ok`:return t.value;case`absent`:throw new Nb(e,`variable "${e}" has no value yet: its source has not completed a scan`);case`failed`:throw Error(`variable "${e}": ${t.reason}`)}}function OD(e){return p.existsSync(s.join(e,`.git`))}function kD(e){let t=s.resolve(e);for(;;){if(OD(t))return t;let e=s.dirname(t);if(e===t)return;t=e}}function AD(e){let t=kD(e);return t===void 0?{root:s.resolve(e),git:!1}:{root:t,git:!0}}function jD(e,t){return e.kind===`absent`?F(`none`):e.kind===`failed`?e:t.kind===`failed`?t:F(t.kind===`ok`?`tracked`:`gone`)}function MD(e,t){return e.kind!==`ok`||e.value.state===`open`?e:t.kind===`failed`?L(`HEAD: ${t.reason}`):t.kind===`ok`&&t.value===e.value.head?e:{kind:`earlier`,value:e.value}}const ND={OPEN:`open`,MERGED:`merged`,CLOSED:`closed`},PD={opened:`open`,locked:`open`,merged:`merged`,closed:`closed`};function FD(e,t,n){return Object.hasOwn(t,n)?F(t[n]):L(`${e}: unknown state ${JSON.stringify(n)}`)}const ID={aheadBehind:`aheadBehind`,head:`head`,sha:`sha`,operation:`operation`,tag:`tag`,committedAt:`timeSinceCommit`,stashCount:`stash`,upstream:`upstream`,repoName:`repoName`,repoUrl:`repoUrl`};function LD(e){return Object.keys(ID).flatMap(t=>{let n=e[t];return n?.kind===`failed`?[`git.${ID[t]}: ${n.reason}`]:[]})}function RD(e,t,n){return t.ok?F(t.stdout):t.reason===`non-zero`&&n===`absent`||t.reason===`non-zero`&&n===t.exitCode?I:L(zD(e,t))}function zD(e,t){return`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??BD(t.stderr)].filter(Boolean).join(`, `)}`}function BD(e){return e.trim().split(`
|
|
73
|
+
`,1)[0]??``}function VD(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function HD(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const UD={github:`gh`,gitlab:`glab`};function WD(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const GD=/^[A-Za-z]:[\\/]/;function KD(e){let t=e.trim();if(GD.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 qD(e){return KD(e)?.host||null}function JD(e){let t=qD(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const YD=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function XD(e){let t=RD(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?ZD(t.value):[]}}function ZD(e){let t=new Map;for(let n of e.split(`
|
|
74
|
+
`)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function QD(e){return e.urls.find(e=>rO(e)!==null)??e.urls[0]??null}function $D(e){return e.find(e=>e.name===`origin`)??e[0]??null}function eO(e){let t=$D(e);return t?QD(t):null}function tO(e){let t=$D(e);return t?t.urls.find(e=>JD(e)!==null)??QD(t):null}function nO(e){let t=(KD(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function rO(e){let t=KD(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 iO(e){let t=eO(e);return t===null?null:rO(t)}function aO(e,t,n,r){return t.ok?r(t.stdout):WD(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??BD(t.stderr)].filter(Boolean).join(`, `)}`)}function oO(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sO(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
|
|
75
|
+
`)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?I:F(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=F(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=F({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function cO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oO(t))return L(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`gh pr view: missing number/state/url/headRefOid`);let o=FD(`gh pr view`,ND,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function lO(e){let t;try{t=JSON.parse(e)}catch(e){return L(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!oO(t))return L(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return L(`glab mr view: missing iid/state/web_url/sha`);let o=FD(`glab mr view`,PD,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function uO(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var dO=class{isGitRepo(e){return OD(e)}async execGitAsync(e,t){return lt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}async resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}async findGitRoot(e){let t=kD(e);return t===void 0?I:F(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return L(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=await this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=VD(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showTimeSinceCommit&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=VD(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=VD(s,iO)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),F(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?F(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?F(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?F(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?F(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?F(`REBASE`):I}catch(e){return L(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return HD(RD(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestampMs(e,t.value):t}commitTimes=new Map;async commitTimestampMs(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestampMs(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestampMs(e,t){let n=HD(RD(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10)*1e3;return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`):F(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?F(0):L(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return F(r?r.split(`
|
|
76
|
+
`).length:0)}async getRemotesAsync(e){let t=uO(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 XD(await this.execGitAsync(YD,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=eO(e);return(n===null?null:nO(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=tO(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return lt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JD(t);return n===`github`?aO(`gh pr view`,await this.execForgeAsync(UD.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,cO):n===`gitlab`?aO(`glab mr view`,await this.execForgeAsync(UD.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,lO):I}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){D(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=RD(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(sO(t.value)):t}};const fO=(e,t)=>D(t);var pO=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??fO}acquire(e,t,n){if(this.closed)return{release:()=>{}};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(e);let i={key:e,watchers:[],refcount:1,debounceTimer:null,onInvalidate:n,targets:t};return this.openWatchers(i),this.slots.set(e,i),this.counters&&this.counters.watchersOpened++,this.makeHandle(e)}makeHandle(e){let t=!1;return{release:()=>{if(t)return;t=!0;let n=this.slots.get(e);n&&(n.refcount=Math.max(0,n.refcount-1),n.refcount===0&&(this.closeSlot(n),this.slots.delete(e)))}}}openWatchers(e){let t=()=>{e.debounceTimer||(e.debounceTimer=setTimeout(()=>{e.debounceTimer=null;try{e.onInvalidate()}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50),e.debounceTimer.unref())};for(let n of e.targets.files)try{let r=p.watch(n,{persistent:!1},t);r.on(`error`,e=>{this.logger(`warn`,`watcher error ${n}: ${e.message}`)}),e.watchers.push(r)}catch(e){this.logger(`warn`,`watch failed ${n}: ${e.message}`)}for(let n of e.targets.dirs)try{let r=n.filenames?new Set(n.filenames):null,i=p.watch(n.path,{persistent:!1},(e,n)=>{r&&(!n||!r.has(n))||t()});i.on(`error`,e=>{this.logger(`warn`,`watcher error ${n.path}: ${e.message}`)}),e.watchers.push(i)}catch(e){this.logger(`warn`,`watch failed ${n.path}: ${e.message}`)}}closeSlot(e){e.debounceTimer&&=(clearTimeout(e.debounceTimer),null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}},mO=class{running=new Map;again=new Set;run(e,t){return this.again.add(e),this.running.has(e)?{kind:`queued`}:{kind:`started`,done:this.start(e,t)}}share(e,t){let n=this.running.get(e);return n===void 0?(this.again.add(e),this.start(e,t)):n}start(e,t){let n=this.loop(e,t);return this.running.set(e,n),n}async loop(e,t){try{do this.again.delete(e),await t();while(this.again.has(e))}finally{this.running.delete(e),this.again.delete(e)}}clear(){this.running.clear(),this.again.clear()}get size(){return this.running.size}},hO=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)}};const gO=`pass`,_O={okMs:5*6e4,failedMs:45e3};function vO(e){return e.kind===`failed`?_O.failedMs:_O.okMs}const yO={showSha:!0,showStashCount:!0};function bO(){let e;return{kind:`pending`,landed:new Promise(t=>{e=t}),land:e}}function xO(e,t){let n=e.reading;e.reading={kind:`read`,outcome:t},n.kind===`pending`&&n.land()}function SO(e,t){e.reading.kind===`pending`&&xO(e,t)}async function CO(e){let t=e.reading;return t.kind===`read`?t.outcome:(await t.landed,CO(e))}function wO(e){return e.holders>0||e.subscriptions>0}function TO(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function EO(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 DO(e){for(let t of e.values.values())if(t.reading.kind===`read`&&t.reading.outcome.kind===`ok`)return t.reading.outcome.value.branch}function OO(e){return t=>L(`${e} threw: ${String(t)}`)}var kO=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;refreshCount=0;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new dO,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Oe,e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new pO({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,refreshes:this.refreshCount,watchers:this.watchers.size()}}resolveEffectiveGitDir(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.dir;let a=this.inner.resolveEffectiveGitDir(e,t);for(this.resolutions.set(n,{dir:a,computedAt:r}),a.then(t=>{t.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${t.reason}`)},()=>{this.resolutions.get(n)?.dir===a&&this.resolutions.delete(n)});this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}getGitInfo(e,t,n={},r){return this.read(e,t,n,r).catch(e=>(this.logger(`error`,`git read threw: ${String(e)}`),L(`git: ${String(e)}`)))}async read(e,t,n,r){let i=await this.resolveEffectiveGitDir(t,r);if(i.kind!==`ok`)return i;let a=this.repo(i.value);e.take(`git:${a.root}`,()=>this.hold(a));let{showPullRequest:o,...s}=n,{value:c,pr:l}=this.ask(a,s,o===!0);c.reading.kind===`pending`?this.misses++:this.hits++;let u=await CO(c);if(l===null||u.kind!==`ok`)return u;let d=await CO(l),f=await CO(c);return f.kind===`ok`?F({...f.value,pullRequest:d}):f}subscribe(e,t){let n=!1,r=null;return{firstDelivery:(async()=>{let i=await this.resolveEffectiveGitDir(e);if(n)return;if(i.kind!==`ok`){this.safeInvoke(t,null);return}let a=this.repo(i.value);a.subscriptions++,this.used(a),r={state:a,release:()=>{a.subscriptions--}};let{value:o}=this.ask(a,yO,!1),s=await CO(o);n||(this.safeInvoke(t,s.kind===`ok`?s.value:null),a.subscribers.add(t))})(),unsubscribe:()=>{n=!0,r&&=(r.state.subscribers.delete(t),r.release(),null)}}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,!wO(t)){t.changedUnused=!0;return}this.changedPass(t,`watch`)}}repo(e){let t=this.repos.get(e);if(t)return this.repos.delete(e),this.repos.set(e,t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new mO,watcher:this.watchers.acquire(`git:${e}`,EO(n),()=>this.changed(e)),period:new hO(()=>{r.refresh.share(gO,()=>this.refreshPass(r))}),values:new Map,subscribers:new Set,holders:0,subscriptions:0,changedUnused:!1,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(gO,()=>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){return e.holders++,this.held(e),this.used(e),()=>{e.holders--,this.held(e)}}used(e){e.changedUnused&&(e.changedUnused=!1,this.changedPass(e,`resume`)),this.evict()}held(e){let t=e.holders>0;e.period.hold(t),e.pr?.period.hold(t)}ask(e,t,n){let r=e.asked.size,i=TO(t),a=e.values.get(i);return a===void 0&&(a={options:t,reading:bO()},e.values.set(i,a),e.asked.add(`first`)),n&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`)),e.asked.size>r&&e.refresh.run(gO,()=>this.refreshPass(e)),{value:a,pr:n?e.pr:null}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=e.asked.size===0?`period`:[...e.asked].join(`,`);e.asked.clear();let r=[...e.values.values()],i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(OO(`git fetch`)))),i===null?null:this.remoteOf(e)]);if(this.repos.get(e.root)!==e)return;this.refreshCount++;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(xO(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of LD(n.value))s.add(e)});for(let t of s)this.logger(`warn`,`git refresh failed (${e.root}): ${t}`);this.deliver(e);let c=DO(e),l=i!==null&&o!==null&&c!==void 0?this.movePr(e,i,c,o):`-`;this.logger(`info`,`git refresh ${e.root} by=${n} values=${r.length} failed=${s.size} pr=${l} took=${Date.now()-t}ms`)}deliver(e){let t=e.values.get(TO(yO));if(t===void 0||t.reading.kind!==`read`)return;let n=t.reading.outcome,r=n.kind===`ok`?n.value:null;for(let t of[...e.subscribers])e.subscribers.has(t)&&this.safeInvoke(t,r)}prSource(e){let t={period:new hO(()=>{this.readPr(e,t)}),seen:new Map,key:``,remote:I,reading:bO(),inFlight:null};return t.period.hold(e.holders>0),t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(OO(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?(t.reading.kind===`read`&&(t.reading=bO()),this.readPr(e,t),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),xO(t,a.outcome),t.period.landed(vO(a.outcome),a.at),`recalled`)}readPr(e,t){let n=t.key;if(t.inFlight?.key===n)return t.inFlight.done;let r=t.remote,i=(r.kind===`ok`?this.inner.resolvePullRequest(e.root,r.value).catch(OO(`PR lookup`)):Promise.resolve(r.kind===`failed`?r:I)).then(r=>{if(t.inFlight?.key===n&&(t.inFlight=null),this.repos.get(e.root)!==e)return;r.kind===`failed`&&this.logger(`warn`,`git refresh failed (${e.root}): git.pr: ${r.reason}`);let i=Date.now();t.seen.delete(n),t.seen.set(n,{outcome:r,at:i});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key===n&&(xO(t,r),t.period.landed(vO(r),i))});return t.inFlight={key:n,done:i},i}safeInvoke(e,t){try{e(t)}catch(e){this.logger(`warn`,`git subscriber threw: ${e.message??String(e)}`)}}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())SO(n,t);e.pr!==null&&SO(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;wO(e)||(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()}};const AO=/\r\n|\r|\n/g,jO=e=>F(e.replace(AO,` `).trim());function MO(e){return t=>{let n=e.exec(t)?.[1];return n===void 0?L(`regex no-match`):F(n.replace(AO,` `))}}const NO=e=>{try{return F(JSON.parse(e))}catch(e){return L(`JSON parse failed: ${e.message}`)}};var PO=class{held=new Map;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.held.has(e)||this.held.set(e,t())}release(){let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}close(){return this.closed=!0,this.release()}get size(){return this.held.size}};const FO=e=>e.getTime()/1e3,IO=e=>new Date(e*1e3);function LO(e,t){return t.kind!==`ttl`||t.durationMs>=500?t:(D(`declareShell "${e}": ttl ${t.durationMs}ms below floor 500ms; clamping`),{kind:`ttl`,durationMs:500})}function RO(e){let t=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(e);if(!t)throw RangeError(`Invalid duration: "${e}"`);let n=parseFloat(t[1]);switch(t[2]){case`ms`:return n;case`s`:return n*1e3;case`m`:return n*6e4;case`h`:return n*36e5;default:throw RangeError(`Unexpected duration unit: "${t[2]}"`)}}const zO=`session.id`;function BO(e,t,n){return{where:`output of "${e}" in ${t}`,read:async()=>{let r=await lt({bin:`/bin/sh`,args:[`-c`,e],cwd:t,category:`user-shell`,signal:n});if(!r.ok&&r.reason===`aborted`)throw n.reason;return r.ok?F(r.stdout):L(`shell "${e}" ${r.exitCode===null?[r.reason,r.error].filter(e=>e!==void 0).join(`: `):`exited with code ${r.exitCode}`} in ${t}`)}}}function VO(e,t,n){return{where:`"${e}"`,read:async()=>{try{let r=await le(e,{encoding:`utf8`,signal:n});return F(t===`first-line`?r.split(/\r?\n/)[0]??``:r)}catch{if(n.aborted)throw n.reason;return L(`file unreadable: ${e}`)}}}}function HO(e,t,n){if(e.kind!==`ok`)return e;let r=t(e.value);return r.kind===`failed`?L(`${r.reason} in ${n}`):r}const UO=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],WO=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],GO=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],KO=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function qO(e,t){let n=[[`2006`,e=>String(e.getFullYear())],[`January`,e=>UO[e.getMonth()]],[`Monday`,e=>GO[e.getDay()]],[`Jan`,e=>WO[e.getMonth()]],[`Mon`,e=>KO[e.getDay()]],[`15`,e=>String(e.getHours()).padStart(2,`0`)],[`06`,e=>String(e.getFullYear()%100).padStart(2,`0`)],[`01`,e=>String(e.getMonth()+1).padStart(2,`0`)],[`02`,e=>String(e.getDate()).padStart(2,`0`)],[`04`,e=>String(e.getMinutes()).padStart(2,`0`)],[`05`,e=>String(e.getSeconds()).padStart(2,`0`)],[`PM`,e=>e.getHours()<12?`AM`:`PM`],[`pm`,e=>e.getHours()<12?`am`:`pm`],[`1`,e=>String(e.getMonth()+1)],[`2`,e=>String(e.getDate())],[`3`,e=>String(e.getHours()%12||12)],[`4`,e=>String(e.getMinutes())],[`5`,e=>String(e.getSeconds())]],r=``,i=0;for(;i<e.length;){let a=!1;for(let[o,s]of n)if(e.startsWith(o,i)){r+=s(t),i+=o.length,a=!0;break}a||(r+=e[i],i++)}return r}const JO={branch:`string`,sha:`string`,dirty:`boolean`,ahead:`number`,behind:`number`,stash:`number`};function YO(e,t,n,r){if(e===null){if(n!==void 0)return n;let e=JO[t];try{return rk(r,e)}catch{return ik(e)}}switch(t){case`branch`:return e.branch===`detached`?``:e.branch;case`sha`:return ta(e.sha,``);case`dirty`:return e.status!==`clean`;case`ahead`:return ta(e.aheadBehind,{ahead:0,behind:0}).ahead;case`behind`:return ta(e.aheadBehind,{ahead:0,behind:0}).behind;case`stash`:return ta(e.stashCount,0)}}function XO(e){try{return b(e)}catch{return e}}function ZO(e){try{return ee(e).isDirectory()}catch{return!1}}function QO(e){let t=XO(e);return ZO(t)?{dir:t,name:null,leaf:!0}:Cb(t)}const $O=e=>`${e.dir}\0${e.name??``}`;var ek=class{watchers=new Map;subscribe(e,t,n){let r=this.watchers.get(e)??this.arm(e);return r.subscribers.set(t,n),r.watcher===null&&n(r.failure),()=>this.unsubscribe(e,t)}arm(e){let t={watcher:null,failure:``,target:QO(e),subscribers:new Map};return t.watcher=this.open(e,t,t.target),this.watchers.set(e,t),t}rearm(e,t){let n=QO(e);if(t.watcher!==null&&$O(n)===$O(t.target))return;let r=this.open(e,t,n);r!==null&&(t.watcher?.close(),t.watcher=r,t.target=n)}open(e,t,n){let{dir:r,name:i}=n,a=s.basename(r);try{return x(r,(n,r)=>{if(!(r===null||i===null||r===i)&&r!==a)return;let o=t.target.leaf;if(this.rearm(e,t),!(!o&&!t.target.leaf))for(let e of t.subscribers.keys())e()})}catch(n){let i=`watch_file ${e}: cannot watch ${r} — ${n instanceof Error?n.message:String(n)}`;t.failure=i;for(let e of t.subscribers.values())e(i);return null}}unsubscribe(e,t){let n=this.watchers.get(e);n&&(n.subscribers.delete(t),n.subscribers.size===0&&(n.watcher?.close(),this.watchers.delete(e)))}dispose(){for(let{watcher:e}of this.watchers.values())e?.close();this.watchers.clear()}size(){return this.watchers.size}},tk=class{buckets=new Map;subscribe(e,t){let n=this.buckets.get(e);if(!n){let t=new Set;n={timer:me(()=>{for(let e of t)e()},e),callbacks:t},this.buckets.set(e,n)}return n.callbacks.add(t),()=>this.unsubscribe(e,t)}unsubscribe(e,t){let n=this.buckets.get(e);n&&(n.callbacks.delete(t),n.callbacks.size===0&&(fe(n.timer),this.buckets.delete(e)))}dispose(){for(let{timer:e}of this.buckets.values())fe(e);this.buckets.clear()}bucketCount(){return this.buckets.size}};function nk(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n)return;n=n[e]}return n}function rk(e,t){if(typeof e!=`string`&&typeof e!=`number`&&typeof e!=`boolean`)throw TypeError(`Expected string|number|boolean from payload, got ${typeof e}`);return t===`string`?Ab(e):t===`number`?jb(e):Mb(e)}function ik(e){return e===`number`?0:e===`boolean`?!1:``}var ak=class{inputMetas=new Map;lastErrors=new Map;policyFaults=new Map;watchMgr=new ek;ttlMgr=new tk;gitSubscriptions=new Map;cleanups=[];inFlight=new Map;reads=new mO;abort=new AbortController;drawn=Db.observable.box(z.TRUECOLOR);drawnAt=()=>this.drawn.get();instant=Db.observable.box(null);now=()=>{let e=this.instant.get();if(e===null)throw Error(`the time was read before any render published its instant`);return IO(e)};engine=CD({clock:this.now,drawnAt:this.drawnAt});gitProvider;ownsGitProvider;holds=new PO;sessionState;constructor(e,t=``,n,r){this.store=e,this.defaultEmptyValue=t,n?(this.gitProvider=n,this.ownsGitProvider=!1):(this.gitProvider=new kO,this.ownsGitProvider=!0),this.sessionState=r}get variableStore(){return this.store}declareLiteral(e,t){this.store.defineBox(e,kb(t),t)}declareFailedDocument(e,t){this.store.defineDocument(e,L(t))}declareInput(e,t,n,r){let i=r===void 0?this.defaultFor(n):r;this.store.defineBox(e,n,i),this.inputMetas.set(e,{path:t,varDefault:r})}declareEnv(e,t,n){let r=process.env[t];if(r!==void 0){this.store.defineBox(e,`string`,r);return}let i=n===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:n;this.store.defineBox(e,`string`,i),this.recordError(e,`env var "${t}" is not set`)}declareShell(e,t,n){this.declareSource(e,BO(t,n.cwd,this.abort.signal),LO(e,n.cache),n.parse)}declareFile(e,t,n){this.declareSource(e,VO(t,n.readMode??`whole`,this.abort.signal),n.cache,n.parse)}declareSource(e,t,n,r){let i=this.publisherFor(e,r,t.where),a=()=>this.runSource(e,t,i);a(),this.registerCachePolicy(e,n,a)}publisherFor(e,t,n){switch(t.kind){case`text`:return this.scalarPublisher(e,jO,t.default,n);case`regex`:return this.scalarPublisher(e,MO(t.regex),t.default,n);case`json`:return this.documentPublisher(e,t.default,n)}}scalarPublisher(e,t,n,r){let i=this.stringInitial(n);return this.store.defineBox(e,`string`,i),n=>{let a=HO(n,t,r);this.noteOutcome(e,a),this.store.setBox(e,ta(a,i))}}documentPublisher(e,t,n){let r=t===void 0?I:F(t);this.store.defineDocument(e,r);let i,a=!1;return this.cleanups.push(()=>clearTimeout(i)),o=>{clearTimeout(i);let s=o.kind===`ok`&&o.value.trim()===``?I:o,c=HO(s,NO,n);this.noteOutcome(e,c);let l=c.kind===`ok`||s.kind===`ok`||t===void 0?c:r,u=a&&s.kind===`ok`&&c.kind!==`ok`,d=()=>{a=c.kind===`ok`,this.store.setDocument(e,l)};u?i=setTimeout(d,250):d()}}runSource(e,t,n){let r=this.reads.run(e,()=>t.read().then(n,e=>{if(e!==this.abort.signal.reason)throw e}));r.kind===`started`&&this.track(e,r.done)}track(e,t){let n=t.finally(()=>{this.inFlight.get(e)===n&&this.inFlight.delete(e)});this.inFlight.set(e,n)}async settled(e){let t=Date.now()+e;for(;this.inFlight.size>0;){let e=t-Date.now();if(e<=0)break;let n,r=await Promise.race([Promise.all(this.inFlight.values()).then(()=>`settled`),new Promise(t=>{n=setTimeout(()=>t(`deadline`),e)})]);if(clearTimeout(n),r===`deadline`)break}return[...this.inFlight.keys()]}declareTemplate(e,t,n={}){let r=this.engine.parse(t);this.declareDerived(e,()=>r.evaluate(wD(this.store)).map(e=>e.plain).join(``),n.varDefault)}declareTime(e,t){this.declareDerived(e,()=>qO(t.format,this.now()),t.varDefault)}declareDerived(e,t,n){this.store.defineComputed(e,`string`,()=>{try{let n=t();return this.lastErrors.delete(e),n}catch(t){let r=t instanceof Error?t.message:String(t);if(this.recordError(e,r),n===void 0)throw Pb(t)?new Nb(e,`variable "${e}": ${r}`):Error(`variable "${e}": ${r}`);return n}})}declareGit(e,t){let n=JO[t.field],r=t.varDefault===void 0?ik(n):rk(t.varDefault,n);this.store.defineBox(e,n,r);let i=this.gitSubscriptions.get(t.cwd);if(!i){let e=new Map,n=this.gitProvider.subscribe(t.cwd,t=>{this.store.runInAction(()=>{for(let[n,r]of e)for(let{name:e,varDefault:i}of r)this.store.setBox(e,YO(t,n,i,this.defaultEmptyValue))})});i={fieldSubs:e,firstDelivery:n.firstDelivery,unsubscribe:n.unsubscribe},this.gitSubscriptions.set(t.cwd,i)}let a=i.fieldSubs.get(t.field);a||(a=[],i.fieldSubs.set(t.field,a)),a.push({name:e,varDefault:t.varDefault}),this.track(e,i.firstDelivery)}declareState(e,t){if(!this.sessionState)throw Error(`declareState("${e}"): SourceRegistry was constructed without a SessionState — state-kind variables require a SessionState (the daemon provides one; tests must supply one)`);let n=this.sessionState,r=t.varDefault??this.stringInitial(void 0);this.store.defineComputed(e,`string`,e=>{let i=e(zO);if(typeof i!=`string`||!i)return r;let a=n.get(i,t.key);return a===null?r:a})}stateRevision(){let e=this.store.has(`session.id`)?this.store.read(zO):``;return this.sessionState!==void 0&&typeof e==`string`&&e!==``?this.sessionState.revision(e):0}applyInput(e){this.store.runInAction(()=>{for(let[t,n]of this.inputMetas){let r=nk(e,n.path),i=this.store.getType(t);if(r!==void 0)try{this.store.setBox(t,rk(r,i)),this.lastErrors.delete(t)}catch(e){this.applyFallback(t,i,n.varDefault,e instanceof Error?e.message:String(e))}else this.applyFallback(t,i,n.varDefault,`input path "${n.path}" not found in payload`)}})}drawAt(e){this.store.runInAction(()=>this.drawn.set(e))}renderAt(e){this.store.runInAction(()=>this.instant.set(e))}getLastError(e){let t=this.lastErrors.get(e),n=this.policyFaults.get(e);return n===void 0?t:t===void 0?n:{timestamp:t.timestamp,message:`${n.message}; ${t.message}`}}cachePolicyFaults(){return this.policyFaults}dispose(){this.abort.abort();for(let e of this.cleanups)e();this.cleanups.length=0;for(let e of this.gitSubscriptions.values())e.unsubscribe();return this.gitSubscriptions.clear(),this.reads.clear(),this.watchMgr.dispose(),this.ttlMgr.dispose(),this.holds.close(),this.ownsGitProvider&&this.gitProvider.close(),this.store.dispose()}registerCachePolicy(e,t,n){switch(t.kind){case`never`:break;case`ttl`:{let e=this.ttlMgr.subscribe(t.durationMs,n);this.cleanups.push(e);break}case`watch_file`:{let r=this.watchMgr.subscribe(t.path,n,t=>this.notePolicy(e,L(t)));this.cleanups.push(r);break}case`key`:{let r=this.engine.parse(t.template),i=()=>{try{return F(r.evaluate(wD(this.store)).map(e=>e.plain).join(``))}catch(e){return Pb(e)?I:L(`cache key: ${e instanceof Error?e.message:String(e)}`)}},a=i();this.notePolicy(e,a);let o=a.kind===`ok`?a.value:void 0,s=(0,Db.reaction)(i,t=>{this.notePolicy(e,t),!(t.kind!==`ok`||t.value===o)&&(o=t.value,n())});this.cleanups.push(s);break}case`depends_on`:{let e=(0,Db.reaction)(()=>t.varNames.map(e=>this.store.changeKey(e)).join(`,`),n);this.cleanups.push(e);break}}}applyFallback(e,t,n,r){if(this.recordError(e,r),n!==void 0){this.store.setBox(e,n);return}try{this.store.setBox(e,rk(this.defaultEmptyValue,t))}catch{this.store.setBox(e,ik(t))}}defaultFor(e){try{return rk(this.defaultEmptyValue,e)}catch{return ik(e)}}stringInitial(e){return e===void 0?typeof this.defaultEmptyValue==`string`?this.defaultEmptyValue:``:e}recordError(e,t){this.lastErrors.set(e,{timestamp:Date.now(),message:t})}notePolicy(e,t){t.kind===`failed`?this.policyFaults.set(e,{timestamp:Date.now(),message:t.reason}):this.policyFaults.delete(e)}noteOutcome(e,t){t.kind===`ok`?this.lastErrors.delete(e):this.recordError(e,t.kind===`failed`?t.reason:`no value`)}};function ok(e,t){let n=nv[e],r=uv(e),i=n.kind===`session`||n.kind===`config`?n.floor:``;return r===`string`?{kind:`input`,path:t,default:``}:{kind:`input`,path:t,type:r,default:i}}const sk=Object.fromEntries([...vv].map(([e,t])=>[t,ok(e,t)])),ck={subscribers:`number`,fps:`number`,shown:`boolean`},lk=Object.keys(ck),uk={project_dir:{kind:`input`,path:`workspace.project_dir`,default:``},[zO]:{kind:`input`,path:`session_id`,default:``},transcript_path:{kind:`input`,path:`transcript_path`,default:``},resume_command:{kind:`input`,path:`resumeCommand`,default:``},config_path:{kind:`input`,path:`configPath`,default:``},...sk,"preset.customized":{kind:`input`,path:`preset.customized`,type:`boolean`,default:!1},"preset.bundled":{kind:`input`,path:`preset.bundled`,type:`boolean`,default:!0},...Object.fromEntries(M_.flatMap(e=>lk.map(t=>[I_(e,t),{kind:`input`,path:I_(e,t),type:ck[t],default:F_[t]}]))),[P_(`by`)]:{kind:`input`,path:P_(`by`),default:N_.by},[P_(`fps`)]:{kind:`input`,path:P_(`fps`),type:`number`,default:0},"term.cols":{kind:`input`,path:`term.cols`,type:`number`,default:80},"tmux.pane":{kind:`input`,path:`tmux.pane`,default:``},"autocompact.window":{kind:`input`,path:`autocompact.window`,type:`number`,default:-1},...Object.fromEntries([`applied`,`lower`,`higher`].map(e=>[`autocompact.${e}`,{kind:`input`,path:`autocompact.${e}`,type:`number`,default:0}])),"autocompact.error":{kind:`input`,path:`autocompact.error`,default:``},"git.repoUrl":{kind:`input`,path:`git.repoUrl`,default:``}},dk=`ne .tmux.pane ""`;function fk(e,t,n){let r=new Set,i=e=>{for(let t of pb(e??``,n).keys())r.add(t)};for(let t of Object.values(e.segments))i(t.template),i(t.bg),i(t.fg),i(t.when);for(let e of t)for(let t of Cg(e))i(t.when),t.kind===`segment`&&(i(t.lead),i(t.trail));for(let t of Object.values(e.variables))t.kind===`template`&&i(t.template),t.kind===`state`&&r.add(zO);for(let t of Object.values(e.actions)){r.add(zO),`copy`in t&&i(t.copy),`open`in t&&i(t.open);let e=`set`in t?yv.get(t.set):void 0,n=`persist`in t?vv.get(t.persist):void 0;e!==void 0&&r.add(e),n!==void 0&&r.add(n)}return r}function pk(e,t,n){let r=xb({...n,variables:{...n.variables,...e.variables},segments:{...n.segments,...e.segments}}),i={};for(let a of fk(e,t,n.helpers)){if(bb(a,r))continue;let e=uk[a];if(e===void 0)throw Error(`synthesized chrome reads ".${a}", which it does not declare and PAYLOAD_INPUTS does not supply`);i[a]=e}return i}function mk(e){return e.replace(/[^A-Za-z0-9]+/g,`_`)}const hk=`groups.`,gk=`menus.`,_k=`edit.`,X=`candybar.`,vk=[hk,gk,_k,X];function yk(e){return vk.some(t=>e.startsWith(t))}function bk(e){let t=mk(e);return vk.find(e=>t.startsWith(mk(e)))}function xk(e,t,n,r){for(let i of[`variables`,`actions`,`segments`])for(let a of Object.keys(t[i]??{}))a.startsWith(n)&&e.issues.push({path:`${i}.${a}`,message:`"${a}" is in the reserved "${n}" namespace (synthesized by ${r}) — rename it`,line:K(e.source,[`root`])})}function Sk(e){return e}function Ck(e,t,n){return n===void 0?gk+mk(e)+`.`+mk(t):wk(n)}function wk(e){return gk+mk(e)}function Tk(e,t){return e+`.`+t}function Ek(e){return e+`.page`}const Dk=[`closeOnPick`,`paged`,`key`,`distribution`],Ok=e=>Dk.includes(e),kk=`"closeOnPick" (bool, default false), "paged" (bool, default true), "key" (string, accordion grouping), "distribution" (one of ${jm.map(e=>`"${e}"`).join(`, `)}; default "van-der-corput")`;function Ak(e){for(let t of Object.keys(e))if(!Ok(t))throw Error(`unknown {{ menu }} option "${t}" — the options dict takes ${kk}`);let t=(t,n)=>{let r=e[t];if(r===void 0)return n;if(typeof r!=`boolean`)throw Error(`{{ menu }} option "${t}" must be a boolean, got ${JSON.stringify(r)} (e.g. (dict "${t}" ${String(!n)}))`);return r},n=e.key;if(n!==void 0&&typeof n!=`string`)throw Error(`{{ menu }} option "key" must be a string naming the accordion group, got ${JSON.stringify(n)}`);if(n===``)throw Error(`{{ menu }} has an empty accordion key — a shared key must be a non-empty name (or omit "key" for an independent menu)`);let r=e.distribution;if(r!==void 0&&!Mm(r))throw Error(`{{ menu }} option "distribution" must be one of: ${jm.join(`, `)}; got ${JSON.stringify(r)}`);return{closeOnPick:t(`closeOnPick`,!1),paged:t(`paged`,!0),key:n,distribution:Pm(r)}}const jk=e=>`from`in e?e.from:e.themes;function Mk(e,t,n){return e===`bool`?hg(t)!==null:`min`in e?gg(t,e)!==null:Qy(jk(e),n).members.includes(t)}function Nk(e,t){if(e===`bool`)return pg.join(` or `);if(!(`min`in e)){let n=jk(e),{members:r}=Qy(n,t),i=r.map(e=>JSON.stringify(e));if(r.length<=8)return`one of ${i.join(`, `)}`;let a=typeof n==`string`?` "${n}"`:``;return`one of the ${r.length}${a} names, such as ${i.slice(0,3).join(`, `)}`}return`an integer from ${e.min} to ${e.max}`}function Pk(e){return{label:e.label,domain:Fk(e.domain)}}function Fk(e){return e===`theme`?{themes:Yy}:e===`bool`||`min`in e?e:{from:e}}function Ik(e,t,n,r,i){let a=Zr(e.label),{domain:o}=e;if(o===`bool`)return{kind:`inline`,template:`{{ action "${r}" "☑ ${a}" "☐ ${a}" }}`,actions:{[r]:{set:t,cycle:[...pg]}},variables:{}};if(`from`in o)return Lk(t,r,i,o.from,e=>({template:`{{ "${a}" }} {{ carousel "${e.apply}" 0 "${e.open}" }}`,rows:[`{{ picker "${e.apply}" "${e.page}" false true true }}`]}));if(`themes`in o)return Lk(t,r,i,o.themes,e=>({template:`{{ action "${e.open}" "${a}" .${n} }} {{ action "${e.open}" (swatch "${e.apply}") }}`,rows:[`{{ swatches "${e.apply}" "${e.page}" }}`,`{{ themePreview "${e.apply}" }}`]}));let s=e=>({set:t,min:o.min,max:o.max,by:e});return{kind:`inline`,template:`{{ action "${r}.down" "◀" }} {{ "${a}" }} {{ .${n} }} {{ action "${r}.up" "▶" }}`,actions:{[`${r}.down`]:s(-o.step),[`${r}.up`]:s(o.step)},variables:{}}}function Lk(e,t,n,r,i){let a={variable:n,key:n,member:t},o=Tk(n,t),s=`${t}.open`,c=Ek(n),l=`${c}.current`,{template:u,rows:d}=i({apply:t,open:s,page:c});return{kind:`picker`,template:u,actions:{[t]:{set:e,from:r},[o]:ai(n,t),[c]:{set:c,int:!0},[l]:{set:c,to:`-1`},[s]:{do:[o,l]}},variables:{[n]:ii(n,P),[c]:{kind:`state`,key:c,default:`0`}},list:{ref:a,rows:d}}}const Rk=Object.fromEntries(Object.entries(nv).map(([e,t])=>[e,t.spec]));function zk(e){return nv[e].domain}function Bk(e,t){return{required:!1,json:{not:{},description:`not allowed here — ${e}`},parse:(e,n,r,i)=>{i[r]!==void 0&&e.issues.push({path:`${n}.${r}`,message:t(`${n}.${r}`),line:K(e.source,[...n.split(`.`),r])})}}}function Vk(e){return Bk(`${e} cannot select a preset`,t=>`${t}: ${e} cannot select a preset. Which preset is active is resolved once, as session pick over globals.preset over "default"; a fragment naming another would be a second authority over that. Set the default arrangement in the top-level globals.preset instead.`)}function Hk(e){return Bk(`${e} cannot change the settings menu glyph`,t=>`${t}: ${e} cannot change the settings menu glyph — one menu is shared by every preset. Set it in the top-level globals.menuGlyph instead.`)}function Uk(e,t,n){return{...e,json:{...e.json,not:{pattern:`\\{\\{`}},parse:(r,i,a,o)=>{let s=o[a];if(typeof s==`string`&&Uh(s)){r.issues.push({path:`${i}.${a}`,message:`${i}.${a}: a rule is not allowed here — ${t} ${n}, so it names a value. Write the rule in globals.${a} (or a preset's globals.${a}) instead.`,line:K(r.source,[...i.split(`.`),a])});return}return e.parse(r,i,a,o)}}}const Wk={default_bg:"nothing reads it — a segment with no `bg:` wears the decoration tint of its place in the bar. Delete the key, and author `bg:` on the segments that need a fixed colour.",default_fg:"nothing reads it — a segment with no `fg:` wears text chosen for contrast against its background. Delete the key, and author `fg:` on the segments that need a fixed colour.",default_truncate_marker:'nothing reads it — a segment clipped to its `width:` always ends in "…". Delete the key.',look:`it was renamed "style" — write the same name as style: "<name>"`,progression:`it was renamed "variation", and its values with it: accent (was secondary-accent), duo (was primary-secondary), mono (was primary)`,charset:"the bar always draws Nerd Font glyphs. Delete the key; `cc-candybar doctor` names what your terminal's font is missing."},Gk={noun:`globals key`,fields:Rk,removed:Wk},Kk={preset:Vk(`a preset`),menuGlyph:Hk(`a preset`)},qk={noun:`preset globals key`,fields:{...Rk,...Kk},removed:Wk};function Jk(e){return iA(e)&&!(e in Kk)}const Yk=`is decided later than any rule could be settled`,Xk={noun:`editGlobals key`,removed:Wk,fields:{...Rk,preset:Vk(`the editGlobals fragment`),menuGlyph:Hk(`the editGlobals fragment`),palette:Uk(Rk.palette,`the editGlobals fragment`,Yk),style:Uk(Rk.style,`the editGlobals fragment`,Yk),effect:Uk(Rk.effect,`the editGlobals fragment`,Yk)}},Zk={noun:`theme default key`,fields:{...Object.fromEntries(ov.map(e=>[e,Rk[e]])),style:Uk(Rk.style,`a theme's default`,`is the look that theme wears by name`)}};function Qk(e,t){if(!i_(t))return e.issues.push({path:`themeDefaults`,message:`themeDefaults must be an object mapping theme names to { shade, variation, style }, got ${a_(t)}`,line:K(e.source,[`themeDefaults`])}),{};let n={};for(let[r,i]of Object.entries(t)){let t=`themeDefaults.${r}`;if(!e.allowedPalettes.has(r)){e.issues.push({path:t,message:`${t}: "${r}" is not an installed theme${Ph(r)}. Expected one of: ${[...e.allowedPalettes].sort().join(`, `)}`,line:K(e.source,[`themeDefaults`,r])});continue}let a=o_(e,Zk,t,i);a!==null&&(n[r]=a)}return n}function $k(e,t,n){return n===void 0?{}:o_(e,Gk,t,n)??{}}function eA(e,t,n){return o_(e,qk,t,n)??{}}function tA(){return D_(qk)}function nA(e,t,n){return o_(e,Xk,t,n)??{}}const rA=new Set(Object.keys(Rk));function iA(e){return rA.has(e)}function aA(e){return Object.hasOwn(Wk,e)?Wk[e]:void 0}function oA(){return[...rA]}const sA=new Map(Object.entries(nv).flatMap(([e,t])=>`floor`in t&&typeof t.floor==`number`?[[e,t.floor]]:[]));function cA(e){let t=new Map;for(let[n,r]of sA){let i=e[n];t.set(n,typeof i==`number`?i:r)}return t}const lA=/^segments\.([^.]+)\.palette$/,uA=/^presets\.(.+)\.root$/,dA=/^presets\.(.+)\.globals\.([^.]+)$/,fA=/^themeDefaults\.(.+)\.([^.]+)$/;function pA(e){return`presets.${e}.root`}function mA(e,t){return`themeDefaults.${e}.${t}`}const hA=e=>ov.includes(e);function gA(e,t){return`presets.${e}.globals.${t}`}function _A(e){if(iA(e))return{scope:`globals`,field:e};let t=lA.exec(e);if(t)return{scope:`segment-palette`,segment:t[1]};let n=dA.exec(e);if(n&&Jk(n[2]))return{scope:`preset-globals`,preset:n[1],field:n[2]};let r=fA.exec(e);if(r&&hA(r[2]))return{scope:`theme-default`,theme:r[1],field:r[2]};let i=uA.exec(e);return i?{scope:`preset-root`,preset:i[1]}:null}function vA(e){switch(e.scope){case`globals`:return[`globals`,e.field];case`preset-globals`:return[`presets`,e.preset,`globals`,e.field];case`segment-palette`:return[`segments`,e.segment,`palette`];case`theme-default`:return[`themeDefaults`,e.theme,e.field]}}const yA=[`location`,`git`,`model-context`,`cost-limits`,`activity`,`session-tools`],bA=[...yA,`other`],xA={location:`location`,git:`git`,"model-context":`model & context`,"cost-limits":`cost & limits`,activity:`activity`,"session-tools":`session tools`,other:`other`},SA=DS({fromString:e=>e}),CA=`edit.mode`,wA=`edit.configure`,TA=`edit.toggle`,EA=`edit.unconfigure`,DA=[TA,EA],OA=`arrange`,kA=`${_k}draft.`;function AA(e,t){return`${e}:${t}`}const jA={variable:CA,key:CA,member:OA},MA=$r(jA);function NA(e){try{return SA.parse(e).referencedCalls().some(e=>e.name===`action`&&e.args[0]===`edit.toggle`)}catch{return!1}}function PA(e){if(Object.values(e.actions??{}).some(e=>`do`in e&&e.do.includes(`edit.toggle`)))return!0;for(let t of Object.values(e.segments??{}))for(let e of[t.template,t.bg,t.fg])if(typeof e==`string`&&NA(e))return!0;return!1}function FA(e,t){if(xk(e,t,_k,`edit mode`),!PA(t))return;let{variables:n,actions:r}=IA();t.variables={...t.variables??{},...n},t.actions={...t.actions??{},...r}}function IA(){return{variables:{[CA]:ii(CA,P),[wA]:ii(wA,P)},actions:{[TA]:ai(CA,OA),[EA]:{set:wA,to:P}}}}const LA=`open`;function RA(e,t,n,r){let i={variable:e,key:e,member:LA};return r.variables[e]=ii(e,P),r.actions[e]=ai(e,LA),r.segments[e]={template:ti(e,`(?)`,`✕`),...zA(n)},Qr(e,i,{kind:`container`,direction:`horizontal`,children:t.map((t,n)=>{let i=`${e}.${n}`;return r.segments[i]={template:t},{kind:`segment`,name:i}})},`drop`)}function zA(e){let[t,...n]=e;return t===void 0?{}:{when:$r(t,...n)}}const BA=`none`;function VA(e){return Pc(e,`background`)}var HA=class extends Error{constructor(e,t,n){super(`Invalid ${t} color ${JSON.stringify(e)}: ${n}`),this.name=`ColorSpecError`}};function UA(e,t,n,r,i){let{palette:a,tint:o,text:s}=e,c=WA(n,i),l=c!==BA,u=l?c===void 0?o:GA(a,c,`bg`):VA(a);e.bg=u;let d=WA(r,i),f=d===void 0?l?(e=>e.hex===o.hex?s:th(a,e,t))(u):void 0:GA(a,d,`fg`);return new H({...l&&{bgcolor:B.fromRgba(u)},...f!==void 0&&{color:B.fromRgba(f)}})}function WA(e,t){if(e!==void 0)return e.evaluate(t).map(e=>e.plain).join(``)}function GA(e,t,n){try{return Pc(e,t)}catch(e){throw e instanceof Nc?new HA(t,n,e.message):e}}const KA=`🔧`,qA={help:[`-h`,`--help`],version:[`-V`,`--version`]},JA=[{member:`session`,label:`⚡ session`},{member:`look`,label:`🎨 look`},{member:`layout`,label:`📐 layout`},{member:`config`,label:`⚙ config`},{member:`tools`,label:`🧰 tools`}],YA=Object.fromEntries(JA.map(e=>[e.member,e.label])),XA={gear:{beside:`theme`,trigger:`⚙`},toggles:{beside:`updateNotice`,trigger:`🧪 toggles`}},ZA=Object.keys(XA),QA=bv(e=>pv[e].place),$A=e=>Object.hasOwn(XA,e),ej=(e,t)=>e===t||$A(e)&&ej(QA[XA[e].beside],t),tj=e=>$A(e)?`${tj(QA[XA[e].beside])} › ${XA[e].trigger}`:e===`door`?`first line`:YA[e],nj=e=>tj(QA[e]),rj=()=>[`door`,...JA.map(e=>e.member)].flatMap(e=>[e,...ZA.filter(t=>ej(t,e))]).map(e=>({path:tj(e),names:mv.filter(t=>QA[t]===e)})).filter(({names:e})=>e.length>0),ij=e=>`${j_[e].label} is off — turn it on in the settings menu's ${nj(j_[e].setting)}, or set globals.${j_[e].setting}: true`,aj=[...new Set(Object.values(j_).map(e=>nj(e.setting)))].join(` or `),oj=Math.max(...Object.values(pv).map(e=>e.configKey.length))+2,sj=[`✚ inserts`,`✖ removes`,`${KA} configures`,`↺ resets layout`],cj={band:[`animates the bar in the band above the prompt, through a Claude Code mod`,`on: installs the candybar-band mod from this checkout and types /reload-plugins`],statusline:[`animates the statusline itself, through the attach launcher shipped with cc-candybar`,`on: exits this Claude Code and starts it again under that launcher, on this session`,`or start one yourself: cc-candybar --help prints the line to type`],pane:[`animates the bar in a tmux pane under this session's`,`on: opens that pane · off: closes it`],tmuxStatus:[`animates the bar in the tmux status line, while this session's pane is the one it shows`,`on: the daemon draws it there · off: puts the status line back as it was`]},lj=`
|
|
77
77
|
cc-candybar - Beautiful powerline statusline for Claude Code
|
|
78
78
|
|
|
79
79
|
Usage: cc-candybar [options]
|
|
80
80
|
|
|
81
81
|
Standalone Commands:
|
|
82
|
-
${
|
|
83
|
-
${
|
|
82
|
+
${qA.help.join(`, `).padEnd(25)}Show this help
|
|
83
|
+
${qA.version.join(`, `).padEnd(25)}Print the version of this runtime (cc-candybar <version>)
|
|
84
84
|
|
|
85
85
|
Debugging:
|
|
86
86
|
CC_CANDYBAR_DEBUG=1 Enable debug logging for troubleshooting
|
|
@@ -97,21 +97,21 @@ Configuration:
|
|
|
97
97
|
the settings listed below, its first line holds ◁ back, ✎ arrange (edit mode)
|
|
98
98
|
and 💾 save, which appears while you have unsaved changes and writes them to
|
|
99
99
|
your config file. Under it are its
|
|
100
|
-
tabs, ${
|
|
101
|
-
${
|
|
100
|
+
tabs, ${JA.map(e=>e.label).join(`, `)};
|
|
101
|
+
${YA.session} holds quick actions and commands, ${YA.layout} a new preset.
|
|
102
102
|
A change applies to this session at once.
|
|
103
103
|
Where each setting is in the menu: the globals field that sets it in a
|
|
104
104
|
config file, then the control's label.
|
|
105
|
-
${
|
|
105
|
+
${rj().flatMap(({path:e,names:t})=>[` ${e}`,...t.map(e=>` ${pv[e].configKey.padEnd(oj)}${pv[e].label}`)]).join(`
|
|
106
106
|
`)}
|
|
107
107
|
The 🧰 tools tab holds 🩺 doctor: click it to check your setup, and click a
|
|
108
108
|
failed row's [fix] to repair it (the same checks \`cc-candybar doctor\` runs).
|
|
109
109
|
|
|
110
110
|
Anywhere the bar shows (?), clicking it reveals these same instructions
|
|
111
|
-
in place. In edit mode: ${
|
|
111
|
+
in place. In edit mode: ${sj.join(`, `)}.
|
|
112
112
|
|
|
113
|
-
Animation lanes (experimental; toggles in the settings menu's ${
|
|
114
|
-
${M_.map(e=>` ${j_[e].label}\n${
|
|
113
|
+
Animation lanes (experimental; toggles in the settings menu's ${aj}):
|
|
114
|
+
${M_.map(e=>` ${j_[e].label}\n${cj[e].map(e=>` ${e}`).join(`
|
|
115
115
|
`)}`).join(`
|
|
116
116
|
`)}
|
|
117
117
|
|
|
@@ -145,14 +145,14 @@ Subcommands:
|
|
|
145
145
|
${M_.join(`, `)}:
|
|
146
146
|
the experimental lane this stream serves,
|
|
147
147
|
which streams only while its toggle in the settings
|
|
148
|
-
menu's ${
|
|
148
|
+
menu's ${aj} is on.
|
|
149
149
|
bar-pane PANE Draw the bar of the Claude Code session in tmux
|
|
150
150
|
pane PANE (e.g. %3) in this pane, as the daemon
|
|
151
151
|
pushes it, while this pane is shown. The bar is
|
|
152
152
|
drawn at PANE's width, so split PANE with -v for a
|
|
153
153
|
pane under it that fits. Experimental:
|
|
154
154
|
runs while ${j_.pane.label} is on in the settings
|
|
155
|
-
menu's ${
|
|
155
|
+
menu's ${nj(j_.pane.setting)}.
|
|
156
156
|
|
|
157
157
|
Config tooling:
|
|
158
158
|
doctor [file] Check your setup the way the bar's 🩺 doctor does —
|
|
@@ -178,17 +178,17 @@ Config tooling:
|
|
|
178
178
|
config [--json] The effective merged config. (All three query the
|
|
179
179
|
running daemon; none spawn one.)
|
|
180
180
|
|
|
181
|
-
`,
|
|
182
|
-
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Lj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${Uj[e]}`)])}}},Gj="re-run `cc-candybar install`";function Kj(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:// — ${Gj}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${Gj}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${Gj}`)}const qj={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}) — ${Gj}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${Gj}`};case`lost`:return Lj([...Kj(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 Jj({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 Yj(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${M_.join(`|`)}>\``:e.checkout===null?Gj:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function Xj(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 — ${Yj(e,`native`)}`];let{bundle:i,source:a}=Jj(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} — ${Yj(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 — ${Yj(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 Zj=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)`},Qj={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`:`${Zj(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:Lj([...new Set(i.flatMap(e=>Xj(n,r,e)))])}};function $j({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function eM(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const tM={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`?eM(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return Lj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=$j(e.value,n),u=Lj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${Nn(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Rn(o.charge.bytes,s)?[`the daemon holds ${Hn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},nM=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function rM(e,t){let n=wj(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Ej(e.terminal):{kind:`unknown`}}function iM({identified:e,tmuxClient:t},n){let r=Tj(e),i=rM(e,n),a=wj(e)===null?nM:`${nM}, 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: ${Dj}`];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 aM={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 Lj(iM(t,n))}}},oM=e=>e.filter(e=>e.role===`statusline`),sM={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})=>uM(e,cM(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:lM(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:Zj(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}}},cM=e=>{let t=oM(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 (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`}},lM=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function uM(e,t){let n=Oj(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 lM(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 jj(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 dM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function fM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return Tj(e);case`bundling`:case`unread`:case`configured`:return[mj(e.name),e.version].filter(e=>e!==null).join(` `)}}function pM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return wj(e);case`bundling`:case`unread`:return mj(e.name);case`configured`:{let t=mj(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 mM(e){let t=pM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${dM(e.glyphs)}`}}const hM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=mM(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=fM(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 ${dM(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=uj[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:yj(i.version,e);if(t===!0)return{ok:!0};let n=mj(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 ${dM(n)} — set a Nerd Font as its font`)}}}};function gM(e){return e.join(`, `)}function _M(e){return`or set missingData: "ignore" on ${gM(e)}`}function vM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${gM(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`?[`${gM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${_M(t)}`]:[`${gM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${_M(t)}`]}function yM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${gM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${gM(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`:`${gM(n)}: ${Zj(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`)?[`${gM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${gM(n)}`]:[]}function bM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${gM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${_M(t)}`];case`failed`:return[`${gM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const xM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>Lj([...vM(e.pullRequests),...yM(e.rateLimits,t),...bM(e.memento)])};function SM({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 ${Pj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const CM=[Wj,Qj,tM,qj,aM,Bj,Vj,Hj,sM,hM,xM,{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`:`${Zj(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:Lj(e.value.flatMap(SM))}],wM=CM.filter(e=>e.takesMark);function TM(e){return CM.map(t=>({check:t,verdict:t.probe(e)}))}function EM(e){return CM.find(t=>t.name===e)}const DM=/^[^\s"=\\]+$/,OM=e=>DM.test(e)?e:JSON.stringify(e),kM=`${X}doctor.`;function AM(e){let t=`${kM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function jM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?wj(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 MM(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 NM(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}=Jj(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const PM=e=>`${e>=0?`+`:``}${Nn(e)}`;function FM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${eM(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`:`${$j(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Un(i.charge)}${i.charge.kind===`stand-in`?`(${PM(-i.charge.gap)})`:``}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function IM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function LM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>RM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${OM(i)}`;let a=oM(r.flatMap(e=>e.bars));return`frames=${oj.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${OM(i)}`}function RM(e){let t=Oj(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 zM(e){let t=kj(e,Rj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${OM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function BM(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 VM(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=mM(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 HM(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function UM(e){return e.flatMap(({check:e,verdict:t})=>{let n=AM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:fg},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:HM(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?fg:dg},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const WM={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function GM(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(WM).map(([t,n])=>[`${e}${t}`,n]))}}const KM=`armed`,qM=`disarmed`,JM=`.armed`,YM=e=>e.endsWith(JM);function XM(e,t,n){let r=`${e}${JM}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${KM}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:KM},[a]:{set:r,to:qM},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:qM}},disarm:a}}const ZM=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function QM(e){return typeof e==`string`&&ZM.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 $M(e){let t=QM(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const eN=[`/compact`,`/model`],tN=`/clear`;function nN(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=XM(`${e}clear`,{arm:tN,confirm:`${tN} ✓ confirm`},[n]);return{template:eN.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${$O} }}`,actions:{...Object.fromEntries(eN.map(e=>[t(e),{slash:$M(e)}])),...r.actions,[n]:{slash:$M(tN)}},variables:r.variables,disarm:r.disarm}}const rN=Array.from({length:10},(e,t)=>(t+1)*1e5),iN=rN[0],aN=rN[rN.length-1];function oN(e){let t;try{t=Da(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=iN&&n<=aN?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${iN}–${aN} tokens)`)}function sN(e,t){let n=Math.min(t??aN,aN),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:rN.filter(e=>e<r).at(-1)??0,higher:rN.find(e=>e>r&&e<=n)??0}}function cN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${$O} }}{{ 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:$M(`/autocompact auto`)},...Object.fromEntries(rN.map(t=>[`${e}${t}`,{slash:$M(`/autocompact ${t}`)}]))}}}const lN=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 }}`,uN=`${X}menu`,dN=`open`,fN=`${X}edit`,pN=`${X}toolbar`,mN=GM(X),hN=`${X}commands`,gN=nN(`${hN}.`),_N=`${X}autocompact`,vN=cN(`${_N}.`,lN),yN=e=>({kind:`segment`,name:e}),bN=`${X}tab`,xN=e=>`${bN}.${e}`,SN=e=>`${xN(e)}.toggle`,CN=e=>({variable:bN,key:bN,member:e}),wN=`${X}save`,TN=`${X}preset.save`,EN=`${X}preset.delete`,DN=e=>`${X}${e}`,ON=e=>`${X}apply.${e}`,kN=e=>`${X}reset.${e}`,AN=`${X}themeDefault.save`,jN=`${X}themeDefault.differs`,MN=`${X}themeDefault.theme`,NN={when:`{{ .${jN} }}`,template:`{{ action "${AN}" (printf "⤓ default for %s" .${MN}) }} {{ swatch "${ON(`theme`)}" .${MN} }}`},PN=`${X}resetAll`,FN=`${uN}.toggle`,IN={variable:uN,key:uN,member:dN},LN=`${X}undo`,RN=`${X}back`,zN=`${RN}.step`,BN=`${X}navigation.back`,VN=RN,HN={template:`{{ if gt .${BN} 0 }}{{ action "${RN}" "◁" }}{{ else }}{{ fg (${QA}) "◁" }}{{ end }}`},UN=`${X}redo`,WN=`${X}doctor`,GN=`${WN}.run`,KN=e=>`${WN}.fix.${e}`,qN=(e,t)=>`${WN}.mark.${e}.${t}`,JN=e=>`${WN}.${e}`,YN={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},XN=fk(`${X}pickers`),ZN=e=>`${X}${e}`,QN=e=>`${ZN(e)}.toggle`,$N=e=>VA(e)?fk(`${X}${e}Pickers`):XN,eP=e=>{let t=$N(BA[RA[e].beside]);return{variable:t,key:t,member:e}},tP={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${EN}" (printf "🚮 delete %s" .${pv.preset.effectiveVar}) }}`}},nP=(e,t)=>`${X}list.${e}.${t}`,rP=e=>`${X}resettable.${e}`,iP=e=>e.length===0?`false`:`(or ${e.map(e=>`.${rP(e)}`).join(` `)})`,aP=M_.map(e=>[j_[e].setting,e]),oP={variables:{},actions:{},segments:{}},sP=Object.fromEntries(aP.map(([e,t])=>[e,EA(`${X}help.${e}`,XA[t],[],oP)])),cP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],lP=e=>{let t=t=>`.${I_(e,t)}`,n=cP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${pv[j_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},uP=`{{ if eq .${P_(`by`)} "feed" }} {{ printf "%2d" (int .${P_(`fps`)}) }} fps{{ end }}`,dP=Object.fromEntries(aP.map(([e,t])=>[e,lP(t)])),fP=Object.keys(pv).map(e=>{let t=pv[e],n=Dk(t.configKey),r=wk({label:t.label,domain:n},t.sessionKey,t.effectiveVar,ON(e),$N(BA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>tP[e])}}),pP=e=>fP.filter(t=>BA[t.name]===e),mP=e=>fP.filter(t=>HA(BA[t.name],e)),hP=e=>t=>`(print ${ri(t)} (ternary ${ri(` •`)} "" ${iP(mP(e).map(e=>e.name))}))`,gP=e=>zA.filter(t=>RA[t].beside===e),_P=e=>pP(e).flatMap(e=>[kP(e),...[sP[e.name]].filter(e=>e!==void 0),...gP(e.name).map(e=>Qr(ZN(e),eP(e),IP(e),`drop`))]);new Set(fP.flatMap(e=>[e.sessionKey,e.configKey]));const vP=XM(PN,{arm:`⟲`,confirm:`⟲ reset all?`},fP.map(e=>kN(e.name))),yP=[`unsaved`,`history.undo`,`history.redo`],bP=e=>`${X}${e}`,xP=bP(`unsaved`),SP=(e,t)=>({body:t,shown:`(gt .${bP(e)} 0)`}),CP=[SP(`unsaved`,`{{ action "${wN}" (printf "💾 save %d" .${xP}) }}`),SP(`history.undo`,`{{ action "${LN}" "↶" }}`),SP(`history.redo`,`{{ action "${UN}" "↷" }}`),{body:vP.template,shown:`(or ${iP(fP.map(e=>e.name))} ${vP.armed})`}],wP={when:`{{ or ${CP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+CP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},TP=[{step:vP,place:`door`},{step:gN,place:`session`}],EP=e=>e.map(e=>e.step.disarm),DP=EP(TP),OP=EP(TP.filter(e=>e.place!==`door`));function kP(e){let t=DN(e.name);return e.control.kind===`inline`?yN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>yN(nP(e.name,n)))},`drop`)}function AP(e){return e===uN}function jP(e){let t=yN(uN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[jP(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 MP(e){return NP(e)>0?e:jP(e)}function NP(e){let t=0;for(let n of Cg(e))n.kind===`segment`&&AP(n.name)&&(t+=1);return t}function PP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&AP(e.name)||e.opens!==void 0&&PP(e.opens.body,!0):e.children.some(e=>PP(e,n))}const FP={door:{direction:`horizontal`,content:[yN(VN)],after:[yN(fN),yN(wN)]},session:{direction:`vertical`,content:[yN(pN),{kind:`container`,direction:`horizontal`,children:[yN(hN),yN(_N)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[yN(TN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[yN(WN),...CM.map(e=>yN(JN(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[yN(AN)]},toggles:{direction:`horizontal`,content:[],after:[]}};function IP(e){let{direction:t,content:n,after:r}=FP[e];return{kind:`container`,direction:t,children:[...n,..._P(e),...r]}}function LP(e){return e.kind===`segment`?AP(e.name)?Qr(e.name,IN,zP,`above`):e:VP(e)}function RP(){return{kind:`container`,direction:`vertical`,children:[IP(`door`),{kind:`container`,direction:`horizontal`,children:IA.map(({member:e})=>Qr(xN(e),CN(e),IP(e),`drop`))}]}}const zP=RP();function BP(e){let t=new Map;for(let e of Cg(zP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${uN}.fold.${nk(t)}`;return e.actions[i]={set:t,to:r.default},i})}function VP(e){return{...e,children:e.children.map(e=>LP(e))}}function HP(e){let t={variables:{[uN]:ii(uN,P)},actions:{[FN]:ai(uN,dN),[GN]:{doctor:`run`},[fN]:{do:[...hA]},...mN.actions,...gN.actions,...vN.actions,[wN]:{save:!0},[LN]:{undo:!0},[zN]:{back:!0},[RN]:{do:[zN,...DP]},[UN]:{redo:!0},[TN]:{preset:`save`},[AN]:{themeDefault:`save`},[EN]:{preset:`delete`,name:`{{ .${pv.preset.effectiveVar} }}`}},segments:{[uN]:{template:`{{ $door := ${ni(uN,ri(e),ri(`✖`))} }}{{ if ${ei(IN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+uP},[pN]:{template:mN.template},[hN]:{template:gN.template,when:gN.when},[_N]:{template:vN.template,bg:vN.bg,when:vN.when},[VN]:HN,[wN]:wP,[AN]:NN,[TN]:{template:`{{ action "${TN}" "+ preset" }}`},[WN]:{template:`{{ action "${GN}" "🩺 doctor" }}`},[fN]:{template:`{{ action "${fN}" "✎ arrange" "✎ done" }}`}}};t.variables[jN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[MN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[BN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of yP)t.variables[bP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[bN]=ii(bN,`session`);for(let{member:e,label:n}of IA){t.actions[SN(e)]=ai(bN,e),t.actions[xN(e)]={do:[SN(e),...OP]};let r=hP(e);t.segments[xN(e)]={template:`{{ ${ni(xN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,gN.variables,vP.variables),WP(t),UP(t),t.actions[uN]={do:[FN,...DP,...BP(t)]},t}function UP(e){for(let t of CM){let n=AM(t.name),r=KN(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?Nj:[];for(let n of i)e.actions[qN(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${qN(t.name,e)}" "${YN[e]}" }}`).join(``);e.segments[JN(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} "${dg}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function WP(e){for(let t of fP){Object.assign(e.actions,t.control.actions);let n=kN(t.name);e.actions[n]={reset:t.configKey},e.variables[rP(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${rP(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[DN(t.name)]={template:`${t.control.template}${dP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[nP(t.name,r)]=n})}Object.assign(e.actions,vP.actions),Object.assign(e.variables,oP.variables),Object.assign(e.actions,oP.actions),Object.assign(e.segments,oP.segments);for(let t of zA){let n=eP(t);e.actions[QN(t)]=ai(n.key,n.member),e.segments[ZN(t)]={template:`{{ action "${QN(t)}" ${hP(t)(RA[t].trigger)} }}`}}}function GP(e){let{variables:t,actions:n}=wA();Object.assign(e.variables,t),Object.assign(e.actions,n)}function KP(e){let t=HP(e.globals.menuGlyph??`🍫`);GP(t);let n={...e.presets},r=[];for(let t of Hy(e.presets)){let{node:i}=Gy(e,t),a=LP(MP(i));r.push(a),n[t]={...Wy(e.presets,t),root:a}}let i=tk(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const qP=`${ak}live`,JP=[`☐ live`,`☑ live`],YP=`${ak}done`,XP=`${ak}cancel`,ZP=`${ak}rewind`,QP=`${ak}changes`,$P=`(gt .${QP} 0)`,eF=`(or ${$P} (gt .${xP} 0))`,tF={variable:qP,key:qP,member:`open`};function nF(e){return`${ak}configuring.p${e}`}function rF(e){return`and ${ei(yA)} (not ${ei(tF)}) (ne .${nF(e)} "true")`}function iF(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${fA} "${Zr(e)}")`).join(` `)} false }}`}}function aF(e,t,n){return`{{ if ${rF(e)} }}${t}{{ else }}${n}{{ end }}`}const oF=`{{ and ${ei(yA)} .preset.customized }}`,sF=sk;function cF(e){return new Map([...Xy(e),...uF(e)])}const lF=`${ak}addable`;function uF(e){return new Map([[lF,{members:Object.keys(e.segments).filter(e=>!sF(e)),library:{groups:cA.map(e=>({id:e,label:lA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function dF(e,t,n){return n.segments[e]={template:t,when:bA,bg:OA},{kind:`segment`,name:e}}function fF(e,t,n){let r=`${ak}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${eh}`}) (action "${r}" "✖") }}`}function pF(e){return`{{ if ${ei(yA)} }}${e}{{ end }}`}function mF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(yA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function hF(e){return e.flatMap(e=>[...Cg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function gF(e,t,n){return`${_A}${e}.${t}.${n}`}function _F(e,t,n,r){let i=yg(n),a=`${ak}${e.presetIdent}`,o=vA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=fk(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:fA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=gF(e.presetIdent,i,r),l=`${_A}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Hg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=wk(Sk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${PA}" }}`,ref:{variable:fA,key:fA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const vF=`${ak}label:`;function yF(e){if(e.startsWith(vF)){let t=e.slice(vF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function bF(e,t,n,r){let{artifacts:i}=n,a=yg(e),o=`${vF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Lg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,mF([r.ref],`{{ ${rF(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Lg.map(e=>[e,r.drafts[e]]))}}function xF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${ak}${i}.insert.${t}`,s=`${ak}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:lF,anchor:n,relation:r};let c=uk(o),l=dk(s,o,void 0),u=mk(l),d=pk(l,c);return a.variables[l]=ii(l,P),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${eh}`}) $m }}{{ end }}`}}function SF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!sF(e.name)),i=e=>SF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Sg(o,i);if(sF(o.name)){n.push(s);continue}let c=yg(o),l=a===r?[xF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=xF(t,u,c,`after`),f=fF(t,u,c),p=t.segments[o.name],m=_F(t,u,o,Rg(p)),h=pF(f),g=pF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>dF(e.host,e.template,t.artifacts)),{...bF(o,p,t,m),lead:h,trail:g},{...s,when:aF(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},dF(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:mF(hF(n),aF(t.presetIdent,`true`,e.when))}}}function CF(e,t,n,r,i,a,o){let s=`${ak}${t}.resetLayout`,c=`${ak}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:oF},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},wF(e,o)]}}function wF(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),wF(n,t)]}:{...e,children:[...e.children,t]}}function TF(e,t,n,r,i,a){let{node:o}=Gy(e,t),s={presetIdent:nk(t),rootKey:tA(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=SF(o,s);return n.variables[nF(s.presetIdent)]=iF(s.configured),CF(c,s.presetIdent,s.rootKey,n,r,i,a)}function EF(e){let t={variables:{},actions:{},segments:{}},n=EA(`${ak}help`,YA,[yA],t);t.variables[qP]=ii(qP,P),t.actions[qP]=ai(qP,tF.member),t.segments[qP]={template:ti(qP,...JP),when:bA};let r={kind:`segment`,name:qP},i=n;t.variables[QP]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[YP]={do:[wN,...hA]},t.segments[YP]={template:`{{ if ${eF} }}{{ action "${YP}" "✓ save" }}{{ else }}{{ action "${YP}" "✓ done" }}{{ end }}`,when:bA},t.actions[ZP]={rewind:!0},t.actions[XP]={do:[ZP,...hA]},t.segments[XP]={template:`{{ action "${XP}" "↩ cancel" }}`,when:`{{ and ${ei(yA)} ${$P} }}`};let a=[{kind:`segment`,name:YP},{kind:`segment`,name:XP}],o={...e.presets},s=[];for(let n of Hy(e.presets)){let c=TF(e,n,t,a,r,i);s.push(c),o[n]={...Wy(e.presets,n),root:c}}let c=tk(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function DF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function OF(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 kF(e,t,n){let r=xg(e,new Set(n.map(bg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const AF=/^-?\d+$/;function jF(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 MF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!AF.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 NF(e,t,n){return r=>r?AF.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 PF(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=>!AF.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 FF(e){return e===`config`?`set-config`:`set-state`}function IF(e,t,n){return t.kind===`int`?MF(`menu page "${e}"`):t.kind===`range`?NF(t.min,t.max,`${n} stepper "${e}"`):jF(t.allowed,`${n} "${e}"`,FF(n))}function LF(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:PF(e,n,t)}))}function RF(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 LF(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,IF(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 zF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};RF(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=RF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const BF=zF({},`config`,qF);function VF(e,t){return BF.register(e,t)}function HF(e){return BF.gateFor(e)}function UF(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:Qy(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:[DF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[DF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Qy(e.insertSegmentFrom,t).members.map(t=>DF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function WF(e,t){let n=Xk(e).get(t);return n===void 0?null:String(n)}function GF(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?aA(n.persist):null;e?.scope===`preset-root`&&t.add(tA(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function KF(e){let t=cF(e);return[...GF(e),...Object.values(e.actions).flatMap(e=>UF(e,t))]}function qF(e){return LF(KF(e),`config`)}function JF(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:ZF(t.segments,YF(t.segments,e.segments??{})),root:Ry(e.root??jy,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:ZF(t.presets,XF(t.presets,e.presets??{})),themeDefaults:ZF(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function YF(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 XF(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 ZF(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function QF(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: ${kg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):tI(e,`${t}.cache`,n.cache)}function $F(e){return{required:!0,json:nI(),parse:(t,n,r,i)=>QF(t,n,i,e)??void 0}}const eI={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&iI(n)?{ttl:n}:d_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return d_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=C_(`cache.watch_file`,n);return r===null?{watch_file:n}:d_(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}:d_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:d_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:d_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function tI(e,t,n){return f_(e,eI,t,n)}function nI(){return A_(eI)}const rI=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function iI(e){return rI.test(e)}function aI(e,t,n){if(n===void 0)return{};if(!i_(n))return e.issues.push({path:t,message:`${t} must be an object, got ${a_(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=p_(e,jI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function oI(){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 ${a_(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function sI(){return{required:!0,json:{enum:[...jg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!jg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${jg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function cI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return e_(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const lI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:d_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?uI(e,t,n):d_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:d_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function uI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return d_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:d_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function dI(){return{required:!1,json:A_(lI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:f_(e,lI,`${t}.parse`,r.parse)??void 0)}}function fI(){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)=>i_(r.parse)&&`json`in r.parse?pI(e,t,r.default):t_(e,t,r,`default`)}}function pI(e,t,n){if(n!==void 0)return mI(n)?n:d_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function mI(e){return e!==null&&hI(e)}function hI(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(hI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(hI)}default:return!1}}const gI={value:oI(),default:__()},_I={path:S_(),type:T_([`string`,`number`,`boolean`]),default:cI()},vI={name:S_(),default:__()},yI={path:w_(),readMode:T_([`whole`,`first-line`]),parse:dI(),cache:$F(`file`),default:fI()},bI={command:S_(),parse:dI(),cache:$F(`shell`),default:fI()};function xI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const SI={template:S_(),default:__()},CI=xI(`a template variable recomputes whenever a variable it reads changes`),wI={layout:S_(),default:__()},TI=xI(`a time variable reads the instant its render is drawn at`),EI={field:sI(),default:__()},DI=xI(`a git variable is refreshed by the daemon's own watch on the repository`),OI={key:S_(),default:__()},kI=`kind`;function AI(e,t,n={}){return{...m_(kI,e,t),parse:(r,i,a)=>{s_(r,n,i,a);let o=c_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const jI={tag:kI,noun:`source kind`,memberNoun:`variable`,arms:{literal:AI(`literal`,gI),input:AI(`input`,_I),env:AI(`env`,vI),file:AI(`file`,yI),shell:AI(`shell`,bI),template:AI(`template`,SI,CI),time:AI(`time`,wI,TI),git:AI(`git`,EI,DI),state:AI(`state`,OI)}};function MI(){return k_(jI)}function NI(){return{type:`object`,additionalProperties:MI()}}const PI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function FI(e){let t=PI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const II=/^[A-Za-z_][A-Za-z0-9_]*$/,LI={pattern:II.source},RI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},zI={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`,...LI}}}]},default:RI}},BI=[`label`,`domain`,`default`],VI=[`min`,`max`,`step`,`atLeast`];function HI(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function UI(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 HI(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 HI(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?HI(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(i_(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!VI.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}}:HI(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 HI(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function WI(e,t,n){if(!i_(n))return HI(e,t,`${t} must be { label, domain, default }, got ${a_(n)}`);for(let r of Object.keys(n))BI.includes(r)||HI(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${BI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||HI(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=UI(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!GI(n.default)||!Vg(o,n.default)?HI(e,`${t}.default`,`default must be ${Gg(o)}, got ${q(n.default)}`):o}function GI(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const KI={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Fg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function qI(e){return Lg.includes(e)}function JI(){return{required:!1,json:{type:`object`,propertyNames:{...LI,not:{enum:[...Lg]}},additionalProperties:zI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return HI(e,a,`${a} must be an object of name → { label, domain, default }, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!II.test(t)){HI(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(qI(t)){HI(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${KI[t]}`);continue}let r=WI(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const YI=ok.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function XI(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${YI})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!sk(i)?i:HI(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${ok.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function ZI(){return{required:!1,json:{type:`object`,propertyNames:LI,additionalProperties:RI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return HI(e,a,`a placement's "settings" must be an object of setting name → value, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))GI(n)?o[t]=n:HI(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${a_(n)}`);return o}}}function QI(e){return new Set(Object.keys(e.segments).filter(e=>!sk(e)))}function $I(e,t,n){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${a_(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=o_(e,n.has(i)?aL:iL,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function eL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?d_(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${FI(t.slice(9))}`)??void 0:$g(e,t,r,n)??void 0}}function tL(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function nL(){return{required:!1,json:NI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return aI(e,`${t}.${n}`,i)}}}const rL={template:eL(),description:__(),group:T_(sA),width:tL(),justify:T_(Kg),truncate:T_(qg),bg:__(),fg:__(),when:__(),palette:x_(),vars:nL(),settings:JI(),missingData:T_(Mg)},iL={noun:`segment key`,fields:rL},aL={noun:`segment key`,fields:{...rL,template:__()}},oL=`#/definitions/LayoutNode`,sL={kind:`container`,direction:`vertical`,children:[]};function cL(e){return{required:!0,json:{const:e},parse:()=>e}}function lL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function uL(){return{required:!0,json:{enum:[..._g]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&_g.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${_g.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function dL(e){return{required:!0,json:{type:`array`,items:{$ref:oL}},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 ${a_(a)}`,line:K(t.source,[`root`])}),[])}}}const fL={noun:`layout-node key`,fields:{kind:cL(`segment`),name:lL(),when:__(),id:XI(),settings:ZI()}},pL=()=>T_(jm),mL={noun:`layout-node key`,fields:{kind:cL(`container`),direction:uL(),children:dL(h_(()=>yL)),when:__(),distribution:pL()}};function hL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const gL={noun:`layout-node key`,fields:{seg:hL(),when:__(),id:XI(),settings:ZI()}},_L={noun:`layout-node key`,fields:{h:dL(h_(()=>yL)),when:__(),distribution:pL()}},vL={noun:`layout-node key`,fields:{v:dL(h_(()=>yL)),when:__(),distribution:pL()}},yL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),sL):{kind:`segment`,name:n};if(!i_(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 ${a_(n)}`,line:K(e.source,[`root`])}),sL;if(n.kind===`container`)return o_(e,mL,t,n)??sL;if(n.kind===`segment`)return o_(e,fL,t,n)??sL;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
181
|
+
`,uj=`readableOn (mix (color "foreground") (bgOf) 60) (bgOf) 3`,dj={socket:`TMUX`,pane:`TMUX_PANE`,truecolor:`CLAUDE_CODE_TMUX_TRUECOLOR`};function fj(e){let t=e[dj.socket]??``,n=e[dj.pane]??``;if(t===``||n===``)return null;let r=e[dj.truecolor]??``;return{socket:t.split(`,`)[0],pane:n,truecolor:r===``?null:r}}const pj=[`moves`,`can-move`,`still`];function mj(e){let t=e.context_window?.current_usage;return t===null?`no`:t===void 0?`unknown`:`yes`}const hj=[`carried`,`missing`,`unanswered`];function gj(e){let t=e.rate_limits;return t?.five_hour!=null||t?.seven_day!=null?`carried`:mj(e)===`no`?`unanswered`:`missing`}function _j(e){return{path:e.transcript_path,answered:mj(e)===`yes`}}const vj=[...pj,`failed`,`drawing`],yj=[`statusline`,`frames`],bj=e=>e?.kind===`frames`?`frames`:`statusline`;var xj=class{seen=new Map;see(e,t,n,r){let i=bj(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 Sj={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`}}},Cj=e=>Sj[e];function wj(e){return Cj(e).glyphs.kind===`bundled`}function Tj(e){return Cj(e).glyphs.kind===`configured`}const Ej=e=>Cj(e).label,Dj=[{since:`3.5.0`,from:57504,to:57507},{since:`3.5.0`,from:57520,to:57554},{since:`3.5.0`,from:57556,to:57556},{since:`3.5.6`,from:57558,to:57559}];function Oj(e,t){let n=t.codePointAt(0);return Dj.some(({since:t,from:r,to:i})=>r<=n&&n<=i&&e!==null&&jj(e,t)===!0)}const kj=Object.keys(Sj);function Aj(e){let t=/^\d+(?:\.\d+)*/.exec(e);return t===null?null:t[0].split(`.`).map(Number)}function jj(e,t){let n=Aj(e),r=Aj(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 Mj(e){for(let t of kj){let n=Cj(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 Nj(e){let t=kj.find(t=>Cj(t).term===e);return t===void 0?null:{name:t,version:null}}function Pj(e){let t=Mj(e.termtype)??Nj(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 Fj(e){let t=e.TERM_PROGRAM,n=kj.find(e=>Cj(e).program===t),r=n===void 0?Nj(e.TERM):{name:n,version:Cj(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 Ij(e){switch(e.kind){case`known`:return Ej(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||null}}function Lj(e){switch(e.kind){case`known`:return Ej(e.terminal.name);case`unknown`:return e.called;case`unnamed`:return e.term||`this terminal`}}function Rj({name:e,version:t}){let n=Cj(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=jj(t,n.since);return r===null?{kind:`unsaid`,since:n.since}:r?{kind:`draws`}:{kind:`older`,since:n.since,version:t}}const zj=kj.filter(e=>Cj(e).links!==null).map(Ej).join(`, `);function Bj(e){if(e.kind===`failed`)return{kind:`unread`,reason:e.reason};let t=e.value.flatMap(({scope:e,path:t,settings:n})=>`statusLine`in n?[{from:{scope:e,path:t},line:n.statusLine}]:[]),n=t[0];if(n===void 0)return{kind:`absent`,read:e.value.map(e=>e.path)};if(!Na(n.line))return{kind:`not-an-object`,value:n.line,from:n.from};for(let{from:e,line:r}of t){if(e.scope!==n.from.scope||!Na(r))break;if(`refreshInterval`in r)return{kind:`present`,refreshInterval:r.refreshInterval,from:e}}return{kind:`present`,refreshInterval:void 0,from:n.from}}function Vj(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 Hj=[`managed`,`project`],Uj=e=>!Hj.includes(e.scope),Wj={managed:()=>null,"project-local":e=>({scope:`project-local`,path:e}),project:(e,t)=>({scope:`project-local`,path:Aa(t.projectDir)}),user:e=>({scope:`user`,path:e})},Gj=[`drawn`,`boxes`],Kj=1024*1024,qj=e=>e.kind===`session`?`session ${e.sessionId}'s statusline client`:`this command's terminal`;function Jj(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 Yj(e){let[t,...n]=e;return t===void 0?{ok:!0}:{ok:!1,reason:t,more:n}}const Xj=dj.truecolor;function Zj(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 Qj={name:`tmuxTruecolor`,label:`tmux truecolor`,takesMark:!1,probe:({tmux:e,claudeSettings:{origin:t}})=>Zj(e,(e,n)=>{if(!e.features.includes(`RGB`)||n.truecolor!==null)return{ok:!0};let r=Vj(t.sources,Xj);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:`${Xj} 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`,Xj],value:`1`}});if(i.kind===`unset`)return o({scope:`user`,path:t.at.userFile});let s=Wj[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 ${Xj} to "1" there`}:o(s)})},$j={name:`utf8`,label:`UTF-8`,takesMark:!1,probe:({tmux:e})=>Zj(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"})},eM={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:`${qj(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 ${qj(e.value.of)} measured`}},tM={variable:`is never read`,action:`is never clicked`,helper:`is never called`,segment:`is in no preset`},nM={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(`
|
|
182
|
+
`).map(e=>e.trim()).filter(e=>e!==``),...e.warnings];return{ok:!1,reason:t,more:n}}case`loaded`:return Yj([...e.warnings,...e.unused.map(({kind:e,name:t})=>`${e} "${t}" ${tM[e]}`)])}}},rM="re-run `cc-candybar install`";function iM(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:// — ${rM}`];let{app:t,missing:n}=e.value;return n.kind===`failed`?[`${t} opens cc-candybar://, but ${n.reason} — ${rM}`]:n.value.map(e=>`${e} is missing, and ${t} runs it — ${rM}`)}const aM={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}) — ${rM}`:`the URL handler runs cc-candybar ${e.handler}; the bar runs ${e.bar} — ${rM}`};case`lost`:return Yj([...iM(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 oM({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 sM(e,t){return t===`frames`?`run \`node ${e.bundle} frames --lane <${M_.join(`|`)}>\``:e.checkout===null?rM:`run \`just install-rust\` and point the statusLine command at ${e.checkout.root}/bin/cc-candybar-native`}function cM(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 — ${sM(e,`native`)}`];let{bundle:i,source:a}=oM(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} — ${sM(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 — ${sM(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 lM=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)`},uM={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`:`${lM(t)}, so which client draws it is unknown — run the doctor again once the bar has redrawn`}:Yj([...new Set(i.flatMap(e=>cM(n,r,e)))])}};function dM({postMortems:e},t){return e.kind===`ok`&&t.kind===`ok`?e.value.filter(e=>t.value.through===null||In(e.identity,t.value.through)):[]}function fM(e,t){return e.kind===`failed`?t:t.filter(t=>t.pid!==e.value.pid)}const pM={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`?fM(e,t.value):[];if(e.kind===`failed`){let t=i.length>0?` — daemon ${i.map(e=>e.pid).join(`, `)} running`:``;return Yj([`${e.reason}${t}`,...r])}let{pid:a,memory:o,limit:s,postMortems:c}=e.value,l=dM(e.value,n),u=Yj([...l.map(e=>`the daemon ran out of memory and restarted (${e.identity}) — post-mortem: ${Object.values(e.artifacts).join(`, `)}`),...c.kind===`failed`?[`the daemon's post-mortems could not be listed: ${c.reason}`]:[],...n.kind===`failed`&&!(c.kind===`ok`&&c.value.length===0)?[`which post-mortems were read could not be read: ${n.reason}`]:[],...r,...i.map(e=>`daemon ${e.pid} (started ${e.started}, rss ${Nn(e.rss)} MB${e.ppid===1?``:`, child of ${e.ppid}`}) runs beside the one serving the bar (${a}) — \`kill ${e.pid}\``),...o.kind===`measured`&&o.charge.kind===`stand-in`?[`the daemon could not read what macOS charges it (${o.charge.unread}), so its memory limit judges ${o.charge.gap===0?`RSS, which counts pages macOS has reclaimed`:`RSS less the ${Nn(o.charge.gap)} MB it last ran over that charge, an estimate`}`]:[],...o.kind===`measured`&&Rn(o.charge.bytes,s)?[`the daemon holds ${Hn(o.charge)} of its ${Nn(s)} MB limit — at the limit it records a post-mortem and restarts`]:[]]);if(u.ok&&o.kind===`unmeasured`)return{ok:!0,note:`the daemon has not measured its memory yet`};let d=l[0];return u.ok||d===void 0?u:{...u,fix:{kind:`post-mortems-read`,through:d.identity}}}},mM=`click 🩺 doctor in the bar's settings menu: if it runs, links work`;function hM(e,t){let n=Ij(e);return t.kind===`ok`&&n!==null&&t.value.includes(n)?{kind:`draws`}:e.kind===`known`?Rj(e.terminal):{kind:`unknown`}}function gM({identified:e,tmuxClient:t},n){let r=Lj(e),i=hM(e,n),a=Ij(e)===null?mM:`${mM}, 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: ${zj}`];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 _M={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 Yj(gM(t,n))}}},vM=e=>e.filter(e=>e.role===`statusline`),yM={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})=>SM(e,bM(t))??[]),[a]=i;if(a===void 0)return e.kind===`failed`?{ok:!1,reason:e.reason}:xM(r.kind===`recent`?`no session has drawn a statusline for this daemon in the last ${300/60} minutes`:lM(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}}},bM=e=>{let t=vM(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 (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`}},xM=e=>({ok:!1,reason:`${e}, so whether it moves is unknown — run the doctor again once the bar has redrawn`});function SM(e,t){let n=Bj(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 xM(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 Uj(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 CM=e=>[...e].map(e=>`U+${e.codePointAt(0).toString(16).toUpperCase()}`).join(` `);function wM(e){switch(e.kind){case`unreported`:case`unasked`:return`this terminal`;case`unknown`:case`unnamed`:return Lj(e);case`bundling`:case`unread`:case`configured`:return[Ej(e.name),e.version].filter(e=>e!==null).join(` `)}}function TM(e){switch(e.kind){case`unreported`:case`unasked`:return null;case`unknown`:case`unnamed`:return Ij(e);case`bundling`:case`unread`:return Ej(e.name);case`configured`:{let t=Ej(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 EM(e){let t=TM(e.terminal);return t===null?void 0:{glyphs:e.glyphs,id:`${t}|${CM(e.glyphs)}`}}const DM={name:`nerdFont`,label:`Nerd Font`,takesMark:!0,probe:({nerdFont:e,marks:t})=>{if(e.kind===`none`)return{ok:!0};let n=EM(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=wM(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 ${CM(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=Sj[i.name].glyphs.since;if(e===null)return{ok:!0};let t=i.version===null?null:jj(i.version,e);if(t===!0)return{ok:!0};let n=Ej(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 ${CM(n)} — set a Nerd Font as its font`)}}}};function OM(e){return e.join(`, `)}function kM(e){return`or set missingData: "ignore" on ${OM(e)}`}function AM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;if(n.kind===`failed`)return[`${OM(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`?[`${OM(t)}: ${r} is not installed, so no pull request is ever shown — install it, ${kM(t)}`]:[`${OM(t)}: ${r} is not logged in to ${i} (${a.loggedOut}) — run \`${r} auth login --hostname ${i}\`, ${kM(t)}`]}function jM(e,t){if(e.kind===`unneeded`)return[];let{segments:n,fact:r}=e;return r.kind===`failed`?[`${OM(n)}: ${r.reason}`]:r.value.length===0?[t.kind===`recent`?`${OM(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`:`${OM(n)}: ${lM(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`)?[`${OM(n)}: Claude Code sent no rate_limits — it sends them only to Claude.ai subscription sessions; on any other account, set missingData: "ignore" on ${OM(n)}`]:[]}function MM(e){if(e.kind===`unneeded`)return[];let{segments:t,fact:n}=e;switch(n.located.kind){case`ok`:return[];case`absent`:return[`${OM(t)}: memento is not installed (or is disabled) for ${n.claudeConfigDir} — install the memento plugin, ${kM(t)}`];case`failed`:return[`${OM(t)}: whether memento is installed could not be read: ${n.located.reason}`]}}const NM={name:`segmentData`,label:`segment data`,takesMark:!1,probe:({data:e,sighted:t})=>Yj([...AM(e.pullRequests),...jM(e.rateLimits,t),...MM(e.memento)])};function PM({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 ${Kj/1024/1024} MiB of`} the transcript ${e} are not JSON objects — the bar skips them, so what it counts from them is missing`]}}}const FM=[nM,uM,pM,aM,_M,Qj,$j,eM,yM,DM,NM,{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`:`${lM(t)}, so which transcript it reads is unknown — run the doctor again once the bar has redrawn`}:Yj(e.value.flatMap(PM))}],IM=FM.filter(e=>e.takesMark);function LM(e){return FM.map(t=>({check:t,verdict:t.probe(e)}))}function RM(e){return FM.find(t=>t.name===e)}const zM=/^[^\s"=\\]+$/,BM=e=>zM.test(e)?e:JSON.stringify(e),VM=`${X}doctor.`;function HM(e){let t=`${VM}${e}.`;return{verdict:`${t}verdict`,reason:`${t}reason`,fixable:`${t}fixable`,sighting:`${t}sighting`}}function UM(e,t){let n=e.kind===`seen`?e.tmuxClient:null,r=e.kind===`seen`?Ij(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 WM(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 GM(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}=oM(t,e);return`${e.client}/${n.kind}/${r.kind===`uncompared`?`-`:r.kind}`}).join(`,`)||`-`}`}const KM=e=>`${e>=0?`+`:``}${Nn(e)}`;function qM({serving:e,processes:t,read:n}){let r=t.kind===`failed`?`daemons=unread others=-`:`daemons=${t.value.length} others=${fM(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`:`${dM(e.value,n).length}/${o.value.length}`;return`${r} memory=${i.kind===`unmeasured`?`unmeasured`:`${Un(i.charge)}${i.charge.kind===`stand-in`?`(${KM(-i.charge.gap)})`:``}:${Nn(i.charge.bytes)}`}/${Nn(a)} postMortems=${s}`}function JM(e){let t=()=>{if(e.pullRequests.kind===`unneeded`)return`-`;let t=e.pullRequests.fact;if(t.kind===`failed`)return`failed`;if(t.value===null)return`no-forge`;let{status:n}=t.value;return typeof n==`string`?n:`logged-out`},n=()=>{if(e.rateLimits.kind===`unneeded`)return`-`;let t=e.rateLimits.fact;if(t.kind===`failed`)return`failed`;let n=e=>t.value.filter(t=>t===e).length;return`${n(`carried`)}/${n(`missing`)}/${n(`unanswered`)}`},r=e.memento.kind===`unneeded`?`-`:e.memento.fact.located.kind===`ok`?`located`:e.memento.fact.located.kind;return`data=pr:${t()},rateLimits:${n()},memento:${r}`}function YM(e,{origin:t,elsewhere:n}){let r=[t,...n],i=r.map(({sources:e})=>XM(e)).join(`,`);if(e.kind===`failed`)return`frames=failed chains=${BM(i)}`;let a=vM(r.flatMap(e=>e.bars));return`frames=${vj.map(e=>a.filter(t=>t.frame===e).length).join(`/`)} chains=${BM(i)}`}function XM(e){let t=Bj(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 ZM(e){let t=Vj(e,Xj);return t.kind===`failed`?`truecolorEnv=failed`:t.value.kind===`unset`?`truecolorEnv=unset`:`truecolorEnv=${BM(`${t.value.from.scope}:${JSON.stringify(t.value.value)}`)}`}function QM(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 $M(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=EM(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 eN(e,t=[]){return t.length===0?e:`${e} (+${t.length} more — run \`cc-candybar doctor\`)`}function tN(e){return e.flatMap(({check:e,verdict:t})=>{let n=HM(e.name);return t.ok?[{key:n.verdict,value:`ok`},{key:n.reason,value:t.note??``},{key:n.fixable,value:fg},{key:n.sighting,value:``}]:[{key:n.verdict,value:`failed`},{key:n.reason,value:eN(t.reason,t.more)},{key:n.fixable,value:t.fix===void 0?fg:dg},{key:n.sighting,value:t.sighting?.glyphs??``}]})}const nN={copySession:{copy:`{{ .session.id }}`},copyResume:{copy:`{{ .resume_command }}`},openProject:{open:`{{ .project_dir }}`},openTranscript:{open:`{{ .transcript_path }}`},openConfig:{open:`{{ .config_path }}`}};function rN(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(nN).map(([t,n])=>[`${e}${t}`,n]))}}const iN=`armed`,aN=`disarmed`,oN=`.armed`,sN=e=>e.endsWith(oN);function cN(e,t,n){let r=`${e}${oN}`,i=`${e}.arm`,a=`${e}.disarm`,o=`(eq .${e} "${iN}")`;return{template:`{{ if ${o} }}{{ action "${e}" "${t.confirm}" }} {{ action "${a}" "✕" }}{{ else }}{{ action "${i}" "${t.arm}" }}{{ end }}`,actions:{[i]:{set:r,to:iN},[a]:{set:r,to:aN},[e]:{do:[a,...n]}},armed:o,variables:{[e]:{kind:`state`,key:r,default:aN}},disarm:a}}const lN=RegExp(`^/[^\\s\\x00-\\x1f\\x7f-\\x9f/][^\\x00-\\x1f\\x7f-\\x9f]*$`);function uN(e){return typeof e==`string`&&lN.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 dN(e){let t=uN(e);if(t.kind===`refused`)throw Error(t.reason);return t.line}const fN=[`/compact`,`/model`],pN=`/clear`;function mN(e){let t=t=>`${e}${t.slice(1)}`,n=`${e}clear.slash`,r=cN(`${e}clear`,{arm:pN,confirm:`${pN} ✓ confirm`},[n]);return{template:fN.map(e=>`{{ action "${t(e)}" "${e}" }} `).join(``)+r.template,when:`{{ ${dk} }}`,actions:{...Object.fromEntries(fN.map(e=>[t(e),{slash:dN(e)}])),...r.actions,[n]:{slash:dN(pN)}},variables:r.variables,disarm:r.disarm}}const hN=Array.from({length:10},(e,t)=>(t+1)*1e5),gN=hN[0],_N=hN[hN.length-1];function vN(e){let t;try{t=Da(e)}catch(e){return L(e instanceof Error?e.message:String(e))}let n=t.autoCompactWindow;return n===void 0?F(`auto`):typeof n==`number`&&Number.isInteger(n)&&n>=gN&&n<=_N?F(n):L(`${e}: autoCompactWindow is ${JSON.stringify(n)}, not a window /autocompact accepts (${gN}–${_N} tokens)`)}function yN(e,t){let n=Math.min(t??_N,_N),r=e===`auto`?n:Math.min(e,n);return{window:e===`auto`?0:e,applied:e===`auto`?0:r,lower:hN.filter(e=>e<r).at(-1)??0,higher:hN.find(e=>e>r&&e<=n)??0}}function bN(e,t){return{template:`{{ if ne .autocompact.error "" }}⇲ ⚠ {{ .autocompact.error }}{{ else }}⇲ {{ if eq .autocompact.window 0 }}auto{{ else }}${t(`.autocompact.applied`)}{{ end }}{{ if ${dk} }}{{ 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:dN(`/autocompact auto`)},...Object.fromEntries(hN.map(t=>[`${e}${t}`,{slash:dN(`/autocompact ${t}`)}]))}}}const xN=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 }}`,SN=`${X}menu`,CN=`open`,wN=`${X}edit`,TN=`${X}toolbar`,EN=rN(X),DN=`${X}commands`,ON=mN(`${DN}.`),kN=`${X}autocompact`,AN=bN(`${kN}.`,xN),jN=e=>({kind:`segment`,name:e}),MN=`${X}tab`,NN=e=>`${MN}.${e}`,PN=e=>`${NN(e)}.toggle`,FN=e=>({variable:MN,key:MN,member:e}),IN=`${X}save`,LN=`${X}preset.save`,RN=`${X}preset.delete`,zN=e=>`${X}${e}`,BN=e=>`${X}apply.${e}`,VN=e=>`${X}reset.${e}`,HN=`${X}themeDefault.save`,UN=`${X}themeDefault.differs`,WN=`${X}themeDefault.theme`,GN={when:`{{ .${UN} }}`,template:`{{ action "${HN}" (printf "⤓ default for %s" .${WN}) }} {{ swatch "${BN(`theme`)}" .${WN} }}`},KN=`${X}resetAll`,qN=`${SN}.toggle`,JN={variable:SN,key:SN,member:CN},YN=`${X}undo`,XN=`${X}back`,ZN=`${XN}.step`,QN=`${X}navigation.back`,$N=XN,eP={template:`{{ if gt .${QN} 0 }}{{ action "${XN}" "◁" }}{{ else }}{{ fg (${uj}) "◁" }}{{ end }}`},tP=`${X}redo`,nP=`${X}doctor`,rP=`${nP}.run`,iP=e=>`${nP}.fix.${e}`,aP=(e,t)=>`${nP}.mark.${e}.${t}`,oP=e=>`${nP}.${e}`,sP={drawn:`[✓ shapes]`,boxes:`[✗ boxes]`},cP=wk(`${X}pickers`),lP=e=>`${X}${e}`,uP=e=>`${lP(e)}.toggle`,dP=e=>$A(e)?wk(`${X}${e}Pickers`):cP,fP=e=>{let t=dP(QA[XA[e].beside]);return{variable:t,key:t,member:e}},pP={layout:{template:`{{ layoutPreview }}`},palette:{template:`{{ themePreview }}`},presetDelete:{when:`{{ not .preset.bundled }}`,template:`{{ action "${RN}" (printf "🚮 delete %s" .${pv.preset.effectiveVar}) }}`}},mP=(e,t)=>`${X}list.${e}.${t}`,hP=e=>`${X}resettable.${e}`,gP=e=>e.length===0?`false`:`(or ${e.map(e=>`.${hP(e)}`).join(` `)})`,_P=M_.map(e=>[j_[e].setting,e]),vP={variables:{},actions:{},segments:{}},yP=Object.fromEntries(_P.map(([e,t])=>[e,RA(`${X}help.${e}`,cj[t],[],vP)])),bP=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],xP=e=>{let t=t=>`.${I_(e,t)}`,n=bP.map(e=>`${1/30} "${e}"`).join(` `);return`{{ if .${pv[j_[e].setting].effectiveVar} }} {{ if ${t(`subscribers`)} }}{{ frames ${n} }} {{ ${t(`fps`)} }} fps{{ if not ${t(`shown`)} }} · off screen{{ end }}{{ else }}no subscriber{{ end }}{{ end }}`},SP=`{{ if eq .${P_(`by`)} "feed" }} {{ printf "%2d" (int .${P_(`fps`)}) }} fps{{ end }}`,CP=Object.fromEntries(_P.map(([e,t])=>[e,xP(t)])),wP=Object.keys(pv).map(e=>{let t=pv[e],n=zk(t.configKey),r=Ik({label:t.label,domain:n},t.sessionKey,t.effectiveVar,BN(e),dP(QA[e]));return{...t,name:e,control:r,beneath:t.previews.map(e=>pP[e])}}),TP=e=>wP.filter(t=>QA[t.name]===e),EP=e=>wP.filter(t=>ej(QA[t.name],e)),DP=e=>t=>`(print ${ri(t)} (ternary ${ri(` •`)} "" ${gP(EP(e).map(e=>e.name))}))`,OP=e=>ZA.filter(t=>XA[t].beside===e),kP=e=>TP(e).flatMap(e=>[VP(e),...[yP[e.name]].filter(e=>e!==void 0),...OP(e.name).map(e=>Qr(lP(e),fP(e),JP(e),`drop`))]);new Set(wP.flatMap(e=>[e.sessionKey,e.configKey]));const AP=cN(KN,{arm:`⟲`,confirm:`⟲ reset all?`},wP.map(e=>VN(e.name))),jP=[`unsaved`,`history.undo`,`history.redo`],MP=e=>`${X}${e}`,NP=MP(`unsaved`),PP=(e,t)=>({body:t,shown:`(gt .${MP(e)} 0)`}),FP=[PP(`unsaved`,`{{ action "${IN}" (printf "💾 save %d" .${NP}) }}`),PP(`history.undo`,`{{ action "${YN}" "↶" }}`),PP(`history.redo`,`{{ action "${tP}" "↷" }}`),{body:AP.template,shown:`(or ${gP(wP.map(e=>e.name))} ${AP.armed})`}],IP={when:`{{ or ${FP.map(e=>e.shown).join(` `)} }}`,template:`{{ $sep := "" }}`+FP.map(e=>`{{ if ${e.shown} }}{{ $sep }}${e.body}{{ $sep = " " }}{{ end }}`).join(``)},LP=[{step:AP,place:`door`},{step:ON,place:`session`}],RP=e=>e.map(e=>e.step.disarm),zP=RP(LP),BP=RP(LP.filter(e=>e.place!==`door`));function VP(e){let t=zN(e.name);return e.control.kind===`inline`?jN(t):Qr(t,e.control.list.ref,{kind:`container`,direction:`vertical`,children:[...e.control.list.rows,...e.beneath].map((t,n)=>jN(mP(e.name,n)))},`drop`)}function HP(e){return e===SN}function UP(e){let t=jN(SN);if(e.kind===`container`&&e.direction===`vertical`){let[n,...r]=e.children;return e.when===void 0&&n!==void 0?{...e,children:[UP(n),...r]}:{kind:`container`,direction:`vertical`,children:[t,e]}}return e.kind===`container`&&e.when===void 0?{...e,children:[t,...e.children]}:{kind:`container`,direction:`horizontal`,children:[t,e]}}function WP(e){return GP(e)>0?e:UP(e)}function GP(e){let t=0;for(let n of Cg(e))n.kind===`segment`&&HP(n.name)&&(t+=1);return t}function KP(e,t=!1){let n=t||e.when!==void 0;return e.kind===`segment`?n&&HP(e.name)||e.opens!==void 0&&KP(e.opens.body,!0):e.children.some(e=>KP(e,n))}const qP={door:{direction:`horizontal`,content:[jN($N)],after:[jN(wN),jN(IN)]},session:{direction:`vertical`,content:[jN(TN),{kind:`container`,direction:`horizontal`,children:[jN(DN),jN(kN)]}],after:[]},look:{direction:`horizontal`,content:[],after:[]},layout:{direction:`horizontal`,content:[jN(LN)],after:[]},config:{direction:`horizontal`,content:[],after:[]},tools:{direction:`vertical`,content:[jN(nP),...FM.map(e=>jN(oP(e.name)))],after:[]},gear:{direction:`horizontal`,content:[],after:[jN(HN)]},toggles:{direction:`horizontal`,content:[],after:[]}};function JP(e){let{direction:t,content:n,after:r}=qP[e];return{kind:`container`,direction:t,children:[...n,...kP(e),...r]}}function YP(e){return e.kind===`segment`?HP(e.name)?Qr(e.name,JN,ZP,`above`):e:$P(e)}function XP(){return{kind:`container`,direction:`vertical`,children:[JP(`door`),{kind:`container`,direction:`horizontal`,children:JA.map(({member:e})=>Qr(NN(e),FN(e),JP(e),`drop`))}]}}const ZP=XP();function QP(e){let t=new Map;for(let e of Cg(ZP))e.kind===`segment`&&e.opens!==void 0&&t.set(e.opens.ref.key,e.opens.ref.variable);return[...t].map(([t,n])=>{let r=e.variables[n];if(r?.kind!==`state`||r.default===void 0)throw Error(`settings menu: the door folds "${t}", but "${n}" is not a state variable the menu declares with a default`);let i=`${SN}.fold.${mk(t)}`;return e.actions[i]={set:t,to:r.default},i})}function $P(e){return{...e,children:e.children.map(e=>YP(e))}}function eF(e){let t={variables:{[SN]:ii(SN,P)},actions:{[qN]:ai(SN,CN),[rP]:{doctor:`run`},[wN]:{do:[...DA]},...EN.actions,...ON.actions,...AN.actions,[IN]:{save:!0},[YN]:{undo:!0},[ZN]:{back:!0},[XN]:{do:[ZN,...zP]},[tP]:{redo:!0},[LN]:{preset:`save`},[HN]:{themeDefault:`save`},[RN]:{preset:`delete`,name:`{{ .${pv.preset.effectiveVar} }}`}},segments:{[SN]:{template:`{{ $door := ${ni(SN,ri(e),ri(`✖`))} }}{{ if ${ei(JN)} }}{{ fg (keptOn (color "error") (bgOf)) $door }}{{ else }}{{ $door }}{{ end }}`+SP},[TN]:{template:EN.template},[DN]:{template:ON.template,when:ON.when},[kN]:{template:AN.template,bg:AN.bg,when:AN.when},[$N]:eP,[IN]:IP,[HN]:GN,[LN]:{template:`{{ action "${LN}" "+ preset" }}`},[nP]:{template:`{{ action "${rP}" "🩺 doctor" }}`},[wN]:{template:`{{ action "${wN}" "✎ arrange" "✎ done" }}`}}};t.variables[UN]={kind:`input`,path:`themeDefault.differs`,type:`boolean`,default:!1},t.variables[WN]={kind:`input`,path:`themeDefault.theme`,type:`string`,default:``},t.variables[QN]={kind:`input`,path:`navigation.back`,type:`number`,default:0};for(let e of jP)t.variables[MP(e)]={kind:`input`,path:e,type:`number`,default:0};t.variables[MN]=ii(MN,`session`);for(let{member:e,label:n}of JA){t.actions[PN(e)]=ai(MN,e),t.actions[NN(e)]={do:[PN(e),...BP]};let r=DP(e);t.segments[NN(e)]={template:`{{ ${ni(NN(e),r(n),r(`▾ ${n}`))} }}`}}return Object.assign(t.variables,ON.variables,AP.variables),nF(t),tF(t),t.actions[SN]={do:[qN,...zP,...QP(t)]},t}function tF(e){for(let t of FM){let n=HM(t.name),r=iP(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?Gj:[];for(let n of i)e.actions[aP(t.name,n)]={doctor:`mark`,check:t.name,mark:n};let a=i.map(e=>` {{ action "${aP(t.name,e)}" "${sP[e]}" }}`).join(``);e.segments[oP(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} "${dg}" }} {{ action "${r}" "[fix]" }}{{ end }}`+(a===``?``:`{{ if ne .${n.sighting} "" }} {{ .${n.sighting} }}${a}{{ end }}`)+`{{ end }}`}}}function nF(e){for(let t of wP){Object.assign(e.actions,t.control.actions);let n=VN(t.name);e.actions[n]={reset:t.configKey},e.variables[hP(t.name)]={kind:`input`,path:`resettable.${t.name}`,type:`boolean`,default:!1};let r=`{{ if .${hP(t.name)} }} {{ action "${n}" "↺" }}{{ end }}`;Object.assign(e.variables,t.control.variables),e.segments[zN(t.name)]={template:`${t.control.template}${CP[t.name]??``}${r}`},t.control.kind===`picker`&&[...t.control.list.rows.map(e=>({template:e})),...t.beneath].forEach((n,r)=>{e.segments[mP(t.name,r)]=n})}Object.assign(e.actions,AP.actions),Object.assign(e.variables,vP.variables),Object.assign(e.actions,vP.actions),Object.assign(e.segments,vP.segments);for(let t of ZA){let n=fP(t);e.actions[uP(t)]=ai(n.key,n.member),e.segments[lP(t)]={template:`{{ action "${uP(t)}" ${DP(t)(XA[t].trigger)} }}`}}}function rF(e){let{variables:t,actions:n}=IA();Object.assign(e.variables,t),Object.assign(e.actions,n)}function iF(e){let t=eF(e.globals.menuGlyph??`🍫`);rF(t);let n={...e.presets},r=[];for(let t of Hy(e.presets)){let{node:i}=Gy(e,t),a=YP(WP(i));r.push(a),n[t]={...Wy(e.presets,t),root:a}}let i=pk(t,r,e);return{...e,variables:{...i,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:n}}const aF=`${_k}live`,oF=[`☐ live`,`☑ live`],sF=`${_k}done`,cF=`${_k}cancel`,lF=`${_k}rewind`,uF=`${_k}changes`,dF=`(gt .${uF} 0)`,fF=`(or ${dF} (gt .${NP} 0))`,pF={variable:aF,key:aF,member:`open`};function mF(e){return`${_k}configuring.p${e}`}function hF(e){return`and ${ei(jA)} (not ${ei(pF)}) (ne .${mF(e)} "true")`}function gF(e){return{kind:`template`,template:`{{ or ${e.map(e=>`(eq .${wA} "${Zr(e)}")`).join(` `)} false }}`}}function _F(e,t,n){return`{{ if ${hF(e)} }}${t}{{ else }}${n}{{ end }}`}const vF=`{{ and ${ei(jA)} .preset.customized }}`,yF=yk;function bF(e){return new Map([...Xy(e),...SF(e)])}const xF=`${_k}addable`;function SF(e){return new Map([[xF,{members:Object.keys(e.segments).filter(e=>!yF(e)),library:{groups:bA.map(e=>({id:e,label:xA[e]})),entry:t=>{let n=e.segments[t];return{group:n.group??`other`,...n.description!==void 0&&{description:n.description}}}}}]])}function CF(e,t,n){return n.segments[e]={template:t,when:MA,bg:BA},{kind:`segment`,name:e}}function wF(e,t,n){let r=`${_k}${e.presetIdent}.remove.${t}`;return e.artifacts.actions[r]={persist:e.rootKey,removeSegment:n},`{{ fg (${`readableOn (color "error") (bgOf) ${eh}`}) (action "${r}" "✖") }}`}function TF(e){return`{{ if ${ei(jA)} }}${e}{{ end }}`}function EF(e,t){return e.reduce((e,t)=>`{{ if and ${ei(jA)} ${ei(t)} }}true{{ else }}${e}{{ end }}`,t)}function DF(e){return e.flatMap(e=>[...Cg(e)].flatMap(e=>e.kind===`segment`&&e.opens?.ref.key===`edit.configure`?[e.opens.ref]:[]))}function OF(e,t,n){return`${kA}${e}.${t}.${n}`}function kF(e,t,n,r){let i=yg(n),a=`${_k}${e.presetIdent}`,o=AA(e.presetIdent,i);e.configured.push(o);let s=`${a}.configure.${t}`,c=wk(s),l=`${s}.fold`;e.artifacts.actions[l]={set:c,to:P},e.artifacts.actions[s]={do:[`${s}.open`,l]},e.artifacts.actions[`${s}.open`]={set:wA,to:o};let u={},d=Object.entries(r).map(([r,o])=>{let s=OF(e.presetIdent,i,r),l=`${kA}p${e.presetIdent}.d${t}.${r}`;e.artifacts.variables[l]={kind:`state`,key:s,default:Hg(n.settings?.[r]??o.default)},u[r]={id:i,key:s,variable:l};let d=`${a}.setting.${t}.${r}`,f=Ik(Pk(o),s,l,d,c);if(Object.assign(e.artifacts.actions,f.actions),Object.assign(e.artifacts.variables,f.variables),f.kind===`inline`)return e.artifacts.segments[d]={template:f.template},{kind:`segment`,name:d};e.artifacts.segments[d]={template:f.template};let p=f.list.rows.map((t,n)=>{let r=`${d}.list.${n}`;return e.artifacts.segments[r]={template:t},{kind:`segment`,name:r}});return Qr(d,f.list.ref,{kind:`container`,direction:`vertical`,children:p},`drop`)});return{term:`{{ action "${s}" "${KA}" }}`,ref:{variable:wA,key:wA,member:o},body:{kind:`container`,direction:`vertical`,children:d},drafts:u}}const AF=`${_k}label:`;function jF(e){if(e.startsWith(AF)){let t=e.slice(AF.length);return t.slice(t.indexOf(`:`)+1)}return e.startsWith(`edit.`)?void 0:e}function MF(e,t,n,r){let{artifacts:i}=n,a=yg(e),o=`${AF}${a}:${e.name}`;i.segments[o]={template:`{{ "${Zr(a)}" }}`,...t.palette!==void 0&&{palette:t.palette}};let s=Object.fromEntries(Lg.flatMap(t=>{let n=e.settings?.[t];return n===void 0?[]:[[t,n]]}));return{...Qr(o,r.ref,r.body,`drop`,EF([r.ref],`{{ ${hF(n.presetIdent)} }}`)),...Object.keys(s).length>0&&{settings:s},drafts:Object.fromEntries(Lg.map(e=>[e,r.drafts[e]]))}}function NF(e,t,n,r){let{presetIdent:i,artifacts:a}=e,o=`${_k}${i}.insert.${t}`,s=`${_k}${i}.insertSeg.${t}`;a.actions[o]={persist:e.rootKey,insertSegmentFrom:xF,anchor:n,relation:r};let c=Sk(o),l=Ck(s,o,void 0),u=Ek(l),d=Tk(l,c);return a.variables[l]=ii(l,P),a.variables[u]={kind:`state`,key:u,default:`0`},a.actions[d]=ai(l,c),a.actions[u]={set:u,int:!0},{host:s,template:`{{ $m := menu "${o}" "✚" "✕" }}{{ if ${ei({variable:l,key:l,member:c})} }}{{ $m }}{{ else }}{{ fg (${`readableOn (color "success") (bgOf) ${eh}`}) $m }}{{ end }}`}}function PF(e,t){let n=[],r=e.children.findIndex(e=>e.kind===`segment`&&!yF(e.name)),i=e=>PF(e,t);for(let[a,o]of e.children.entries()){if(o.kind===`container`){n.push(i(o));continue}let s=Sg(o,i);if(yF(o.name)){n.push(s);continue}let c=yg(o),l=a===r?[NF(t,String(t.posCounter.n++),c,`before`)]:[],u=String(t.posCounter.n++),d=NF(t,u,c,`after`),f=wF(t,u,c),p=t.segments[o.name],m=kF(t,u,o,Rg(p)),h=TF(f),g=TF(m.term),_={kind:`container`,direction:`horizontal`,children:[...l.map(e=>CF(e.host,e.template,t.artifacts)),{...MF(o,p,t,m),lead:h,trail:g},{...s,when:_F(t.presetIdent,`false`,o.when??`true`),lead:h,trail:g,drafts:m.drafts},CF(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:EF(DF(n),_F(t.presetIdent,`true`,e.when))}}}function FF(e,t,n,r,i,a,o){let s=`${_k}${t}.resetLayout`,c=`${_k}${t}.customized`;return r.actions[s]={reset:n},r.segments[c]={template:`{{ action "${s}" "↺ reset layout" }}`,when:vF},{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[...i,{kind:`segment`,name:c},a]},IF(e,o)]}}function IF(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),IF(n,t)]}:{...e,children:[...e.children,t]}}function LF(e,t,n,r,i,a){let{node:o}=Gy(e,t),s={presetIdent:mk(t),rootKey:pA(t),segments:e.segments,artifacts:n,posCounter:{n:0},configured:[]},c=PF(o,s);return n.variables[mF(s.presetIdent)]=gF(s.configured),FF(c,s.presetIdent,s.rootKey,n,r,i,a)}function RF(e){let t={variables:{},actions:{},segments:{}},n=RA(`${_k}help`,sj,[jA],t);t.variables[aF]=ii(aF,P),t.actions[aF]=ai(aF,pF.member),t.segments[aF]={template:ti(aF,...oF),when:MA};let r={kind:`segment`,name:aF},i=n;t.variables[uF]={kind:`input`,path:`history.sinceEdit`,type:`number`,default:0},t.actions[sF]={do:[IN,...DA]},t.segments[sF]={template:`{{ if ${fF} }}{{ action "${sF}" "✓ save" }}{{ else }}{{ action "${sF}" "✓ done" }}{{ end }}`,when:MA},t.actions[lF]={rewind:!0},t.actions[cF]={do:[lF,...DA]},t.segments[cF]={template:`{{ action "${cF}" "↩ cancel" }}`,when:`{{ and ${ei(jA)} ${dF} }}`};let a=[{kind:`segment`,name:sF},{kind:`segment`,name:cF}],o={...e.presets},s=[];for(let n of Hy(e.presets)){let c=LF(e,n,t,a,r,i);s.push(c),o[n]={...Wy(e.presets,n),root:c}}let c=pk(t,s,e);return{...e,variables:{...c,...e.variables,...t.variables},actions:{...e.actions,...t.actions},segments:{...e.segments,...t.segments},presets:o}}function zF(e){return e.op===`remove`?`remove:${e.target}`:`insert:${e.segment}:${e.anchor}:${e.relation}`}function BF(e){let t=e.split(`:`);return t[0]===`remove`&&t.length===2&&t[1]?{op:`remove`,target:t[1]}:t[0]===`insert`&&t.length===4&&t[1]&&t[2]&&(t[3]===`before`||t[3]===`after`)?{op:`insert`,segment:t[1],anchor:t[2],relation:t[3]}:null}function VF(e,t,n){let r=xg(e,new Set(n.map(bg).filter(e=>e.includes(t)).flat()));return r===e?{seg:e}:{seg:e,id:r}}const HF=/^-?\d+$/;function UF(e,t,n=`set-state`){let r=e.filter(e=>e.includes(`/`));if(r.length>0)throw Error(`makeAllowListValidator(${t}): values contain "/" — the ${n} wire shape splits values on "/" so slash-bearing options cannot be addressed. Offending values: ${r.join(`, `)}`);if(e.includes(``))throw Error(`makeAllowListValidator(${t}): empty string is not a writable option — the validator rejects empty input before the allow-list check, so an "" in the allowed list could be rendered but never delivered. Remove "" from the allowed list.`);let i=new Set(e),a=[...e];return e=>e?i.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown ${t} "${e}" (have: ${a.join(`, `)})`}:{ok:!1,reason:`${t} value is required`}}function WF(e){return t=>{if(!t)return{ok:!1,reason:`${e} value is required`};if(!HF.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 GF(e,t,n){return r=>r?HF.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 KF(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=>!HF.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 qF(e){return e===`config`?`set-config`:`set-state`}function JF(e,t,n){return t.kind===`int`?WF(`menu page "${e}"`):t.kind===`range`?GF(t.min,t.max,`${n} stepper "${e}"`):UF(t.allowed,`${n} "${e}"`,qF(n))}function YF(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:KF(e,n,t)}))}function XF(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 YF(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,JF(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 ZF(e,t,n){let r=[],i=0,a=new WeakMap;return{register(n,a){let o={key:n,allowed:a};XF(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=XF(e,r,n(o),t);return a.set(o,{epoch:i,gate:c}),c}}}const QF=ZF({},`config`,aI);function $F(e,t){return QF.register(e,t)}function eI(e){return QF.gateFor(e)}function tI(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:Qy(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:[zF({op:`remove`,target:e.removeSegment})]}}]:`insertSegment`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:[zF({op:`insert`,segment:e.insertSegment,anchor:e.anchor,relation:e.relation})]}}]:`insertSegmentFrom`in e?[{key:e.persist,spec:{kind:`allow-list`,allowed:Qy(e.insertSegmentFrom,t).members.map(t=>zF({op:`insert`,segment:t,anchor:e.anchor,relation:e.relation}))}}]:[{key:e.persist,spec:{kind:`range`,min:e.min,max:e.max}}]:[]}function nI(e,t){let n=cA(e).get(t);return n===void 0?null:String(n)}function rI(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?_A(n.persist):null;e?.scope===`preset-root`&&t.add(pA(e.preset))}return[...t].map(e=>({key:e,spec:{kind:`allow-list`,allowed:[]}}))}function iI(e){let t=bF(e);return[...rI(e),...Object.values(e.actions).flatMap(e=>tI(e,t))]}function aI(e){return YF(iI(e),`config`)}function oI(e,t){return{globals:{...t.globals,...e.globals??{}},variables:{...t.variables,...e.variables??{}},segments:lI(t.segments,sI(t.segments,e.segments??{})),root:Ry(e.root??jy,t.root),actions:{...t.actions,...e.actions??{}},styles:{...t.styles,...e.styles??{}},presets:lI(t.presets,cI(t.presets,e.presets??{})),themeDefaults:lI(t.themeDefaults,e.themeDefaults??{}),editGlobals:{...t.editGlobals,...e.editGlobals??{}},helpers:{...t.helpers,...e.helpers??{}}}}function sI(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 cI(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 lI(e,t){return{...e,...Object.fromEntries(Object.entries(t).map(([t,n])=>[t,{...e[t],...n}]))}}function uI(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: ${kg.join(`, `)})`,line:K(e.source,t.split(`.`))}),null):pI(e,`${t}.cache`,n.cache)}function dI(e){return{required:!0,json:mI(),parse:(t,n,r,i)=>uI(t,n,i,e)??void 0}}const fI={noun:`cache`,arms:{ttl:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&gI(n)?{ttl:n}:d_(e,t,`cache.ttl must be a duration string like "5s", "100ms", "2m", "1h"; got ${q(n)}`)},watch_file:{json:{type:`string`,pattern:`^/`},parse:(e,t,n)=>{if(typeof n!=`string`)return d_(e,t,`cache.watch_file must be a path string, got ${q(n)}`);let r=C_(`cache.watch_file`,n);return r===null?{watch_file:n}:d_(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}:d_(e,t,`cache.depends_on must be an array of variable-name strings, got ${q(n)}`)},key:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`&&n!==``?{key:n}:d_(e,t,`cache.key must be a non-empty template string, got ${q(n)}`)},never:{json:{const:!0},parse:(e,t,n)=>n===!0?{never:!0}:d_(e,t,`cache.never must be the literal boolean true, got ${q(n)}`)}}};function pI(e,t,n){return f_(e,fI,t,n)}function mI(){return A_(fI)}const hI=/^(\d+(?:\.\d+)?)(ms|s|m|h)$/;function gI(e){return hI.test(e)}function _I(e,t,n){if(n===void 0)return{};if(!i_(n))return e.issues.push({path:t,message:`${t} must be an object, got ${a_(n)}`,line:K(e.source,t.split(`.`))}),{};let r={};for(let[i,a]of Object.entries(n)){let n=p_(e,UI,`${t}.${i}`,a);n!==null&&(r[i]=n)}return r}function vI(){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 ${a_(i)}`,line:K(e.source,t.split(`.`))});return}return i}}}function yI(){return{required:!0,json:{enum:[...jg]},parse:(e,t,n,r)=>{let i=r.field;if(typeof i!=`string`||!jg.includes(i)){e.issues.push({path:`${t}.field`,message:`git field must be one of: ${jg.join(`, `)}, got ${JSON.stringify(i)}`,line:K(e.source,[...t.split(`.`),`field`])});return}return i}}}function bI(){return{required:!1,json:{type:[`string`,`number`,`boolean`]},parse:(e,t,n,r)=>{let i=r.type;return e_(e,t,r,i===`number`||i===`boolean`||i===`string`?i:`string`)}}}const xI={noun:`parse`,arms:{text:{json:{const:!0},parse:(e,t,n)=>n===!0?{text:!0}:d_(e,t,`parse.text must be the literal boolean true, got ${q(n)}`)},regex:{json:{type:`string`},parse:(e,t,n)=>typeof n==`string`?SI(e,t,n):d_(e,t,`parse.regex must be a pattern string, got ${q(n)}`)},json:{json:{const:!0},parse:(e,t,n)=>n===!0?{json:!0}:d_(e,t,`parse.json must be the literal boolean true, got ${q(n)}`)}}};function SI(e,t,n){let r;try{new RegExp(n),r=RegExp(`${n}|`).exec(``).length-1}catch(n){return d_(e,t,`parse.regex is not a valid regular expression: ${n.message}`)}return r>=1?{regex:n}:d_(e,t,`parse.regex must contain a capture group — its group 1 is the value; got ${JSON.stringify(n)}`)}function CI(){return{required:!1,json:A_(xI),parse:(e,t,n,r)=>(r.regex!==void 0&&e.issues.push({path:`${t}.regex`,message:`${t}.regex was retired; the regex is the parse step's regex arm now: parse: { regex: ${JSON.stringify(r.regex)} }`,line:K(e.source,[...t.split(`.`),`regex`])}),r.parse===void 0?void 0:f_(e,xI,`${t}.parse`,r.parse)??void 0)}}function wI(){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)=>i_(r.parse)&&`json`in r.parse?TI(e,t,r.default):t_(e,t,r,`default`)}}function TI(e,t,n){if(n!==void 0)return EI(n)?n:d_(e,`${t}.default`,`${t}.default must be a JSON value (a json-parsed source's document), got ${q(n)}`)??void 0}function EI(e){return e!==null&&DI(e)}function DI(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(DI);let t=Object.getPrototypeOf(e);return(t===Object.prototype||t===null)&&Object.values(e).every(DI)}default:return!1}}const OI={value:vI(),default:__()},kI={path:S_(),type:T_([`string`,`number`,`boolean`]),default:bI()},AI={name:S_(),default:__()},jI={path:w_(),readMode:T_([`whole`,`first-line`]),parse:CI(),cache:dI(`file`),default:wI()},MI={command:S_(),parse:CI(),cache:dI(`shell`),default:wI()};function NI(e){return{cache:`${e}, so it takes no cache policy — delete the key`}}const PI={template:S_(),default:__()},FI=NI(`a template variable recomputes whenever a variable it reads changes`),II={layout:S_(),default:__()},LI=NI(`a time variable reads the instant its render is drawn at`),RI={field:yI(),default:__()},zI=NI(`a git variable is refreshed by the daemon's own watch on the repository`),BI={key:S_(),default:__()},VI=`kind`;function HI(e,t,n={}){return{...m_(VI,e,t),parse:(r,i,a)=>{s_(r,n,i,a);let o=c_(r,t,i,a);return o===null?null:{kind:e,...o}}}}const UI={tag:VI,noun:`source kind`,memberNoun:`variable`,arms:{literal:HI(`literal`,OI),input:HI(`input`,kI),env:HI(`env`,AI),file:HI(`file`,jI),shell:HI(`shell`,MI),template:HI(`template`,PI,FI),time:HI(`time`,II,LI),git:HI(`git`,RI,zI),state:HI(`state`,BI)}};function WI(){return k_(UI)}function GI(){return{type:`object`,additionalProperties:WI()}}const KI=new Map([[`gitTaculous`,{kind:`built-in`,to:`gitaculous`}],[`git`,{kind:`built-in`,to:`gitaculous`}],[`settings.menu`,{kind:`built-in`,to:`candybar.menu`}],[`ticket`,{kind:`plugin`,to:`plugins.lit.ticket`,source:`promptctl/links-issue-tracker`}]]);function qI(e){let t=KI.get(e);if(t===void 0)return``;switch(t.kind){case`built-in`:return` (the built-in segment "${e}" was renamed to "${t.to}" — update this reference)`;case`plugin`:return` (the built-in segment "${e}" became "${t.to}", a segment of the plugin \`cc-candybar plugin install ${t.source}\` installs — update this reference)`}}const JI=/^[A-Za-z_][A-Za-z0-9_]*$/,YI={pattern:JI.source},XI={anyOf:[{type:`boolean`},{type:`string`},{type:`integer`}]},ZI={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`,...YI}}}]},default:XI}},QI=[`label`,`domain`,`default`],$I=[`min`,`max`,`step`,`atLeast`];function eL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function tL(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 eL(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 eL(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?eL(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(i_(n)){let{min:r,max:i,step:a=1,atLeast:o}=n;return Object.keys(n).filter(e=>!$I.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}}:eL(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 eL(e,t,`domain must be "bool", a list of words, or { min, max }, got ${q(n)}`)}function nL(e,t,n){if(!i_(n))return eL(e,t,`${t} must be { label, domain, default }, got ${a_(n)}`);for(let r of Object.keys(n))QI.includes(r)||eL(e,`${t}.${r}`,`Unknown setting key "${r}". Expected one of: ${QI.join(`, `)}`);let{label:r}=n,i=typeof r==`string`&&r.length>0&&!/[\n\r]/.test(r);i||eL(e,`${t}.label`,`a setting needs a one-line, non-empty "label" — the name its control shows, spliced into a synthesized template string — got ${q(r)}`);let a=tL(e,`${t}.domain`,n.domain);if(!i||a===void 0)return;let o={label:r,domain:a,default:n.default};return!rL(n.default)||!Vg(o,n.default)?eL(e,`${t}.default`,`default must be ${Gg(o)}, got ${q(n.default)}`):o}function rL(e){return typeof e==`boolean`||typeof e==`string`||typeof e==`number`}const iL={theme:`its default for this segment is segments.<name>.palette, and a placement sets its own with settings: { ${Fg}: "<theme>" }`,effect:`a placement follows the bar's effect, or sets its own with settings: { effect: "<effect>" }`};function aL(e){return Lg.includes(e)}function oL(){return{required:!1,json:{type:`object`,propertyNames:{...YI,not:{enum:[...Lg]}},additionalProperties:ZI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return eL(e,a,`${a} must be an object of name → { label, domain, default }, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i)){if(!JI.test(t)){eL(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(aL(t)){eL(e,`${a}.${t}`,`setting "${t}" is one every placement already has — ${iL[t]}`);continue}let r=nL(e,`${a}.${t}`,n);r!==void 0&&(o[t]=r)}return o}}}const sL=vk.map(e=>e.replace(/\./g,`\\.`)).join(`|`);function cL(){return{required:!1,json:{type:`string`,minLength:1,pattern:`^(?!${sL})[^:/]+$`},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return typeof i==`string`&&i.length>0&&!/[:/]/.test(i)&&!yk(i)?i:eL(e,`${t}.${n}`,`a placement "id" must be a non-empty string without "/" or ":", outside the reserved ${vk.map(e=>`"${e}"`).join(`, `)} namespaces, got ${q(i)}`)}}}function lL(){return{required:!1,json:{type:`object`,propertyNames:YI,additionalProperties:XI},parse:(e,t,n,r)=>{let i=r[n];if(i===void 0)return;let a=`${t}.${n}`;if(!i_(i))return eL(e,a,`a placement's "settings" must be an object of setting name → value, got ${a_(i)}`);let o=Object.create(null);for(let[t,n]of Object.entries(i))rL(n)?o[t]=n:eL(e,`${a}.${t}`,`setting "${t}" must be a boolean, a word, or a number, got ${a_(n)}`);return o}}}function uL(e){return new Set(Object.keys(e.segments).filter(e=>!yk(e)))}function dL(e,t,n){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`segments`,message:`segments must be an object, got ${a_(t)}`,line:K(e.source,[`segments`])}),{};let r={};for(let[i,a]of Object.entries(t)){let t=o_(e,n.has(i)?_L:gL,`segments.${i}`,a);t!==null&&(r[i]=t)}return r}function fL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>r[n]===void 0?d_(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${qI(t.slice(9))}`)??void 0:$g(e,t,r,n)??void 0}}function pL(){return{required:!1,json:{anyOf:[{const:`auto`},{const:`fill`},{type:`integer`,minimum:1}]},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(i===`auto`)return`auto`;if(i===`fill`)return`fill`;if(typeof i==`number`&&Number.isInteger(i)&&i>0)return i;e.issues.push({path:`${t}.${n}`,message:`width must be "auto", "fill", or a positive integer, got ${q(i)}`,line:K(e.source,[...t.split(`.`),n])})}}}}function mL(){return{required:!1,json:GI(),parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0)return _I(e,`${t}.${n}`,i)}}}const hL={template:fL(),description:__(),group:T_(yA),width:pL(),justify:T_(Kg),truncate:T_(qg),bg:__(),fg:__(),when:__(),palette:x_(),vars:mL(),settings:oL(),missingData:T_(Mg)},gL={noun:`segment key`,fields:hL},_L={noun:`segment key`,fields:{...hL,template:__()}},vL=`#/definitions/LayoutNode`,yL={kind:`container`,direction:`vertical`,children:[]};function bL(e){return{required:!0,json:{const:e},parse:()=>e}}function xL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a segment node must have a non-empty "name" (a segment name), got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}function SL(){return{required:!0,json:{enum:[..._g]},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&_g.includes(i)?i:(e.issues.push({path:`${t}.${n}`,message:`a container "direction" must be one of: ${_g.join(`, `)} (got ${JSON.stringify(i)})`,line:K(e.source,[`root`])}),`vertical`)}}}function CL(e){return{required:!0,json:{type:`array`,items:{$ref:vL}},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 ${a_(a)}`,line:K(t.source,[`root`])}),[])}}}const wL={noun:`layout-node key`,fields:{kind:bL(`segment`),name:xL(),when:__(),id:cL(),settings:lL()}},TL=()=>T_(jm),EL={noun:`layout-node key`,fields:{kind:bL(`container`),direction:SL(),children:CL(h_(()=>jL)),when:__(),distribution:TL()}};function DL(){return{required:!0,json:{type:`string`},parse:(e,t,n,r)=>{let i=r[n];return typeof i==`string`&&i.length>0?i:(e.issues.push({path:`${t}.${n}`,message:`a "seg" node must have a non-empty segment name, got ${q(i)}`,line:K(e.source,[`root`])}),``)}}}const OL={noun:`layout-node key`,fields:{seg:DL(),when:__(),id:cL(),settings:lL()}},kL={noun:`layout-node key`,fields:{h:CL(h_(()=>jL)),when:__(),distribution:TL()}},AL={noun:`layout-node key`,fields:{v:CL(h_(()=>jL)),when:__(),distribution:TL()}},jL=(e,t,n)=>{if(typeof n==`string`)return n.length===0?(e.issues.push({path:t,message:`a bare-string layout node must be a non-empty segment name`,line:K(e.source,[`root`])}),yL):{kind:`segment`,name:n};if(!i_(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 ${a_(n)}`,line:K(e.source,[`root`])}),yL;if(n.kind===`container`)return o_(e,EL,t,n)??yL;if(n.kind===`segment`)return o_(e,wL,t,n)??yL;if(n.kind===`cells`)return e.issues.push({path:t,message:`kind: "cells" is no longer supported — use the h-arm spelling instead:
|
|
183
183
|
Old: { kind: "cells", segments: ["seg1", "seg2"] }
|
|
184
|
-
New: { h: ["seg1", "seg2"] }`,line:K(e.source,[`root`])}),sL;if(n.kind===`group`){let r=o_(e,EL,t,n);return r===null?sL:(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}),OL(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:K(e.source,[`root`])}),sL}if(a){let r=o_(e,gL,t,n);return r===null?sL:{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=o_(e,_L,t,n);return r===null?sL:{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=o_(e,vL,t,n);return r===null?sL:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:K(e.source,[`root`])}),sL};function bL(){return{required:!0,json:{type:`object`,propertyNames:{pattern:ky.source},additionalProperties:{$ref:oL}},parse:(e,t,n,r)=>{let i=r[n];if(!i_(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!ky.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:K(e.source,[...t.split(`.`),n,r])});continue}a[r]=yL(e,`${t}.${n}.${r}`,o)}return a}}}const xL={noun:`root key`,fields:{rows:bL(),when:__(),distribution:pL()}};function SL(e,t,n){return i_(n)&&`rows`in n?o_(e,xL,t,n)??{rows:{}}:yL(e,t,n)}function CL(){return{required:!0,json:{type:`string`,pattern:ky.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!ky.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 "${P}", got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}function wL(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}}function TL(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=$g(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:K(e.source,[...t.split(`.`),n])});return}return i}}}}const EL={noun:`layout-node key`,fields:{kind:cL(`group`),name:CL(),label:TL(),open:v_(),direction:T_(_g),key:wL(),bg:__(),fg:__(),when:__(),distribution:pL(),children:dL(h_(()=>yL))}};function DL(e){return e.key??`groups.`+e.name}function OL(e){let t=rk+e.name;return Qr(t,{variable:t,key:DL(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function kL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function AL(e,t){lk(e,t,rk,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&kL(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}.`)&&DL(t)===DL(r)&&kL(e,t.path,`group "${t.name}" shares key "${DL(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=DL(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&kL(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=rk+e.name,r=DL(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ii(r,i.get(r)),o[t]=ai(r,e.name),s[t]={template:ti(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const jL=`menu`,ML=`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`,NL=e=>e.kind===`call`&&e.name===`dict`,PL=e=>e.kind===`literal`&&typeof e.value!=`object`,FL=e=>Yr(``,e,2)===void 0;function IL(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&&NL(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(NL))return t(`whose options (dict …) is not its last argument — ${ML}`);if(i!==void 0&&a===void 0&&!PL(i)&&FL(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Yr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${ML}`);let c=a===void 0?{}:vw(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=vk(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=ck(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 "${fk(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 LL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===jL).map(IL)}catch{return`parse-failed`}}function RL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(jL)}catch{return!1}}function zL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function BL(e,t){lk(e,t,ik,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))RL(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:K(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&RL(i)&&zL(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 Cg(Iy(t.root)))typeof n.when==`string`&&RL(n.when)&&zL(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||!RL(r))continue;let n=LL(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:VL(r.apply);n!==void 0&&zL(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function VL(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(uk(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function HL(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 Hy(e.presets)){let a=new Map,s=new Map;for(let c of Cg(Gy(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,LL(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=yg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||VL(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=uk(i),f=dk(u,i,l.key),p=mk(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=pk(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=ai(f,d),n[f]=ii(f,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const UL=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function WL(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function GL(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function KL(e,t){if(t===void 0)return{};if(!i_(t))return Z(e,`actions`,`actions must be an object, got ${a_(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=qL(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function qL(e,t,n){if(!i_(n))return Z(e,t,`${t} must be an action object, got ${a_(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=UL.filter(e=>e in n);return r.length===1?JL[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${UL.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const JL={set:(e,t,n)=>OR(e,t,n,`set`,wR),persist:(e,t,n)=>OR(e,t,n,`persist`,TR),copy:YL(`copy`),open:YL(`open`),reset:XL,undo:QL(`undo`),redo:QL(`redo`),back:QL(`back`),rewind:QL(`rewind`),save:QL(`save`),preset:$L,themeDefault:eR,doctor:nR,ceiling:rR,slash:iR,do:aR};function YL(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=$g(t,n,r,e);return i===null?null:{[e]:i}}}function XL(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=oR(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 ZL={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 QL(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 — ${ZL[e]}), got ${q(r[e])}`),null)}}function $L(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${q(r)}`),null;if(r===`save`)return{preset:`save`};let a=$g(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function eR(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${q(n.themeDefault)}`),null)}const tR={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function nR(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(tR,r),a=i?tR[r]:[...new Set(Object.values(tR).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(tR).map(e=>`"${e}"`).join(`, `)}, got ${q(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?wM:CM;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${q(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return Nj.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${Nj.map(e=>`"${e}"`).join(` or `)}, got ${q(c)}`),null)}function rR(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Z(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${q(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Z(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${q(a)}`),null):{ceiling:`set`,to:a}}function iR(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=QM(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}function aR(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${q(r)}`),null):{do:r}}function oR(e,t,n,r,i,a){let o=$g(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 sR={set:`the SessionState key to write`,persist:`the config globals field to write`};function cR(e,t,n,r){let i=sR[r],a=oR(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 lR(e){return e===`set`?`set-state`:`set-config`}const uR={to:kR(`set`)},dR={to:kR(`persist`)},fR={from:AR(`set`)},pR={from:AR(`persist`)},mR={min:FR(),max:FR(),by:FR()},hR={int:MR()},gR={cycle:jR(`set`)},_R={cycle:jR(`persist`)},vR={removeSegment:NR(`removeSegment`)},yR={insertSegment:NR(`insertSegment`),anchor:NR(`anchor`),relation:PR()},bR={insertSegmentFrom:AR(`persist`),anchor:NR(`anchor`),relation:PR()},xR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},SR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function CR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>c_(e,t,n,r),c=E_(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?g_(s,...n):s}}const wR=[CR(`set`,uR),CR(`set`,fR),CR(`set`,mR,[xR,SR]),CR(`set`,hR),CR(`set`,gR)],TR=[CR(`persist`,dR),CR(`persist`,pR),CR(`persist`,mR,[xR,SR]),CR(`persist`,_R),CR(`persist`,vR),CR(`persist`,yR,[],[`insertSegment`]),CR(`persist`,bR,[],[`insertSegmentFrom`])];function ER(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 DR(e){let t=ER(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 OR(e,t,n,r,i){let a=cR(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${DR(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 kR(e){let t=lR(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>oR(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 AR(e){let t=lR(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${q(o)}`)}}}function jR(e){let t=lR(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 ${a_(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 MR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${q(r[n])}`);return}return!0}}}function NR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=$g(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 PR(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${q(i)}`);return}return i}}}function FR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${q(i)}`);return}return i}}}function IR(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const LR={noun:`style key`,fields:{hueShift:b_(),chromaScale:b_({min:0}),lightnessScale:b_(),lightnessShift:b_()}};function RR(e,t){if(!i_(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${a_(t)}`,line:K(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:K(e.source,[`styles`,r])});continue}if(og(r)){e.issues.push({path:`styles.${r}`,message:IR(`styles.${r}`,r,`globals.endcaps`),line:K(e.source,[`styles`,r])});continue}let t=o_(e,LR,`styles.${r}`,i);t!==null&&(n[r]={...Sc,...t})}return n}const zR={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:SL(e,`${t}.${n}`,r[n])},globals:{required:!1,json:Uk(),parse:(e,t,n,r)=>r[n]===void 0?void 0:Hk(e,`${t}.${n}`,r[n])}}};function BR(e,t){if(!i_(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${a_(t)}`,line:K(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:K(e.source,[`presets`,r])});continue}let t=o_(e,zR,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function VR(e,t){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${a_(t)}`,line:K(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${q(i)}`,line:K(e.source,[`helpers`,r])});continue}n[r]=i}return n}const HR=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 UR(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 WR(e){let t=HR.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${UR(t)}`}function GR(e){let t=HR.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${UR(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const KR={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 qR(e,t){let n=new Map;for(let e of Object.keys(t)){let t=nk(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:K(e.source,[`presets`])})}function JR(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||Uh(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:og(i)?IR(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:K(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:K(e.source,[`globals`,`preset`])}),qR(e,t.presets);let i=xb(t);for(let t of i.names)t!==`settings`&&!t.startsWith(ZR)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:K(e.source,[`variables`,t])});let a=(t,n,r)=>{NP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${uN}" ${NP(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}),PP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${uN}" 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:KR[i](n),line:r});let a=new Map;for(let e of Cg(t)){if(e.kind!==`segment`)continue;let t=yg(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=xg(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`||vg[e.direction]===`cell`);return vg[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:vg[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,wg(t,n)]):e.opens===void 0?[]:[[e.opens.body,Tg(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=Iy(n),o=My(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:KR[t](n),line:K(e.source,n.split(`.`))});for(let[a,o]of Ly(n,r)){let n=K(e.source,o.split(`.`));if(a.when!==void 0&&(lz(e,`${o}.when`,a.when,i,{line:n}),cz(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(AP(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${uN}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${uN}"`,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${FI(a.name)}`,line:n}),az(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`,Fy(t.root)]]);for(let e of Hy(t.presets)){let{node:n,path:r}=Gy(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,K(e.source,t.split(`.`)));gz(e,t,i,()=>!0)}const YR=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function XR(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=K(e.source,[`actions`,n,r]);if(!Hy(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Hy(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(`, `)})${FI(i)}`,line:c})},p=new Set(bg(Gy(t,a).node)),m=(r,i)=>{!PI.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${FI(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 ZR=`settings.`;function QR(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>ZR+e)])}}function $R(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:K(e.source,[`segments`,t,`settings`,n])})},a=nz(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Bg(n,tz(n)))i(e,`the defaults do not stand together: ${t}`)}function ez(e){return nz(e).length>0||Bg(e,tz(e)).length>0}function tz(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function nz(e){let t=t=>zg(rz(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||zg(rz(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${iz(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 rz(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function iz(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&zg(n)!==void 0).map(([e])=>e)}function az(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=Rg(a),s=`${r}: placement "${yg(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(`, `)})`:Vg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Ph(a):``}, but it must be ${Gg(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])=>Vg(o[e],t))||ez(o)))for(let{message:t}of Bg(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function oz(e,t,n,r,i){n.kind===`template`&&lz(e,`${t}.template`,n.template,r,{segCtx:i}),Ag(n)&&`key`in n.cache&&lz(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function sz(e,t,n,r,i){if(!(!Ag(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:K(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function cz(e,t,n,r){try{uA.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function lz(e,t,n,r,i){for(let[a,o]of pb(n,r.helpers)){if(bb(a,r))continue;if(a.startsWith(ZR)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??K(e.source,t.split(`.`))});continue}if(o!==null){uz(e,o,`Template references unknown variable ".${a}"${GR(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&bb(n,r)?` (segment-local vars are namespaced — write ".${n}")`:GR(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??K(e.source,t.split(`.`))})}}function uz(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:K(e.source,[`helpers`,t])})}function dz(e,t,n,r,i){let a=n.set,o=Dk(pv[r].configKey),s=`${a} takes ${xk(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:K(e.source,[`actions`,t,`min`])});return}let c=mz(n,i);if(c===pz){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:K(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!bk(o,e.value,i));if(l.length!==0){if(a===pv.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>og(e.value)))){let r=pv.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:IR(`actions.${t}.to`,n.to,`set: "${r}", to`),line:K(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:K(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=fz?r.join(`, `):`${r.slice(0,fz).join(`, `)} and ${r.length-fz} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:K(e.source,[`actions`,t,n])})}}}const fz=3,pz=Symbol(`any integer`);function mz(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?Qy(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)}]:pz}function hz(e,t){return Object.entries(e).filter(([e])=>t(e))}function gz(e,t,n,r){let i=cF(t),a=Zy(i);for(let[n,o]of hz(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 ${eb(r,i)}`,line:K(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;_v.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:K(e.source,[`actions`,n,`set`])});let s=xv.get(o.set);s!==void 0&&dz(e,n,o,s,i)}for(let[n,i]of hz(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&&GL(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:K(e.source,[`actions`,n,`do`])})});for(let[n,i]of hz(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=aA(r);if(o===null){let t=qk(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${Jk().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:K(e.source,[`actions`,n,a])});continue}let s=YR.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){XR(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Hy(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: ${Hy(t.presets).join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Ph(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${FI(o.segment)}`,line:K(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:K(e.source,[`actions`,n,a])})}}for(let[i,a]of hz(t.variables,r)){oz(e,`variables.${i}`,a,n);let t=WR(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:K(e.source,[`variables`,i])})}for(let[i,a]of hz(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))oz(e,`segments.${i}.vars.${t}`,r,n,i);let r=Rg(a);$R(e,i,r);let o=QR(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){lz(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of _b(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){uz(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:K(e.source,[`segments`,i,n])})}}}}for(let[i,a]of hz(t.variables,r))sz(e,`variables.${i}`,a,n);for(let[i,a]of hz(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))sz(e,`segments.${i}.vars.${t}`,r,n,i)}function _z(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=vz(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:K(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function vz(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of pb(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Ag(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function yz(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function bz(e,t){return s.resolve(e,yz(t))}function xz(e,t){return typeof t==`string`&&t!==``?bz(e,t):void 0}function Sz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const Cz=new Set([`data`,`segments`,`helpers`,`actions`]),wz=`plugin.json5`,Tz=/^[a-z][a-z0-9_]*$/;function Ez(e){let t=s.basename(s.dirname(e));return Tz.test(t)?t:void 0}const Dz=`plugins.`;function Oz(e){return`${Dz}${e}.data`}function kz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Az(e)}}}function Az(e){return e instanceof Jg?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 jz(e,t){return e.map(e=>bz(s.dirname(t),e))}function Mz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=Ez(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 ${wz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${wz} and list that`;return o(t,a===void 0?e.config:Fz(Pz(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 ${Tz}: 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=Pz(e.config,a),u=kz(()=>{let i=p.readFileSync(n,`utf-8`),o=JF(Vz(n,a,{source:i,json:ui.default.parse(i)},t),l);return r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,Fz(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function Nz(e){let t=`${Dz}${e}.`;return e=>e.startsWith(t)}function Pz(e,t){let n=Nz(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 Fz(e,t,n){return{...e,variables:{...e.variables,[Oz(t)]:{kind:`dropped`,reason:Sz(n),definition:n.path}}}}function Iz(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Lz(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Iz)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:Sz(e)}));return t=>{let i=Iz(t);if(i===void 0)return[];let a=e.config.variables[Oz(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function Rz(e,t){let n=Hy(e.presets).flatMap(t=>[...Cg(Gy(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,zz(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Iz(t),r=n===void 0?void 0:e.variables[Oz(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=>_b(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...yb(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${Oz(Iz(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function zz(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,Bz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function Bz(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 Vz(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Jg(e,a)};if(!i_(r))return a.push({path:``,message:`a plugin definition must be an object, got ${a_(r)}`}),o();for(let e of Object.keys(r))Cz.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: ${[...Cz].join(`, `)}`});let s=qz(r.data,e,i,a);if(i_(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(Lh()),groups:[]},l=aI(c,`data`,{[Oz(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!i_(t)||!i_(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=i_(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:Uz(t,Gz(t,$I(c,r.segments,new Set))),helpers:Uz(t,VR(c,r.helpers)),actions:Uz(t,Kz(t,KL(c,r.actions)))};for(let[e,t]of Hz(u))try{uA.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*Hz(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function Uz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${Dz}${e}.${t}`,n]))}function Wz(e,t){return`${Dz}${e}.${t}`}function Gz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,n.kind===`state`?{...n,key:Wz(e,n.key)}:n]))}]))}function Kz(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:Wz(e,n.set)}:n]))}function qz(e,t,n,r){if(typeof e==`string`&&e!==``)return bz(s.dirname(t),e);if(i_(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(i_(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 Jz(e){let t=[...[...(process.env.XDG_DATA_DIRS||Zz()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),Yz(),...e===null?[]:[s.join(e,Xz)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function Yz(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const Xz=s.join(`.cc-candybar`,`plugins`);function Zz(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function Qz(e){let t=Jz(e),n=new Map,r=[],i=[];for(let e of t){let t=$z(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,wz));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${wz}: move this file to ${s.join(e,`<name>`,wz)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function $z(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()||eB(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 eB(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function tB(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const nB=[`json5`,`json`];function rB(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?nB.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...nB.map(e=>s.join(r,`.cc-candybar.${e}`)),...nB.map(e=>`${iB()}.${e}`)])]}function iB(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function aB(e,t,n){let r=[],i=new Map;for(let a of rB(e,t,n)){let e=tB(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:oB(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 oB(e){let t=iB();return e.find(e=>nB.some(n=>e===`${t}.${n}`))??`${t}.${nB[0]}`}function sB(e,t,n){let r=aB(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 cB(e){return lB(e).join(`
|
|
185
|
-
`)||null}function
|
|
184
|
+
New: { h: ["seg1", "seg2"] }`,line:K(e.source,[`root`])}),yL;if(n.kind===`group`){let r=o_(e,RL,t,n);return r===null?yL:(e.groups.push({name:r.name,label:r.label,...r.open!==void 0&&{open:r.open},...r.direction!==void 0&&{direction:r.direction},...r.key!==void 0&&{key:r.key},...r.bg!==void 0&&{bg:r.bg},...r.fg!==void 0&&{fg:r.fg},...r.when!==void 0&&{when:r.when},path:t}),BL(r))}let r=`h`in n,i=`v`in n,a=`seg`in n;if(+!!r+ +!!i+ +!!a>1){let r=[`seg`,`h`,`v`].filter(e=>e in n);return e.issues.push({path:t,message:`a layout node may have exactly one of "seg", "h", or "v" — got ${r.map(e=>`"${e}"`).join(` and `)} together`,line:K(e.source,[`root`])}),yL}if(a){let r=o_(e,OL,t,n);return r===null?yL:{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=o_(e,kL,t,n);return r===null?yL:{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=o_(e,AL,t,n);return r===null?yL:{kind:`container`,direction:`vertical`,children:r.v,...r.when!==void 0&&{when:r.when},...r.distribution!==void 0&&{distribution:r.distribution}}}return e.issues.push({path:`${t}.kind`,message:`a layout node "kind" must be "container", "segment", or "group", or use the terse A-grammar: a bare string, or an object with "seg", "h", or "v" (got ${JSON.stringify(n.kind)})`,line:K(e.source,[`root`])}),yL};function ML(){return{required:!0,json:{type:`object`,propertyNames:{pattern:ky.source},additionalProperties:{$ref:vL}},parse:(e,t,n,r)=>{let i=r[n];if(!i_(i))return e.issues.push({path:`${t}.${n}`,message:`"rows" must be an object of row name → layout node, got ${a_(i)}`,line:K(e.source,[...t.split(`.`),n])}),{};let a={};for(let[r,o]of Object.entries(i)){if(!ky.test(r)){e.issues.push({path:`${t}.${n}.${r}`,message:`row name "${r}" must be an identifier (letters, digits, _; not starting with a digit) — it names the row in the config file and merges by name over the bundled default's rows`,line:K(e.source,[...t.split(`.`),n,r])});continue}a[r]=jL(e,`${t}.${n}.${r}`,o)}return a}}}const NL={noun:`root key`,fields:{rows:ML(),when:__(),distribution:TL()}};function PL(e,t,n){return i_(n)&&`rows`in n?o_(e,NL,t,n)??{rows:{}}:jL(e,t,n)}function FL(){return{required:!0,json:{type:`string`,pattern:ky.source},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`string`||!ky.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 "${P}", got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}function IL(){return{required:!1,json:{type:`string`,minLength:1},parse:(e,t,n,r)=>{let i=r[n];if(i!==void 0){if(typeof i!=`string`||i===``||i.includes(`/`)){e.issues.push({path:`${t}.${n}`,message:`a group "key" must be a non-empty, slash-free SessionState key, got ${q(i)}`,line:K(e.source,[`root`])});return}return i}}}}function LL(){return{required:!0,json:{type:`string`,pattern:`^[^\\n\\r]*$`},parse:(e,t,n,r)=>{let i=$g(e,t,r,n);if(i!==null){if(/[\n\r]/.test(i)){e.issues.push({path:`${t}.${n}`,message:`${t}.${n}: group label must not contain newlines`,line:K(e.source,[...t.split(`.`),n])});return}return i}}}}const RL={noun:`layout-node key`,fields:{kind:bL(`group`),name:FL(),label:LL(),open:v_(),direction:T_(_g),key:IL(),bg:__(),fg:__(),when:__(),distribution:TL(),children:CL(h_(()=>jL))}};function zL(e){return e.key??`groups.`+e.name}function BL(e){let t=hk+e.name;return Qr(t,{variable:t,key:zL(e),member:e.name},{kind:`container`,direction:e.direction??`vertical`,children:e.children,...e.distribution!==void 0&&{distribution:e.distribution}},`drop`,e.when)}function VL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function HL(e,t){xk(e,t,hk,`group nodes`);let n=e.groups;if(n.length===0)return;let r=new Set;for(let t of n)r.has(t.name)&&VL(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}.`)&&zL(t)===zL(r)&&VL(e,t.path,`group "${t.name}" shares key "${zL(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=zL(t);if(i.has(n)||i.set(n,P),t.open===!0){let r=i.get(n);r!==`closed`&&VL(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=hk+e.name,r=zL(e),c=n.filter(t=>t!==e&&e.path.startsWith(t.path+`.`)).length,l=` `.repeat(c);a[t]=ii(r,i.get(r)),o[t]=ai(r,e.name),s[t]={template:ti(t,`${l}${e.label} ▸`,`${l}${e.label} ▾`),...e.bg!==void 0&&{bg:e.bg},...e.fg!==void 0&&{fg:e.fg}}}t.variables={...t.variables??{},...a},t.actions={...t.actions??{},...o},t.segments={...t.segments??{},...s}}const UL=`menu`,WL=`a menu binds its trigger text the way a cycle action binds a display — write {{ menu "applyTheme" "▸" "▾" }} (one per state) or {{ menu "insertHere" "+" }} (one static display for both), with the rare knobs in ONE trailing dict: {{ menu "applyTheme" "▸" "▾" (dict "closeOnPick" true "paged" false "key" "pickers") }} (defaults: closeOnPick false, paged true, no key). The renderer no longer appends ▸/▾ of its own (candybar-settings-ui-aok.4), and the older positional tail ("pageAction" closeOnPick paged "key") was removed — the page cursor is synthesized from the menu's identity`,GL=e=>e.kind===`call`&&e.name===`dict`,KL=e=>e.kind===`literal`&&typeof e.value!=`object`,qL=e=>Yr(``,e,2)===void 0;function JL(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&&GL(i)?i:void 0,o=a===void 0?r:r.slice(0,-1);if(o.some(GL))return t(`whose options (dict …) is not its last argument — ${WL}`);if(i!==void 0&&a===void 0&&!KL(i)&&qL(o.length-1))return t(`whose last argument is neither a literal nor a literal (dict …) — the renderer tells a display from the options dict by the value it evaluates to, so this call could be read as ${o.length} displays or as ${o.length-1} plus options, and both are legal. Make the options explicit as a trailing (dict …) — {{ menu "${n.value}" (printf "…") (printf "…") (dict) }} binds dynamic displays unambiguously — or bind the trigger text as literals`);let s=Yr(`whose trigger`,o.length,2);if(s!==void 0)return t(`${s} — ${WL}`);let c=a===void 0?{}:vw(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=Ak(c)}catch(e){return t(`with invalid options — ${e.message}`)}let u=l.key;if(u!==void 0){let e=bk(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 "${wk(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 YL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedCalls().filter(e=>e.name===UL).map(JL)}catch{return`parse-failed`}}function XL(e){let t=DS({fromString:e=>e});try{return t.parse(e).referencedFunctions().has(UL)}catch{return!1}}function ZL(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,[`root`])})}function QL(e,t){xk(e,t,gk,`{{ menu }} helpers`);for(let[n,r]of Object.entries(t.helpers??{}))XL(r)&&e.issues.push({path:`helpers.${n}`,message:`helper "${n}" uses {{ menu }}, but a menu must live directly in a segment template — its identity is derived from the segment it sits in, which a shared helper does not have. Inline the {{ menu }} call into each segment that needs it.`,line:K(e.source,[`helpers`,n])});let n=t.segments??{};for(let[t,r]of Object.entries(n))for(let n of[`bg`,`fg`,`when`]){let i=r[n];typeof i==`string`&&XL(i)&&ZL(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 Cg(Iy(t.root)))typeof n.when==`string`&&XL(n.when)&&ZL(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||!XL(r))continue;let n=YL(r);if(n!==`parse-failed`)for(let r of n){let n=r.kind===`issue`?r.message:$L(r.apply);n!==void 0&&ZL(e,`segments.${t}`,`segment "${t}" has a {{ menu }} ${n}.`)}}}function $L(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(Sk(e)===`closed`)return`whose apply action is named "${P}", which collides with the menu's closed-state sentinel and leaves it unopenable. Rename the action`}function eR(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 Hy(e.presets)){let a=new Map,s=new Map;for(let c of Cg(Gy(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,YL(t.template));let l=i.get(c.name);if(l===`parse-failed`)continue;let u=yg(c);for(let[e,t]of l.entries()){if(t.kind===`issue`||$L(t.apply)!==void 0)continue;let{apply:i,options:l}=t,d=Sk(i),f=Ck(u,i,l.key),p=Ek(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=Tk(f,d),_=`${c.name}\0${e}`,v=s.get(g);if(v!==void 0&&v!==_){o(c.name,`two {{ menu }} disclosures resolve to the same identity ("${g}") — ${l.key===void 0?`a segment cannot contain two menus over the same apply action "${i}"`:`menus sharing key "${l.key}" must have distinct apply actions`}.`);continue}s.set(g,_),r[g]=ai(f,d),n[f]=ii(f,P),n[p]={kind:`state`,key:p,default:`0`},r[p]={set:p,int:!0}}}}return{...e,variables:{...e.variables,...n},actions:{...e.actions,...r}}}const tR=[`set`,`persist`,`copy`,`open`,`reset`,`undo`,`redo`,`back`,`rewind`,`save`,`preset`,`themeDefault`,`doctor`,`ceiling`,`slash`,`do`];function nR(e){return e.ceiling===`set`?[`set`,e.to]:[`clear`]}function rR(e){return`from`in e||`int`in e||`insertSegmentFrom`in e}function iR(e,t){if(t===void 0)return{};if(!i_(t))return Z(e,`actions`,`actions must be an object, got ${a_(t)}`),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){let t=aR(e,`actions.${r}`,i);t!==null&&(n[r]=t)}return n}function Z(e,t,n){e.issues.push({path:t,message:n,line:K(e.source,t.split(`.`))})}function aR(e,t,n){if(!i_(n))return Z(e,t,`${t} must be an action object, got ${a_(n)}`),null;if(`persistWhen`in n)return Z(e,t,`${t}.persistWhen was removed: declare the \`set\` alone — a session pick is a draft until a \`{ save: true }\` action writes every unsaved setting to the config file`),null;let r=tR.filter(e=>e in n);return r.length===1?oR[r[0]](e,t,n):(Z(e,t,`action must declare exactly one of: ${tR.join(`, `)}${r.length>1?` (found: ${r.join(`, `)})`:``}`),null)}const oR={set:(e,t,n)=>BR(e,t,n,`set`,IR),persist:(e,t,n)=>BR(e,t,n,`persist`,LR),copy:sR(`copy`),open:sR(`open`),reset:cR,undo:uR(`undo`),redo:uR(`redo`),back:uR(`back`),rewind:uR(`rewind`),save:uR(`save`),preset:dR,themeDefault:fR,doctor:mR,ceiling:hR,slash:gR,do:_R};function sR(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=$g(t,n,r,e);return i===null?null:{[e]:i}}}function cR(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=vR(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 lR={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 uR(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 — ${lR[e]}), got ${q(r[e])}`),null)}}function dR(e,t,n){let r=n.preset,i=r===`save`?[`preset`]:[`preset`,`name`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a preset action. Expected only: ${i.join(`, `)}`);if(r!==`save`&&r!==`delete`)return Z(e,`${t}.preset`,`preset must be "save" or "delete", got ${q(r)}`),null;if(r===`save`)return{preset:`save`};let a=$g(e,t,n,`name`);return a===null?null:{preset:`delete`,name:a}}function fR(e,t,n){for(let r of Object.keys(n))r!==`themeDefault`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a themeDefault action. Expected only: themeDefault`);return n.themeDefault===`save`?{themeDefault:`save`}:(Z(e,`${t}.themeDefault`,`themeDefault must be "save" (it saves the look the session draws as the active theme's default), got ${q(n.themeDefault)}`),null)}const pR={run:[`doctor`],fix:[`doctor`,`check`],mark:[`doctor`,`check`,`mark`]};function mR(e,t,n){let r=n.doctor,i=typeof r==`string`&&Object.hasOwn(pR,r),a=i?pR[r]:[...new Set(Object.values(pR).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(pR).map(e=>`"${e}"`).join(`, `)}, got ${q(r)}`),null;if(r===`run`)return{doctor:`run`};let o=n.check,s=r===`mark`?IM:FM;if(typeof o!=`string`||!s.some(e=>e.name===o))return Z(e,`${t}.check`,`doctor ${r} must name a check (have: ${s.map(e=>e.name).join(`, `)}), got ${q(o)}`),null;if(r===`fix`)return{doctor:`fix`,check:o};let c=n.mark;return Gj.includes(c)?{doctor:`mark`,check:o,mark:c}:(Z(e,`${t}.mark`,`doctor mark must be ${Gj.map(e=>`"${e}"`).join(` or `)}, got ${q(c)}`),null)}function hR(e,t,n){let r=n.ceiling,i=r===`clear`?[`ceiling`]:[`ceiling`,`to`];for(let r of Object.keys(n))i.includes(r)||Z(e,`${t}.${r}`,`Unknown key "${r}" on a ceiling action. Expected only: ${i.join(`, `)}`);if(r===`clear`)return{ceiling:`clear`};if(r!==`set`)return Z(e,`${t}.ceiling`,`ceiling must be "set" or "clear", got ${q(r)}`),null;let a=n.to;return typeof a!=`string`||a.trim()===``?(Z(e,`${t}.to`,`ceiling set needs \`to\`: a memento ceiling value such as "+100_000", "400000" or "off", got ${q(a)}`),null):{ceiling:`set`,to:a}}function gR(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=uN(n.slash);return r.kind===`refused`?(Z(e,`${t}.slash`,r.reason),null):{slash:r.line}}function _R(e,t,n){for(let r of Object.keys(n))r!==`do`&&Z(e,`${t}.${r}`,`Unknown key "${r}" on a do action. Expected only: do`);let r=n.do;return!Array.isArray(r)||r.length<2||r.some(e=>typeof e!=`string`||e===``)?(Z(e,`${t}.do`,`do must list at least two action names (the first is the click's face, the rest ride along in the same click), got ${q(r)}`),null):{do:r}}function vR(e,t,n,r,i,a){let o=$g(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 yR={set:`the SessionState key to write`,persist:`the config globals field to write`};function bR(e,t,n,r){let i=yR[r],a=vR(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 xR(e){return e===`set`?`set-state`:`set-config`}const SR={to:VR(`set`)},CR={to:VR(`persist`)},wR={from:HR(`set`)},TR={from:HR(`persist`)},ER={min:qR(),max:qR(),by:qR()},DR={int:WR()},OR={cycle:UR(`set`)},kR={cycle:UR(`persist`)},AR={removeSegment:GR(`removeSegment`)},jR={insertSegment:GR(`insertSegment`),anchor:GR(`anchor`),relation:KR()},MR={insertSegmentFrom:HR(`persist`),anchor:GR(`anchor`),relation:KR()},NR={ok:e=>e.min<e.max,issue:e=>({field:`min`,message:`min (${e.min}) must be less than max (${e.max})`})},PR={ok:e=>e.by!==0,issue:()=>({field:`by`,message:`by must be a non-zero integer (the per-click increment; negative steps down)`})};function FR(e,t,n=[],r){let i=Object.keys(t),a=r??i,o=[e],s=(e,n,r)=>c_(e,t,n,r),c=E_(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?g_(s,...n):s}}const IR=[FR(`set`,SR),FR(`set`,wR),FR(`set`,ER,[NR,PR]),FR(`set`,DR),FR(`set`,OR)],LR=[FR(`persist`,CR),FR(`persist`,TR),FR(`persist`,ER,[NR,PR]),FR(`persist`,kR),FR(`persist`,AR),FR(`persist`,jR,[],[`insertSegment`]),FR(`persist`,MR,[],[`insertSegmentFrom`])];function RR(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 zR(e){let t=RR(e),n=t[t.length-1];return`a ${e} action declares exactly one value source: ${t.length===1?n:`${t.slice(0,-1).join(`, `)}, or ${n}`}`}function BR(e,t,n,r,i){let a=bR(e,t,n,r),o=i.filter(e=>e.detect.some(e=>e in n));if(o.length!==1)return Z(e,t,`${zR(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 VR(e){let t=xR(e);return{required:!0,json:{type:`string`},parse:(n,r,i,a)=>vR(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 HR(e){let t=xR(e);return{required:!0,json:{anyOf:[{type:`string`,minLength:1},{type:`array`,items:{type:`string`,minLength:1},minItems:1,uniqueItems:!0}]},parse:(n,r,i,a)=>{let o=a[i],s=`${r}.${i}`;if(typeof o==`string`){if(o===``){Z(n,s,`${i} must be a non-empty domain name`);return}return o}if(Array.isArray(o)&&o.every(e=>typeof e==`string`)){let r=o;if(r.length===0){Z(n,s,`${i} must name a domain (a non-empty string) or declare an inline domain (a non-empty array of values)`);return}if(r.some(e=>e===``)){Z(n,s,`${i} array members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}let a=r.filter(e=>e.includes(`/`));if(a.length>0){Z(n,s,`${i} array member(s) ${a.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(r).size!==r.length){Z(n,s,`${i} array members must be unique — a duplicated value would render the same picker option twice`);return}return r}Z(n,s,`${i} must be a domain name (a string) or an inline domain (an array of strings), got ${q(o)}`)}}}function UR(e){let t=xR(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 ${a_(o)}`);return}let c=o;if(c.length<2){Z(n,s,`cycle needs at least two members (one member has no successor — use a literal "to")`);return}let l=c.some(e=>e===``),u=c.filter(e=>e.includes(`/`));if(l){Z(n,s,`cycle members must be non-empty — an empty value cannot be delivered on the ${t} wire`);return}if(u.length>0){Z(n,s,`cycle member(s) ${u.map(e=>`"${e}"`).join(`, `)} contain "/" — ${e} values must be slash-free`);return}if(new Set(c).size!==c.length){Z(n,s,`cycle members must be unique — the successor of a duplicated member is ambiguous`);return}return c}}}function WR(){return{required:!0,json:{const:!0},parse:(e,t,n,r)=>{if(r[n]!==!0){Z(e,`${t}.${n}`,`int must be the literal true (declares the key an unbounded integer cursor — a paged picker's page key), got ${q(r[n])}`);return}return!0}}}function GR(e){return{required:!0,json:{type:`string`},parse:(t,n,r,i)=>{let a=$g(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 KR(){return{required:!0,json:{enum:[`before`,`after`]},parse:(e,t,n,r)=>{let i=r[n];if(i!==`before`&&i!==`after`){Z(e,`${t}.${n}`,`relation must be "before" or "after", got ${q(i)}`);return}return i}}}function qR(){return{required:!0,json:{type:`integer`},parse:(e,t,n,r)=>{let i=r[n];if(typeof i!=`number`||!Number.isInteger(i)){Z(e,`${t}.${n}`,`${n} must be an integer, got ${q(i)}`);return}return i}}}function JR(e,t,n){return`${e}: "${t}" is an endcaps shape, not a style — endcaps were renamed from "style" to "endcaps"; write ${n}: "${t}"`}const YR={noun:`style key`,fields:{hueShift:b_(),chromaScale:b_({min:0}),lightnessScale:b_(),lightnessShift:b_()}};function XR(e,t){if(!i_(t))return e.issues.push({path:`styles`,message:`styles must be an object mapping style names to adaptation objects, got ${a_(t)}`,line:K(e.source,[`styles`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)){e.issues.push({path:`styles.${r}`,message:`style name ${JSON.stringify(r)} must be non-empty and slash-free — a style picker writes the name on the set-state wire, which rejects empty values and splits on "/"`,line:K(e.source,[`styles`,r])});continue}if(og(r)){e.issues.push({path:`styles.${r}`,message:JR(`styles.${r}`,r,`globals.endcaps`),line:K(e.source,[`styles`,r])});continue}let t=o_(e,YR,`styles.${r}`,i);t!==null&&(n[r]={...Sc,...t})}return n}const ZR={noun:`preset key`,fields:{root:{required:!1,json:{$ref:`#/definitions/RootFragment`},parse:(e,t,n,r)=>r[n]===void 0?void 0:PL(e,`${t}.${n}`,r[n])},globals:{required:!1,json:tA(),parse:(e,t,n,r)=>r[n]===void 0?void 0:eA(e,`${t}.${n}`,r[n])}}};function QR(e,t){if(!i_(t))return e.issues.push({path:`presets`,message:`presets must be an object mapping preset names to config fragments, got ${a_(t)}`,line:K(e.source,[`presets`])}),{};let n={};for(let[r,i]of Object.entries(t)){if(r===``||r.includes(`/`)||/[\n\r]/.test(r)){e.issues.push({path:`presets.${r}`,message:`preset name ${JSON.stringify(r)} must be non-empty, slash-free, and newline-free — a preset picker writes the name on the set-state wire (which rejects empty values and splits on "/"), and edit mode splices it into a synthesized template string`,line:K(e.source,[`presets`,r])});continue}let t=o_(e,ZR,`presets.${r}`,i);t!==null&&(n[r]=t)}return n}function $R(e,t){if(t===void 0)return{};if(!i_(t))return e.issues.push({path:`helpers`,message:`helpers must be an object, got ${a_(t)}`,line:K(e.source,[`helpers`])}),{};let n=Object.create(null);for(let[r,i]of Object.entries(t)){if(typeof i!=`string`){e.issues.push({path:`helpers.${r}`,message:`helpers.${r} must be a string template body, got ${q(i)}`,line:K(e.source,[`helpers`,r])});continue}n[r]=i}return n}const ez=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 tz(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 nz(e){let t=ez.get(e);return t===void 0?void 0:`variables.${e} is no longer read: ${tz(t)}`}function rz(e){let t=ez.get(e);return t===void 0?``:` — ".${e}" is no longer a variable: ${tz(t)}; a "${t.segment}" template reads it as ".settings.${t.setting}"`}const iz={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 az(e,t){let n=new Map;for(let e of Object.keys(t)){let t=mk(e),r=n.get(t);r?r.push(e):n.set(t,[e])}for(let[t,r]of n)r.length<2||e.issues.push({path:`presets`,message:`preset names ${r.map(e=>JSON.stringify(e)).join(` and `)} both collapse to the same synthesis identifier "${t}" — edit mode's synthesized reset affordance would silently steal one preset's action for the other. Rename one.`,line:K(e.source,[`presets`])})}function oz(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||Uh(i)||Object.prototype.hasOwnProperty.call(t.styles,i))continue;let r=`${n.join(`.`)}.style`;e.issues.push({path:r,message:og(i)?JR(r,i,a):`${r} "${i}" does not match any declared style (have: ${Object.keys(t.styles).join(`, `)})`,line:K(e.source,[...n,`style`])})}t.globals.preset!==void 0&&!Object.prototype.hasOwnProperty.call(t.presets,t.globals.preset)&&e.issues.push({path:`globals.preset`,message:`globals.preset "${t.globals.preset}" does not match any declared preset (have: ${Object.keys(t.presets).join(`, `)})`,line:K(e.source,[`globals`,`preset`])}),az(e,t.presets);let i=xb(t);for(let t of i.names)t!==`settings`&&!t.startsWith(lz)||e.issues.push({path:`variables`,message:`variable "${t}" is named under "settings", which a segment's templates read as its placement's own settings (.settings.<name>) — rename it`,line:K(e.source,[`variables`,t])});let a=(t,n,r)=>{GP(t)>1&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SN}" ${GP(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}),KP(t)&&e.issues.push({path:n,message:`${n} places the global settings menu anchor "${SN}" 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:iz[i](n),line:r});let a=new Map;for(let e of Cg(t)){if(e.kind!==`segment`)continue;let t=yg(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=xg(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`||vg[e.direction]===`cell`);return vg[e.direction]===`row`&&!n?t:void 0}let s=(e,t)=>e.kind===`segment`?`band`:vg[e.direction]===`cell`?`cell`:t,c=(e,t)=>e.kind===`container`?e.children.map((e,n)=>[e,wg(t,n)]):e.opens===void 0?[]:[[e.opens.body,Tg(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=Iy(n),o=My(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:iz[t](n),line:K(e.source,n.split(`.`))});for(let[a,o]of Ly(n,r)){let n=K(e.source,o.split(`.`));if(a.when!==void 0&&(xz(e,`${o}.when`,a.when,i,{line:n}),bz(e,`${o}.when`,a.when,n)),a.kind===`segment`){if(HP(a.name)){(a.id!==void 0||a.settings!==void 0)&&e.issues.push({path:o,message:`${r} gives the global settings menu anchor "${SN}" an id or settings — the anchor only marks where the menu goes, so place it as the bare name "${SN}"`,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${qI(a.name)}`,line:n}),_z(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`,Fy(t.root)]]);for(let e of Hy(t.presets)){let{node:n,path:r}=Gy(t,e);d.set(r,n)}for(let[t,n]of d)a(n,t,K(e.source,t.split(`.`)));Oz(e,t,i,()=>!0)}const sz=[`removeSegment`,`insertSegment`,`insertSegmentFrom`];function cz(e,t,n,r,i,a,o){let s=`actions.${n}.${r}`,c=K(e.source,[`actions`,n,r]);if(!Hy(t.presets).includes(a)){e.issues.push({path:s,message:`actions.${n}: "${i}" names preset "${a}" which is not declared (have: ${Hy(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(`, `)})${qI(i)}`,line:c})},p=new Set(bg(Gy(t,a).node)),m=(r,i)=>{!KI.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${qI(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 lz=`settings.`;function uz(e,t){return{...e,names:new Set([...e.names,...Object.keys(t).map(e=>lz+e)])}}function dz(e,t,n){let r=e=>`segments.${t}.settings.${e}`,i=(n,i)=>{e.issues.push({path:r(n),message:`${r(n)}: ${i}`,line:K(e.source,[`segments`,t,`settings`,n])})},a=mz(n);for(let{setting:e,message:t}of a)i(e,t);if(!(a.length>0))for(let{setting:e,message:t}of Bg(n,pz(n)))i(e,`the defaults do not stand together: ${t}`)}function fz(e){return mz(e).length>0||Bg(e,pz(e)).length>0}function pz(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.default]))}function mz(e){let t=t=>zg(hz(e,t))?.atLeast;return Object.keys(e).flatMap(n=>{let r=t(n);if(r===void 0)return[];if(r===n||zg(hz(e,r))===void 0)return[{setting:n,message:`atLeast "${r}" must name another range setting of this segment (its range settings: ${gz(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 hz(e,t){return Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0}function gz(e,t){return Object.entries(e).filter(([e,n])=>e!==t&&zg(n)!==void 0).map(([e])=>e)}function _z(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=Rg(a),s=`${r}: placement "${yg(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(`, `)})`:Vg(c,a)?void 0:`sets "${t}" to ${JSON.stringify(a)}${c.domain===`theme`?Ph(a):``}, but it must be ${Gg(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])=>Vg(o[e],t))||fz(o)))for(let{message:t}of Bg(o,c))e.issues.push({path:r,message:`${s}: ${t}`,line:i})}function vz(e,t,n,r,i){n.kind===`template`&&xz(e,`${t}.template`,n.template,r,{segCtx:i}),Ag(n)&&`key`in n.cache&&xz(e,`${t}.cache.key`,n.cache.key,r,{segCtx:i})}function yz(e,t,n,r,i){if(!(!Ag(n)||!(`depends_on`in n.cache)))for(let a=0;a<n.cache.depends_on.length;a++){let o=n.cache.depends_on[a];if(r.names.has(o))continue;let s=i===void 0?void 0:`${i}.${o}`,c=s!==void 0&&r.names.has(s)?` (segment-local vars are namespaced — write "${s}")`:``;e.issues.push({path:`${t}.cache.depends_on[${a}]`,message:`cache.depends_on references unknown variable "${o}"${c}`,line:K(e.source,[...t.split(`.`),`cache`,`depends_on`])})}}function bz(e,t,n,r){try{SA.parse(n)}catch(n){e.issues.push({path:t,message:`Template parse error in ${t}: ${n.message}`,line:r})}}function xz(e,t,n,r,i){for(let[a,o]of pb(n,r.helpers)){if(bb(a,r))continue;if(a.startsWith(lz)){let n=o===null?``:` through helper "${o}"`,r=a.slice(9),s=i?.segCtx===void 0||i.settings===void 0?`Template reads ".${a}"${n}, but only a segment's own templates have settings — call it from a segment that declares "${r}"`:`Template reads ".${a}"${n}, but segment "${i.segCtx}" has no setting "${r}" (it has: ${Object.keys(i.settings).join(`, `)}) — declare it under segments.${i.segCtx}.settings`;e.issues.push({path:t,message:s,line:i?.line??K(e.source,t.split(`.`))});continue}if(o!==null){Sz(e,o,`Template references unknown variable ".${a}"${rz(a)}`);continue}let n=i?.segCtx===void 0?void 0:`${i.segCtx}.${a}`,s=n!==void 0&&bb(n,r)?` (segment-local vars are namespaced — write ".${n}")`:rz(a);e.issues.push({path:t,message:`Template references unknown variable ".${a}"${s}`,line:i?.line??K(e.source,t.split(`.`))})}}function Sz(e,t,n){let r=`helpers.${t}`;e.issues.some(e=>e.path===r&&e.message===n)||e.issues.push({path:r,message:n,line:K(e.source,[`helpers`,t])})}function Cz(e,t,n,r,i){let a=n.set,o=zk(pv[r].configKey),s=`${a} takes ${Nk(o,i)}`;if(`min`in n&&(o===`bool`||!(`min`in o))){e.issues.push({path:`actions.${t}.min`,message:`actions.${t}: a stepper writes the integers from ${n.min} to ${n.max}, and ${a} is not an integer range; ${s}`,line:K(e.source,[`actions`,t,`min`])});return}let c=Ez(n,i);if(c===Tz){e.issues.push({path:`actions.${t}.int`,message:`actions.${t}.int: an int cursor writes whatever integer the template binds, and a click outside the ${a} domain would change nothing; ${s}`,line:K(e.source,[`actions`,t,`int`])});return}let l=c.filter(e=>!Mk(o,e.value,i));if(l.length!==0){if(a===pv.style.sessionKey&&(`from`in n&&n.from===`endcaps`||c.every(e=>og(e.value)))){let r=pv.endcaps.sessionKey;e.issues.push(`to`in n?{path:`actions.${t}.to`,message:JR(`actions.${t}.to`,n.to,`set: "${r}", to`),line:K(e.source,[`actions`,t,`to`])}:{path:`actions.${t}.set`,message:`actions.${t}.set: "${a}" here writes only endcaps shapes, not styles — endcaps were renamed from "style" to "endcaps"; write set: "${r}"`,line:K(e.source,[`actions`,t,`set`])});return}for(let n of new Set(l.map(e=>e.field))){let r=l.filter(e=>e.field===n).map(e=>JSON.stringify(e.value)),i=r.length<=wz?r.join(`, `):`${r.slice(0,wz).join(`, `)} and ${r.length-wz} more`,o=`actions.${t}.${n}`;e.issues.push({path:o,message:`${o}: ${i} ${r.length===1?`is`:`are`} outside the ${a} domain — a click would write it and nothing would change; ${s}`,line:K(e.source,[`actions`,t,n])})}}}const wz=3,Tz=Symbol(`any integer`);function Ez(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?Qy(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)}]:Tz}function Dz(e,t){return Object.entries(e).filter(([e])=>t(e))}function Oz(e,t,n,r){let i=bF(t),a=Zy(i);for(let[n,o]of Dz(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 ${eb(r,i)}`,line:K(e.source,[`actions`,n,t])});continue}if(!(`set`in o))continue;_v.has(o.set)&&e.issues.push({path:`actions.${n}.set`,message:`actions.${n} sets "${o.set}", which has no session pick — globals.${o.set} is set in the config file only, so a click would change nothing; write it with { persist: "${o.set}", … } instead`,line:K(e.source,[`actions`,n,`set`])});let s=xv.get(o.set);s!==void 0&&Cz(e,n,o,s,i)}for(let[n,i]of Dz(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&&rR(o)?`"${r}" takes its value from the template (from/int/insertSegmentFrom), so it can only be the first member — only the first is bound the region's display`:void 0:`"${r}" is listed twice — each member fires once per click`;s!==void 0&&e.issues.push({path:`actions.${n}.do`,message:`actions.${n} do: ${s}`,line:K(e.source,[`actions`,n,`do`])})});for(let[n,i]of Dz(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=_A(r);if(o===null){let t=aA(r);e.issues.push({path:`actions.${n}.${a}`,message:t===void 0?`actions.${n}: "${r}" is not a config globals field (have: ${oA().join(`, `)}), a "segments.<name>.palette" target, a "presets.<name>.globals.<field>" target, a "themeDefaults.<theme>.<shade|variation|style>" target, or a "presets.<name>.root" target`:`actions.${n}: the globals field "${r}" was removed: ${t}`,line:K(e.source,[`actions`,n,a])});continue}let s=sz.filter(e=>e in i);if(o.scope!==`preset-root`&&s.length>0){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is not a "presets.<name>.root" target — ${s.map(e=>`"${e}"`).join(`/`)} is a tree op and applies only to one`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`preset-root`){cz(e,t,n,a,r,o.preset,i);continue}if(o.scope===`preset-globals`&&!Hy(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: ${Hy(t.presets).join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`theme-default`&&!e.allowedPalettes.has(o.theme)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names theme "${o.theme}" which is not installed${Ph(o.theme)} (have: ${[...e.allowedPalettes].sort().join(`, `)})`,line:K(e.source,[`actions`,n,a])});continue}if(o.scope===`segment-palette`){if(!Object.prototype.hasOwnProperty.call(t.segments,o.segment)){e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" names segment "${o.segment}" which is not declared (have segments: ${Object.keys(t.segments).join(`, `)})${qI(o.segment)}`,line:K(e.source,[`actions`,n,a])});continue}`min`in i&&e.issues.push({path:`actions.${n}.${a}`,message:`actions.${n}: "${r}" is a segment palette target and cannot use a bounded stepper (min/max/by) — use "to", "from", or "cycle" instead`,line:K(e.source,[`actions`,n,a])})}}for(let[i,a]of Dz(t.variables,r)){vz(e,`variables.${i}`,a,n);let t=nz(i);t!==void 0&&e.issues.push({path:`variables.${i}`,message:t,line:K(e.source,[`variables`,i])})}for(let[i,a]of Dz(t.segments,r)){if(a.vars)for(let[t,r]of Object.entries(a.vars))vz(e,`segments.${i}.vars.${t}`,r,n,i);let r=Rg(a);dz(e,i,r);let o=uz(n,r);for(let n of[`template`,`bg`,`fg`,`when`]){let s=a[n];if(typeof s==`string`){xz(e,`segments.${i}.${n}`,s,o,{segCtx:i,settings:r});for(let{name:r,site:a,via:o}of _b(s,t.helpers)){if(Object.prototype.hasOwnProperty.call(t.actions,r))continue;let s=a===`options`?` (in a picker, menu, carousel, swatch, swatches or themePreview)`:``;if(o!==null){Sz(e,o,`Template references unknown action "${r}"${s}`);continue}e.issues.push({path:`segments.${i}.${n}`,message:`${n} references unknown action "${r}"${s}`,line:K(e.source,[`segments`,i,n])})}}}}for(let[i,a]of Dz(t.variables,r))yz(e,`variables.${i}`,a,n);for(let[i,a]of Dz(t.segments,r))if(a.vars)for(let[t,r]of Object.entries(a.vars))yz(e,`segments.${i}.vars.${t}`,r,n,i)}function kz(e,t,n=()=>!0){let{graph:r,nodeInfo:i}=Az(t),a=new Map,o=[];for(let e of r.keys())a.set(e,0);for(let e of r.keys())if(!(!n(e)||a.get(e)!==0)&&s(e))return;function s(t){a.set(t,1),o.push(t);for(let c of r.get(t)??[]){if(!n(c))continue;let t=a.get(c);if(t===1){let t=o.indexOf(c),n=[...o.slice(t),c],r=n[0],a=i.get(r);return e.issues.push({path:a?.declarationPath??`variables.${r}`,message:`Dependency cycle: ${n.join(` → `)}`,line:K(e.source,a?.linePathParts??[`variables`,r])}),!0}if(t===0&&s(c))return!0}return a.set(t,2),o.pop(),!1}}function Az(e){let t=new Set(Object.keys(e.variables)),n=new Map;for(let t of Object.keys(e.variables))n.set(t,{declarationPath:`variables.${t}`,linePathParts:[`variables`,t]});for(let[r,i]of Object.entries(e.segments))if(i.vars)for(let e of Object.keys(i.vars)){let i=`${r}.${e}`;t.add(i),n.set(i,{declarationPath:`segments.${r}.vars.${e}`,linePathParts:[`segments`,r,`vars`,e]})}let r=new Map;for(let e of t)r.set(e,new Set);let i=(n,i)=>{for(let a of pb(i,e.helpers).keys()){if(t.has(a)){r.get(n).add(a);continue}let e=a.split(`.`)[0];e!==a&&t.has(e)&&r.get(n).add(e)}},a=(e,n)=>{if(n.kind===`template`&&i(e,n.template),Ag(n)&&(`key`in n.cache&&i(e,n.cache.key),`depends_on`in n.cache))for(let i of n.cache.depends_on)t.has(i)&&r.get(e).add(i)};for(let[t,n]of Object.entries(e.variables))a(t,n);for(let[t,n]of Object.entries(e.segments))if(n.vars)for(let[e,r]of Object.entries(n.vars))a(`${t}.${e}`,r);return{graph:r,nodeInfo:n}}function jz(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)?C.homedir()+e.slice(1):e}function Mz(e,t){return s.resolve(e,jz(t))}function Nz(e,t){return typeof t==`string`&&t!==``?Mz(e,t):void 0}function Pz(e){return`plugin ${e.path} was not loaded: ${e.reason}`}const Fz=new Set([`data`,`segments`,`helpers`,`actions`]),Iz=`plugin.json5`,Lz=/^[a-z][a-z0-9_]*$/;function Rz(e){let t=s.basename(s.dirname(e));return Lz.test(t)?t:void 0}const zz=`plugins.`;function Bz(e){return`${zz}${e}.data`}function Vz(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,reason:Hz(e)}}}function Hz(e){return e instanceof Jg?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 Uz(e,t){return e.map(e=>Mz(s.dirname(t),e))}function Wz(e,t,n,r){let i=new Map;return e.reduce((e,n)=>{let a=Rz(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 ${Iz}, and the folder's name is the plugin's: move this file to <dir>/<name>/${Iz} and list that`;return o(t,a===void 0?e.config:qz(Kz(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 ${Lz}: 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=Kz(e.config,a),u=Vz(()=>{let i=p.readFileSync(n,`utf-8`),o=oI($z(n,a,{source:i,json:ui.default.parse(i)},t),l);return r(o,a,l!==e.config),o});if(u.ok)return{...e,config:u.value,loaded:[...e.loaded,n],rendering:new Map([...e.rendering,[a,n]])};let d={path:n,plugin:a,reason:u.reason};return o(u.reason,qz(l,a,d))},{config:n.config,rendering:n.rendering,loaded:[],dropped:[]})}function Gz(e){let t=`${zz}${e}.`;return e=>e.startsWith(t)}function Kz(e,t){let n=Gz(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 qz(e,t,n){return{...e,variables:{...e.variables,[Bz(t)]:{kind:`dropped`,reason:Pz(n),definition:n.path}}}}function Jz(e){return e.startsWith(`plugins.`)?e.slice(8).split(`.`)[0]:void 0}function Yz(e,t){let n=new Set([...Object.keys(e.config.variables),...Object.keys(e.config.segments)].map(Jz)),r=[...t,...e.dropped].filter(e=>e.plugin===void 0).map(e=>({definition:e.path,notice:Pz(e)}));return t=>{let i=Jz(t);if(i===void 0)return[];let a=e.config.variables[Bz(i)];return a?.kind===`dropped`?[{definition:a.definition,notice:a.reason}]:n.has(i)?[]:r}}function Xz(e,t){let n=Hy(e.presets).flatMap(t=>[...Cg(Gy(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,Zz(e,t.map(e=>e.notice),n.filter(t=>t.name===e))])),a=t=>{let n=Jz(t),r=n===void 0?void 0:e.variables[Bz(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=>_b(t,e.helpers).map(e=>e.name)),...c],e.actions),d=l(s.flatMap(t=>[...yb(t,e.helpers)]),e.helpers),f=new Set([...r.flatMap(({cause:e})=>e.map(e=>e.definition)),...[...u,...d].map(([,e])=>e.definition)]);return{config:{...e,segments:{...e.segments,...i},actions:{...e.actions,...Object.fromEntries(u.map(([e])=>[e,{copy:`{{ .${Bz(Jz(e)??``)} }}`}]))},helpers:{...e.helpers,...Object.fromEntries(d.map(([e,t])=>[e,`{{ fail ${JSON.stringify(t.notice)} }}`]))}},reached:f}}function Zz(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,Qz(e,t)]));return{template:`{{ ${JSON.stringify(r)} }}`,bg:`error`,description:`stands in for a segment whose plugin did not load`,settings:a}}function Qz(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 $z(e,t,{source:n,json:r},{checkout:i}){let a=[],o=()=>{throw new Jg(e,a)};if(!i_(r))return a.push({path:``,message:`a plugin definition must be an object, got ${a_(r)}`}),o();for(let e of Object.keys(r))Fz.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: ${[...Fz].join(`, `)}`});let s=aB(r.data,e,i,a);if(i_(r.segments)||a.push({path:`segments`,message:`"segments" must be an object naming the plugin's segments`}),a.length>0||s===void 0)return o();let c={source:n,issues:a,allowedPalettes:new Set(Lh()),groups:[]},l=_I(c,`data`,{[Bz(t)]:{kind:`file`,path:s,parse:{json:!0},cache:{watch_file:s},default:{}}});for(let[e,t]of Object.entries(r.segments))if(!(!i_(t)||!i_(t.vars)))for(let[n,r]of Object.entries(t.vars)){let t=i_(r)?r.kind:void 0;typeof t!=`string`||t===`state`||a.push({path:`segments.${e}.vars.${n}`,message:`a plugin segment's vars may declare only state variables (kind: "state"), never a source such as ${JSON.stringify(t)}: a plugin's only source is its data file`})}let u={variables:l,segments:tB(t,rB(t,dL(c,r.segments,new Set))),helpers:tB(t,$R(c,r.helpers)),actions:tB(t,iB(t,iR(c,r.actions)))};for(let[e,t]of eB(u))try{SA.parse(t)}catch(t){a.push({path:e,message:`Template parse error in ${e}: ${t.message}`})}return a.length>0&&o(),u}function*eB(e){for(let[t,n]of Object.entries(e.segments??{}))for(let e of[`template`,`bg`,`fg`,`when`]){let r=n[e];r!==void 0&&(yield[`segments.${t}.${e}`,r])}for(let[t,n]of Object.entries(e.helpers??{}))yield[`helpers.${t}`,`{{ define "${t}" }}${n}{{ end }}`];for(let[t,n]of Object.entries(e.actions??{}))`copy`in n&&(yield[`actions.${t}.copy`,n.copy]),`open`in n&&(yield[`actions.${t}.open`,n.open]),`preset`in n&&n.preset===`delete`&&(yield[`actions.${t}.name`,n.name])}function tB(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[`${zz}${e}.${t}`,n]))}function nB(e,t){return`${zz}${e}.${t}`}function rB(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,n.vars===void 0?n:{...n,vars:Object.fromEntries(Object.entries(n.vars).map(([t,n])=>[t,n.kind===`state`?{...n,key:nB(e,n.key)}:n]))}]))}function iB(e,t){return Object.fromEntries(Object.entries(t).map(([t,n])=>[t,`set`in n?{...n,set:nB(e,n.set)}:n]))}function aB(e,t,n,r){if(typeof e==`string`&&e!==``)return Mz(s.dirname(t),e);if(i_(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(i_(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 oB(e){let t=[...[...(process.env.XDG_DATA_DIRS||lB()).split(`:`).filter(e=>e!==``)].reverse().map(e=>s.join(e,`cc-candybar`,`plugins`)),sB(),...e===null?[]:[s.join(e,cB)]];return t.filter((e,n)=>t.lastIndexOf(e)===n)}function sB(){let e=process.env.XDG_DATA_HOME||s.join(C.homedir(),`.local`,`share`);return s.join(e,`cc-candybar`,`plugins`)}const cB=s.join(`.cc-candybar`,`plugins`);function lB(){let e=`/usr/local/share:/usr/share`;return process.platform===`darwin`?`${s.join(process.env.HOMEBREW_PREFIX||`/opt/homebrew`,`share`)}:${e}`:e}function uB(e){let t=oB(e),n=new Map,r=[],i=[];for(let e of t){let t=dB(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,Iz));for(let n of t.files)i.push({path:s.join(e,n),plugin:void 0,reason:`a plugin is a folder holding its ${Iz}: move this file to ${s.join(e,`<name>`,Iz)}`})}return{roots:t,definitions:[...n.values()],unchecked:r,strays:i}}function dB(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()||fB(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 fB(e,t){if(!t.isSymbolicLink())return!1;try{return p.statSync(s.join(e,t.name)).isDirectory()}catch{return!0}}function pB(e){try{return p.statSync(e,{throwIfNoEntry:!1})===void 0?`absent`:`present`}catch(t){return{path:e,error:t.message}}}const mB=[`json5`,`json`];function hB(e,t,n){if(n!==void 0)return[n];let r=t??process.cwd();return[...new Set([...e?mB.map(t=>s.join(e,`.cc-candybar.${t}`)):[],...mB.map(e=>s.join(r,`.cc-candybar.${e}`)),...mB.map(e=>`${gB()}.${e}`)])]}function gB(){let e=process.env.XDG_CONFIG_HOME??s.join(C.homedir(),`.config`);return s.join(e,`cc-candybar`,`config`)}function _B(e,t,n){let r=[],i=new Map;for(let a of hB(e,t,n)){let e=pB(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:vB(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 vB(e){let t=gB();return e.find(e=>mB.some(n=>e===`${t}.${n}`))??`${t}.${mB[0]}`}function yB(e,t,n){let r=_B(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 bB(e){return xB(e).join(`
|
|
185
|
+
`)||null}function xB(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 SB(e,t){let n=hB(e,t).filter(e=>pB(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 CB(e,t,n,r){return e===null?{...NB,config:oI(NB.raw,t)}:TB(e,p.readFileSync(e,`utf-8`),t,n,r)}const wB={projectDir:null,checkout:null,beneath:{dropped:[],rendering:new Map}};function TB(e,t,n,r,i){let a=IB(e,t,i,(t,a)=>{let o=Wz(Uz(t,e),r,{config:n,rendering:r.beneath.rendering},(t,n,r)=>jB(t,n,r,e,i)),s=Yz(o,r.beneath.dropped);return{inherited:new Set([...uL(o.config),...a.filter(e=>s(e).length>0)]),layer:{plugins:o,owning:s}}}),{plugins:o,owning:s}=a.layer,c=Xz(oI(a.raw,o.config),s);return{source:t,raw:a.raw,warnings:[...a.warnings,...o.dropped.map(Pz)],plugins:{loaded:o.loaded,dropped:o.dropped,reached:c.reached,rendering:o.rendering},config:c.config}}const EB=new WeakMap;function DB(e,t,n,r){let i=JSON.stringify([[...r??[]].sort(),e.map(e=>[e,kB(e)])]),a=EB.get(n)??new Map;EB.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=Wz(e,t,{config:n,rendering:new Map},(e,t,n)=>jB(e,t,n,`<installed plugins>`,r));return a.set(o,{key:i,layer:c}),c}function OB(e,t,n){return Wz(e,{projectDir:null,checkout:n},{config:t,rendering:new Map},(e,t,n)=>jB(e,t,n,`<plugin install>`,void 0)).dropped}function kB(e){try{let t=p.statSync(e);return`${t.ino}:${t.size}:${t.mtimeMs}`}catch(e){return e.code??`unreadable`}}function AB(e,t,n,r,i=e=>p.readFileSync(e,`utf-8`),a){let o={projectDir:r.projectDir,checkout:r.cwd===null?null:AD(r.cwd)},s=uB(o.projectDir),c=DB(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=TB(t,i(t),d.at(-1)?.config??u,{...o,beneath:{dropped:[...l.dropped,...d.flatMap(e=>e.plugins.dropped)],rendering:e?.rendering??l.rendering}},a);n.warned(r.warnings),d.push({...r,path:t})}let f=new Set(d.flatMap(e=>[...e.plugins.reached])),m=e=>f.has(e.path),h=l.dropped.filter(m),g=l.dropped.filter(e=>!m(e));n.warned(h.map(Pz));let _={checkout:o.checkout,roots:s.roots,loaded:l.loaded,dropped:h,unreached:g,reached:f,rendering:d.at(-1)?.plugins.rendering??l.rendering},v=d.at(-1);if(v===void 0)return{layers:d,base:u,installed:_,config:PB(CB(null,u,wB),`<default>`,a)};try{return{layers:d,base:u,installed:_,config:PB(v,v.path,a)}}catch(e){for(let e of d.slice(0,-1))n.entered(e.path),PB(e,e.path,a);throw n.entered(v.path),e}}function jB(e,t,n,r,i){if(n){PB(MB(e),r,i);return}let a=Gz(t),o=[],s={source:``,issues:o,allowedPalettes:new Set,groups:[]};if(Oz(s,e,xb(e),a),kz(s,e,a),o.length>0)throw new Jg(r,o)}function MB(e){return{config:e,raw:{root:e.root,presets:e.presets},source:``}}const NB={raw:{},source:``,warnings:[],plugins:{loaded:[],dropped:[],reached:new Set,rendering:new Map}};function PB({config:e,raw:t,source:n},r=`<config>`,i=new Set(Lh())){let a=[],o={source:n,issues:a,allowedPalettes:i,groups:[]};if(oz(o,e,t),kz(o,e),a.length>0)throw new Jg(r,a);let s=eR(e,a);if(a.length>0)throw new Jg(r,a);return RF(iF(s))}function FB(e,t,n=new Set(Lh()),r=LB){return IB(e,t,n,()=>({inherited:r,layer:null})).raw}function IB(e,t,n,r){let i=RB(e,t),a=Zg(e,t),o=a===null?[]:[a],s=[],c={source:t,issues:s,allowedPalettes:n??new Set(Lh()),groups:[]};if(!i_(i))throw new Jg(e,[{path:``,message:`Config root must be an object, got ${a_(i)}`}],o);let{inherited:l,layer:u}=r(i.plugins===void 0?[]:VB({...c,issues:[]},i.plugins)??[],i_(i.segments)?Object.keys(i.segments):[]),d=zB(c,i,l);if(s.length>0)throw new Jg(e,s,o);return{raw:d,warnings:o,layer:u}}const LB=new Set;function RB(e,t){try{return ui.default.parse(t)}catch(t){let n=t;throw new Jg(e,[{path:``,message:`JSON5 syntax error: ${n.message}`,line:n.lineNumber,col:n.columnNumber}])}}function zB(e,t,n){for(let n of Object.keys(t))BB.has(n)||e.issues.push({path:n,message:`Unknown top-level key "${n}". Expected one of: ${[...BB].join(`, `)}`,line:K(e.source,[n])});let r={};return t.globals!==void 0&&(r.globals=$k(e,`globals`,t.globals)),t.variables!==void 0&&(r.variables=_I(e,`variables`,t.variables)),t.segments!==void 0&&(r.segments=dL(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.
|
|
186
186
|
Replace: layout: [["seg1", "seg2"], ["seg3"]]
|
|
187
187
|
With: root: { v: [{ h: ["seg1", "seg2"] }, "seg3"] }
|
|
188
|
-
Single-row example: root: { h: ["seg1", "seg2"] }`,line:K(e.source,[`layout`])}),t.root!==void 0&&(r.root=SL(e,`root`,t.root)),t.actions!==void 0&&(r.actions=KL(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:K(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=RR(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Bk(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=BR(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=Wk(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=VR(e,t.helpers)),t.plugins!==void 0&&(r.plugins=kB(e,t.plugins)),AL(e,r),BL(e,r),CA(e,r),lk(e,r,X,`the global settings menu`),r}const OB=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function kB(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 ${a_(t)}`,line:K(e.source,[`plugins`])})}const AB={},jB=nN(`commands.`),MB=cN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),NB=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,PB=`{{ \$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 (${NB}) (basename .project_dir) (ne (${NB}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,FB=`{{ ${QA} }}`,IB={min:0,max:100,step:5},LB={warnAt:{label:`warning at %`,domain:IB,default:50},errorAt:{label:`error at %`,domain:{...IB,atLeast:`warnAt`},default:80}};function RB(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:IB,default:80}}}const zB={globals:{palette:`tokyo-night`},variables:{...jB.variables,...QO,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:PB},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:FB,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:GM(``).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:jB.template,when:jB.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:RB(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:RB(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:LB,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:LB,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) ${eh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:MB.template,bg:MB.bg,when:MB.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...GM(``).actions,...jB.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...MB.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:AB,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${eh} }}{{ \$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 (${QA}) 2 (readableOn (color "accent") (bgOf) ${eh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${eh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:lN(`.`),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 .)) }}`}},BB=new Set([zB.globals.palette,...Object.keys(zB.themeDefaults),...Object.values(zB.segments).map(e=>e.palette)].filter(e=>e!==void 0)),VB=JF(CB(`<default>`,JSON.stringify(zB),BB),zB),HB=Hy(VB.presets);function UB(e){return HB.includes(e)}const WB=Object.freeze({});function GB(e,t){return e.kind===`decided`?t[e.name]??WB:WB}function KB(e,t){return{...e,...Object.fromEntries(ov.map(n=>[n,e[n]??t[n]]))}}const qB=e=>L_(t=>e[j_[t].setting]);function JB(e,t,n,r){let i=cv(e);return Ih(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function YB(e,t,n){let r=Uy(t(`preset`),e.globals.preset,e.presets),i=Ky(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Dy(a.palette,t(`theme`),i.palette),s=KB(i,GB(o,e.themeDefaults));return{...Object.fromEntries(iv.map(e=>[e,JB(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yh(a.style,t(`style`),s.style,e.styles),effect:rg(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function XB(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?dg:fg;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const ZB=Object.entries(pv),QB=new Set(hv.map(e=>e.sessionKey)),$B=()=>!1;function eV(e,t){return YB(e,e=>QB.has(e)?t(e):null,$B)}const tV=[`preset`,`theme`];function nV(e,t,n){let r=new Set(tV.slice(0,n).map(e=>pv[e].sessionKey));return YB(e,e=>r.has(e)?t(e):null,$B)}function rV(e,t){let n=Array.from({length:tV.length+1},(n,r)=>nV(e,t,r));return e=>{let t=tV.indexOf(e);return n[t===-1?tV.length:t]}}function iV(e,t,n,r){return e.flatMap(([e,i])=>{let a=XB(t,e);return a===null||a===XB(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function aV(e,t,n){return XB(eV(e,t),n)}function oV(e,t){let n=eV(e,t);return iV(ZB,n,rV(e,t),t=>sV(e,n.preset,t.configKey))}function sV(e,t,n){return n in(Wy(e.presets,t).globals??{})?iA(t,n):n}function cV(e,t,n){let r=Uy(t(pv.preset.sessionKey),e.globals.preset,e.presets),i=aA(n);return{key:i?.scope===`globals`?sV(e,r,i.field):n,globals:Ky(e,r)}}function lV(e,t){let{preset:n}=eV(e,t);return fV(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ug(a,s);return c===void 0||Hg(c)===Hg(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function uV(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Hy(e.presets).flatMap(n=>{let i=fV(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 Bg(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:Ug(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const dV=new WeakMap;function fV(e,t){let n=dV.get(e)??new Map;dV.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Cg(Gy(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Rg(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 pV(e,t){let n=eV(e,t);return{from:n.preset,globals:Wy(e.presets,n.preset).globals??{},picks:iV(ZB.filter(([e])=>e!==`preset`),n,rV(e,t),e=>e.configKey),placements:lV(e,t)}}function mV(e,t){return YB({...e,globals:{palette:t},presets:{}},()=>null,$B)}function hV(e,t){let n=eV(e,t),r=XB(n,`theme`);if(r===null)return{kind:`rule`};let i=mV(e,r),a=Ky(e,n.preset),o=Object.fromEntries(ov.map(e=>[e,XB(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:ov.some(e=>o[e]!==XB(i,e))}}function gV(e){return{sessionKeys:hv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Ik(e)?HB.map(t=>iA(t,e)):[],...rA(e)?Lh().map(t=>nA(t,e)):[]]}}function _V(e){return new Set(hv.map(e=>e.configKey).filter(t=>gV(t).fileKeys.some(t=>bV(e,yV(t)))))}function vV(e,t,n){let r=oV(e,n),i=new Set(r.map(e=>e.configKey)),a=bv(e=>i.has(pv[e].configKey)||t.has(pv[e].configKey)),o=hV(e,n);return{unsaved:r.length+lV(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function yV(e){let t=aA(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return oA(t)}function bV(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&bV(e[n],r)}const xV=Lh(),SV=new Set(xV),CV=new Set(ig),wV=e=>e?SV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${xV.join(`, `)})`}:{ok:!1,reason:`theme name is required`},TV=e=>e?CV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${ig.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},EV=new Set([`1`,`true`]),DV=new Set([`0`,`false`]),OV={endcaps:TV,theme:wV,"toolbar-expanded":e=>EV.has(e)?{ok:!0,value:`1`}:DV.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},kV=zF(OV,`state`,IV);function AV(e,t){return kV.register(e,t)}function jV(e){return kV.gateFor(e)}function MV(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:Qy(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 NV(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(OV,e.key))}function PV(e,t,n){let r=xv.get(n);if(r!==void 0)return aV(e,t,r);for(let[,t]of Pg(e))if(t.key===n)return t.default??null;return null}function FV(e){let t=cF(e);return NV(Object.values(e.actions).flatMap(e=>MV(e,t)))}function IV(e){return LF(FV(e))}const LV=`update.dismissed`,RV=`updateNotice`,zV=pv.updateNotice.sessionKey;function BV(e){return e.kind===`source`?e.newer.digest:La(e.newer)}const VV=e=>`${e.version} [${Ke(e.digest)}]`;function HV(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:VV(e.newer),running:VV(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:La(e.newer),running:La(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${za}@${La(e.newer)}`,`install`]}}}}const UV={kind:`idle`},WV={kind:`running`};function GV(e,t,n){if(e===null)return[];let r=BV(e);if(!n.enabled||n.dismissed===r)return[];let i=HV(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(`
|
|
189
|
-
`),c=Hr([{verb:br,args:[s]}]),l=t.kind===`running`?ly(`[${i.busy}]`,c):ly(`[${i.act}]`,Hr([{verb:Nr,args:[n.sessionId]}]));return[{severity:sy,message:s,lines:[[ly(a,c),l,ly(`[dismiss]`,Hr([{verb:mr,args:[n.sessionId,
|
|
190
|
-
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:iH(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const sH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function cH(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?sH[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const lH={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},uH=Object.keys(lH);function dH(e,t){let n=cH(t.color),r=cH(t.bgcolor),i={};for(let e of uH){if(t[e]!==!0)continue;let n=lH[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 fH=new H;function pH(e){return{ok:!0,band:new qf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(dH(t.slice(r,i.start),fH)),n.push(dH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(dH(t.slice(r),fH)),n})}}function mH(e){let t=oH(pn(e)).output;try{return pH(t)}catch(e){return pH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}function hH(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const gH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function _H(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:gH[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const vH={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},yH=Object.keys(vH);function bH(e){return e.replaceAll(`#`,`##`)}function xH(e){let t=yH.filter(t=>e[t]===!0).map(e=>{let t=vH[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${_H(e.color)}`,`bg=${_H(e.bgcolor)}`,...t].join(`,`)}]`}const SH=new H;function CH(e){let t={},n=(e,n)=>{let r=xH(n)+bH(e);if(n.link===void 0)return r;let i=hH(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new qf().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),SH)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),SH)),r.join(``)}),links:t}}function wH(e){let t=oH(pn(e)).output;try{return CH(t)}catch(e){return CH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}const TH={band:e=>JSON.stringify(mH(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:wH(e)})};var EH=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const DH={"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 OH=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 EH.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await EH.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(DH).length} models`),this.executionCache=DH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(DH).length} models`),DH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const kH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function AH(e){if(typeof e==`string`)return kH.exec(e)?.[1]}function jH(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 MH(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 NH(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=jH(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`?AH(MH(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 PH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function FH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function IH(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=WH(i,t,s.value);let c=VH(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function LH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(zH(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=MH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||RH.test(r)?`claude-code`:`prompt`}const RH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function zH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function BH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=LH(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:NH(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 VH(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 HH(e){let t=VH(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return BH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function UH(e){let t=[];for(let n of e.split(`
|
|
191
|
-
`)){let e=HH(n);e&&t.push(e)}return t}function WH(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function GH(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function KH(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=WH(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>UH(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}var qH=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function JH(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 YH=new Map,XH={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},ZH={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function QH(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function $H(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function eU(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const tU={entries:0,cost:0,breakdown:eU(),days:new Map};async function nU(e,t){let n=QH(new Date($H())),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 OH.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=QH(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...XH};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 rU(e){let t=0,n=0,r=eU(),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)??{...XH};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:ZH,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function iU(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var aU=class{sessions=new Map;flight=new qH;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new qH;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:ZH,i=t?.cost?.total_cost_usd??null;return F({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=QH(wO(n)),i=PH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return L(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...XH},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??YH:YH;c||=a.has(r);let l=a.get(r)??XH;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?F({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):I}async observeSpeed(e,t,n){if(!e)return I;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=JH(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),F({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return I;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,F(a);if(!t)return a?F(a):I;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),F(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await IH(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of GH(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 KH(e,r,tU,nU);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 GH(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...rU(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=$H(),i=await FH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await iU(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},oU=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await KH(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of GH(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function sU(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 cU=class{fold;constructor(e={}){this.fold=new oU(void 0,sU,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return L(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),I):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),F({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const lU={messageCount:0,nonPrompts:0,recent:[]},uU=new Set([`turn`,`interrupt`,`claude-code`]);function dU(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!uU.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function fU(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 pU=class{fold;constructor(e={}){this.fold=new oU(lU,dU,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:fU(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const mU={command:null,todos:[],pending:[],done:[]};function hU(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 gU(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 _U(e,t){if(t.isSidechain)return e;let n=gU(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=hU(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 vU(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>hU(e,t.name),[]),done:e.done}}var yU=class{fold;constructor(e={}){this.fold=new oU(mU,_U,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`activity (${e}): ${n.reason}`):F(vU(n.value))}};function bU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function xU(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 SU(e,t,n,r){return xU(ut(bU(e,t,n,r)),n)}async function CU(e,t,n,r){return xU(await lt(bU(e,t,n,r)),n)}const wU=e=>`${e.socket}\n${e.pane}`;var TU=class{names=new Map;asking=new qH;constructor(e=Date.now){this.now=e}getSessionName(e){let t=wU(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await CU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?F(r):I:L(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const EU=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var DU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=EU(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=EU(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function OU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const kU=s.join(`lib`,`ceiling_config.py`),AU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function jU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function MU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return L(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return F(n)}function NU(e,t){if(!p.existsSync(e))return I;let n;try{n=jU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return L(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return I;let i=MU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return I;let a=[kU,AU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?F(r.installPath):L(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function PU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function FU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function IU(e){let t;try{t=JSON.parse(e)}catch{return L(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?F({ceiling:i,session:r}):L(`memento read: unexpected answer: ${e.trim()}`)}async function LU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
|
|
188
|
+
Single-row example: root: { h: ["seg1", "seg2"] }`,line:K(e.source,[`layout`])}),t.root!==void 0&&(r.root=PL(e,`root`,t.root)),t.actions!==void 0&&(r.actions=iR(e,t.actions)),t.looks!==void 0&&e.issues.push({path:`looks`,message:`"looks" was renamed "styles" — move the block under styles: { … } (and globals.look to globals.style)`,line:K(e.source,[`looks`])}),t.styles!==void 0&&(r.styles=XR(e,t.styles)),t.themeDefaults!==void 0&&(r.themeDefaults=Qk(e,t.themeDefaults)),t.presets!==void 0&&(r.presets=QR(e,t.presets)),t.editGlobals!==void 0&&(r.editGlobals=nA(e,`editGlobals`,t.editGlobals)),t.helpers!==void 0&&(r.helpers=$R(e,t.helpers)),t.plugins!==void 0&&(r.plugins=VB(e,t.plugins)),HL(e,r),QL(e,r),FA(e,r),xk(e,r,X,`the global settings menu`),r}const BB=new Set([`globals`,`variables`,`segments`,`layout`,`looks`,`root`,`actions`,`styles`,`themeDefaults`,`presets`,`editGlobals`,`helpers`,`plugins`]);function VB(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 ${a_(t)}`,line:K(e.source,[`plugins`])})}const HB={},UB=mN(`commands.`),WB=bN(`autocompact.`,e=>`{{ template "formatTokenCount" ${e} }}`),GB=`trimPrefix "/" (trimPrefix .project_dir .current_dir)`,KB=`{{ \$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 (${GB}) (basename .project_dir) (ne (${GB}) "") }}{{ end }}{{ end }}{{ action "copyDir" (abbreviatePath \$dir) }}`,qB=`{{ ${uj} }}`,JB={min:0,max:100,step:5},YB={warnAt:{label:`warning at %`,domain:JB,default:50},errorAt:{label:`error at %`,domain:{...JB,atLeast:`warnAt`},default:80}};function XB(e){return{budget:{label:`budget $`,domain:{min:0,max:1e4,step:5},default:e},warnAt:{label:`warning at %`,domain:JB,default:80}}}const ZB={globals:{palette:`tokyo-night`},variables:{...UB.variables,...uk,current_dir:{kind:`input`,path:`workspace.current_dir`,default:`?`},"model.display_name":{kind:`input`,path:`model.display_name`,default:``},"effort.level":{kind:`input`,path:`effort.level`,default:``},"effort.glyphs":{kind:`literal`,value:`? `},version:{kind:`input`,path:`version`,default:``},home:{kind:`input`,path:`home`,default:``},"tmux.session":{kind:`input`,path:`tmux.session`,default:``},"host.name":{kind:`input`,path:`host.name`,default:``},"host.user":{kind:`input`,path:`host.user`,default:``},"host.ssh":{kind:`input`,path:`host.ssh`,type:`boolean`,default:!1},"git.repoName":{kind:`input`,path:`git.repoName`,default:``},"git.branch":{kind:`input`,path:`git.branch`,default:``},"git.sha":{kind:`input`,path:`git.sha`,default:``},"git.ahead":{kind:`input`,path:`git.ahead`,type:`number`,default:0},"git.behind":{kind:`input`,path:`git.behind`,type:`number`,default:0},"git.staged":{kind:`input`,path:`git.staged`,type:`number`,default:0},"git.unstaged":{kind:`input`,path:`git.unstaged`,type:`number`,default:0},"git.untracked":{kind:`input`,path:`git.untracked`,type:`number`,default:0},"git.conflicts":{kind:`input`,path:`git.conflicts`,type:`number`,default:0},"git.upstream":{kind:`input`,path:`git.upstream`,default:``},"git.tracking":{kind:`input`,path:`git.tracking`,default:``},"git.stash":{kind:`input`,path:`git.stash`,type:`number`,default:0},"git.status":{kind:`input`,path:`git.status`,default:`clean`},"git.operation":{kind:`input`,path:`git.operation`,default:``},"git.timeSinceCommit":{kind:`input`,path:`git.timeSinceCommit`,type:`number`,default:0},"git.color.branch":{kind:`literal`,value:`primary`},"git.color.staged":{kind:`literal`,value:`success`},"git.color.unstaged":{kind:`literal`,value:`warning`},"git.color.untracked":{kind:`literal`,value:`accent`},"git.color.conflicts":{kind:`literal`,value:`error`},"git.color.ahead":{kind:`literal`,value:`success`},"git.color.behind":{kind:`literal`,value:`warning`},"git.color.stash":{kind:`literal`,value:`accent`},"git.detail":{kind:`state`,key:`git-detail`,default:`collapsed`},"git.prNumber":{kind:`input`,path:`git.prNumber`,type:`number`,default:0},"git.prState":{kind:`input`,path:`git.prState`,default:``},"git.prUrl":{kind:`input`,path:`git.prUrl`,default:``},"git.prError":{kind:`input`,path:`git.prError`,default:``},"cache.expiresAt":{kind:`input`,path:`cache.expiresAt`,type:`number`,default:0},"session.cost":{kind:`input`,path:`session.cost`,type:`number`,default:0},"session.tokens":{kind:`input`,path:`session.tokens`,type:`number`,default:0},"today.cost":{kind:`input`,path:`today.cost`,type:`number`,default:0},"today.tokens":{kind:`input`,path:`today.tokens`,type:`number`,default:0},"block.nativeUtilization":{kind:`input`,path:`block.nativeUtilization`,type:`number`,default:0},"block.resetsAt":{kind:`input`,path:`block.resetsAt`,type:`number`,default:0},"weekly.percentage":{kind:`input`,path:`weekly.percentage`,type:`number`,default:0},"weekly.resetsAt":{kind:`input`,path:`weekly.resetsAt`,type:`number`,default:0},"burn.costPerHour":{kind:`input`,path:`burn.costPerHour`,type:`number`,default:-1},"block.etaMinutes":{kind:`input`,path:`block.etaMinutes`,type:`number`,default:-1},"weekly.etaMinutes":{kind:`input`,path:`weekly.etaMinutes`,type:`number`,default:-1},"speed.input":{kind:`input`,path:`speed.input`,type:`number`,default:-1},"speed.output":{kind:`input`,path:`speed.output`,type:`number`,default:-1},"speed.total":{kind:`input`,path:`speed.total`,type:`number`,default:-1},"speed.history":{kind:`input`,path:`speed.history`,type:`string`,default:``},"context.totalTokens":{kind:`input`,path:`context.totalTokens`,type:`number`,default:0},"context.contextLeft":{kind:`input`,path:`context.contextLeft`,type:`number`,default:100},"memento.ceiling":{kind:`input`,path:`memento.ceiling`,type:`number`,default:-1},"memento.off":{kind:`input`,path:`memento.off`,type:`boolean`,default:!1},"memento.session":{kind:`input`,path:`memento.session`,default:``},"memento.error":{kind:`input`,path:`memento.error`,default:``},"metrics.lastResponseTime":{kind:`input`,path:`metrics.lastResponseTime`,type:`number`,default:0},"metrics.responseTime":{kind:`input`,path:`metrics.responseTime`,type:`number`,default:0},"metrics.sessionDuration":{kind:`input`,path:`metrics.sessionDuration`,type:`number`,default:0},"metrics.messageCount":{kind:`input`,path:`metrics.messageCount`,type:`number`,default:0},"metrics.linesAdded":{kind:`input`,path:`metrics.linesAdded`,type:`number`,default:0},"metrics.linesRemoved":{kind:`input`,path:`metrics.linesRemoved`,type:`number`,default:0},"activity.command":{kind:`input`,path:`activity.command`,type:`string`,default:``},"activity.todo.total":{kind:`input`,path:`activity.todo.total`,type:`number`,default:0},"activity.todo.completed":{kind:`input`,path:`activity.todo.completed`,type:`number`,default:0},"activity.todo.position":{kind:`input`,path:`activity.todo.position`,type:`number`,default:0},"activity.todo.active":{kind:`input`,path:`activity.todo.active`,type:`string`,default:``},"activity.tool.running":{kind:`input`,path:`activity.tool.running`,type:`string`,default:``},"activity.tool.done":{kind:`input`,path:`activity.tool.done`,type:`string`,default:``}},segments:{directory:{group:`location`,description:"The current directory, shortened fish-style — `~` under home, project-relative inside the project. Click to copy the full path.",template:KB},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:qB,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:rN(``).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:UB.template,when:UB.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:XB(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:XB(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:YB,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:YB,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) ${eh} }}`,when:`{{ gt .cache.expiresAt 0 }}`},context:{group:`model-context`,description:`Context used, in tokens and percent remaining, heating as it fills.`,template:`◔ {{ formatInteger .context.totalTokens }} ({{ .context.contextLeft }}%)`,bg:`{{ ramp .context.contextLeft "step" 0 "error" 21 "warning" 41 (tint) }}`,when:`{{ gt .context.totalTokens 0 }}`},ceiling:{group:`model-context`,description:`The memento plugin's context ceiling for this session: − and + move it by 100K, ∞ lifts it, ↺ drops this session's own setting.`,template:`{{ if ne .memento.error "" }}⌈ ⚠ {{ .memento.error }} {{ action "ceiling.clear" "↺" }}{{ else }}⌈ {{ if .memento.off }}off{{ else }}{{ template "formatTokenCount" .memento.ceiling }} {{ action "ceiling.lower" "−" }} {{ action "ceiling.raise" "+" }} {{ action "ceiling.off" "∞" }}{{ end }}{{ if ne .memento.session "" }} {{ action "ceiling.clear" "↺" }}{{ end }}{{ end }}`,bg:`{{ if ne .memento.error "" }}{{ color "error" }}{{ else }}{{ tint }}{{ end }}`,when:`{{ or (ge .memento.ceiling 0) (ne .memento.error "") }}`},autocompact:{group:`model-context`,description:`Claude Code's auto-compact window: − and + move it by 100K, ↺ returns it to auto. Clicks type /autocompact into this session, so the controls show only inside tmux.`,template:WB.template,bg:WB.bg,when:WB.when},metrics:{group:`activity`,description:`Response times, session duration, message count, and lines added/removed.`,template:`{{ if .metrics.lastResponseTime }} Δ {{ template "formatResponseTime" .metrics.lastResponseTime }}{{ end }}{{ if .metrics.responseTime }} ⧖ {{ template "formatResponseTime" .metrics.responseTime }}{{ end }}{{ if .metrics.sessionDuration }} ⧗ {{ template "formatDuration" .metrics.sessionDuration }}{{ end }}{{ if .metrics.messageCount }} ◆ {{ .metrics.messageCount }}{{ end }}{{ if .metrics.linesAdded }} + {{ .metrics.linesAdded }}{{ end }}{{ if .metrics.linesRemoved }} - {{ .metrics.linesRemoved }}{{ end }} `,when:`{{ or (gt .metrics.lastResponseTime 0.0) (gt .metrics.responseTime 0.0) (gt .metrics.sessionDuration 0.0) (gt .metrics.messageCount 0) (gt .metrics.linesAdded 0) (gt .metrics.linesRemoved 0) }}`},activity:{group:`activity`,description:`What Claude is doing: the slash command that opened the turn, the in-progress todo, and the tools in flight.`,template:`{{ if .activity.command }} ⌘ {{ .activity.command }}{{ end }}{{ if .activity.todo.total }}{{ if .activity.todo.active }} ☐ {{ .activity.todo.position }}/{{ .activity.todo.total }} {{ abbrev 32 .activity.todo.active }}{{ else }} ☑ {{ .activity.todo.completed }}/{{ .activity.todo.total }}{{ end }}{{ end }}{{ if .activity.tool.running }} ⟳ {{ template "formatToolTally" .activity.tool.running }}{{ end }}{{ if .activity.tool.done }} ✓ {{ template "formatToolTally" .activity.tool.done }}{{ end }} `,when:`{{ or (ne .activity.command "") (gt .activity.todo.total 0) (ne .activity.tool.running "") (ne .activity.tool.done "") }}`}},root:{rows:{identity:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`}]},status:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`activity`}]}}},actions:{...rN(``).actions,...UB.actions,copyDir:{copy:`{{ .current_dir }}`},stepTheme:{set:`theme`,from:`themes`},gitDetail:{set:`git-detail`,cycle:[`collapsed`,`expanded`]},"ceiling.raise":{ceiling:`set`,to:`+100_000`},"ceiling.lower":{ceiling:`set`,to:`-100_000`},"ceiling.off":{ceiling:`set`,to:`off`},"ceiling.clear":{ceiling:`clear`},...WB.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:HB,presets:{default:{},compact:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`context`}]},globals:{padding:0}},verbose:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},zen:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`directory`},{kind:`segment`,name:`context`}]},globals:{endcaps:`plain`,style:`dim`}},git:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`gitPr`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`segment`,name:`context`},{kind:`segment`,name:`activity`}]}]}},usage:{root:{kind:`container`,direction:`vertical`,children:[{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`burnrate`}]},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`session`},{kind:`segment`,name:`today`},{kind:`segment`,name:`speed`},{kind:`segment`,name:`tokenSparkline`}]}]}},dense:{root:{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`host`},{kind:`segment`,name:`directory`},{kind:`segment`,name:`gitaculous`},{kind:`segment`,name:`model`},{kind:`container`,direction:`horizontal`,children:[{kind:`segment`,name:`context`},{kind:`segment`,name:`ceiling`},{kind:`segment`,name:`autocompact`}]},{kind:`segment`,name:`cacheTimer`},{kind:`segment`,name:`block`},{kind:`segment`,name:`weekly`},{kind:`segment`,name:`session`},{kind:`segment`,name:`activity`}]},globals:{padding:0}}},editGlobals:{endcaps:`plain`,default_separator:` | `},helpers:{effortGauge:`{{ \$ord := default 0 (get (dict "low" 1 "medium" 2 "high" 3 "xhigh" 4 "max" 5) .effort.level) }}{{ \$glyphs := compact (splitList " " .effort.glyphs) }}{{ $bubble := readableOn (mix (bgOf) (color "accent") 40) (bgOf) 1.08 }}{{ $climbing := readableOn (stepped 1 (color "primary") 1 (color "secondary") 1 (color "accent")) $bubble ${eh} }}{{ \$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 (${uj}) 2 (readableOn (color "accent") (bgOf) ${eh})) (index $glyphs $ord) }}{{ end }}`,gitPaint:`{{ fg (readableOn (color .color) (bgOf) ${eh}) .text }}`,gitCollapsed:`{{ template "gitBranch" . }}{{ template "gitAheadBehind" . }}{{ template "gitFlags" . }}`,gitExpanded:`(git){{ template "gitRepo" . }}{{ template "gitOperation" . }}{{ template "gitSha" . }}{{ template "gitFlags" . }} {{ template "gitBranch" . }}{{ template "gitUpstream" . }}{{ template "gitStash" . }}{{ template "gitAge" . }}`,gitBranch:`⎇ {{ template "gitPaint" (dict "color" .git.color.branch "text" .git.branch) }}`,gitRepo:`{{ if and .settings.repo (ne .git.repoName "") }} {{ .git.repoName }}{{ end }}`,gitOperation:`{{ if and .settings.operation (ne .git.operation "") }} [{{ .git.operation }}]{{ end }}`,gitSha:`{{ if and .settings.sha (ne .git.sha "") }} {{ .git.sha }}{{ end }}`,gitFlags:`{{ if and .settings.flags (or (gt .git.staged 0) (gt .git.unstaged 0) (gt .git.untracked 0) (gt .git.conflicts 0)) }} {{ if gt .git.staged 0 }}{{ template "gitPaint" (dict "color" .git.color.staged "text" "S") }}{{ end }}{{ if gt .git.unstaged 0 }}{{ template "gitPaint" (dict "color" .git.color.unstaged "text" "U") }}{{ end }}{{ if gt .git.untracked 0 }}{{ template "gitPaint" (dict "color" .git.color.untracked "text" "?") }}{{ end }}{{ if gt .git.conflicts 0 }}{{ template "gitPaint" (dict "color" .git.color.conflicts "text" (printf "!%v" .git.conflicts)) }}{{ end }}{{ end }}`,gitAheadBehind:`{{ if and .settings.aheadBehind (or (gt .git.ahead 0) (gt .git.behind 0)) }} {{ if gt .git.ahead 0 }}{{ template "gitPaint" (dict "color" .git.color.ahead "text" (printf "+%v" .git.ahead)) }}{{ end }}{{ if and (gt .git.ahead 0) (gt .git.behind 0) }}/{{ end }}{{ if gt .git.behind 0 }}{{ template "gitPaint" (dict "color" .git.color.behind "text" (printf "-%v" .git.behind)) }}{{ end }}{{ end }}`,gitUpstream:`{{ if and .settings.upstream (ne .git.upstream "") }} [{{ .git.upstream }}{{ template "gitAheadBehind" . }}]{{ end }}`,gitStash:`{{ if and .settings.stash (gt .git.stash 0) }} {{ template "gitPaint" (dict "color" .git.color.stash "text" (printf "(%v stashed)" .git.stash)) }}{{ end }}`,gitAge:`{{ if and .settings.age (gt .git.timeSinceCommit 0) }} ◷ {{ template "formatTimeSince" .git.timeSinceCommit }}{{ end }}`,formatCost:'{{ if lt . 0.01 }}<$0.01{{ else }}${{ printf "%.2f" . }}{{ end }}',formatTokenCount:xN(`.`),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 .)) }}`}},QB=new Set([ZB.globals.palette,...Object.keys(ZB.themeDefaults),...Object.values(ZB.segments).map(e=>e.palette)].filter(e=>e!==void 0)),$B=oI(FB(`<default>`,JSON.stringify(ZB),QB),ZB),eV=Hy($B.presets);function tV(e){return eV.includes(e)}const nV=Object.freeze({});function rV(e,t){return e.kind===`decided`?t[e.name]??nV:nV}function iV(e,t){return{...e,...Object.fromEntries(ov.map(n=>[n,e[n]??t[n]]))}}const aV=e=>L_(t=>e[j_[t].setting]);function oV(e,t,n,r){let i=cv(e);return Ih(t[e],i.kind===`session`?n(e):null,r[e],i.floor,i.parse)}function sV(e,t,n){let r=Uy(t(`preset`),e.globals.preset,e.presets),i=Ky(e,r),a=t(`edit.mode`)===`arrange`?e.editGlobals:{},o=Dy(a.palette,t(`theme`),i.palette),s=iV(i,rV(o,e.themeDefaults));return{...Object.fromEntries(iv.map(e=>[e,oV(e,a,t,s)])),preset:r,presetCustomized:n(r),theme:o,style:Yh(a.style,t(`style`),s.style,e.styles),effect:rg(a.effect,t(`effect`),s.effect),separator:a.default_separator??s.default_separator}}function cV(e,t){let n=e[t];switch(typeof n){case`boolean`:return n?dg:fg;case`number`:return String(n);case`string`:return n;default:return n.kind===`decided`?n.name:null}}const lV=Object.entries(pv),uV=new Set(hv.map(e=>e.sessionKey)),dV=()=>!1;function fV(e,t){return sV(e,e=>uV.has(e)?t(e):null,dV)}const pV=[`preset`,`theme`];function mV(e,t,n){let r=new Set(pV.slice(0,n).map(e=>pv[e].sessionKey));return sV(e,e=>r.has(e)?t(e):null,dV)}function hV(e,t){let n=Array.from({length:pV.length+1},(n,r)=>mV(e,t,r));return e=>{let t=pV.indexOf(e);return n[t===-1?pV.length:t]}}function gV(e,t,n,r){return e.flatMap(([e,i])=>{let a=cV(t,e);return a===null||a===cV(n(e),e)?[]:[{...i,value:a,target:r(i)}]})}function _V(e,t,n){return cV(fV(e,t),n)}function vV(e,t){let n=fV(e,t);return gV(lV,n,hV(e,t),t=>yV(e,n.preset,t.configKey))}function yV(e,t,n){return n in(Wy(e.presets,t).globals??{})?gA(t,n):n}function bV(e,t,n){let r=Uy(t(pv.preset.sessionKey),e.globals.preset,e.presets),i=_A(n);return{key:i?.scope===`globals`?yV(e,r,i.field):n,globals:Ky(e,r)}}function xV(e,t){let{preset:n}=fV(e,t);return wV(e,n).flatMap(({id:e,setting:r,key:i,decl:a,saved:o})=>{let s=t(i),c=s===null?void 0:Ug(a,s);return c===void 0||Hg(c)===Hg(o)?[]:[{preset:n,id:e,setting:r,key:i,value:c}]})}function SV(e,t,n){let r=new Map(n.map(e=>[e.key,e.value]));return Hy(e.presets).flatMap(n=>{let i=wV(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 Bg(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:Ug(e.decl,n);return[e.setting,i??e.saved]}))).map(({message:t})=>`placement "${e}": ${t}`)})})}const CV=new WeakMap;function wV(e,t){let n=CV.get(e)??new Map;CV.set(e,n);let r=n.get(t);if(r!==void 0)return r;let i=[...Cg(Gy(e,t).node)].flatMap(t=>t.kind!==`segment`||t.drafts===void 0?[]:Object.entries(t.drafts).map(([n,{id:r,key:i}])=>{let a=Rg(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 TV(e,t){let n=fV(e,t);return{from:n.preset,globals:Wy(e.presets,n.preset).globals??{},picks:gV(lV.filter(([e])=>e!==`preset`),n,hV(e,t),e=>e.configKey),placements:xV(e,t)}}function EV(e,t){return sV({...e,globals:{palette:t},presets:{}},()=>null,dV)}function DV(e,t){let n=fV(e,t),r=cV(n,`theme`);if(r===null)return{kind:`rule`};let i=EV(e,r),a=Ky(e,n.preset),o=Object.fromEntries(ov.map(e=>[e,cV(a[e]===void 0?n:i,e)]));return{kind:`look`,theme:r,look:o,differs:ov.some(e=>o[e]!==cV(i,e))}}function OV(e){return{sessionKeys:hv.filter(t=>t.configKey===e).map(e=>e.sessionKey),fileKeys:[e,...Jk(e)?eV.map(t=>gA(t,e)):[],...hA(e)?Lh().map(t=>mA(t,e)):[]]}}function kV(e){return new Set(hv.map(e=>e.configKey).filter(t=>OV(t).fileKeys.some(t=>MV(e,jV(t)))))}function AV(e,t,n){let r=vV(e,n),i=new Set(r.map(e=>e.configKey)),a=bv(e=>i.has(pv[e].configKey)||t.has(pv[e].configKey)),o=DV(e,n);return{unsaved:r.length+xV(e,n).length,resettable:a,themeDefault:o.kind===`look`&&o.differs?{differs:!0,theme:o.theme}:{differs:!1}}}function jV(e){let t=_A(e);if(t===null||t.scope===`preset-root`)throw Error(`reset layer "${e}" is not a value path`);return vA(t)}function MV(e,t){let[n,...r]=t;return n===void 0?e!==void 0:typeof e==`object`&&!!e&&MV(e[n],r)}const NV=Lh(),PV=new Set(NV),FV=new Set(ig),IV=e=>e?PV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown theme "${e}" (have: ${NV.join(`, `)})`}:{ok:!1,reason:`theme name is required`},LV=e=>e?FV.has(e)?{ok:!0,value:e}:{ok:!1,reason:`unknown endcaps "${e}" (have: ${ig.join(`, `)})`}:{ok:!1,reason:`endcaps name is required`},RV=new Set([`1`,`true`]),zV=new Set([`0`,`false`]),BV={endcaps:LV,theme:IV,"toolbar-expanded":e=>RV.has(e)?{ok:!0,value:`1`}:zV.has(e)?{ok:!0,value:``}:{ok:!1,reason:`expected boolean-ish (1, 0, true, false), got "${e}"`}},VV=ZF(BV,`state`,JV);function HV(e,t){return VV.register(e,t)}function UV(e){return VV.gateFor(e)}function WV(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:Qy(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 GV(e){return e.filter(e=>e.spec.kind!==`allow-list`||!Object.hasOwn(BV,e.key))}function KV(e,t,n){let r=xv.get(n);if(r!==void 0)return _V(e,t,r);for(let[,t]of Pg(e))if(t.key===n)return t.default??null;return null}function qV(e){let t=bF(e);return GV(Object.values(e.actions).flatMap(e=>WV(e,t)))}function JV(e){return YF(qV(e))}const YV=`update.dismissed`,XV=`updateNotice`,ZV=pv.updateNotice.sessionKey;function QV(e){return e.kind===`source`?e.newer.digest:La(e.newer)}const $V=e=>`${e.version} [${Ke(e.digest)}]`;function eH(e){switch(e.kind){case`source`:return{headline:`Newer source`,newer:$V(e.newer),running:$V(e.running),act:`rebuild`,busy:`rebuilding…`,command:{bin:`pnpm`,args:[`build`],cwd:e.root}};case`release`:return{headline:`Newer release`,newer:La(e.newer),running:La(e.running),act:`upgrade`,busy:`upgrading…`,command:{bin:`pnpm`,args:[`dlx`,`${za}@${La(e.newer)}`,`install`]}}}}const tH={kind:`idle`},nH={kind:`running`};function rH(e,t,n){if(e===null)return[];let r=QV(e);if(!n.enabled||n.dismissed===r)return[];let i=eH(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(`
|
|
189
|
+
`),c=Hr([{verb:br,args:[s]}]),l=t.kind===`running`?ly(`[${i.busy}]`,c):ly(`[${i.act}]`,Hr([{verb:Nr,args:[n.sessionId]}]));return[{severity:sy,message:s,lines:[[ly(a,c),l,ly(`[dismiss]`,Hr([{verb:mr,args:[n.sessionId,YV,r]}])),ly(`[disable]`,Hr([{verb:xr,args:[n.sessionId,XV,`false`]},{verb:mr,args:[n.sessionId,ZV,`false`]}]))],...o.map(e=>[ly(e,c)])]}]}function iH(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 aH(e){switch(e.kind){case`current`:return[`info`,`build: current ${$V(e.stamp)}`];case`stale`:return[`info`,`build: stale — source ${$V(e.source)}, running ${$V(e.running)}`];case`not-source-checkout`:return[`info`,`build: not a source checkout`];case`unchecked`:return[`warn`,`build: unchecked: ${e.reason}`]}}function oH(e){switch(e.kind){case`current`:return[`info`,`release: current ${La(e.installed)}`];case`stale`:return[`info`,`release: stale — latest ${La(e.latest)}, running ${La(e.installed)}`];case`ahead`:return[`info`,`release: ahead — running ${La(e.installed)}, latest ${La(e.latest)}`];case`unchecked`:return[`warn`,`release: unchecked: ${e.reason}`]}}function sH(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const cH=e=>e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e!==``).at(-1);function lH(e){let t=e.exitCode===null?``:` (exit ${e.exitCode})`,n=cH(e.stderr)??e.error??cH(e.stdout)??`no output`;return`${e.reason}${t}: ${n}`}function uH(){let e=[$F(XV,[`false`]),HV(ZV,[`false`]),HV(YV,[])];return()=>e.forEach(e=>e())}function dH(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=tH,d=null,f=sH(s),p=sH(s),m=()=>iH(c,l);function h(){let e=m(),t=e===null?null:QV(e);(d===null?null:d.identity)!==t&&(d?.dispose(),d=t===null?null:{identity:t,dispose:HV(YV,[t])})}function g(){c=Qe(t,Ye),f(aH(c)),h()}async function _(){l=Va(qe,await Ba(za,a,i)),p(oH(l)),h()}return{arm(){uH(),g(),setInterval(g,n).unref(),c.kind===`not-source-checkout`&&(_(),setInterval(()=>void _(),r).unref())},notice:e=>rH(m(),u,e),act(){let e=m();if(e===null)throw new J(`apply-update: nothing newer is known to apply`);let t=eH(e);if(u.kind===`running`)throw new J(`apply-update: already ${t.busy}`);u=nH,s(`info`,`apply-update: ${t.act} — ${t.command.bin} ${t.command.args?.join(` `)??``}`),lt({...t.command,category:`update.apply`,timeoutMs:6e5}).then(n=>{if(n.ok){u=tH,s(`info`,`apply-update: ${t.act} succeeded`),g(),o();return}let r=lH(n);u={kind:`failed`,identity:QV(e),reason:r},s(`error`,`apply-update: ${t.act} failed: ${r}`)})}}}function fH(e,t){try{return F(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?I:L(e.message)}}function pH(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function mH(e){let{targets:t,intervalMs:n,stat:r,exit:i,log:a}=e,o=t.map(e=>({path:e,stamp:fH(e,r)})),s=o.filter(({stamp:e})=>e.kind!==`failed`),c=null,l=()=>{for(let{path:e,stamp:t}of s){let n=fH(e,r);if(n.kind===`failed`){a(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!pH(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 hH=`${Dv}${Ev}`;function gH(e){return`${hH}⚠ cc-candybar: ${_H(e)}${Ov}\n`}function _H(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: ${Tv(e.message,60)}`;case`render_failed`:return`render failed: ${Tv(e.message,60)}`;case`switched_off`:return`switched off: ${Tv(e.message,60)}`;case`malformed_response`:return`malformed daemon response: ${Tv(e.message,60)}`}}function vH(e){switch(e.kind){case`ok`:return{output:e.value,kick:!1,debug:null};case`transient`:return{output:`
|
|
190
|
+
`,kick:!0,debug:`daemon unavailable (transient: ${e.cause}: ${e.message}) — kicking daemon`};case`permanent`:return{output:gH(e),kick:!1,debug:`daemon refused request (permanent: ${e.cause}) — not kicking`}}}const yH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`blackBright`,`redBright`,`greenBright`,`yellowBright`,`blueBright`,`magentaBright`,`cyanBright`,`whiteBright`];function bH(e){if(e===void 0||e.isDefault)return;let t=e.fixedValue;if(t!==void 0)return t.hex;let n=e.type===z.STANDARD&&e.number!==void 0?yH[e.number]:void 0;if(n===void 0)throw Error(`frames: no band colour for ${e.name}`);return n}const xH={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},SH=Object.keys(xH);function CH(e,t){let n=bH(t.color),r=bH(t.bgcolor),i={};for(let e of SH){if(t[e]!==!0)continue;let n=xH[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 wH=new H;function TH(e){return{ok:!0,band:new qf().decode(e).map(e=>{let t=e.plain,n=[],r=0;for(let i of e.spans){if(!(i.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof i.style} style`);i.start>r&&n.push(CH(t.slice(r,i.start),wH)),n.push(CH(t.slice(i.start,i.end),i.style)),r=i.end}return r<t.length&&n.push(CH(t.slice(r),wH)),n})}}function EH(e){let t=vH(pn(e)).output;try{return TH(t)}catch(e){return TH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}function DH(e){return`ccb`+te(`sha256`).update(e).digest(`hex`).slice(0,12)}const OH=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightblack`,`brightred`,`brightgreen`,`brightyellow`,`brightblue`,`brightmagenta`,`brightcyan`,`brightwhite`];function kH(e){if(e===void 0||e.isDefault)return`terminal`;switch(e.type){case z.STANDARD:{let t=e.number===void 0?void 0:OH[e.number];if(t!==void 0)return t;break}case z.EIGHT_BIT:if(e.number!==void 0)return`colour${e.number}`;break;case z.TRUECOLOR:{let t=e.fixedValue;if(t!==void 0)return t.hex;break}case z.DEFAULT:case z.WINDOWS:break}throw Error(`frames: no tmux colour for ${e.name}`)}const AH={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},jH=Object.keys(AH);function MH(e){return e.replaceAll(`#`,`##`)}function NH(e){let t=jH.filter(t=>e[t]===!0).map(e=>{let t=AH[e];if(t===null)throw Error(`frames: a tmux status line cannot draw ${e} text`);return t});return`#[${[`none`,`fg=${kH(e.color)}`,`bg=${kH(e.bgcolor)}`,...t].join(`,`)}]`}const PH=new H;function FH(e){let t={},n=(e,n)=>{let r=NH(n)+MH(e);if(n.link===void 0)return r;let i=DH(n.link);return t[i]=n.link,`#[range=user|${i}]${r}#[norange]`};return{rows:new qf().decode(e).map(e=>{let t=e.plain,r=[],i=0;for(let a of e.spans){if(!(a.style instanceof H))throw Error(`frames: the decoder gave a span a ${typeof a.style} style`);a.start>i&&r.push(n(t.slice(i,a.start),PH)),r.push(n(t.slice(a.start,a.end),a.style)),i=a.end}return i<t.length&&r.push(n(t.slice(i),PH)),r.join(``)}),links:t}}function IH(e){let t=vH(pn(e)).output;try{return FH(t)}catch(e){return FH(`${Dv}${Ev}⚠ cc-candybar ${wv(e instanceof Error?e.message:String(e))}${Ov}\n`)}}const LH={band:e=>JSON.stringify(EH(e)),statusline:(e,t)=>t,pane:(e,t)=>t,tmuxStatus:e=>JSON.stringify({ok:!0,tmuxStatus:IH(e)})};var RH=class{static CACHE_DIR=k();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return D(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(D(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(D(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return D(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),D(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ge(50);else throw e}return D(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),D(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&D(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){D(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){D(`Cache for ${e} is locked, waiting...`),await ge(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(D(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(D(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return D(`No shared ${e} usage cache found`),null;D(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ge(75)}}return D(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){D(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),D(`[CACHE-SET] ${e} disk cache stored`)}catch(t){D(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const zH={"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 BH=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 RH.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await RH.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=he({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){D(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){D(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(D(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),D(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(D(`Invalid pricing data structure`),e(null))}catch(t){D(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{D(`Response error:`,t),e(null)})});r.on(`error`,t=>{D(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{D(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return D(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return D(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),D(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(D(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(zH).length} models`),this.executionCache=zH,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(zH).length} models`),zH)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return D(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),D(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const VH=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function HH(e){if(typeof e==`string`)return VH.exec(e)?.[1]}function UH(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 WH(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 GH(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=UH(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`?HH(WH(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 KH(e){if(e!==void 0)return[e];let t=re();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function qH(e){let t=[];for(let n of e){let e=d(n,`projects`);if(g(e))try{let n=await sa(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=d(e,r.name);t.push(n)}}catch(t){D(`Failed to read projects directory ${e}:`,t)}}return t}async function JH(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await sa(a)).filter(e=>e.startsWith(`agent-`)&&e.endsWith(`.jsonl`));for(let o of t){let t=d(a,o);if(n?.has(t)){r.push(t);continue}let s=await pa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=nU(i,t,s.value);let c=$H(ma(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){D(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function YH(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(ZH(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=WH(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||XH.test(r)?`claude-code`:`prompt`}const XH=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function ZH(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function QH(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=YH(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:GH(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 $H(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 eU(e){let t=$H(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return QH(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function tU(e){let t=[];for(let n of e.split(`
|
|
191
|
+
`)){let e=eU(n);e&&t.push(e)}return t}function nU(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function rU(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function iU(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await pa(e,a===void 0?void 0:{offset:a.offset,ino:a.ino},s?.size);if(t.kind!==`ok`)return t;let c=t.value;c.reset&&(o=n),i=nU(c.reset?[]:i,e,c),(s===void 0||c.reset)&&(s={size:c.size,stamp:c.stamp});let l=c.start+c.lines.length;if(o=await r(o,ma(c,e=>tU(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return F({folded:{cursor:a,value:o},longLines:i})}}var aU=class{inflight=new Map;run(e,t){return this.inflight.get(e)??this.start(e,t)}start(e,t){let n=t();this.inflight.set(e,n);let r=()=>{this.inflight.get(e)===n&&this.inflight.delete(e)};return n.then(r,r),n}get size(){return this.inflight.size}};function oU(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 sU=new Map,cU={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},lU={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function uU(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function dU(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function fU(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const pU={entries:0,cost:0,breakdown:fU(),days:new Map};async function mU(e,t){let n=uU(new Date(dU())),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 BH.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=uU(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...cU};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 hU(e){let t=0,n=0,r=fU(),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)??{...cU};n.cost+=t.cost,n.input+=t.input,n.output+=t.output,n.cacheCreation+=t.cacheCreation,n.cacheRead+=t.cacheRead,i.set(e,n)}}if(t===0)return{sessionInfo:lU,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}async function gU(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}var _U=class{sessions=new Map;flight=new aU;seeded=new Map;seededDay=``;rescanIntervalMs;speedFlight=new aU;staleAgeMs;log;renderTally={hits:0,misses:0};sweeps=0;scans={seed:0,rescan:0};sweepTimer=null;constructor(e={}){this.log=e.logger??Oe,this.staleAgeMs=e.staleAgeMs??864e5,this.rescanIntervalMs=e.rescanIntervalMs??6e4;let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps,seeds:this.scans.seed,rescans:this.scans.rescan}}async getUsageInfo(e,t){let n=await this.ingest(e,t?.transcript_path,this.renderTally);if(n.kind===`failed`)return n;let r=n.kind===`ok`?n.value.sessionInfo:lU,i=t?.cost?.total_cost_usd??null;return F({session:{...r,cost:i??r.cost,officialCost:i}})}async getTodayInfo(e,t,n){let r=uU(IO(n)),i=KH(t);try{await this.ensureSeeded(r,i,n*1e3)}catch(e){return L(`usage seed: ${e instanceof Error?e.message:String(e)}`)}let a=await this.ingest(e?.session_id??``,e?.transcript_path,this.renderTally);if(a.kind===`failed`)return a;let o=i.map(e=>d(e,`projects`)+f),s={...cU},c=!1;for(let[t,{record:n}]of this.sessions){let i=n?.transcriptPath??``,a=t===e?.session_id||o.some(e=>i.startsWith(e))?n?.days??sU:sU;c||=a.has(r);let l=a.get(r)??cU;s.cost+=l.cost,s.input+=l.input,s.output+=l.output,s.cacheCreation+=l.cacheCreation,s.cacheRead+=l.cacheRead}return c?F({cost:s.cost,tokens:s.input+s.output+s.cacheCreation+s.cacheRead,tokenBreakdown:{input:s.input,output:s.output,cacheCreation:s.cacheCreation,cacheRead:s.cacheRead},date:r}):I}async observeSpeed(e,t,n){if(!e)return I;let r=ra(t);return this.speedFlight.run(`${e}:${r}`,async()=>{let i=await this.ingest(e,t,this.renderTally,r);if(i.kind===`failed`)return i;let a=oU(i.kind===`ok`?i.value.sessionInfo.tokenBreakdown:null,n),{ring:o}=this.hold(e),s;for(let e of o)e.atMs<a.atMs&&(s===void 0||e.atMs>s.atMs)&&(s=e);return o.push(a),o.sort((e,t)=>e.atMs-t.atMs),o.length>64&&o.shift(),F({...s!==void 0&&{prev:s},cur:a,samples:[...o]})})}async ingest(e,t,n,r){if(!e)return I;let i=r??ra(t),a=this.see(e)?.record;if(a&&i!==``&&a.transcriptStamp===i)return n.hits++,F(a);if(!t)return a?F(a):I;n.misses++;let o;try{o=await this.flight.run(`${e}:${i}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:s,outcome:c}=o;if(c.kind!==`ok`)return c;let l={files:c.value.files,sessionInfo:c.value.sessionInfo,days:c.value.days,transcriptStamp:c.value.mainStamp,transcriptPath:t};return this.sessions.get(e)?.record===s&&(this.hold(e).record=l),F(l)}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[]};return this.sessions.set(e,n),n}async refold(e,t,n){let r=await JH(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of rU(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 iU(e,r,pU,mU);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 rU(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...hU(i),mainStamp:a})}ensureSeeded(e,t,n){this.seededDay!==e&&(this.seeded.clear(),this.seededDay=e);let r=t.join(`\0`),i=this.seeded.get(r);if(!i){let e=this.seed(t,`seed`),i={done:e,scanning:e,startedAtMs:n};return this.seeded.set(r,i),this.settle(r,i,e),e}return i.scanning===void 0&&n-i.startedAtMs>=this.rescanIntervalMs&&(i.startedAtMs=n,i.scanning=this.seed(t,`rescan`),this.settle(r,i,i.scanning)),i.done}settle(e,t,n){n.then(()=>{t.scanning=void 0},n=>{this.log(`warn`,`usageStore scan: ${n instanceof Error?n.message:String(n)}`),this.seeded.get(e)===t&&this.seeded.delete(e)})}async scanned(){await Promise.allSettled([...this.seeded.values()].map(e=>e.scanning))}async seed(e,t){let n=Date.now(),r=dU(),i=await qH(e),a=[];for(let e of i){let t;try{t=await sa(e)}catch{continue}for(let n of t){if(!n.endsWith(`.jsonl`))continue;let t=d(e,n),i;try{i=await ca(t)}catch{continue}i.mtimeMs<r||a.push({sessionId:n.slice(0,-6),path:t,stamp:ia(i)})}}let o={hits:0,misses:0};await gU(a,8,async e=>{let n=await this.ingest(e.sessionId,e.path,o,e.stamp);n.kind===`failed`&&this.log(`warn`,`usageStore ${t}: ${n.reason}`)}),this.log(`info`,`usageStore ${t} sessions=${a.length} read=${o.misses} dirs=${e.join(`,`)} ms=${Date.now()-n}`),this.scans[t]++}sweepStale(){let e=Date.now(),t=0,n=0,r=0;for(let[i,{lastSeenAt:a,record:o}]of this.sessions)if(!(e-a<=this.staleAgeMs)){if(o?.days.has(this.seededDay)){n++;continue}this.sessions.delete(i),t++,o===void 0&&r++}return t>0&&this.sweeps++,(t>0||n>0)&&this.log(`info`,`usageStore sweep dropped=${t} noRecord=${r} held=${n}`),t}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.sessions.clear(),this.seeded.clear()}},vU=class{states=new Map;constructor(e,t,n=Oe,r=256){this.empty=e,this.step=t,this.log=n,this.maxSessions=r}async read(e,t){let n=this.states.get(e),r=ra(t);if(n&&r!==``&&n.cursor.stamp===r)return this.touch(e,n),{kind:`ok`,value:n.value};let i=await iU(t,n,this.empty,(e,t)=>t.reduce(this.step,e));if(i.kind===`failed`)return i;if(i.kind===`absent`)return{kind:`ok`,value:n?.value??this.empty};let{folded:a,longLines:o}=i.value;for(let e of rU(o))this.log(`info`,e);for(this.touch(e,a);this.states.size>this.maxSessions;){let e=this.states.keys().next().value;if(e===void 0)break;this.states.delete(e)}return{kind:`ok`,value:a.value}}touch(e,t){this.states.delete(e),this.states.set(e,t)}};function yU(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 bU=class{fold;constructor(e={}){this.fold=new vU(void 0,yU,e.logger)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return D(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);D(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){let r=await this.fold.read(e,t);if(r.kind===`failed`)return L(`context transcript: ${r.reason}`);let i=r.value;return i===void 0?(D(`No main chain entries with usage data found`),I):(D(`Most recent main chain context: ${i} tokens (limit: ${n})`),F({totalTokens:i,maxTokens:n,...this.ratioPercentages(i,n)}))}async getContextInfo(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=e.context_window?.context_window_size??2e5;return this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,n)}};const xU={messageCount:0,nonPrompts:0,recent:[]},SU=new Set([`turn`,`interrupt`,`claude-code`]);function CU(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!SU.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function wU(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 TU=class{fold;constructor(e={}){this.fold=new vU(xU,CU,e.logger)}async getMetricsInfo(e,t){if(D(`Getting metrics from hook data for session: ${e}`),!t.cost)return I;let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.cost.total_api_duration_ms/1e3,lastResponseTime:wU(n.value.recent),sessionDuration:t.cost.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.cost.total_lines_added,linesRemoved:t.cost.total_lines_removed})}};const EU={command:null,todos:[],pending:[],done:[]};function DU(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 OU(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 kU(e,t){if(t.isSidechain)return e;let n=OU(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=DU(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 AU(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>DU(e,t.name),[]),done:e.done}}var jU=class{fold;constructor(e={}){this.fold=new vU(EU,kU,e.logger)}async getActivityInfo(e,t){let n=await this.fold.read(e,t.transcript_path);return n.kind===`failed`?L(`activity (${e}): ${n.reason}`):F(AU(n.value))}};function MU(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function NU(e,t){if(e.ok)return{kind:`ok`,stdout:e.stdout};if(e.reason===`rate-limited`)return{kind:`rate-limited`,reason:e.error??`rate-limited`};let n=e.error??[e.reason,e.stderr.trim()].filter(e=>e!==``).join(`: `);return{kind:`failed`,reason:`tmux ${t[0]} failed (${n})`}}function PU(e,t,n,r){return NU(ut(MU(e,t,n,r)),n)}async function FU(e,t,n,r){return NU(await lt(MU(e,t,n,r)),n)}const IU=e=>`${e.socket}\n${e.pane}`;var LU=class{names=new Map;asking=new aU;constructor(e=Date.now){this.now=e}getSessionName(e){let t=IU(e),n=this.names.get(t);if(n&&this.now()-n.at<3e4)return Promise.resolve(n.outcome);let r=this.asking.run(t,()=>this.ask(t,e));return n?Promise.resolve(n.outcome):r}async ask(e,t){D(`Getting tmux session name for pane ${t.pane} on ${t.socket}`);let n=await FU(t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]),r=n.kind===`ok`?n.stdout.trim():``,i=n.kind===`ok`?r?F(r):I:L(n.reason);for(this.names.delete(e),this.names.set(e,{outcome:i,at:this.now()});this.names.size>64;)this.names.delete(this.names.keys().next().value);return i}};const RU=e=>JSON.stringify([e.sessionId,e.projectDir,e.cwd,e.claudeConfigDir,e.env===void 0?null:Mt.map(t=>e.env?.[t]??null)]);var zU=class{readings=new Map;inFlight=new Map;constructor(e,t=Date.now){this.edge=e,this.now=t}getCeiling(e){let t=RU(e),n=this.readings.get(t);if(n&&this.now()-n.at<1e4)return Promise.resolve(n.outcome);let r=this.inFlight.get(t)??this.fetch(t,e);return n?Promise.resolve(n.outcome):r}fetch(e,t){let n=this.edge.locate(t),r=(n.kind===`ok`?this.edge.read(n.value,t):Promise.resolve(n)).then(t=>{if(this.inFlight.get(e)!==r)return t;for(this.readings.delete(e),this.readings.set(e,{outcome:t,at:this.now()});this.readings.size>64;)this.readings.delete(this.readings.keys().next().value);return t}).finally(()=>{this.inFlight.get(e)===r&&this.inFlight.delete(e)});return this.inFlight.set(e,r),r}move(e,t){let n=this.edge.locate(e);if(n.kind!==`ok`)throw Error(n.kind===`failed`?n.reason:`memento is not installed or not enabled for this project`);let r=RU(e);try{this.edge.move(n.value,e,t)}finally{this.readings.delete(r),this.inFlight.delete(r),this.fetch(r,e)}}};function BU(e,t){return{...e,claudeConfigDir:xa(t.claudeConfigDir),env:t.mementoEnv}}const VU=s.join(`lib`,`ceiling_config.py`),HU=s.join(`skills`,`ceiling`,`bin`,`ceiling`);function UU(e,t){let n=typeof e==`object`&&e?e.plugins:void 0;if(typeof n!=`object`||!n)throw Error(`${t} has no "plugins" object`);return Object.entries(n).filter(([e])=>e.split(`@`)[0]===`memento`).flatMap(([e,n])=>{if(!Array.isArray(n))throw Error(`${t}: "${e}" is not a list of installs`);return n.map(n=>{let{scope:r,installPath:i,projectPath:a}=n??{};if(typeof r!=`string`||typeof i!=`string`)throw Error(`${t}: an install of "${e}" has no scope/path`);return typeof a==`string`?{key:e,scope:r,installPath:i,projectPath:a}:{key:e,scope:r,installPath:i}})})}function WU(e,t){let n=!0;for(let r of e){if(!p.existsSync(r))continue;let e;try{e=JSON.parse(p.readFileSync(r,`utf8`))?.enabledPlugins?.[t]}catch(e){return L(`memento lookup: ${r}: ${e.message}`)}typeof e==`boolean`&&(n=e)}return F(n)}function GU(e,t){if(!p.existsSync(e))return I;let n;try{n=UU(JSON.parse(p.readFileSync(e,`utf8`)),e)}catch(e){return L(`memento lookup: ${e.message}`)}let r=n.find(e=>e.projectPath===t)??n.find(e=>e.scope===`user`);if(r===void 0)return I;let i=WU([s.join(s.dirname(s.dirname(e)),`settings.json`),s.join(t,`.claude`,`settings.json`),s.join(t,`.claude`,`settings.local.json`)],r.key);if(i.kind!==`ok`)return i;if(!i.value)return I;let a=[VU,HU].filter(e=>!p.existsSync(s.join(r.installPath,e)));return a.length===0?F(r.installPath):L(`memento at ${r.installPath} has no ${a.join(` or `)} — upgrade the plugin`)}function KU(e,t=process.env){let n=new Set([`CLAUDE_PROJECT_DIR`,`CLAUDE_CODE_SESSION_ID`,...e.env===void 0?[]:Mt]);return{...Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e))),...e.env,CLAUDE_CODE_SESSION_ID:e.sessionId,CLAUDE_PROJECT_DIR:e.projectDir||e.cwd}}function qU(e){return e.stderr.trim()||e.error||`${e.reason}${e.exitCode===null?``:` (exit ${e.exitCode})`}`}function JU(e){let t;try{t=JSON.parse(e)}catch{return L(`memento read: not JSON: ${e.trim()}`)}let{ceiling:n,session:r}=t??{},i=n===`off`||typeof n==`number`&&n>=0?n:void 0;return i!==void 0&&(r===null||typeof r==`string`)?F({ceiling:i,session:r}):L(`memento read: unexpected answer: ${e.trim()}`)}async function YU(e,t){let n=await lt({bin:`python3`,args:[`-c`,`
|
|
192
192
|
import json, math, sys
|
|
193
193
|
sys.path.insert(0, sys.argv[1])
|
|
194
194
|
from ceiling_config import CONFIG_NAME, anchored, ceiling_in, in_force, session_directory
|
|
@@ -197,18 +197,18 @@ ceiling = in_force(directory, anchored(sys.argv[3]))
|
|
|
197
197
|
layer = ceiling_in(directory / CONFIG_NAME)
|
|
198
198
|
print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
|
|
199
199
|
"session": layer.text if layer else None}))
|
|
200
|
-
`,s.join(e,`lib`),t.sessionId,t.cwd],env:
|
|
201
|
-
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!
|
|
202
|
-
`).at(-1).trim();function
|
|
203
|
-
`).map(e=>Zo(e.replace(
|
|
204
|
-
`);if(i.length>1)return n();let a=Math.max(0,t.width-FW(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];OW(c,c.cellLength+a,n)}),n()}function LW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=RW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Nv(a.style)};if(e.style.link){i();let r=RW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function RW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>zW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function zW(e,t){let n=e.copy();return n.style=t,n}function BW(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 VW(e,t){let{look:n}=BW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function HW(e,t){let{layout:n}=BW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function UW(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 WW(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,GW(e,t,o,n,r,i));return i}function GW(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=Qy(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=vv.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=Qy(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=Qy(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:JW(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:JW(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:WL(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:JW(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 KW(e){return e.kind===`do`?KW(e.head):e}function qW(e){switch(KW(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function JW(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function YW(e,t){return e.has(t)?Ab(e.read(t)):``}function XW(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function ZW(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function QW(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Nv(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Nv(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function $W(e,t){return Math.max(e.members.indexOf(YW(t,e.stateVar)),0)}function eG(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[($W(e,r)+1)%e.members.length];return{effects:[{verb:mr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:hr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:gr,args:[XW(e.text,wD(r))]}],active:!1};case`open`:return{effects:[{verb:_r,args:[XW(e.target,wD(r))]}],active:!1};case`persist-literal`:{let t=YW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=YW(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[($W(e,r)+1)%e.members.length];return{effects:[{verb:xr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Sr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Dr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`back`:return{effects:[{verb:jr,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:Mr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Tr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Er,args:[i,XW(e.name,wD(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Pr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ir,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Rr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:zr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Or,args:[i,e.key,DF(e.op)]}],active:!1};case`do`:{let a=eG(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>eG(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Or,args:[i,e.key,DF(r)]}],active:!1}}}}function tG(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,$W(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 nG(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=BW(n,`action "${e}"`).store,{display:a,boundValue:o}=tG(e,KW(r),t,i),s=YW(i,`session.id`),{effects:c,active:l}=eG(r,a.plain,o,i,s);return QW(a,Hr(c),l)}function rG(e){return{action:{fn:(t,...n)=>nG(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function iG(e,t){return ZW(`✕`,Hr([{verb:mr,args:[YW(e,`session.id`),t,P]}]),!1)}function aG(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(th(e,t,n))})}function oG({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function sG(e,t,n){return new H({color:B.fromRgba(Uc(Gm(e,`warning`),t,eh,n))})}function cG(e,t,n){return H.combine([aG(e,t,n),sG(e,t,n)])}function lG(e,t,n){return aG(e.palette,Oh(e.palette,e.disclosure,t,n),n)}function uG(e){let t=B.fromRgba(Gm(e,`background`)),n=G.fromFragments(ym.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Gm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const dG=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},fG=e=>new H({bold:e});function pG(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>dG(a,H.combine([lG(e,{...n,distribution:t},i),fG(o)]));let o=aG(e.palette,a,i);return(e,t,i,a)=>mG(i,H.combine([o,fG(a)]),r(t,n))}const mG=(e,t,n)=>dG(G.fromFragments([dG(e,t),dG(` `,t),uG(n)]));function hG(e,t){return t===void 0?(e,t,n)=>dG(n):(n,r,i)=>mG(i,void 0,t(r,e))}function gG(e,t,n,r,i){let a=aG(e.palette,i,r);return(e,r,i,o)=>dG(G.fromFragments([dG(o?`[`:` `,a),uG(n(r,t)),dG(o?`]`:` `,a)]))}function _G(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=>vG(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function vG(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function yG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function bG(e){return{current:null,drawnAt:e}}function xG(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 SG(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 CG(e){return new G(e).cellLength}function wG(e){let{width:t,chromeCols:n,padding:r}=BW(e,`a row fit`);return Math.max(1,t-n-2*r)}function TG(e){let{padding:t,seamCols:n}=BW(e,`a row fit`);return Math.max(1,wG(e)-(CG(`✕`)+2*t+n))}function EG(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 DG(e,t,n){let r=CG(`←`)+1+CG(`→`)+1,i=EG(e,t,n);return(i.length>1?EG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function OG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function kG(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 AG(e,t,n){let r=e.compiled.get(t),i=r&&KW(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 jG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=BW(a,`picker`).store,d=YW(u,`session.id`),f=`stateVar`in t?YW(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`?TG(a):wG(a):1/0,h=(r.kind===`led`?0:CG(`✕`)+1)+c.reduce((e,t)=>e+CG(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?DG(_.map(e=>e.cellLength),m,h):_G(g.entries,g.groups,i),y=parseInt(YW(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=>Hr([{verb:mr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:mr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Hr([...eG(l,e,e,u,d).effects,...C]),ie=(e,n)=>QW(e,re(t.options[n])),ae=r.kind===`led`?[]:[ZW(`✕`,Hr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>ZW(e,Hr([...eG(l,r,r,u,d).effects,{verb:mr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(ZW(`←`,te(x-1),!1));let w=x<v.length-1?[ZW(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[OG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[OG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(OG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>CG(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:wv(a),s=` `.repeat(n-CG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(OG([ie(p(r,yG(c,m)),r)],i))}}return se}function MG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{vD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=kG(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=AG(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=SG(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]=jG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,pG(u,Pm(void 0),VW(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),sG(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function NG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function PG(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 FG(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=BW(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=YW(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return OG([],!0);let d=YW(o,t.stateVar),f=NG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Hr(eG(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=QW(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):QW(hG(VW(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Hr(eG(n.compiled.get(a),p(0),void 0,o,c).effects)),b=PG(e=>v(e).cellLength,u,CG(`◀`)+1+y.cellLength+1+CG(`▶`),TG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return OG([...ee(-1).reverse(),ZW(`◀`,h(-1),!1),y,ZW(`▶`,h(1),!1),...ee(1)],!0)}function IG(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(vD(`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&&qW(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=AG(e,n,`carousel`),l=SG(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 FG(n,c,e,pG(l,Pm(void 0),VW(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function LG(e,t,n){let r=AG(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 RG(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 zG(e,t,n,r){let i=LG(e,t,n),a=r??YW(BW(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,VW(e,`{{ ${n} }}`))}function BG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(vD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return uG(zG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=LG(e,r,`swatches`),o=kG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=SG(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]=jG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,gG(s,VW(e,`{{ swatches }}`),a.paletteOf,c,s.bg),sG(s.palette,s.bg,c),u===0?[]:(()=>{let t=NG(l,YW(BW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[RG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const VG=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function HG(e,t,n,r){let i=hh(e,n,r),a=(t,n)=>({text:t,colour:n,ink:th(e,n,r)});return[[km(t).map((n,i)=>{let a=Km(e,n);return{text:VG[i%VG.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Gm(e,`warning`)),a(`error`,Gm(e,`error`))]]]}function UG(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:oG({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function WG(e,t,n,r,i){let a=HG(e,t,n,r).map(e=>UG(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
205
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
206
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
200
|
+
`,s.join(e,`lib`),t.sessionId,t.cwd],env:KU(t),timeoutMs:3e3,category:`memento.read`});return n.ok?JU(n.stdout):L(qU(n))}function XU(e,t,n){let r=ut({bin:s.join(e,HU),args:n.kind===`set`?[`set`,`session`,n.to]:[`clear`,`session`],env:KU(t),timeoutMs:5e3,category:`memento.move`});if(!r.ok)throw Error(qU(r))}function ZU(e,t){return GU(Ca(e),t)}function QU(){return{locate:e=>ZU(e.claudeConfigDir,e.projectDir),read:YU,move:XU}}function $U(e){return{gitProvider:new kO({watchers:e.watchers,logger:e.logger}),usageStore:new _U({logger:e.logger}),contextProvider:new bU({logger:e.logger}),metricsProvider:new TU({logger:e.logger}),activityProvider:new jU({logger:e.logger}),tmuxService:new LU,mementoProvider:new zU(QU()),autoCompact:vN,log:e.logger}}const eW=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function tW(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}async function nW(e){let t=await rW(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function rW(e){for(let t of[65536,1048576]){let n=await _a(e,t);if(n.kind!==`ok`)return n;let r=iW(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function iW(e,t){let n=e.toString(`utf8`).split(`
|
|
201
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!eW.test(t))continue;let r=tW(t);if(r!=null)return r}return null}function aW(e,t,n){return Me({dir:e.project_dir,env:n===void 0?[]:[[ya,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function oW(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function sW(e){return{...Object.fromEntries(iv.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:tV(e.preset)}}}const cW={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function lW(e){return e?.prState===void 0?e?.prError===void 0?e?.prEarlier===void 0?`-`:`earlier-${e.prEarlier}`:`failed`:e.prState}const uW=10*1e3;function dW(e,t,n,r){let i=n-(t*1e3-r);if(i<3e5||e<=0)return;let a=e/i,o=(100-e)/a;return Math.max(0,Math.round(o/6e4))}function fW(e,t){if(!(t<60))return e*3600/t}function pW(e,t,n,r){let i=r-t;if(i<50||i>uW)return;let a=n-e;if(!(a<=0))return a*1e3/i}function mW(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=pW(t.input,t.atMs,n.input,n.atMs),i=pW(t.output,t.atMs,n.output,n.atMs),a=pW(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 hW(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>uW)continue;let o=pW(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function gW(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function _W(e){let t=[],n=(e,n)=>{try{let e=n();return e===``?void 0:e}catch(n){t.push(`host.${e}: ${String(n)}`);return}},r=n(`name`,()=>gW(C.hostname())),i=n(`user`,()=>C.userInfo().username);return{host:{...r!==void 0&&{name:r},...i!==void 0&&{user:i},...e.ssh!==void 0&&{ssh:e.ssh}},failures:t}}function vW(e,t){let n=[],r=t=>pb(t,e.helpers).keys(),i=Ky(e,t);for(let e of Hh){let t=i[e];if(Uh(t))for(let e of r(t))n.push(e)}for(let i of Cg(Gy(e,t).node)){if(i.when)for(let e of r(i.when))n.push(e);i.kind===`segment`&&n.push(...yW(e,i.name))}return xW(e,n)}function yW(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(t=>t?[...pb(t,e.helpers).keys()]:[]):[]}function bW(e,t,n){return xW(e,[...yW(e,t),...n.flatMap(t=>[...pb(t,e.helpers).keys()])])}function xW(e,t){let n=new Map;for(let[t,r]of Object.entries(e.variables))n.set(t,r);for(let[t,r]of Object.entries(e.segments))if(r.vars)for(let[e,i]of Object.entries(r.vars))n.set(`${t}.${e}`,i);let r=[...t],i=new Set,a=t=>pb(t,e.helpers).keys(),o=new Set;for(;r.length>0;){let e=r.pop();for(let t of CW(n,e)){if(i.has(t))continue;i.add(t);let e=n.get(t);if(e){if(e.kind===`input`)o.add(e.path);else if(e.kind===`template`)for(let t of a(e.template))r.push(t)}}}return o}function SW(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=vW(e,n);return t.set(n,i),i}}function CW(e,t){let n=t;for(;n.length>0;){if(e.has(n))return[n];let t=n.lastIndexOf(`.`);if(t<0)break;n=n.slice(0,t)}let r=`${t}.`,i=[];for(let t of e.keys())t.startsWith(r)&&i.push(t);return i}function wW(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function TW(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.timeSinceCommit`)&&{showTimeSinceCommit:!0},...Object.keys(cW).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}async function EW(e,t,n,r,i,a,o,{configPath:s,...c}){let l=e=>wW(i,e),u=IO(t).getTime(),d=o.tmux??null,f=(e,t,n)=>t?n().catch(t=>L(`${e}: ${String(t)}`)):Promise.resolve(I),[p,m,h,g,_,v,y,b,ee,x,S]=await Promise.all([f(`git`,l(`git`),()=>n.gitProvider.getGitInfo(n.holds,r??e.workspace?.current_dir,TW(i),e.workspace?.project_dir)),f(`session`,l(`session.cost`)||l(`session.tokens`)||l(`burn`),()=>n.usageStore.getUsageInfo(e.session_id,e)),f(`today`,l(`today`),()=>n.usageStore.getTodayInfo(e,o.claudeConfigDir,t)),f(`context`,l(`context`)||l(`autocompact`),()=>n.contextProvider.getContextInfo(e)),f(`metrics`,l(`metrics`)||l(`burn`),()=>n.metricsProvider.getMetricsInfo(e.session_id,e)),f(`activity`,l(`activity`),()=>n.activityProvider.getActivityInfo(e.session_id,e)),f(`tmux`,l(`tmux.session`),()=>d===null?Promise.resolve(I):n.tmuxService.getSessionName(d)),f(`cache`,l(`cache`),()=>nW(e.transcript_path)),f(`speed`,l(`speed`),()=>n.usageStore.observeSpeed(e.session_id,e.transcript_path,u)),f(`memento`,l(`memento`),()=>n.mementoProvider.getCeiling(BU({sessionId:e.session_id,projectDir:e.workspace?.project_dir??``,cwd:r??e.workspace?.current_dir??``},o))),f(`autocompact`,l(`autocompact`),()=>Promise.resolve(n.autoCompact(Sa(xa(o.claudeConfigDir)))))]),te=[],ne=e=>{if(e.kind===`failed`){te.push(e.reason);return}return e.kind===`ok`?e.value:void 0},C=PW(p,u),re=_W(o);te.push(...re.failures);let ie=ne(m),ae=ne(h),w=ne(g),T=ne(_),oe=ne(v),E=ne(y),se=ne(b),ce=kW(x);x.kind===`failed`&&te.push(`memento: ${x.reason}`);let le=DW(S,w?.maxTokens);S.kind===`failed`&&te.push(`autocompact: ${S.reason}`);for(let e of te)n.log(`warn`,`provider fetch failed: ${e}`);let ue=e.rate_limits?.five_hour,de=e.rate_limits?.seven_day,fe=ue?dW(ue.used_percentage,ue.resets_at,18e6,u):void 0,pe=de?dW(de.used_percentage,de.resets_at,6048e5,u):void 0,me=ie?.session.cost,he=T?.sessionDuration,ge=l(`burn`)&&me!=null&&he!=null?fW(me,he):void 0,_e=ne(ee),ve=_e===void 0?void 0:mW(_e),ye=_e===void 0?void 0:hW(_e),be=ve!==void 0||ye!==void 0?{...ve,...ye!==void 0&&{history:ye}}:void 0,xe=NW(process.env.HOME??process.env.USERPROFILE),Se=e.workspace?{...e.workspace,current_dir:NW(e.workspace.current_dir)??``,project_dir:NW(e.workspace.project_dir)??``,added_dirs:(e.workspace.added_dirs??[]).map(e=>NW(e)??e)}:e.workspace,Ce=ie===void 0?void 0:MW({cost:ie.session.cost,tokens:ie.session.tokens}),we=ae===void 0?void 0:{cost:ae.cost,tokens:ae.tokens},Te=T===void 0?void 0:MW({lastResponseTime:T.lastResponseTime,responseTime:T.responseTime,sessionDuration:T.sessionDuration,messageCount:T.messageCount,nonPrompts:T.nonPrompts,linesAdded:T.linesAdded,linesRemoved:T.linesRemoved}),Ee=oe===void 0?void 0:AW(oe);return{...e,...Se!==void 0&&{workspace:Se},...xe!==void 0&&{home:xe},...C.git!==void 0&&{git:C.git},...d!==null&&{tmux:{pane:d.pane,...E!==void 0&&{session:E}}},host:re.host,...sW(a),history:n.history(e.session_id),navigation:{back:n.navigation(e.session_id)},feeds:n.feeds(e.session_id),...c,...s!==null&&{configPath:s},resumeCommand:aW(Se,e.session_id,o.claudeConfigDir),...Ce!==void 0&&{session:Ce},...we!==void 0&&{today:we},...ge!==void 0&&{burn:{costPerHour:ge}},...be!==void 0&&{speed:be},...l(`block`)&&ue!==void 0&&{block:{nativeUtilization:ue.used_percentage,resetsAt:ue.resets_at,...fe!==void 0&&{etaMinutes:fe}}},...de!==void 0&&{weekly:{percentage:de.used_percentage,resetsAt:de.resets_at,...pe!==void 0&&{etaMinutes:pe}}},...se!==void 0&&{cache:{expiresAt:se}},...w!==void 0&&{context:{totalTokens:w.totalTokens,contextLeft:w.contextLeftPercentage}},...Te!==void 0&&{metrics:Te},...Ee!==void 0&&{activity:Ee},...ce!==void 0&&{memento:ce},...le!==void 0&&{autocompact:le}}}function DW(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return yN(e.value,t)}}const OW=e=>e.trim().split(`
|
|
202
|
+
`).at(-1).trim();function kW(e){switch(e.kind){case`absent`:return;case`failed`:return{error:OW(e.reason)};case`ok`:{let{ceiling:t,session:n}=e.value;return{ceiling:t===`off`?0:t,off:t===`off`,session:n??``}}}}function AW(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=jW(e.running),i=jW(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 jW(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function MW(e){let t={},n=!1;for(let r of Object.keys(e)){let i=e[r];i!=null&&(t[r]=i,n=!0)}return n?t:void 0}function NW(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function PW(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=s===void 0?void 0:Math.floor((t-s)/1e3),l=r(n.stashCount),u=r(n.upstream),d=n.upstream===void 0?void 0:r(jD(n.upstream,n.aheadBehind)),f=r(n.repoName),p=r(n.repoUrl),m=n.pullRequest===void 0?void 0:MD(n.pullRequest,n.head),h={};switch(m?.kind){case`ok`:h={prNumber:m.value.number,prState:m.value.state,prUrl:m.value.url};break;case`failed`:h={prError:m.reason};break;case`earlier`:h={prEarlier:m.value.state};break;case`absent`:case void 0:break}return{git:{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},...c!==void 0&&{timeSinceCommit:c},...l!==void 0&&{stash:l},...u!==void 0&&{upstream:u},...d!==void 0&&{tracking:d},...f!==void 0&&{repoName:f},...p!==void 0&&{repoUrl:p},...h}}}function FW(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const IW={kind:`hidden`},LW={kind:`shown`};function RW(e,t){try{return FW(e,t)?LW:IW}catch(e){return{kind:`failed`,message:e instanceof Error?e.message:String(e)}}}function zW(e,t){let n=G.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function BW(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function VW({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function HW({text:e,placement:t,lead:n,trail:r}){return{text:UW(e),placement:t,...n!==void 0&&{lead:UW(n)},...r!==void 0&&{trail:UW(r)}}}function UW(e){let t=e.blankCopy(e.plain);t.style=Nv(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Nv(i).clearMetaAndLinks(),n,r);return t}function WW(e){let t=VW(e);if(t.length===1)return e.text;let n=zW(t);return n.style=e.text.style,n}function GW(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=zW(e,a).pad(o),d=new G(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:zW([d,...c],a)},...l.length>0&&{trail:zW([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(BW(u,n,p),[{text:u,...f}])}const KW=RegExp(`\\x1b\\[[0-9;]*m|${ad.source}`,`g`);function qW(e){return Math.max(0,...e.split(`
|
|
203
|
+
`).map(e=>Zo(e.replace(KW,``))))}function JW(e,t){let n=()=>e.map(e=>({owner:WW(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=ry(e.map(WW),t).split(`
|
|
204
|
+
`);if(i.length>1)return n();let a=Math.max(0,t.width-qW(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];BW(c,c.cellLength+a,n)}),n()}function YW(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=XW(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Nv(a.style)};if(e.style.link){i();let r=XW([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function XW(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>ZW(e.frag,n?n.add(e.style):e.style)),i=G.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function ZW(e,t){let n=e.copy();return n.style=t,n}function QW(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 $W(e,t){let{look:n}=QW(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function eG(e,t){let{layout:n}=QW(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function tG(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 nG(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,rG(e,t,o,n,r,i));return i}function rG(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=Qy(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=vv.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=Qy(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=Qy(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:oG(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:oG(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`ceiling`in n)return{kind:`ceiling`,args:nR(n)};if(`slash`in n)return{kind:`slash`,line:n.slash};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:oG(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 iG(e){return e.kind===`do`?iG(e.head):e}function aG(e){switch(iG(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`ceiling`:case`slash`:case`do`:return!1}}function oG(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function sG(e,t){return e.has(t)?Ab(e.read(t)):``}function cG(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function lG(e,t,n,r){let i=new G(e,{style:H.combine([r,new H({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function uG(e,t,n=!1){let r=new H({link:t,bold:n?!0:void 0}),i=new G(e.plain,{style:H.combine([Nv(e.style),r])});for(let t of e.spans)i.stylize(H.combine([Nv(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function dG(e,t){return Math.max(e.members.indexOf(sG(t,e.stateVar)),0)}function fG(e,t,n,r,i){switch(e.kind){case`set-literal`:{let t=sG(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=sG(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=sG(r,e.stateVar);return{effects:[{verb:mr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(dG(e,r)+1)%e.members.length];return{effects:[{verb:mr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:hr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:gr,args:[cG(e.text,wD(r))]}],active:!1};case`open`:return{effects:[{verb:_r,args:[cG(e.target,wD(r))]}],active:!1};case`persist-literal`:{let t=sG(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=sG(r,e.stateVar);return{effects:[{verb:xr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(dG(e,r)+1)%e.members.length];return{effects:[{verb:xr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Sr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Dr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:kr,args:[i]}],active:!1};case`redo`:return{effects:[{verb:Ar,args:[i]}],active:!1};case`back`:return{effects:[{verb:jr,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:Mr,args:[i]}],active:!1};case`save`:return{effects:[{verb:Cr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:wr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Tr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Er,args:[i,cG(e.name,wD(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:Pr,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:Fr,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:Ir,args:[i,e.check,e.mark]}],active:!1};case`ceiling`:return{effects:[{verb:Rr,args:[i,...e.args]}],active:!1};case`slash`:return{effects:[{verb:zr,args:[i,e.line]}],active:!1};case`layout-op`:return{effects:[{verb:Or,args:[i,e.key,zF(e.op)]}],active:!1};case`do`:{let a=fG(e.head,t,n,r,i);return{effects:[...a.effects,...e.rest.flatMap(e=>fG(e,t,void 0,r,i).effects)],active:a.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:Or,args:[i,e.key,zF(r)]}],active:!1}}}}function pG(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Xr(`action "${e}"`,n,t.members.length,dG(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 mG(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=QW(n,`action "${e}"`).store,{display:a,boundValue:o}=pG(e,iG(r),t,i),s=sG(i,`session.id`),{effects:c,active:l}=fG(r,a.plain,o,i,s);return uG(a,Hr(c),l)}function hG(e){return{action:{fn:(t,...n)=>mG(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function gG(e,t){return lG(`✕`,Hr([{verb:mr,args:[sG(e,`session.id`),t,P]}]),!1)}function _G(e,t,n){return new H({bgcolor:B.fromRgba(t),color:B.fromRgba(th(e,t,n))})}function vG({tint:e,text:t}){return new H({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function yG(e,t,n){return new H({color:B.fromRgba(Uc(Gm(e,`warning`),t,eh,n))})}function bG(e,t,n){return H.combine([_G(e,t,n),yG(e,t,n)])}function xG(e,t,n){return _G(e.palette,Oh(e.palette,e.disclosure,t,n),n)}function SG(e){let t=B.fromRgba(Gm(e,`background`)),n=G.fromFragments(ym.map(n=>new G(`▀`,{style:new H({color:B.fromRgba(Gm(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const CG=(e,t)=>{let n=typeof e==`string`?new G(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},wG=e=>new H({bold:e});function TG(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>CG(a,H.combine([xG(e,{...n,distribution:t},i),wG(o)]));let o=_G(e.palette,a,i);return(e,t,i,a)=>EG(i,H.combine([o,wG(a)]),r(t,n))}const EG=(e,t,n)=>CG(G.fromFragments([CG(e,t),CG(` `,t),SG(n)]));function DG(e,t){return t===void 0?(e,t,n)=>CG(n):(n,r,i)=>EG(i,void 0,t(r,e))}function OG(e,t,n,r,i){let a=_G(e.palette,i,r);return(e,r,i,o)=>CG(G.fromFragments([CG(o?`[`:` `,a),SG(n(r,t)),CG(o?`]`:` `,a)]))}function kG(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=>AG(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function AG(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function jG(e,t){return new G(e).truncate(t,{marker:`…`}).plain}function MG(e){return{current:null,drawnAt:e}}function NG(e,t,n,r,i,a,o){let s={segName:t,placementId:n,palette:r,disclosure:i,tint:a,text:o,bg:void 0,drops:[]};return e.current=s,s}function PG(e,t){let n=e.current;if(n===null)throw Error(`${t} is only available inside a segment's templates — there is no active segment here. Segment-scoped functions cannot be used in variable declarations or layout-node "when" predicates, which are evaluated outside any segment.`);return n}function FG(e){return new G(e).cellLength}function IG(e){let{width:t,chromeCols:n,padding:r}=QW(e,`a row fit`);return Math.max(1,t-n-2*r)}function LG(e){let{padding:t,seamCols:n}=QW(e,`a row fit`);return Math.max(1,IG(e)-(FG(`✕`)+2*t+n))}function RG(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 zG(e,t,n){let r=FG(`←`)+1+FG(`→`)+1,i=RG(e,t,n);return(i.length>1?RG(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function BG(e,t){let n=[];for(let t of e)n.length>0&&n.push(new G(` `)),n.push(t);let r=G.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function VG(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 HG(e,t,n){let r=e.compiled.get(t),i=r&&iG(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 UG(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=QW(a,`picker`).store,d=sG(u,`session.id`),f=`stateVar`in t?sG(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`?LG(a):IG(a):1/0,h=(r.kind===`led`?0:FG(`✕`)+1)+c.reduce((e,t)=>e+FG(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?zG(_.map(e=>e.cellLength),m,h):kG(g.entries,g.groups,i),y=parseInt(sG(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=>Hr([{verb:mr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:mr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],C=r.kind===`own`&&r.onPick?ne:[],re=e=>Hr([...fG(l,e,e,u,d).effects,...C]),ie=(e,n)=>uG(e,re(t.options[n])),ae=r.kind===`led`?[]:[lG(`✕`,Hr(ne),!1,s)];ae.push(...c.map(({glyph:e,option:r})=>lG(e,Hr([...fG(l,r,r,u,d).effects,{verb:mr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&ae.push(lG(`←`,te(x-1),!1));let w=x<v.length-1?[lG(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[BG([...ae,...e.map(e=>ie(_[e],e)),...w],i)]}let T=new H({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new G(`${S[0].label}${oe}`,{style:T})]:[],se=[BG([...ae,...E,...w],i)];for(let e of S){S.length>1&&se.push(BG([new G(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>FG(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:wv(a),s=` `.repeat(n-FG(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(BG([ie(p(r,jG(c,m)),r)],i))}}return se}function WG(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{vD(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=VG(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=HG(e,n,`picker`);if(l.library!==void 0)throw Error(`{{ picker "${n}" … }} ranges a catalogue domain, which lays out as one row per member; a catalogue renders in a {{ menu }} body`);let u=PG(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=UG(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,TG(u,Pm(void 0),$W(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),yG(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function GG(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function KG(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 qG(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=QW(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=sG(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return BG([],!0);let d=sG(o,t.stateVar),f=GG(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let n=Hr(fG(s,p(e),p(e),o,c).effects);return m.set(e,n),n},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=uG(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):uG(DG($W(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),Hr(fG(n.compiled.get(a),p(0),void 0,o,c).effects)),b=KG(e=>v(e).cellLength,u,FG(`◀`)+1+y.cellLength+1+FG(`▶`),LG(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return BG([...ee(-1).reverse(),lG(`◀`,h(-1),!1),y,lG(`▶`,h(1),!1),...ee(1)],!0)}function JG(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(vD(`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&&aG(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=HG(e,n,`carousel`),l=PG(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return qG(n,c,e,TG(l,Pm(void 0),$W(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function YG(e,t,n){let r=HG(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 XG(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 ZG(e,t,n,r){let i=YG(e,t,n),a=r??sG(QW(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,$W(e,`{{ ${n} }}`))}function QG(e,t,n){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(vD(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return SG(ZG(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`},swatches:{fn:(r,i)=>{let a=YG(e,r,`swatches`),o=VG(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=PG(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=UG(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,OG(s,$W(e,`{{ swatches }}`),a.paletteOf,c,s.bg),yG(s.palette,s.bg,c),u===0?[]:(()=>{let t=GG(l,sG(QW(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[XG(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const $G=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function eK(e,t,n,r){let i=hh(e,n,r),a=(t,n)=>({text:t,colour:n,ink:th(e,n,r)});return[[km(t).map((n,i)=>{let a=Km(e,n);return{text:$G[i%$G.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Gm(e,`warning`)),a(`error`,Gm(e,`error`))]]]}function tK(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new G(` ${e} `,{style:vG({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new G(e)),r.push(a)}return r}function nK(e,t,n,r,i){let a=eK(e,t,n,r).map(e=>tK(e,i)),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
205
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function rK(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(vD(`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}=$W(e,`{{ themePreview }}`);return nK(r===void 0?a:ZG(e,r,`themePreview`),o,{...PG(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),LG(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const iK=e=>e.slice(e.lastIndexOf(`.`)+1),aK=(e,t)=>{let n=new G(iK(e));return n.truncate(t,{marker:`…`}),n.plain};function oK(e,t){let n=e.map(e=>e.map(({name:e})=>FG(iK(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 sK(e,t,n,r){let i=oK(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${aK(s,i)} `,{style:vG(Mh(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
|
|
206
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function cK(e,t){return{layoutPreview:{fn:()=>sK(eG(e,`{{ layoutPreview }}`),$W(e,`{{ layoutPreview }}`).decor,t.drawnAt(),LG(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function lK(e,t,n,r){let i=PG(r.activeSegment,`{{ menu }}`),a=r.action,o=Ck(i.placementId,e,n.key),s=Ek(o),c=Sk(e),l=QW(a,`menu`).store,u=sG(l,o)===c,d=sG(l,`session.id`),f=u?P:c,p=lG(Xr(`{{ menu "${e}" }}`,t,2,+!!u),Hr([{verb:mr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=hh(i.palette,i.disclosure,t).plane,l=HG(a,e,`menu`);return UG(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,P],[s,`0`]],onPick:n.closeOnPick},n.paged,a,TG(i,n.distribution,$W(a,`{{ menu }}`),l.paletteOf,t,c),yG(i.palette,c,t))})():[]),p}const uK=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function dK(e,t){let n=t[t.length-1],r=uK(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:Ak(r??{})}}function fK(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=dK(t,n);return lK(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function pK(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=mK(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function mK(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 hK(e){let t={fn:(()=>{let t=PG(e,`{{ bgOf }}`);if(t.bg===void 0)throw Error(`{{ bgOf }} is not available while segments.${t.segName}'s own "bg:" is being evaluated — the background is what that template computes. Reach for a palette color there instead, e.g. bg: '{{ darken (color "surface") 1 }}'.`);return t.bg.hex}),argTypes:[],arity:{kind:`exact`},returnType:`string`},n={fn:(()=>PG(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=PG(e,`{{ keptOn }}`),i=Pc(r,t),a=Pc(r,n),o=Ts(Gc(i,z.TRUECOLOR),Gc(a,z.TRUECOLOR)),s=Math.min(eh,Math.max(o,3));return(Wc(i,e.drawnAt(),(e,t)=>Ts(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=nD(()=>PG(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...gK(s)];return pK({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 gK(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 _K(e){let t=[],n=[];for(let r of e){if(!r.contains(`
|
|
207
207
|
`)){n.push(r);continue}let e=r.split(`
|
|
208
|
-
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function oK(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function sK(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function cK(e){return{...e,cells:e.cells.map(AW)}}function lK(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,...uK(e,r)]}function uK(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 dK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:lK(e.direction,e.children.map((t,i)=>n(t,[...r,fK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function fK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:vg[e.direction]}}const pK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Pm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,wg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),lK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,fK(e,r))))}},mK={drop:e=>e.place,above:()=>`above`},hK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},gK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:yg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Tg(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,_K(e,t))};function _K(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=ED(t.scope,e.settings);if(t.gate.kind===`failed`)return vK(e,a,t,t.gate.message);try{if(!CW(i.when,a))return[];let n=xy(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:kA(n)},s=e.opens!==void 0&&CW(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:mK[g.placement](e)})),v=aK(LW(l,m)).map((e,t)=>({cells:NW(e,{...h,lead:t===0?LW(u,m):[],trail:t===0?LW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:NW(LW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>NW(LW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?hK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(kW(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],C=_.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...S,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(ne)].flatMap(kW)),[...re,...C]}catch(n){return vK(e,a,t,n.message??String(n))}}function vK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:NW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:kA(n.palette)},lead:yK(e.lead,e,t,n),trail:yK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function yK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const bK={container:pK,segment:gK};function xK(e){return bK[e]}function SK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:EO(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 CK(e,t){switch(Og(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 wK(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:SK(n.cache),parse:CK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:SK(n.cache),parse:CK(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function TK(e,t){let n=lx.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 EK(e,t,n){let{compiled:r,loadWarnings:i}=OK(e,t,n.cwd,DK);return{...r,loadWarnings:i}}const DK=(e,t)=>MK(t);function OK(e,t,n,r){let i=kK(e),a=AK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:jK(e,t,n)}}function kK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of yv)n in t&&r.set(e,n);for(let[t,n]of Pg(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function AK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function jK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{wK(t,i,a,n)}catch(e){r.push(`Variable "${i}": ${e.message??String(e)}`)}for(let[i,a]of Object.entries(e.segments))if(a.vars)for(let[e,o]of Object.entries(a.vars))try{wK(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function MK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>BW(n,`now`).registry.now(),i=()=>BW(n,`drawnAt`).registry.drawnAt(),a=bG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Hy(e.presets),l=cF(e),u=CD({extraFuncs:{...rG(n),...MG(n,a),...IG(n,a),...GG(n,a),...BG(n,a,r),...XG(n,a),...eK(o),...rK(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=TK(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map(t);n.compiled=WW(f,e.actions,h,l);let g=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};g[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let _=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},v=t=>{let r=Rg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Wg(t,e,a,t=>String(BW(n,`setting ${e}`).store.read(t.variable)))});return Object.freeze(i)},y=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:_(e.when,t,`when`),parse:(e,n)=>_(e,t,n),compileChild:y,placementSettings:v};return xK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=Gy(e,t);b.set(t,y(n,r))}let ee=new Map(Hh.map(e=>[e,new Map])),x=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of x)for(let n of Hh){let r=t[n];if(!Uh(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:NK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function NK(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function PK(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function FK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Qh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Zh[e]}}function IK(e,t){return e.kind===`decided`?e.name:Zh[t]}function LK(e){return RK(e).filter(e=>!e.name.startsWith(ak)).map(e=>e.id)}function RK(e){return e.kind===`container`?e.children.flatMap(RK):[e,...e.opens===void 0?[]:RK(e.opens.body)]}function zK(...e){return BK(...e).text}function BK(e,t,n,r,i,a,o,s,c=YB(e,()=>null,()=>!1)){try{var l=na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set;r.renderAt(a),r.drawAt(cg(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Zv(o),padding:o.padding,seamCols:Qv(o),look:void 0,layout:void 0};l.u(UW(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Om[c.variation],shade:Em[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(IK(_,`palette`),IK(v,`style`),IK(y,`effect`)));let S=wD(n),te=Gh(_,e=>{let n=PK(t,`palette`,e);return Ey(FK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=Gh(v,n=>Jh(FK(`style`,PK(t,`style`,n),S,p),e.styles)),C=Gh(y,e=>ng(FK(`effect`,PK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=Cy(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Uv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:sK,hold:cK});u?.clear();let w=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},T=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Mh(i,a,c),f=xG(t.activeSegment,e.name,e.id,i,d,l,u),p=jA(f,c,o.bg,o.fg,n),h=()=>hh(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)m.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:p,get trigger(){return aG(i,h().state,c)},get band(){return aG(i,h().plane,c)},get close(){return cG(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},oe=(e,t,r)=>{let i=t?EW(e.when,S):wW,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${LK(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:S,palette:ie,gate:a,padding:o.padding,region:r,perSegmentSink:u,onSegmentError:d,evaluateSegment:T,lookupSegment:w,renderChild:(e,t,n)=>oe(e,t,Ah(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,jh(n)),closeDisclosure:e=>iG(n,e),placed:ae.placed};return xK(e.kind).render(e,s)},E=t.roots.get(g);if(E===void 0)throw Error(`Preset "${g}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${By}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=EW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(yF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return CW(t.segments[e.name].when,ED(S,e.settings))}catch{return!0}};h.layout=()=>dK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=yF(e);return r===void 0?[]:[{name:r,address:t,palette:xy(n.theme,ie)}]}));let ce=oK(oe(E,!0,kh(ee))).map(({line:e,row:t})=>{let n=IW(e.cells,o);return ny(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||RK(E).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:ce.map(e=>e.text).join(`
|
|
209
|
-
`),motion:le}}catch(e){l.e=e}finally{l.d()}}function
|
|
210
|
-
`)||null}function oq(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vB(t.layers,VB,{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??VB,l=a.find(e=>e.path===t.home)?.raw??{},u=new QK,d=new qO(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=OK(o,d,e,r.compile??DK),n.push(...f.loadWarnings),jV(o),HF(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:uW(o),lastRenderCellsBySegment:new Map,authoredRoots:rq(c,l),fileHeldSettings:_V(l),unused:[...new Map(a.flatMap(e=>WK(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function sq(e,t,n,r){let i=aB(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[uB(e,t),cB(i)],s,c=null;try{s=oq(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Jg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:aq(o),state:null,error:e instanceof Jg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:aq(o),state:s,error:null}}function cq(e,t,n){return oq(e,{layers:[],home:``,projectDir:t},[],n)}var lq=class{entries=new Map;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??MK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=nq(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=sq(e,t,n,this.deps);a.state!==null&&this.log(`info`,eq(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??cq(t,e,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++;let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&(r.watcher?.release(),this.entries.delete(n),this.retire(r.state,`evict`))}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,tq(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=sq(e.projectDir,e.cwd,e.configFile,this.deps);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,eq(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=iq(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const uq=16384;var dq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<uq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%uq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,expired:0,hits:0,misses:0,invalidations:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function fq(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 pq={load:()=>({}),save:()=>{},flush:()=>{}};var mq=class{sessions;storage;head=0;atom=(0,Db.createAtom)(`SessionState`);constructor(e=pq,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,Db.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,Db.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,Db.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 hq(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 gq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return hq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const _q=new Set([`1`,`true`]),vq=new Set([`0`,`false`,``]);function yq(e,t){let n=Wq(e),r=n.scope===`segment-palette`?`string`:uv(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(_q.has(t))return`true`;if(vq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function bq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function xq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Sq(e){return/^\s*$/.test(e)?null:_i(e)}function Cq(e,t){return e!==null&&yi(e,t)!==void 0}function wq(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(wq),...i}}return e}function Tq(e){if(!My(e))return wq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,wq(t)])),...n}}const Eq=zB,Dq=Eq.segments,Oq=Eq.presets,kq=Eq.root;function Aq(e,t,n,r){if(!Cq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function jq(e,t){let n=oA(t);return t.scope===`segment-palette`&&Aq(e,[`segments`,t.segment],Dq[t.segment],n.join(`.`)),n}function Mq(e){return _i(Di(e))}function Nq(){return Object.entries(kq.rows).map(([e,t])=>{let n=wq(t);return{path:[`root`],fragment:Mq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Pq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function Fq(e,t){if(t===void 0)return null;let n=Tq(t);return{path:e,fragment:Mq(n),unit:{path:e,value:n}}}function Iq(e,t){let n=[`presets`,t],r=[...n,`root`],i=Oq[t];Aq(e,n,i,r.join(`.`));let a=Pq(e,r)??Fq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Lq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function Rq(e,t){return[...Nq(),Pq(e,[`root`]),Iq(e,t)].filter(e=>e!==null).reduce(Lq,new Map)}function zq(e,t,n){for(let{node:r,...i}of Rq(e,t).values())if(Xi(r,n))return i;throw new J(`${Bq(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 Bq(e,t){return Iq(e,t)?.path??[`root`]}function Vq(e,t){return t.scope===`preset-root`?Bq(e,t.preset):oA(t)}function Hq(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function Uq(e){let t=aA(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function Wq(e){let t=Uq(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,nJ(t,r)),xq(t.path,r,e.logger),e.record(t.path,n,r)}function Kq(e,t,n){let r=Yq(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const qq=()=>{};function Jq(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function Yq(e,t,n){let r=Xq(e,t);if(r===null)return[];let i=new Set(eJ($q(r),$q(n)));return eJ(Qq(e,r),Qq(e,n)).filter(e=>!i.has(e))}function Xq(e,t){try{return Zq(e,t)}catch(e){if(e instanceof Jg)return null;throw e}}function Zq(e,t){return vB(t===null?e.above:[e.path,...e.above],VB,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function Qq(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function $q(e){return e.layers.at(-1)?.config??e.base}function eJ(e,t,n=``){return!tJ(e)||!tJ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>eJ(e[r],t[r],n===``?r:`${n}.${r}`))}function tJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nJ(e,t){try{return Zq(e,t)}catch(e){throw e instanceof Jg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function rJ(e,t){let n=Wq(t),r=Sq(bq(e)??``),i=r===null?void 0:yi(r,oA(n));return i!==void 0&&`value`in i?i.value:void 0}function iJ(e,t,n){aJ(e,t,n,[])}function aJ(e,t,n,r){let i=bq(t.path),a=n.reduce((e,[t,n])=>Vi(e,jq(Sq(e),Wq(t)),yq(t,n),Ti),i??``);Gq(e,t,i,Jq(t,()=>oJ(a,t.path,r,e=>e)),Kq)}function oJ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=zq(Sq(s),n,i),l=ea(Hq(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function sJ(e,t,n){let r=Sq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of Rq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(Iq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function cJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!UB(t[1])?2:0)}function lJ(e,t,n){let r=n.map(Uq),i=bq(t.path);if(i===null)return;let a=r.reduce((e,t)=>cJ(e,Vq(Sq(e),t)),i);a!==i&&Gq(e,t,i,a,qq)}function uJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function dJ(e,t){let n=new Set([...HB,...uJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(nk));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(nk(e)))}function fJ(e,t,n,r,i,a){let o=bq(t.path),s=Sq(o??``),c=dJ(s,t),l=[`presets`,c],u=Jq(t,()=>Iq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=iA(c,e);return[jq(s,Wq(n)),yq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return Gq(e,t,o,Jq(t,()=>oJ(p,t.path,a.map(e=>({...e,preset:c})),sJ)),Kq),c}function pJ(e,t,n,r){let i=bq(t.path);Gq(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),Kq)}function mJ(e,t,n){if(UB(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=bq(t.path),a=Sq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);Gq(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>cJ(e,t),i),qq)}function hJ(e,t,n,r){let i=Uq(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=bq(t.path),o=r.op===`remove`?r.target:r.anchor,s=Jq(t,()=>zq(Sq(a??``),i.preset,o)),c=Hq(a??``,s),{after:l,placed:u}=gJ(c,s.path,r,()=>{let e=nJ(t,c).config;return Hy(e.presets).map(t=>Gy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return Gq(e,t,a,l,Kq),u}function gJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=kF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const _J={load:()=>({}),save:()=>{}},vJ=new Set(hv.map(e=>e.sessionKey)),yJ=e=>vJ.has(e)||e.startsWith(_A),bJ=8*1024*1024,xJ={past:[],future:[]},SJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var CJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=_J){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)??xJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??xJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(SJ(n));r.set(SJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:fq(this.sessionState,e=>yJ(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:jJ(i,n),o=r.get(e),s=o===void 0?a:FJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,NJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(SJ)),a=n.net.filter(e=>!i.has(SJ(e))),o=EJ(IJ(PJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(RJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=EJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...OJ(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(SJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:IJ(n,t),future:IJ(i,t),...a!==void 0&&{savepoint:{at:IJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(SJ(e))),below:IJ(a.below,t)}}}),new J(`${r}: ${o.map(RJ).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):bq(t.file)}write(e,t,n){t.kind===`file`?xq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||wJ(n)>bJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,TJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${bJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function wJ(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 TJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...OJ(n,1,[])}:{past:e,future:t.slice(1),...OJ(n,0,[])}}function EJ(e){return e.slice(-50)}const DJ=e=>e===yA.member;function OJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:kJ(e.net,n),below:e.below}}}function kJ(e,t){let n=new Map(e.map(e=>[SJ(e),e]));for(let e of t){let t=n.get(SJ(e));n.set(SJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const AJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function jJ(e,t){let n=[...e.past,t],r=EJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...OJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...MJ(e.future,a),...i.below]},n.length-r.length,t)}}function MJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function NJ(e,t){return{past:e.past.slice(0,-1),future:EJ([...e.future,t]),...OJ(e.savepoint,0,AJ(t))}}function PJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...MJ(r,t.at-i.length),...t.below]}function FJ(e,t){if(DJ(t.after)&&!DJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!DJ(t.after)&&DJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function IJ(e,t){return e.map(e=>e.filter(e=>!t.has(SJ(e)))).filter(e=>e.length>0)}function LJ(e){return e.map(RJ).join(`, `)}function RJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function zJ(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 BJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(zJ))}function VJ(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(zJ)&&BJ(t.below)}function HJ(e){if(typeof e!=`object`||!e)return!1;let t=e;return BJ(t.past)&&BJ(t.future)&&(t.savepoint===void 0||VJ(t.savepoint))}function UJ(e,t){let n=e=>e.kind===`file`||yJ(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 WJ(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(HJ)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,UJ(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const GJ=e=>!yJ(e)&&!YM(e)&&e!==`update.dismissed`;var KJ=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:fq(e,GJ,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Db.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const qJ=`click.error`;function JJ(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,qJ,JSON.stringify(i))}function YJ(e,t,n){let r=XJ(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,qJ,JSON.stringify({...r,answered:!0}))}function XJ(e,t){let n=e.get(t,qJ);return n===null?null:QJ(n)}function ZJ(e,t,n,r){let i=XJ(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function QJ(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function $J(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const eY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function tY(e){let t=e=>({kind:`failed`,reason:e});if(!eY(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!eY(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Nj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Nj.join(` or `)}`)}return{kind:`ok`,value:e}}function nY(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const rY=e=>$J(e,`doctor-marks.json`,{},tY),iY=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},aY=(e,t)=>e.includes(t)?e:[...e,t],oY=e=>$J(e,`doctor-clicked-terminals.json`,[],iY);var sY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const cY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},lY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),uY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=lY(e,t);return r===void 0?n:r.projectDir},dY=(e,t)=>lY(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function fY(e){let t=new Map;for(let n of e.split(`
|
|
211
|
-
`)){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*
|
|
208
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function vK(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}function yK(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:r.length===0?n:[],ground:i},deeper:r}}function bK(e){return{...e,cells:e.cells.map(HW)}}function xK(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,...SK(e,r)]}function SK(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 CK(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:xK(e.direction,e.children.map((t,i)=>n(t,[...r,wK(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function wK(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:vg[e.direction]}}const TK={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Pm(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,wg(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),xK(e.direction,e.children.map((n,r)=>t.renderChild(n,t.gate.kind===`shown`,wK(e,r))))}},EK={drop:e=>e.place,above:()=>`above`},DK={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},OK={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:yg(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse($r(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Tg(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,kK(e,t))};function kK(e,t){let n=t.lookupSegment(e.name);if(!n)throw Error(`Layout segment "${e.name}" has no matching segment`);let{seg:r,compiled:i}=n;if(t.gate.kind===`hidden`)return[];let a=ED(t.scope,e.settings);if(t.gate.kind===`failed`)return AK(e,a,t,t.gate.message);try{if(!FW(i.when,a))return[];let n=xy(e.settings.theme,t.palette),o={id:e.id,effect:e.settings.effect,ground:VA(n)},s=e.opens!==void 0&&FW(e.opens.open,t.scope),{styles:c,fragments:l,lead:u,trail:d,drops:f,open:p}=t.evaluateSegment(e,a,n,t.region,{bg:i.bg,fg:i.fg,body:i.template,lead:e.lead,trail:e.trail},s),m=p?c.trigger:c.closed,h={width:r.width??`auto`,justify:r.justify??`left`,truncate:r.truncate??`right`,baseStyle:m,padding:t.padding,placement:o},g=e.opens,_=g===void 0?[]:t.renderBody(g.body,s,c.disclosure).map(e=>({...e,place:EK[g.placement](e)})),v=_K(YW(l,m)).map((e,t)=>({cells:GW(e,{...h,lead:t===0?YW(u,m):[],trail:t===0?YW(d,m):[]}),band:`own`,place:`flow`})),y=f.map(e=>({cells:GW(YW([e],c.band),{...h,baseStyle:c.band}),band:`deeper`,place:`flow`})),b=(e,t,n)=>GW(YW([e],t),{...h,width:`auto`,baseStyle:t,padding:n}),ee=_.findIndex(e=>e.band===`own`),{lead:x,stays:S}=g!==void 0&&ee!==-1?DK[g.placement](v,()=>b(t.closeDisclosure(g.key),c.close,t.padding)):{lead:[],stays:v},te=x.flatMap(e=>b(new G(` `.repeat(VW(e).reduce((e,t)=>e+t.cellLength,0))),c.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],C=_.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),re=[...S,...y];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...re.flatMap(e=>e.cells),..._.flatMap(ne)].flatMap(VW)),[...re,...C]}catch(n){return AK(e,a,t,n.message??String(n))}}function AK(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:GW([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:VA(n.palette)},lead:jK(e.lead,e,t,n),trail:jK(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function jK(e,t,n,r){if(e===void 0)return[];try{return r.evaluateSegment(t,n,r.palette,r.region,{bg:void 0,fg:void 0,body:e,lead:void 0,trail:void 0},!1).fragments}catch(e){return r.onSegmentError?.(t.id,e.message??String(e)),[]}}const MK={container:TK,segment:OK};function NK(e){return MK[e]}function PK(e){if(`ttl`in e)return{kind:`ttl`,durationMs:RO(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 FK(e,t){switch(Og(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 IK(e,t,n,r){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:PK(n.cache),parse:FK(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:PK(n.cache),parse:FK(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{varDefault:n.default});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`git`:e.declareGit(t,{field:n.field,cwd:r,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function LK(e,t){let n=lx.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 RK(e,t,n){let{compiled:r,loadWarnings:i}=BK(e,t,n.cwd,zK);return{...r,loadWarnings:i}}const zK=(e,t)=>WK(t);function BK(e,t,n,r){let i=VK(e),a=HK(i);return{compiled:r(a,i),compileKey:a,loadWarnings:UK(e,t,n)}}function VK(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of yv)n in t&&r.set(e,n);for(let[t,n]of Pg(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1)}}function HK(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function UK(e,t,n){let r=[];for(let[i,a]of Object.entries(e.variables))try{IK(t,i,a,n)}catch(e){r.push(`Variable "${i}": ${e.message??String(e)}`)}for(let[i,a]of Object.entries(e.segments))if(a.vars)for(let[e,o]of Object.entries(a.vars))try{IK(t,`${i}.${e}`,o,n)}catch(t){r.push(`Variable "${i}.${e}": ${t.message??String(t)}`)}return r}function WK({config:e,stateReads:t}){let n={bound:void 0,compiled:new Map},r=()=>QW(n,`now`).registry.now(),i=()=>QW(n,`drawnAt`).registry.drawnAt(),a=MG(i),o={action:n,activeSegment:a},s=Object.keys(e.styles),c=Hy(e.presets),l=bF(e),u=CD({extraFuncs:{...hG(n),...WG(n,a),...JG(n,a),...rK(n,a),...QG(n,a,r),...cK(n,a),...fK(o),...hK(a),styles:{fn:()=>s,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>c,argTypes:[],arity:{kind:`exact`}}},clock:r,drawnAt:i}),d=LK(u,e.helpers),f=e=>u.parse(e,d),p=new Map,m=e=>{let t=p.get(e);if(t!==void 0)return t;let n=f(e);return p.set(e,n),n},h=new Map(t);n.compiled=nG(f,e.actions,h,l);let g=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=f)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};g[t]={when:n.when===void 0?void 0:e(n.when,`when`,m),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let _=(e,t,n)=>{try{return m(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},v=t=>{let r=Rg(e.segments[t.name]),i=Object.create(null);for(let[e,a]of Object.entries(r))Object.defineProperty(i,e,{enumerable:!0,get:()=>Wg(t,e,a,t=>String(QW(n,`setting ${e}`).store.read(t.variable)))});return Object.freeze(i)},y=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:_(e.when,t,`when`),parse:(e,n)=>_(e,t,n),compileChild:y,placementSettings:v};return NK(e.kind).compile(e,n)},b=new Map;for(let t of c){let{node:n,path:r}=Gy(e,t);b.set(t,y(n,r))}let ee=new Map(Hh.map(e=>[e,new Map])),x=[[`globals`,e.globals],...Object.entries(e.presets).map(([e,t])=>[`presets.${e}.globals`,t.globals??{}])];for(let[e,t]of x)for(let n of Hh){let r=t[n];if(!Uh(r))continue;let i=`${e}.${n}`,a=ee.get(n),o=a.get(r);a.set(r,o===void 0?{where:i,template:GK(f,i,r)}:{where:`${o.where}, ${i}`,template:o.template})}return{segments:g,roots:b,activeSegment:a,menuRuntime:o,globalExpressions:ee}}function GK(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}function KK(e,t,n){let r=e.globalExpressions.get(t).get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the render but no compiled template exists — registerDslConfig and the resolution disagree about isExpression`);return r}function qK(e,t,n,r){try{return t.template.evaluate(n).map(e=>e.plain).join(``)}catch(n){return r({kind:`rule`,slot:e,message:Qh(t.where,e,`the rule failed — ${n instanceof Error?n.message:String(n)}`)}),Zh[e]}}function JK(e,t){return e.kind===`decided`?e.name:Zh[t]}function YK(e){return XK(e).filter(e=>!e.name.startsWith(_k)).map(e=>e.id)}function XK(e){return e.kind===`container`?e.children.flatMap(XK):[e,...e.opens===void 0?[]:XK(e.opens.body)]}function ZK(...e){return QK(...e).text}function QK(e,t,n,r,i,a,o,s,c=sV(e,()=>null,()=>!1)){try{var l=na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set;r.renderAt(a),r.drawAt(cg(o.colorCompatibility));let h={store:n,registry:r,width:o.width,chromeCols:Zv(o),padding:o.padding,seamCols:Qv(o),look:void 0,layout:void 0};l.u(tG(t.menuRuntime.action,h));let{preset:g,theme:_,style:v,effect:y,transitions:b}=c,ee={variation:Om[c.variation],shade:Em[c.shade]},x=(e,t,n)=>({...i,term:{cols:o.width},theme:{effective:e},style:{effective:t},effect:{effective:n}});r.applyInput(x(JK(_,`palette`),JK(v,`style`),JK(y,`effect`)));let S=wD(n),te=Gh(_,e=>{let n=KK(t,`palette`,e);return Ey(qK(`palette`,n,S,p),n.where,e=>p({kind:`rule`,slot:`palette`,message:e}))}),ne=Gh(v,n=>Jh(qK(`style`,KK(t,`style`,n),S,p),e.styles)),C=Gh(y,e=>ng(qK(`effect`,KK(t,`effect`,e),S,p)));(te!==_||ne!==v||C!==y)&&r.applyInput(x(te.name,ne.name,C.name));let re=te.value,ie=Cy(re,ne.value);h.look={basePalette:re,palette:ie,decor:ee};let ae=(c.effects??new Uv(``)).motion(C.value,a,{transitions:b,source:{config:e,preset:g,revision:r.stateRevision(),width:o.width},returned:yK,hold:bK});u?.clear();let w=n=>{let r=e.segments[n],i=t.segments[n];return r!==void 0&&i!==void 0?{seg:r,compiled:i}:void 0},T=(e,n,i,a,o,s)=>{try{let c=r.drawnAt(),{tint:l,text:u,disclosure:d}=Mh(i,a,c),f=NG(t.activeSegment,e.name,e.id,i,d,l,u),p=UA(f,c,o.bg,o.fg,n),h=()=>hh(i,d,c);s&&(f.bg=h().state);let g=o.body.evaluate(n),_=f.drops.length>0||s;if(_){let e=h();f.bg=e.state;for(let t of e.shortfalls)m.add(t)}let v=o.lead?.evaluate(n)??[],y=o.trail?.evaluate(n)??[];return{styles:{closed:p,get trigger(){return _G(i,h().state,c)},get band(){return _G(i,h().plane,c)},get close(){return bG(i,h().state,c)},disclosure:d},fragments:g,lead:v,trail:y,drops:f.drops,open:_}}finally{t.activeSegment.current=null}},oe=(e,t,r)=>{let i=t?RW(e.when,S):IW,a=i.kind===`failed`?{...i,report:()=>{let t=`when over ${YK(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:i.message,message:`${t}: ${i.message} — what it gates is hidden`})}}:i,s={scope:S,palette:ie,gate:a,padding:o.padding,region:r,perSegmentSink:u,onSegmentError:d,evaluateSegment:T,lookupSegment:w,renderChild:(e,t,n)=>oe(e,t,Ah(r,n)),renderBody:(e,t,n)=>oe(e,a.kind===`shown`&&t,jh(n)),closeDisclosure:e=>gG(n,e),placed:ae.placed};return NK(e.kind).render(e,s)},E=t.roots.get(g);if(E===void 0)throw Error(`Preset "${g}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${By}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let se=e=>{let n=RW(e.when,S);if(e.kind===`container`)return n.kind===`shown`;if(jF(e.name)===void 0)return!1;if(n.kind!==`shown`)return n.kind===`failed`;try{return FW(t.segments[e.name].when,ED(S,e.settings))}catch{return!0}};h.layout=()=>CK(E,se).map(e=>e.flatMap(({name:e,address:t,settings:n})=>{let r=jF(e);return r===void 0?[]:[{name:r,address:t,palette:xy(n.theme,ie)}]}));let ce=vK(oe(E,!0,kh(ee))).map(({line:e,row:t})=>{let n=JW(e.cells,o);return ny(n.map(e=>e.owner),o,ae.row(t,n))});ae.drawn();let le=ce.some(e=>e.moves)?`moves`:y.kind===`expression`||b||XK(E).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:ce.map(e=>e.text).join(`
|
|
209
|
+
`),motion:le}}catch(e){l.e=e}finally{l.d()}}function*$K(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*eq(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 Hy(e.presets)){for(let n of Cg(Gy(e,t).node))n.when!==void 0&&(yield n.when);let n=Ky(e,t);for(let e of Hh){let t=n[e];Uh(t)&&(yield t)}}for(let[,t]of $K(e))t.kind===`template`&&(yield t.template),Ag(t)&&`key`in t.cache&&(yield t.cache.key);for(let t of Object.values(e.actions))`copy`in t&&(yield t.copy),`open`in t&&(yield t.open),`preset`in t&&t.preset===`delete`&&(yield t.name)}function tq(e,t){return e===t||t.startsWith(`${e}.`)||e.startsWith(`${t}.`)}function nq(e,t){let n=new Set,r=new Set,i=new Set;for(let e of eq(t)){for(let r of pb(e,t.helpers).keys())n.add(r);for(let{name:n}of _b(e,t.helpers))r.add(n);for(let n of vb(e,t.helpers))i.add(n)}for(let[,e]of $K(t))if(Ag(e)&&`depends_on`in e.cache)for(let t of e.cache.depends_on)n.add(t);let a=new Set(r);for(let e of r){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)a.add(e)}let o=new Set,s=new Set;for(let e of a){let n=t.actions[e];if(n!==void 0&&(`set`in n&&o.add(n.set),`insertSegment`in n&&s.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)s.add(e)}for(let e of Hy(t.presets))for(let n of Cg(Gy(t,e).node))n.kind===`segment`&&s.add(n.name);let c=(e,t)=>[...n].some(t=>tq(t,e))||t.kind===`state`&&o.has(t.key),l=e=>[...e].filter(e=>!yk(e)),u=(e,t,n)=>l(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),d=new Map($K(e));return[...u(`variable`,d.keys(),e=>c(e,d.get(e))),...u(`action`,Object.keys(e.actions??{}),e=>a.has(e)),...u(`helper`,Object.keys(e.helpers??{}),e=>i.has(e)),...u(`segment`,Object.keys(e.segments??{}),e=>s.has(e))]}var rq=class{kind=`box`;cell;lastChangedAt;constructor(e,t,n){this.name=e,this.type=t,lq(e,t,n,`initial value`),this.cell=Db.observable.box(n,{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){lq(this.name,this.type,e,`set value`),!Object.is(this.cell.get(),e)&&(this.cell.set(e),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}},iq=class{kind=`computed`;cell;constructor(e,t,n){if(this.name=e,this.type=t,this.cell=(0,Db.computed)(()=>{let e=n();return lq(this.name,this.type,e,`computed result`),e},{keepAlive:!0}),typeof this.cell.suspend_!=`function`)throw TypeError(`Variable "${e}": this MobX's computed has no suspend_; release() cannot unsubscribe it`);if(typeof this.cell.keepAlive_!=`boolean`)throw TypeError(`Variable "${e}": this MobX's computed has no keepAlive_ flag; release() cannot lift it`)}read(){return this.cell.get()}release(){this.cell.keepAlive_=!1,this.cell.suspend_()}lastUpdatedMs(){return null}},aq=class{kind=`document`;cell;lastChangedAt;constructor(e,t){this.name=e,this.cell=Db.observable.box(cq(t),{deep:!1}),this.lastChangedAt=Date.now()}read(){return this.cell.get()}set(e){let t=cq(e);sq(this.cell.get(),t)||(this.cell.set(t),this.lastChangedAt=Date.now())}lastUpdatedMs(){return this.lastChangedAt}};function oq(e){return JSON.stringify(e)}function sq(e,t){return oq(e)===oq(t)}function cq(e){return e.kind===`ok`?{kind:`ok`,value:Ob(e.value)}:e}function lq(e,t,n,r){let i=kb(n);if(i!==t)throw TypeError(`Variable "${e}": ${r} type ${i} does not match declared type ${t}`)}var uq=class{nodes=Db.observable.map(void 0,{deep:!1});defineBox(e,t,n){this.declare(e,new rq(e,t,n))}defineDocument(e,t){this.declare(e,new aq(e,t))}defineComputed(e,t,n){let r=e=>this.read(e);this.declare(e,new iq(e,t,()=>n(r)))}read(e){return this.requireVar(e).read()}readDocument(e){let t=this.requireNode(e);if(t.kind!==`document`)throw TypeError(`Variable "${e}" is a ${t.kind}, not a document`);return t.read()}setDocument(e,t){let n=this.requireNode(e);if(n.kind!==`document`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a document (use defineDocument to create one)`);(0,Db.runInAction)(()=>n.set(t))}setBox(e,t){let n=this.requireNode(e);if(n.kind!==`box`)throw TypeError(`Variable "${e}" is a ${n.kind}, not a box (use defineBox to create a settable variable)`);(0,Db.runInAction)(()=>n.set(t))}runInAction(e){(0,Db.runInAction)(e)}has(e){return this.nodes.has(e)}getType(e){return this.requireVar(e).type}getKind(e){return this.requireNode(e).kind}changeKey(e){let t=this.requireNode(e);if(t.kind===`document`)return oq(t.read());try{return String(t.read())}catch(e){return`failed:${e instanceof Error?e.message:String(e)}`}}getNode(e){let t=this.requireNode(e);return t.kind===`document`?{name:t.name,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}:{name:t.name,type:t.type,kind:t.kind,read:()=>t.read(),lastUpdatedMs:()=>t.lastUpdatedMs()}}names(){return[...this.nodes.keys()]}dispose(){if(this.disposed)return 0;this.disposed=!0;let e=0;return(0,Db.runInAction)(()=>{for(let t of this.nodes.values())t instanceof iq&&(t.release(),e++)}),e}disposed=!1;requireNode(e){let t=this.nodes.get(e);if(!t)throw ReferenceError(`Unknown variable "${e}"`);return t}requireVar(e){let t=this.requireNode(e);if(t.kind===`document`)throw TypeError(`Variable "${e}" is a document; read its fields by path (.${e}.<field>)`);return t}declare(e,t){if(this.disposed)throw Error(`Variable "${e}": cannot declare on a disposed store`);if(this.nodes.has(e))throw Error(`Variable "${e}" is already declared`);(0,Db.runInAction)(()=>this.nodes.set(e,t))}};function dq(e){return Math.floor(e/4)}function fq(e,{plugins:t,config:n}){let{checkout:r,loaded:i,dropped:a,unreached:o}=t,s=r===null?`-`:`${r.git?`git`:`dir`}:${r.root}`,c=e=>{let t=Rz(e),r=t===void 0?void 0:n.variables[Bz(t)];return r?.kind===`file`?r.path:`none`};return`config load ${e.join(` < `)||`<default>`}: plugins loaded=${i.length} dropped=${a.length} unplaced=${o.length} checkout=${s}`+i.map(e=>` +${e} data=${c(e)}`).join(``)+a.map(e=>` -${e.path} (${e.reason})`).join(``)+o.map(e=>` ~${e.path} (${e.reason})`).join(``)}function pq(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function mq(e,t,n){return e+`\0`+t+`\0`+(n??``)}function hq(e,t){return new Set(Hy(e.presets).filter(n=>Gy(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function gq(e,t){let n=new Map,{roots:r,loaded:i,dropped:a,unreached:o}=e.state.plugins;for(let t of[...hB(e.projectDir,e.cwd,e.configFile),...r,...i,...[...a,...o].map(e=>e.path)]){let{dir:e,name:r}=Cb(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}=Cb(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 _q(e){return e.filter(Boolean).join(`
|
|
210
|
+
`)||null}function vq(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=AB(t.layers,$B,{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??$B,l=a.find(e=>e.path===t.home)?.raw??{},u=new uq,d=new ak(u,o.globals.default_empty_value??``,r.gitService,r.sessionState),f;try{f=BK(o,d,e,r.compile??zK),n.push(...f.loadWarnings),UV(o),eI(o)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:SW(o),lastRenderCellsBySegment:new Map,authoredRoots:hq(c,l),fileHeldSettings:kV(l),unused:[...new Map(a.flatMap(e=>nq(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering}}}function yq(e,t,n,r){let i=_B(e,t,n),a={layers:i.kind===`chain`?i.layers:[],home:i.home,projectDir:e},o=[SB(e,t),bB(i)],s,c=null;try{s=vq(t,a,o,r,e=>{c=e})}catch(e){return e instanceof Jg&&o.push(...e.warnings),{layers:a.layers,home:a.home,failedFile:c,warning:_q(o),state:null,error:e instanceof Jg||e instanceof Error?e.message:String(e)}}return{layers:a.layers,home:a.home,warning:_q(o),state:s,error:null}}function bq(e,t,n){return vq(e,{layers:[],home:``,projectDir:t},[],n)}var xq=class{entries=new Map;sweep=null;closed=!1;now;holds=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.now=t.now??Date.now,this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Oe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{}}compileOf(e,t){return this.compiles.get(e)??WK(t)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760}getOrCreate(e,t,n){let r=mq(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`,fq(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??bq(t,e,this.deps),watcher:null,watcherKey:null,usedAt:this.now()};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Nn(this.accountedBytes())}/${Nn(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o),o}hold(e,t,n){let r=this.getOrCreate(e,t,n),{state:i}=r,a=this.holdOf(i);a.holders++,r.usedAt=this.now(),this.armSweep();let o=!1;return{entry:r,state:i,[Symbol.dispose]:()=>{if(o)throw Error(`render-cache hold released twice`);o=!0,a.holders--,this.reclaim(i,a)}}}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),3e5/5),this.sweep.unref?.())}releaseIdle(){let e=0;for(let t of this.entries.values())this.now()-t.usedAt<3e5||(e+=t.state.registry.holds.release());e>0&&this.log(`info`,`render-cache idle released=${e} entries=${this.entries.size}`),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 yq(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes();for(let[n,r]of this.entries){if(t())return;r!==e&&this.drop(n,r,`evict`)}}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t){let n=this.holdOf(e);n.retired={reason:t,held:n.holders},this.reclaim(e,n)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,pq(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=t.warning,e.lastError=t.error,t.state!==null){this.log(`info`,fq(t.layers,t.state));let n=e.state;e.state=t.state,this.serve(t.state),this.retire(n,`reload`)}this.fit(e),this.refreshWatcher(e,t),this.observers.onReload?.(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.failedFile=t.error===null?null:t.failedFile;let n=gq(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}firstState(){return this.entries.values().next().value?.state??null}};const Sq=16384;var Cq=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;watchersOpened=0;watchersClosed=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<Sq){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%Sq}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,refreshes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:qe,sourceDigest:Xe(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},gitCache:e.gitCache,usageCache:e.usageCache,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function wq(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 Tq={load:()=>({}),save:()=>{},flush:()=>{}};var Eq=class{sessions;storage;head=0;atom=(0,Db.createAtom)(`SessionState`);constructor(e=Tq,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,Db.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,Db.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,Db.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 Dq(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 Oq=class{timer=null;pending=null;constructor(e,t=500,n=Oe){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return Dq(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,!this.timer&&(this.timer=setTimeout(()=>this.flush(),this.debounceMs),this.timer.unref())}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending;try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let t=`${this.filePath}.tmp`;p.writeFileSync(t,JSON.stringify(e),{mode:384}),p.chmodSync(t,384),p.renameSync(t,this.filePath),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}};const kq=new Set([`1`,`true`]),Aq=new Set([`0`,`false`,``]);function jq(e,t){let n=nJ(e),r=n.scope===`segment-palette`?`string`:uv(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(kq.has(t))return`true`;if(Aq.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function Mq(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function Nq(e,t,n){try{if(t===null){p.rmSync(pt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function Pq(e){return/^\s*$/.test(e)?null:_i(e)}function Fq(e,t){return e!==null&&yi(e,t)!==void 0}function Iq(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(Iq),...i}}return e}function Lq(e){if(!My(e))return Iq(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Iq(t)])),...n}}const Rq=ZB,zq=Rq.segments,Bq=Rq.presets,Vq=Rq.root;function Hq(e,t,n,r){if(!Fq(e,t)&&n===void 0)throw new J(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function Uq(e,t){let n=vA(t);return t.scope===`segment-palette`&&Hq(e,[`segments`,t.segment],zq[t.segment],n.join(`.`)),n}function Wq(e){return _i(Di(e))}function Gq(){return Object.entries(Vq.rows).map(([e,t])=>{let n=Iq(t);return{path:[`root`],fragment:Wq({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function Kq(e,t){let n=e===null?void 0:yi(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function qq(e,t){if(t===void 0)return null;let n=Lq(t);return{path:e,fragment:Wq(n),unit:{path:e,value:n}}}function Jq(e,t){let n=[`presets`,t],r=[...n,`root`],i=Bq[t];Hq(e,n,i,r.join(`.`));let a=Kq(e,r)??qq(r,i?.root);return a!==null&&Ji(a.fragment)?a:null}function Yq(e,t){let n=qi(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function Xq(e,t){return[...Gq(),Kq(e,[`root`]),Jq(e,t)].filter(e=>e!==null).reduce(Yq,new Map)}function Zq(e,t,n){for(let{node:r,...i}of Xq(e,t).values())if(Xi(r,n))return i;throw new J(`${Qq(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 Qq(e,t){return Jq(e,t)?.path??[`root`]}function $q(e,t){return t.scope===`preset-root`?Qq(e,t.preset):vA(t)}function eJ(e,{unit:t}){return t===null?e:Vi(e,t.path,Di(t.value),Ti)}function tJ(e){let t=_A(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function nJ(e){let t=tJ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function rJ(e,t,n,r,i){i(t,n,mJ(t,r)),Nq(t.path,r,e.logger),e.record(t.path,n,r)}function iJ(e,t,n){let r=sJ(e,t,n);if(r.length>0)throw new J(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const aJ=()=>{};function oJ(e,t){try{return t()}catch(t){throw!(t instanceof J)||e.above.length===0?t:new J(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function sJ(e,t,n){let r=cJ(e,t);if(r===null)return[];let i=new Set(fJ(dJ(r),dJ(n)));return fJ(uJ(e,r),uJ(e,n)).filter(e=>!i.has(e))}function cJ(e,t){try{return lJ(e,t)}catch(e){if(e instanceof Jg)return null;throw e}}function lJ(e,t){return AB(t===null?e.above:[e.path,...e.above],$B,{entered:()=>{},warned:()=>{}},{projectDir:e.projectDir,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function uJ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function dJ(e){return e.layers.at(-1)?.config??e.base}function fJ(e,t,n=``){return!pJ(e)||!pJ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>fJ(e[r],t[r],n===``?r:`${n}.${r}`))}function pJ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mJ(e,t){try{return lJ(e,t)}catch(e){throw e instanceof Jg?new J(`refused: the config file would not load after this click — ${e.message}`):e}}function hJ(e,t){let n=nJ(t),r=Pq(Mq(e)??``),i=r===null?void 0:yi(r,vA(n));return i!==void 0&&`value`in i?i.value:void 0}function gJ(e,t,n){_J(e,t,n,[])}function _J(e,t,n,r){let i=Mq(t.path),a=n.reduce((e,[t,n])=>Vi(e,Uq(Pq(e),nJ(t)),jq(t,n),Ti),i??``);rJ(e,t,i,oJ(t,()=>vJ(a,t.path,r,e=>e)),iJ)}function vJ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=Zq(Pq(s),n,i),l=ea(eJ(s,c),c.path,i,a,Di(o));if(l===null)throw new J(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function yJ(e,t,n){let r=Pq(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of Xq(r,t)){if(!Xi(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?xi(e,c):Di(s.value);if(a!==`#`)return Vi(e,[...i,`rows`,a],l,Ti);if(Jq(r,t)!==null)throw new J(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return Vi(e,i,l,Ti)}return e}function bJ(e,t){return Ui(e,t,t[0]===`presets`&&t.length>2&&!tV(t[1])?2:0)}function xJ(e,t,n){let r=n.map(tJ),i=Mq(t.path);if(i===null)return;let a=r.reduce((e,t)=>bJ(e,$q(Pq(e),t)),i);a!==i&&rJ(e,t,i,a,aJ)}function SJ(e){let t=e===null?void 0:yi(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function CJ(e,t){let n=new Set([...eV,...SJ(e),...t.above.flatMap(e=>Object.keys(ui.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(mk));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(mk(e)))}function wJ(e,t,n,r,i,a){let o=Mq(t.path),s=Pq(o??``),c=CJ(s,t),l=[`presets`,c],u=oJ(t,()=>Jq(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?xi(o??``,u.fragment):Di(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],Di(r)]]],f=i.map(([e,t])=>{let n=gA(c,e);return[Uq(s,nJ(n)),jq(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>Vi(e,t,n,Ti),Vi(o??``,l,`{}`,Ti));return rJ(e,t,o,oJ(t,()=>vJ(p,t.path,a.map(e=>({...e,preset:c})),yJ)),iJ),c}function TJ(e,t,n,r){let i=Mq(t.path);rJ(e,t,i,Vi(i??``,[`themeDefaults`,n],Di(r),Ti),iJ)}function EJ(e,t,n){if(tV(n))throw new J(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=Mq(t.path),a=Pq(i??``);if(i===null||a===null||yi(a,r)===void 0)throw new J(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=yi(a,[`globals`,`preset`]);rJ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>bJ(e,t),i),aJ)}function DJ(e,t,n,r){let i=tJ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=Mq(t.path),o=r.op===`remove`?r.target:r.anchor,s=oJ(t,()=>Zq(Pq(a??``),i.preset,o)),c=eJ(a??``,s),{after:l,placed:u}=OJ(c,s.path,r,()=>{let e=mJ(t,c).config;return Hy(e.presets).map(t=>Gy(e,t).node)});if(l===null)throw new J(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return rJ(e,t,a,l,iJ),u}function OJ(e,t,n,r){switch(n.op){case`remove`:return{after:Qi(e,t,n.target),placed:null};case`insert`:{let i=VF(n.segment,n.anchor,r());return{after:$i(e,t,i,n.anchor,n.relation),placed:i}}}}const kJ={load:()=>({}),save:()=>{}},AJ=new Set(hv.map(e=>e.sessionKey)),jJ=e=>AJ.has(e)||e.startsWith(kA),MJ=8*1024*1024,NJ={past:[],future:[]},PJ=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var FJ=class{state=new Map;moves=new Map;head=0;constructor(e,t,n=kJ){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??NJ;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}revision(e){return this.moves.get(e)??0}history(e){return this.state.get(e)??NJ}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(PJ(n));r.set(PJ(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:wq(this.sessionState,e=>jJ(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:UJ(i,n),o=r.get(e),s=o===void 0?a:qJ(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new J(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,GJ(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new J(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(PJ)),a=n.net.filter(e=>!i.has(PJ(e))),o=RJ(JJ(KJ(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new J(`rewind: ${r.map(XJ).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new J(`redo: nothing to redo`);let a=[...n,i],o=RJ(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...BJ(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(PJ)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:JJ(n,t),future:JJ(i,t),...a!==void 0&&{savepoint:{at:JJ([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(PJ(e))),below:JJ(a.below,t)}}}),new J(`${r}: ${o.map(XJ).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):Mq(t.file)}write(e,t,n){t.kind===`file`?Nq(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){this.moves.delete(e),this.moves.set(e,++this.head);for(let[e]of this.moves){if(this.moves.size<=1024)break;this.moves.delete(e)}let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||IJ(n)>MJ;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,LJ(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${MJ} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function IJ(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 LJ({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...BJ(n,1,[])}:{past:e,future:t.slice(1),...BJ(n,0,[])}}function RJ(e){return e.slice(-50)}const zJ=e=>e===jA.member;function BJ(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:VJ(e.net,n),below:e.below}}}function VJ(e,t){let n=new Map(e.map(e=>[PJ(e),e]));for(let e of t){let t=n.get(PJ(e));n.set(PJ(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const HJ=e=>e.map(e=>({...e,before:e.after,after:e.before}));function UJ(e,t){let n=[...e.past,t],r=RJ(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...BJ(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...WJ(e.future,a),...i.below]},n.length-r.length,t)}}function WJ(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function GJ(e,t){return{past:e.past.slice(0,-1),future:RJ([...e.future,t]),...BJ(e.savepoint,0,HJ(t))}}function KJ(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...WJ(r,t.at-i.length),...t.below]}function qJ(e,t){if(zJ(t.after)&&!zJ(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!zJ(t.after)&&zJ(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function JJ(e,t){return e.map(e=>e.filter(e=>!t.has(PJ(e)))).filter(e=>e.length>0)}function YJ(e){return e.map(XJ).join(`, `)}function XJ(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function ZJ(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 QJ(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(ZJ))}function $J(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(ZJ)&&QJ(t.below)}function eY(e){if(typeof e!=`object`||!e)return!1;let t=e;return QJ(t.past)&&QJ(t.future)&&(t.savepoint===void 0||$J(t.savepoint))}function tY(e,t){let n=e=>e.kind===`file`||jJ(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 nY(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(eY)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,tY(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),O(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const rY=e=>!jJ(e)&&!sN(e)&&e!==`update.dismissed`;var iY=class{past=new Map;depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:wq(e,rY,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Db.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)}};const aY=`click.error`;function oY(e,t,n,r){let i={text:n,at:r,answered:!1};e.set(t,aY,JSON.stringify(i))}function sY(e,t,n){let r=cY(e,t);!(r?.at===n.at&&r.text===n.text)||r.answered||e.set(t,aY,JSON.stringify({...r,answered:!0}))}function cY(e,t){let n=e.get(t,aY);return n===null?null:uY(n)}function lY(e,t,n,r){let i=cY(e,t);return i===null?{kind:`none`}:n<i.at+5?{kind:`held`,error:i}:r===`request`&&!i.answered?{kind:`owed`,error:i}:{kind:`over`}}function uY(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let{text:n,at:r,answered:i}=t;return typeof n==`string`&&typeof r==`number`&&(i===void 0||typeof i==`boolean`)?{text:n,at:r,answered:i===!0}:null}function dY(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&&O(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const fY=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function pY(e){let t=e=>({kind:`failed`,reason:e});if(!fY(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!fY(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!Gj.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${Gj.join(` or `)}`)}return{kind:`ok`,value:e}}function mY(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const hY=e=>dY(e,`doctor-marks.json`,{},pY),gY=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},_Y=(e,t)=>e.includes(t)?e:[...e,t],vY=e=>dY(e,`doctor-clicked-terminals.json`,[],gY);var yY=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const bY=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},xY=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),SY=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=xY(e,t);return r===void 0?n:r.projectDir},CY=(e,t)=>xY(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function wY(e){let t=new Map;for(let n of e.split(`
|
|
211
|
+
`)){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*TY(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 EY={pullRequests:e=>TW(e).showPullRequest===!0,rateLimits:e=>wW(e,`block`)||wW(e,`weekly`),memento:e=>wW(e,`memento`)};function DY(e,t){let n=new Map;for(let r of Cg(Gy(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=>Ng(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,bW(e,t,n.get(t))])),a=e=>r.filter(t=>EY[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`),memento:a(`memento`)}}
|
|
212
212
|
/*!
|
|
213
213
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
214
214
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -236,9 +236,9 @@ print(json.dumps({"ceiling": "off" if ceiling == math.inf else ceiling,
|
|
|
236
236
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
237
237
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
238
238
|
*/
|
|
239
|
-
function
|
|
239
|
+
function OY(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function kY(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+=`
|
|
240
240
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
241
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
241
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=OY(t.toml,t.ptr),i=kY(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})}};
|
|
242
242
|
/*!
|
|
243
243
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
244
244
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -266,7 +266,7 @@ function gY(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
266
266
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
267
267
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
268
268
|
*/
|
|
269
|
-
function
|
|
269
|
+
function AY(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+=`
|
|
270
270
|
`: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)}
|
|
271
271
|
/*!
|
|
272
272
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
@@ -295,7 +295,7 @@ function vY(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
295
295
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
296
296
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
297
297
|
*/
|
|
298
|
-
let
|
|
298
|
+
let jY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var MY=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(jY);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}};
|
|
299
299
|
/*!
|
|
300
300
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
301
301
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -323,7 +323,7 @@ let yY=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
323
323
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
324
324
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
325
325
|
*/
|
|
326
|
-
function
|
|
326
|
+
function NY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function PY(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function FY(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?KY(e):GY(e);return e.d++,t}return r===34||r===39?AY(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?IY(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?zY(e,r,t):e.s.charCodeAt(e.p+2)===58?BY(e,r,t):IY(e,e.p,r,0,t)}function IY(e,t,n,r,i){let a=n,o=0,s=!1;if(a===105)return(e.s.charCodeAt(++e.p)!==110||e.s.charCodeAt(++e.p)!==102)&&Q.x(`invalid value`,e,t),e.p++,(r||1)/0;if(a===110)return(e.s.charCodeAt(++e.p)!==97||e.s.charCodeAt(++e.p)!==110)&&Q.x(`invalid value`,e,t),e.p++,NaN;if(a===48){if(++e.p>=e.s.length||PY(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return LY(e,t,16,i);if(a===98)return LY(e,t,2,i);if(a===111)return LY(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else NY(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!PY(a,i));)o||=1,a===95?(o&1||Q.x(`illegal underscore`,e),o+=11,s=!0):o===1&&a===46?o=2:(o===1||o===3)&&(a===101||a===69)?o=4:o===4&&(a===43||a===45)?o=6:NY(a)?o>9?o-=11:o&1||o++:Q.x(`illegal character in numeric literal`,e);if(!o){let t=(n-48)*(r||1);return e.bi===!0?BigInt(t):t}o&1||Q.x(`unfinished numeric value`,e,t);let c=e.s.slice(t,e.p);return s&&(c=c.replaceAll(`_`,``)),o>1?parseFloat(c):RY(e,c,10,t)}function LY(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!PY(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):NY(i,n)?a&1&&a--:Q.x(`illegal character in numeric literal`,e);a&1&&Q.x(`unfinished numeric value`,e);let o=e.s.slice(t+2,e.p);return a&&(o=o.replaceAll(`_`,``)),RY(e,o,n,t)}function RY(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 zY(e,t,n){let r=e.p++,i;if(!NY(t)||!NY(e.s.charCodeAt(e.p++))||!NY(e.s.charCodeAt(e.p++))||!NY(e.s.charCodeAt(e.p++)))return IY(e,e.p=r,t,0,n);if(e.p+=5,NY(e.s.charCodeAt(e.p++))||Q.x(`invalid date-time: date part is malformed`,e,r),e.p>=e.s.length||((t=e.s.charCodeAt(e.p))!==32||(i=!0,!NY(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return VY(e,e.s.slice(r,e.p),3,!1,r);if(e.s.charCodeAt(e.p+=3)!==58&&Q.x(`invalid date-time: time part is malformed`,e,r),e.s.charCodeAt(e.p+=3)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;NY(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return VY(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return VY(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return VY(e,e.s.slice(r,e.p),2,i,r)}function BY(e,t,n){let r=e.p;if(!NY(t)||!NY(e.s.charCodeAt(++e.p)))return IY(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;NY(e.s.charCodeAt(++e.p)););return VY(e,e.s.slice(r,e.p),4,!1,r)}function VY(e,t,n,r,i,a){if(e.ld){let a=new MY(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)}}
|
|
327
327
|
/*!
|
|
328
328
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
329
329
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -351,7 +351,7 @@ function xY(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
351
351
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
352
352
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
353
353
|
*/
|
|
354
|
-
function
|
|
354
|
+
function HY(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 UY(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;HY(e)}}
|
|
355
355
|
/*!
|
|
356
356
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
357
357
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -379,7 +379,7 @@ function AY(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
379
379
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
380
380
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
381
381
|
*/
|
|
382
|
-
function
|
|
382
|
+
function WY(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(AY(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 GY(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(UY(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=WY(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),UY(e,!0,!0);let l=FY(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),UY(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 KY(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(UY(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(FY(e,93)),UY(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)}
|
|
383
383
|
/*!
|
|
384
384
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
385
385
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -407,7 +407,7 @@ function MY(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
407
407
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
408
408
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
409
409
|
*/
|
|
410
|
-
function
|
|
410
|
+
function qY(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 JY(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 YY(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++,UY(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=WY(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=qY(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(JY(n,u,a),o=!0)}else{a=n.p;let e=qY(n,WY(n),s,c,0);!e&&!o&&JY(n,e,a),UY(n,!0,!0);let t=FY(n,void 0);e&&!o&&(e[1][e[0]]=t)}UY(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),UY(n)}return r}``.isWellFormed;
|
|
411
411
|
/*!
|
|
412
412
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
413
413
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -435,7 +435,7 @@ function FY(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
|
|
|
435
435
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
436
436
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
437
437
|
*/
|
|
438
|
-
const
|
|
438
|
+
const XY=e=>e.codePointAt(0).toString(16).toUpperCase(),ZY=String.raw`
|
|
439
439
|
ObjC.import("AppKit");
|
|
440
440
|
ObjC.import("CoreText");
|
|
441
441
|
function lacksOf(font, points) {
|
|
@@ -482,49 +482,49 @@ function run(argv) {
|
|
|
482
482
|
: iterm(argv[1], points),
|
|
483
483
|
);
|
|
484
484
|
}
|
|
485
|
-
`;function
|
|
486
|
-
`).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
|
|
487
|
-
`,`:family=${
|
|
488
|
-
`)){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
|
|
485
|
+
`;function QY(e){let t=ut({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,ZY,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new yY(`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 $Y=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),eX=e=>[...e].map(XY).join(`,`);function tX(e,t){let n=QY([`font`,e.kind,e.name,eX(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:$Y(r)}}}function nX(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=>!Oj(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const rX=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function iX(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=>nX(e,n));if(t!==null)return r[0];let i=r.find(e=>!rX(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 aX(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=QY([`iterm`,r??``,eX(n)]);return i.kind===`failed`?i:iX(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:$Y(e.lacks)})),r,e)}function oX(e,t){let n=e.split(`
|
|
486
|
+
`).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 sX=e=>e.replace(/[\\:,=-]/g,`\\$&`);function cX(e,t){let n=ut({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
487
|
+
`,`:family=${sX(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new yY(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return oX(n.stdout,t)}function lX(e,t){return process.platform===`darwin`?tX(e,t):cX(e.name,t)}function uX(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 dX(e){return e===`darwin`?`Menlo`:`monospace`}const fX=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function pX(e){let t=fX(e.font)?e.font:{},n=fX(t.normal)?t.normal:{},r=(fX(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 mX(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=YY(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=pX(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=mX(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function hX(e,t){let n=C.homedir(),r=uX(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:mX(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??dX(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=lX({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 gX={iterm2:aX,alacritty:(e,t,n)=>hX(t,n)};function _X(e,t,n){return gX[e.name](e.version,t,n)}function vX(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 yX=e=>dY(e,`doctor-post-mortems-read.json`,{through:null},vX);function bX(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const xX={realpath:e=>bX(()=>p.realpathSync(e)),checkoutOf:Je,digest:e=>bX(()=>Ge(e)),nativeShipped:Wa(process.platform,process.arch)};function SX(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 CX=e=>({marks:hY(e),clicked:vY(e),postMortemsRead:yX(e)}),wX=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function TX(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 EX=/^(sshd|mosh-server)\b/;function DX(e,t){let n=wY(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of TY(n,t))if(EX.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function OX(e){let t=ut({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new yY(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return DX(t.stdout,e)}const kX=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function AX(e,t){let n=[];for(let r of e.split(`
|
|
488
|
+
`)){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 jX(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=kX.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function MX(){let e=ut({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:AX(e.stdout,jX)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function NX(e){let t=PU(e,`doctor.tmux`,[`display`,`-p`,`-t`,e.pane,`#{client_termfeatures} #{client_termtype} #{client_termname} #{client_pid} #{client_utf8}`]);if(t.kind===`rate-limited`)throw new yY(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:TX(t.stdout)}function PX(e){return{probeTmux:NX,remoteLogin:OX,fontInUse:_X,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ka(process.platform),install:xX,daemons:MX,forge:zX,memento:ZU,transcript:IX}}function FX(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
|
|
489
489
|
`)+1,i=n.lastIndexOf(`
|
|
490
490
|
`)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
|
|
491
|
-
`)){let t
|
|
492
|
-
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const
|
|
493
|
-
`);let i=
|
|
491
|
+
`)){let t=$H(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function IX(e){let t=va(e,Kj+1);return t.kind===`ok`?F(FX(t.value.buf,t.value.fromStart)):t}function LX(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 RX={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function zX(e){if(kD(e)===void 0)return{kind:`ok`,value:null};let t=XD(ut({bin:`git`,args:[...YD],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=tO(t.value);if(n===null)return{kind:`ok`,value:null};let r=JD(n);if(r===null)return{kind:`ok`,value:null};let i=UD[r],a=RX[r],o=a.loginHost(qD(n)),s=ut({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return BX(i,o,a.nonZero,s)}function BX(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):WD(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:BD(r.stderr)}):{kind:`failed`,reason:zD(e,r)}}function VX(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
|
|
492
|
+
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const HX=e=>bX(()=>ja(e));function UX(e,t){let n=e=>JSON.stringify([e.managedDir,e.projectDir,e.userFile]),r=n(e),i=[],a=new Map;for(let o of t){let t={managedDir:e.managedDir,projectDir:o.projectDir,userFile:Sa(o.claudeConfigDir)},s=n(t);if(s===r)i.push(o);else{let e=a.get(s)??{at:t,bars:[]};e.bars.push(o),a.set(s,e)}}let o=(e,t)=>({at:e,sources:HX(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 WX(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function GX(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:Fj(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:Pj(t),tmuxClient:t}}}}function KX(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(wj(s))return{kind:`bundling`,name:s,version:c};if(!Tj(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 qX(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:qe};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function JX(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function YX(e,t,n,r,i){return{pullRequests:JX(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:JX(t.rateLimits,()=>i),memento:JX(t.memento,()=>({located:e.memento(r,n.projectDir),claudeConfigDir:r}))}}function XX(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 ZX(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=sV(d.config,r,()=>!1),p=WX(e,t.tmux),m=GX(p,t.terminalEnv),h=[...new Set([...ty(f),...ey(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:KX(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:VX(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:YX(e,DY(d.config,f.preset),n,xa(t.claudeConfigDir),a),transcripts:LX(e,o),claudeSettings:UX({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Sa(xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function QX(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;O(e,Vi(Ea(e),t.path,JSON.stringify(t.value),Ei));let r=e=>({...e,sources:HX(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||In(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const $X={connectMs:200,budgetMs:500};async function eZ(e){let n=e.includes(`--json`),r=await tZ();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${ln(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
493
|
+
`);let i=nZ(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(uZ(r.value))}function tZ(){return nn({kind:`stats`},$X,e=>`stats`in e?e.stats:void 0)}function nZ(e,t=rZ){let n=Cq.referenceSnapshot(),r=iZ(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=oZ(e.version,e.sourceDigest??null),a=oZ(qe,Xe());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const rZ=Object.keys(Cq.referenceSnapshot());function iZ(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!aZ(e))return[];if(!aZ(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(...iZ(e[i],t[i],a)):r.push(a)}return r}function aZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function oZ(e,t){return`${e} [${t===null?`no digest`:Ke(t)}]`}function sZ(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function cZ(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function lZ(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 uZ(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${oZ(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${lZ(e.uptimeSec)}`),t.push(` rss ${sZ(e.rssBytes)}`),t.push(` heapUsed ${sZ(e.heapUsedBytes)}`),t.push(` heapTotal ${sZ(e.heapTotalBytes)}`),t.push(` external ${sZ(e.externalBytes)}`),t.push(` arrayBuffers ${sZ(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${cZ(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(` refreshes ${e.gitCache.refreshes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${cZ(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${sZ(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${sZ(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` accounted ${sZ(e.renderCache.accountedBytes)} / ${sZ(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let n=Object.entries(e.subprocesses.byCategory),r=n.reduce((e,[t])=>Math.max(e,t.length),13);for(let[i,a]of n){let n=e.subprocesses.p50DurationMs[i],o=e.subprocesses.p99DurationMs[i],s=n!==void 0&&o!==void 0?` (p50 ${n}ms · p99 ${o}ms)`:``;t.push(` ${i.padEnd(r)} ${a}${s}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
494
494
|
`)+`
|
|
495
|
-
`}const
|
|
496
|
-
`).join(` — `));let t=
|
|
497
|
-
`);return{inMode:n!==`0`,screen:r}}function wZ(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 TZ(e,t){let n=SZ(e,`claude-input.type`,wZ(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 EZ(){return{read:CZ,type:TZ}}function DZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function OZ(e){return kZ(()=>decodeURIComponent(e))}function kZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function AZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const jZ=(e,t)=>AZ(OZ(e),t),MZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,OZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},NZ=(e,t)=>AZ(OZ(e),t),PZ=(e,t)=>AZ(OZ(e),t),FZ=(e,t)=>{let n=DZ(OZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},IZ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=jV(XZ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}BZ(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})`)},LZ=/^-?\d+$/;function RZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const zZ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!LZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=XZ(t,a),c=jV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&LZ.test(u)?VZ(l,parseInt(u,10)):HZ(`step-state`,r,l,PV(s,e=>t.sessionState.get(a,e),r)),f=RZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);BZ(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 BZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(_A));if(i.length===0)return;let a=uV(XZ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function VZ(e,t){return Math.max(e.min,Math.min(e.max,t))}function HZ(e,t,n,r){if(r===null)return n.min;if(!LZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return VZ(n,parseInt(r,10))}const UZ=`render-origin`;function WZ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function GZ(e){return JSON.stringify(e)}function KZ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function qZ(e,t){let n=JZ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function JZ(e,t){let n=e.sessionState.get(t,UZ);return n===null?null:WZ(KZ(n),e.sessionState,t)}function YZ(e,t,n){let r=JZ(e,t);if(r===null)return;let{path:i}=ZZ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function XZ(e,t){return e.configFor(qZ(e,t))}function ZZ(e){return sB(e.projectDir,e.cwd,e.configFile??void 0)}function QZ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const $Z=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=qZ(t,a),s=t.configFor(o),c=HF(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=ZZ(o),d=cV(s,e=>t.sessionState.get(a,e),r);iJ(QZ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},eQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!LZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=qZ(t,a),c=t.configFor(s),l=HF(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=ZZ(s),f=cV(c,e=>t.sessionState.get(a,e),r),p=rJ(d.path,f.key),m=typeof p==`number`?VZ(u,p):HZ(`step-config`,r,u,WF(f.globals,r)),h=RZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);iJ(QZ(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})`)},tQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=oV(a,o),c=lV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=jV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});rQ(`save`,l,c);let d=ZZ(i);aJ(QZ(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(nQ)].join(` `)} → ${d.path} (session=${r})`)},nQ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Hg(e.value)}`;function rQ(e,t,n){for(let r of n){let n=t.validate(r.key,Hg(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const iQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=t.configFor(i),o=pV(a,e=>t.sessionState.get(r,e)),s=jV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});rQ(`save-preset`,s,o.placements);let l=ZZ(i),u=fJ(QZ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...hv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,pv.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(nQ)].join(` `)} → ${l.path} (session=${r})`)},aQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n),i=qZ(t,r),a=hV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=ZZ(i);pJ(QZ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(oV(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ov.map(e=>pv[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} ${ov.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},oQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=qZ(t,i),o=ZZ(a);mJ(QZ(t,i),o,r),t.reloadConfig(a);let s=pv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},sQ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=qZ(t,i),o=HF(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=ZZ(a),l=r.map(gV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);lJ(QZ(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 cQ(e,t){let n=(e,t)=>[...Cg(Gy(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Hy(t.presets).flatMap(e=>n(t,e).map(t=>vA(nk(e),yg(t)))));return Hy(e.presets).flatMap(t=>n(e,t).map(e=>({member:vA(nk(t),yg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function lQ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[fA]:[]])}const uQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=qZ(t,a),s=t.configFor(o),c=HF(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=OF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=ZZ(o),f=hJ(QZ(t,a),d,r,u);t.reloadConfig(o);let p=lQ(cQ(s,t.configFor(o)),t.sessionState.get(a,fA)).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})`)},dQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n);t.journal.commit();let i=t.history.undo(r);YZ(t,r,i),t.dlog(`info`,`undo: restored ${LJ(i)} (session=${r})`)},fQ=(e,t)=>{let n=DZ(OZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,jV(XZ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},pQ=(e,t)=>{let n=DZ(OZ(e));t.journal.commit();let r=t.history.rewind(n);YZ(t,n,r),t.dlog(`info`,`rewind: put back ${LJ(r)||`nothing`} as edit mode found it (session=${n})`)},mQ=(e,t)=>{let[n=``]=kZ(()=>Vr(e)),r=DZ(n);t.journal.commit();let i=t.history.redo(r);YZ(t,r,i),t.dlog(`info`,`redo: re-applied ${LJ(i)} (session=${r})`)},hQ=(e,t)=>{DZ(OZ(e)),t.applyUpdate()},gQ=`client-hints`;function _Q(e,t){let n=e.sessionState.get(t,gQ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function vQ(e,t,n){let r=TM(n);e.sessionState.setBatch(t,UM(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${VM(n.nerdFont,n.marks)} ${jM(n.terminal,n.clicked)} ${MM(n.terminal,n.width)} ${NM(n.install)} ${FM(n.daemon)} ${IM(n.data)} ${BM(n.transcripts)} ${LM(n.frames,n.claudeSettings)} ${zM(n.claudeSettings.origin.sources)} (session=${t})`)}function yQ(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,CO(new Date)),i;try{i=zX(e.doctor,_Q(e,t),qZ(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:dY(n,r)},RX(t,r),fX(e.doctorStores))}catch(e){throw e instanceof sY?new J(e.message):e}return{...i,urlHandler:FX(e.arrival),install:uX(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:bQ(e,i)}}function bQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?wj(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>aY(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 xQ=(e,t)=>{let n=DZ(OZ(e));vQ(t,n,yQ(t,n))},SQ=(e,t)=>{let n=rZ(OZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new J(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},CQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n),a=EM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=yQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=BX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Ij(s.fix)} (session=${i})`),vQ(t,i,c.value)},wQ=(e,t)=>{let[n=``,r=``,i=``]=kZ(()=>Vr(e)),a=DZ(n),o=EM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!Nj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${Nj.join(` or `)}`);let s=yQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>nY(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),vQ(t,a,{...s,marks:u})},TQ=(e,t)=>{let[n=``,...r]=kZ(()=>Vr(e)),i=DZ(n),a=qZ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=WL(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=OU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},_Q(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},EQ=(e,t)=>{let[n=``,r=``]=kZ(()=>Vr(e)),i=DZ(n),a=Object.values(t.configFor(qZ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=xZ(t.claudeInput,_Q(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},DQ=`config-override`,OQ=new Map([[gr,jZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=DZ(kZ(()=>decodeURIComponent(e.slice(0,n)))),i=kZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,DQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,DQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[_r,MZ],[mr,IZ],[hr,zZ],[xr,$Z],[Sr,eQ],[Dr,sQ],[Cr,tQ],[wr,iQ],[Tr,aQ],[Er,oQ],[Or,uQ],[kr,dQ],[Ar,mQ],[jr,fQ],[Mr,pQ],[yr,NZ],[br,PZ],[vr,FZ],[Nr,hQ],[Pr,xQ],[Fr,CQ],[Ir,wQ],[Lr,SQ],[Rr,TQ],[zr,EQ]]),kQ=new Set([mr,hr,xr,Sr,Dr,Cr,wr,Tr,Er,Or,kr,Ar,jr,Mr,vr,Nr,Pr,Fr,Ir,Rr,zr]),AQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Gr(Ur(e))){if(!i&&kQ.has(a)){let e=Vr(o);e.length>0&&e[0]&&(i=e[0])}let e=OQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&JJ(t.sessionState,i,n.join(`
|
|
498
|
-
`),CO(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function jQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const MQ=new Map([...OQ,[pr,AQ]].map(([e,t])=>[e,jQ(t)]));Object.freeze([...MQ.keys()]);const NQ=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`]),PQ=[[`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`]],FQ=[[`workspace.added_dirs`,`string-list`]];function IQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of PQ){let i=zQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=LQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of FQ){let i=zQ(n,e),a=i===void 0?r:RQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))NQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function LQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function RQ(e){return Array.isArray(e)&&e.every(e=>LQ(e)===`string`)?`string-list`:LQ(e)}function zQ(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 BQ(e,t){switch(e){case`vars`:return{what:e,vars:VQ(t)};case`segments`:return{what:e,segments:KQ(t)};case`config`:return{what:e,config:XQ(t)}}}function VQ(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=WQ(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=HQ(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:UQ(r.lastUpdatedMs())})}return o}function HQ(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function UQ(e){return e===null?null:Math.max(0,Date.now()-e)}function WQ(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,GQ(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}`,GQ(i));return t}function GQ(e){return e.kind}function KQ(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=JQ(n),o=qQ(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:YQ(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function qQ(e){let t=new Map;for(let n of Hy(e.presets))for(let r of Cg(Gy(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=yg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function JQ(e){let t=[],n=new Set;for(let r of Cg(Fy(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 YQ(e,t,n){let r=new Set;for(let i of pb(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function XQ(e){return e===null?null:e.config}const ZQ=[`vars`,`segments`,`config`];function QQ(e){return typeof e==`string`&&ZQ.includes(e)}function $Q(e){return Math.max(1,e-2)}const e$={moving:1e3/30,still:1e3},t$=1e3;function n$(e){return M_.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 r$(e,t){e.push(t);let n=e.findIndex(e=>e>t-t$);e.splice(0,n)}const i$=e=>({resp:e,bytes:JSON.stringify(e)}),a$=(e,t)=>j_[t].elsewhere===null?e.statusline:e.bar,o$=e=>Math.round(1e3/e);var s$=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return R_;let n=this.deps.now()-t$,r=this.shown(t);return L_(e=>{let i=t.rates.get(e);if(i===void 0)return F_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:o$(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=o$(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:i$(t.resp),statusline:i$(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||a$(i,t).bytes!==a$(r,t).bytes)&&r$(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=a$(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:KA(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function c$(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 l$=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,u$=`#{session_id} #{client_control_mode} #{pane_id}`;function d$(e){let t=new Set;for(let n of e.split(`
|
|
499
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
500
|
-
`)){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
|
|
495
|
+
`}const dZ=e=>({kind:`ok`,value:e}),fZ=e=>({kind:`failed`,reason:e});var pZ=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const mZ=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function hZ(e){return mZ.test(e)?e:null}function gZ(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return dZ(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return dZ({app:n,missing:fZ(`its script could not be read (${r.reason})`)});let i=to(r.value);return dZ({app:n,missing:i===null?fZ("its script is not one `cc-candybar install` wrote"):dZ([i.node,i.script].filter(t=>!e.exists(t)))})}async function _Z(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 vZ(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${fr}://${Lr}/${n}`);return(r===null?await _Z(e,n):null)??{kind:`lost`,unopened:r,opener:gZ(e)}}function yZ(e,t,n){let r=ut({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?dZ(r.stdout):fZ(r.stderr.trim()||r.error||r.reason)}const bZ=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${fr}://probe"));u.isNil() ? "" : u.path.js`;async function xZ(){let e=await tZ();if(e.kind!==`ok`)return fZ(ln(e).split(`
|
|
496
|
+
`).join(` — `));let t=nZ(e.value,[`handlerProbes`]);if(t!==null)return fZ(t);let{version:n,handlerProbes:r}=e.value;return dZ({version:n,arrivals:r})}function SZ(){return{platform:process.platform,sockets:{own:vt(),handler:yt()},now:Date.now,nonce:ne,daemon:xZ,open:e=>{let t=yZ(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=yZ(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,bZ]);if(e.kind===`failed`)return e;let t=e.value.trim();return dZ(t===``?null:t)},script:e=>yZ(`doctor.osadecompile`,`/usr/bin/osadecompile`,[no(e)]),exists:p.existsSync}}const CZ=/^─{20,}/,wZ=/^❯(\s|$)/,TZ=/›\s*stashed$/;function EZ(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>CZ.test(e)?[t]:[]).at(-2);return n===void 0||!wZ.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function DZ(e){if(e.inMode)return{kind:`in-mode`};let t=EZ(e);return t===null?{kind:`no-prompt`}:TZ.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function OZ(e){return/^❯\s*\S/u.test(EZ(e)?.prompt??``)}const kZ=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function AZ(e){return e.screen.some(e=>kZ.test(e))}const jZ={"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 MZ(e){return e===void 0?{kind:`refused`,reason:`this session's statusline client reports no tmux facts (it predates this daemon) — rebuild or reinstall cc-candybar`}:e===null?{kind:`refused`,reason:`this Claude Code is not running inside tmux — the bar can only act in a tmux pane`}:{kind:`pane`,hint:e}}function NZ(e,t,n){let r=MZ(t);if(r.kind===`refused`)return r;let i=r.hint,a=DZ(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:jZ[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function PZ(e,t,n,r){let i=PU(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function FZ(e){let t=PZ(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
|
|
497
|
+
`);return{inMode:n!==`0`,screen:r}}function IZ(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 LZ(e,t){let n=PZ(e,`claude-input.type`,IZ(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 RZ(){return{read:FZ,type:LZ}}function zZ(e){if(!e)throw new J(`session id is required`);if(e.includes(`/`)||e.includes(`..`))throw new J(`invalid session id "${e}"`);return e}function BZ(e){return VZ(()=>decodeURIComponent(e))}function VZ(e){try{return e()}catch(e){throw e instanceof URIError?new J(`malformed wire encoding: ${e.message}`):e}}function HZ(e,t){let n=ut({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.pbcopy rate-limited: ${n.error??``}`);return}throw Error(`pbcopy failed (${n.reason}, exit ${n.exitCode??`null`})`)}}const UZ=(e,t)=>HZ(BZ(e),t),WZ=(e,t)=>{let n=ut({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,BZ(e)],category:`click.open`});if(!n.ok){if(n.reason===`rate-limited`){t.dlog(`warn`,`click.open rate-limited: ${n.error??``}`);return}throw Error(`open -a "Visual Studio Code" failed (${n.reason}, exit ${n.exitCode??`null`})`)}},GZ=(e,t)=>HZ(BZ(e),t),KZ=(e,t)=>HZ(BZ(e),t),qZ=(e,t)=>{let n=zZ(BZ(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},JZ=(e,t)=>{let[n=``,...r]=VZ(()=>Vr(e)),i=zZ(n),a=UV(cQ(t,i));if(r.length===0)throw new J(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new J(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new J(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new J(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}QZ(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})`)},YZ=/^-?\d+$/;function XZ(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const ZZ=(e,t)=>{let[n=``,r=``,i=``]=VZ(()=>Vr(e)),a=zZ(n);if(!r)throw new J(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!YZ.test(i))throw new J(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=cQ(t,a),c=UV(s),l=c.rangeParamsFor(r);if(!l)throw new J(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&YZ.test(u)?$Z(l,parseInt(u,10)):eQ(`step-state`,r,l,KV(s,e=>t.sessionState.get(a,e),r)),f=XZ(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new J(`step-state: ${p.reason}`);QZ(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 QZ(e,t,n,r){let i=r.filter(e=>e.key.startsWith(kA));if(i.length===0)return;let a=SV(cQ(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new J(`${n}: refused — ${a.join(`; `)}`)}function $Z(e,t){return Math.max(e.min,Math.min(e.max,t))}function eQ(e,t,n,r){if(r===null)return n.min;if(!YZ.test(r))throw new J(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return $Z(n,parseInt(r,10))}const tQ=`render-origin`;function nQ(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function rQ(e){return JSON.stringify(e)}function iQ(e){let t;try{t=JSON.parse(e)}catch{throw new J(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new J(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new J(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function aQ(e,t){let n=oQ(e,t);if(n===null)throw new J(`session ${t} has not rendered yet — no config to act on`);return n}function oQ(e,t){let n=e.sessionState.get(t,tQ);return n===null?null:nQ(iQ(n),e.sessionState,t)}function sQ(e,t,n){let r=oQ(e,t);if(r===null)return;let{path:i}=lQ(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function cQ(e,t){return e.configFor(aQ(e,t))}function lQ(e){return yB(e.projectDir,e.cwd,e.configFile??void 0)}function uQ(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const dQ=(e,t)=>{let[n=``,r=``,i=``]=VZ(()=>Vr(e)),a=zZ(n),o=aQ(t,a),s=t.configFor(o),c=eI(s);if(!r)throw new J(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`set-config: ${l.reason}`);let u=lQ(o),d=bV(s,e=>t.sessionState.get(a,e),r);gJ(uQ(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},fQ=(e,t)=>{let[n=``,r=``,i=``]=VZ(()=>Vr(e)),a=zZ(n);if(!r)throw new J(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!YZ.test(i))throw new J(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=aQ(t,a),c=t.configFor(s),l=eI(c),u=l.rangeParamsFor(r);if(!u)throw new J(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=lQ(s),f=bV(c,e=>t.sessionState.get(a,e),r),p=hJ(d.path,f.key),m=typeof p==`number`?$Z(u,p):eQ(`step-config`,r,u,nI(f.globals,r)),h=XZ(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new J(`step-config: ${g.reason}`);gJ(uQ(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})`)},pQ=(e,t)=>{let[n=``]=VZ(()=>Vr(e)),r=zZ(n),i=aQ(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=vV(a,o),c=xV(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=UV(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save: ${t.reason}`);return[e.target,t.value]});hQ(`save`,l,c);let d=lQ(i);_J(uQ(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(mQ)].join(` `)} → ${d.path} (session=${r})`)},mQ=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Hg(e.value)}`;function hQ(e,t,n){for(let r of n){let n=t.validate(r.key,Hg(r.value));if(!n.ok)throw new J(`${e}: ${n.reason}`)}}const gQ=(e,t)=>{let[n=``]=VZ(()=>Vr(e)),r=zZ(n),i=aQ(t,r),a=t.configFor(i),o=TV(a,e=>t.sessionState.get(r,e)),s=UV(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new J(`save-preset: ${t.reason}`);return[e.configKey,t.value]});hQ(`save-preset`,s,o.placements);let l=lQ(i),u=wJ(uQ(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...hv.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,pv.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(mQ)].join(` `)} → ${l.path} (session=${r})`)},_Q=(e,t)=>{let[n=``]=VZ(()=>Vr(e)),r=zZ(n),i=aQ(t,r),a=DV(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new J(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=lQ(i);TJ(uQ(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(vV(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=ov.map(e=>pv[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} ${ov.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},vQ=(e,t)=>{let[n=``,r=``]=VZ(()=>Vr(e)),i=zZ(n);if(!r)throw new J(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=aQ(t,i),o=lQ(a);EJ(uQ(t,i),o,r),t.reloadConfig(a);let s=pv.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},yQ=(e,t)=>{let[n=``,...r]=VZ(()=>Vr(e)),i=zZ(n),a=aQ(t,i),o=eI(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new J(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=lQ(a),l=r.map(OV),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);xJ(uQ(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 bQ(e,t){let n=(e,t)=>[...Cg(Gy(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(Hy(t.presets).flatMap(e=>n(t,e).map(t=>AA(mk(e),yg(t)))));return Hy(e.presets).flatMap(t=>n(e,t).map(e=>({member:AA(mk(t),yg(e)),node:e})).filter(({member:e})=>!r.has(e)))}function xQ(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[wA]:[]])}const SQ=(e,t)=>{let[n=``,r=``,i=``]=VZ(()=>Vr(e)),a=zZ(n),o=aQ(t,a),s=t.configFor(o),c=eI(s);if(!r)throw new J(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new J(`apply-layout-op: ${l.reason}`);let u=BF(l.value);if(u===null)throw new J(`apply-layout-op: "${l.value}" is not a layout op token`);let d=lQ(o),f=DJ(uQ(t,a),d,r,u);t.reloadConfig(o);let p=xQ(bQ(s,t.configFor(o)),t.sessionState.get(a,wA)).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})`)},CQ=(e,t)=>{let[n=``]=VZ(()=>Vr(e)),r=zZ(n);t.journal.commit();let i=t.history.undo(r);sQ(t,r,i),t.dlog(`info`,`undo: restored ${YJ(i)} (session=${r})`)},wQ=(e,t)=>{let n=zZ(BZ(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,UV(cQ(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},TQ=(e,t)=>{let n=zZ(BZ(e));t.journal.commit();let r=t.history.rewind(n);sQ(t,n,r),t.dlog(`info`,`rewind: put back ${YJ(r)||`nothing`} as edit mode found it (session=${n})`)},EQ=(e,t)=>{let[n=``]=VZ(()=>Vr(e)),r=zZ(n);t.journal.commit();let i=t.history.redo(r);sQ(t,r,i),t.dlog(`info`,`redo: re-applied ${YJ(i)} (session=${r})`)},DQ=(e,t)=>{zZ(BZ(e)),t.applyUpdate()},OQ=`client-hints`;function kQ(e,t){let n=e.sessionState.get(t,OQ);if(n===null)throw new J(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new J(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new J(`client hints record is not an object: ${n}`);return zt(r)}function AQ(e,t,n){let r=LM(n);e.sessionState.setBatch(t,tN(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${$M(n.nerdFont,n.marks)} ${UM(n.terminal,n.clicked)} ${WM(n.terminal,n.width)} ${GM(n.install)} ${qM(n.daemon)} ${JM(n.data)} ${QM(n.transcripts)} ${YM(n.frames,n.claudeSettings)} ${ZM(n.claudeSettings.origin.sources)} (session=${t})`)}function jQ(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,FO(new Date)),i;try{i=ZX(e.doctor,kQ(e,t),aQ(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:CY(n,r)},XX(t,r),wX(e.doctorStores))}catch(e){throw e instanceof yY?new J(e.message):e}return{...i,urlHandler:qX(e.arrival),install:SX(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:MQ(e,i)}}function MQ(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?Ij(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>_Y(e,r))}catch(t){return e.dlog(`warn`,`doctor: clicked terminal not filed for ${JSON.stringify(r)}: ${t instanceof Error?t.message:String(t)}`),n}}const NQ=(e,t)=>{let n=zZ(BZ(e));AQ(t,n,jQ(t,n))},PQ=(e,t)=>{let n=hZ(BZ(e));if(n===null)throw new J(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new J(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},FQ=(e,t)=>{let[n=``,r=``]=VZ(()=>Vr(e)),i=zZ(n),a=RM(r);if(a===void 0)throw new J(`doctor-fix: unknown check "${r}"`);let o=jQ(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new J(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=QX(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new J(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${Jj(s.fix)} (session=${i})`),AQ(t,i,c.value)},IQ=(e,t)=>{let[n=``,r=``,i=``]=VZ(()=>Vr(e)),a=zZ(n),o=RM(r);if(o===void 0)throw new J(`doctor-mark: unknown check "${r}"`);if(!Gj.includes(i))throw new J(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${Gj.join(` or `)}`);let s=jQ(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new J(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>mY(e,...l));if(u.kind===`failed`)throw new J(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),AQ(t,a,{...s,marks:u})},LQ=(e,t)=>{let[n=``,...r]=VZ(()=>Vr(e)),i=zZ(n),a=aQ(t,i),o=Object.values(t.configFor(a).actions).filter(e=>`ceiling`in e).find(e=>{let t=nR(e);return t.length===r.length&&t.every((e,t)=>e===r[t])});if(o===void 0)throw new J(`ceiling: "${r.join(` `)}" is not a move this config declares`);let s=o.ceiling===`set`?{kind:`set`,to:o.to}:{kind:`clear`},c=BU({sessionId:i,projectDir:a.projectDir,cwd:a.cwd},kQ(t,i));t.memento.move(c,s),t.dlog(`info`,`ceiling: ${r.join(` `)} (session=${i} claudeConfigDir=${c.claudeConfigDir})`)},RQ=(e,t)=>{let[n=``,r=``]=VZ(()=>Vr(e)),i=zZ(n),a=Object.values(t.configFor(aQ(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new J(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=NZ(t.claudeInput,kQ(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new J(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)},zQ=`config-override`,BQ=new Map([[gr,UZ],[`load-config`,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new J(`load-config: expected <sessionId>/<path> (missing separator)`);let r=zZ(VZ(()=>decodeURIComponent(e.slice(0,n)))),i=VZ(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new J(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new J(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,zQ),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,zQ,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[_r,WZ],[mr,JZ],[hr,ZZ],[xr,dQ],[Sr,fQ],[Dr,yQ],[Cr,pQ],[wr,gQ],[Tr,_Q],[Er,vQ],[Or,SQ],[kr,CQ],[Ar,EQ],[jr,wQ],[Mr,TQ],[yr,GZ],[br,KZ],[vr,qZ],[Nr,DQ],[Pr,NQ],[Fr,FQ],[Ir,IQ],[Lr,PQ],[Rr,LQ],[zr,RQ]]),VQ=new Set([mr,hr,xr,Sr,Dr,Cr,wr,Tr,Er,Or,kr,Ar,jr,Mr,vr,Nr,Pr,Fr,Ir,Rr,zr]),HQ=(e,t)=>{let n=[],r=!1,i=null;for(let{verb:a,value:o}of Gr(Ur(e))){if(!i&&VQ.has(a)){let e=Vr(o);e.length>0&&e[0]&&(i=e[0])}let e=BQ.get(a);if(!e){n.push(`unknown effect verb "${a}"`);continue}try{e(o,t)}catch(e){e instanceof J||(r=!0),n.push(`${a}: ${e instanceof Error?e.message:String(e)}`)}}if(n.length>0){i&&oY(t.sessionState,i,n.join(`
|
|
498
|
+
`),FO(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new J(e)}};function UQ(e){return(t,n)=>{let r=n.history.begin(),i=n.navigation.begin(r.sessionState),a=[];try{e(t,{...n,sessionState:r.sessionState,journal:r,navigating:i.sessionState})}catch(e){a.push(e)}i.commit();try{r.commit()}catch(e){a.push(e)}if(a.length===1)throw a[0];if(a.length>1)throw Error(a.map(e=>String(e.message??e)).join(`; `))}}const WQ=new Map([...BQ,[pr,HQ]].map(([e,t])=>[e,UQ(t)]));Object.freeze([...WQ.keys()]);const GQ=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`]),KQ=[[`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`]],qQ=[[`workspace.added_dirs`,`string-list`]];function JQ(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of KQ){let i=ZQ(n,e);if(i==null)t.missingRequired.push(e);else{let n=YQ(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of qQ){let i=ZQ(n,e),a=i===void 0?r:XQ(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))GQ.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function YQ(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function XQ(e){return Array.isArray(e)&&e.every(e=>YQ(e)===`string`)?`string-list`:YQ(e)}function ZQ(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 QQ(e,t){switch(e){case`vars`:return{what:e,vars:$Q(t)};case`segments`:return{what:e,segments:i$(t)};case`config`:return{what:e,config:c$(t)}}}function $Q(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=n$(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=e$(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:t$(r.lastUpdatedMs())})}return o}function e$(e){if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`absent`:return{type:`document`,value:`(not yet scanned)`};case`failed`:return{type:`document`,value:t.reason}}}function t$(e){return e===null?null:Math.max(0,Date.now()-e)}function n$(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,r$(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}`,r$(i));return t}function r$(e){return e.kind}function i$(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=o$(n),o=a$(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:s$(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function a$(e){let t=new Map;for(let n of Hy(e.presets))for(let r of Cg(Gy(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=yg(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function o$(e){let t=[],n=new Set;for(let r of Cg(Fy(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 s$(e,t,n){let r=new Set;for(let i of pb(e,t).keys()){if(n.has(i)){r.add(i);continue}let e=i.split(`.`);for(;e.length>1;){e.pop();let t=e.join(`.`);if(n.has(t)){r.add(t);break}}}return Array.from(r).sort()}function c$(e){return e===null?null:e.config}const l$=[`vars`,`segments`,`config`];function u$(e){return typeof e==`string`&&l$.includes(e)}function d$(e){return Math.max(1,e-2)}const f$={moving:1e3/30,still:1e3},p$=1e3;function m$(e){return M_.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 h$(e,t){e.push(t);let n=e.findIndex(e=>e>t-p$);e.splice(0,n)}const g$=e=>({resp:e,bytes:JSON.stringify(e)}),_$=(e,t)=>j_[t].elsewhere===null?e.statusline:e.bar,v$=e=>Math.round(1e3/e);var y$=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&(i.noted++,this.wake(e))}subscribe(e,t){let n=this.requests.get(e);if(n!==void 0&&!this.deps.lanes(n.req)[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e)??this.open(e);return r.followers.set(t,null),r.rates.has(t.lane)||r.rates.set(t.lane,[]),this.send(r,t),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${r.followers.size} data=${this.requests.has(e)?`Y`:`N`}`),()=>this.unsubscribe(r,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e){let t=this.feeds.get(e);if(t!==void 0)switch(t.phase.kind){case`drawing`:t.phase.again=!0;return;case`due`:clearTimeout(t.phase.timer),this.draw(t);return;case`waiting`:this.draw(t);return}}wakeWhere(e){for(let{sessionId:t,req:n}of this.watched())e(n)&&this.wake(t)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e){let t=this.feeds.get(e);if(t===void 0)return R_;let n=this.deps.now()-p$,r=this.shown(t);return L_(e=>{let i=t.rates.get(e);if(i===void 0)return F_;let a=0;for(let n of t.followers.keys())n.lane===e&&a++;let o=0;for(let e of i)e>n&&o++;return{subscribers:a,fps:o,shown:r}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e)),phase:{kind:`waiting`},last:null,since:t,drawn:0,noted:0,moving:0,unseen:0,failed:0,pushed:0,pace:v$(this.deps.periods.still),drawMs:0,summarizedAt:t};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),this.draw(n),n}unsubscribe(e,t){e.followers.delete(t)&&([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),!(e.followers.size>0)&&(e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)))}draw(e){return this.step(e).catch(t=>{if(this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${w(t)}`),this.feeds.get(e.sessionId)!==e)return;let n=this.deps.now();this.schedule(e,null,n,n)})}async step(e){let t=this.requests.get(e.sessionId);if(t===void 0){e.phase={kind:`waiting`};return}let{req:n}=t,r={kind:`drawing`,again:!1};e.phase=r;let i=this.deps.now(),a=await this.deps.render(n,e.pace),o=this.deps.now();if(this.drawn++,e.drawn++,e.drawMs+=o-i,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,a),this.push(e,a),this.feeds.get(e.sessionId)===e)){if(o-e.summarizedAt>=6e4&&this.summarize(e,`running`),r.again){this.draw(e);return}this.schedule(e,a,i,o)}}schedule(e,t,n,r){let i=t?.moves===!0,a=i&&this.shown(e);a&&e.moving++,i&&!a&&e.unseen++;let o=a?this.deps.periods.moving:this.deps.periods.still;e.pace=v$(o),e.phase={kind:`due`,timer:setTimeout(()=>void this.draw(e),Math.max(0,n+o-r))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.requests.get(e.sessionId);if(n!==void 0){let t=this.deps.lanes(n.req);for(let n of[...e.followers.keys()])t[n.lane]||(this.unsubscribe(e,n),this.refuse(e.sessionId,n))}if(e.followers.size===0)return;let r={bar:g$(t.resp),statusline:g$(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);let a=this.deps.now();for(let[t,n]of e.rates)(i===null||_$(i,t).bytes!==_$(r,t).bytes)&&h$(n,a);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=_$(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:ij(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now();this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round((n-e.since)/1e3)}s drawn=${e.drawn} noted=${e.noted} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function b$(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 x$=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,S$=`#{session_id} #{client_control_mode} #{pane_id}`;function C$(e){let t=new Set;for(let n of e.split(`
|
|
499
|
+
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function w$(e,t){let n=new Set;for(let r of e.split(`
|
|
500
|
+
`)){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 T$(e,t){let n=new Map;for(let t of e.split(`
|
|
501
501
|
`)){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(`
|
|
502
|
-
`)){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
|
|
503
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
504
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=B$(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,[F$(`@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)} ${v$} 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,z$(n));if(r===null||this.closed)return null;let i=V$(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,x$(r),e])}),i!==n.status){let e=w$(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,_$,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,A$(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,H$(n));if(i===null)return;let a=U$(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,G$);if(r===null||this.closed)return;let i=K$(r[0]??``);if(n.kind===`none`&&Y$(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`&&Y$(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...y$,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${k$(`${this.deps.handler} ${J$(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,G$);if(r===null)return;let i=X$(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=X$(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,M$(t));return n.kind===`ok`?N$(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,M$(t)));return n.kind===`ok`?N$(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,O$(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,O$(t),n)))}};const Q$=`CC_CANDYBAR_CONFIG`;function $$(e,t){return xz(t,e[Q$])}const $=e=>({arity:e,keep:!0}),e1=e=>({arity:e,keep:!1}),t1={"--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":e1(`none`),"--background":e1(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":e1(`optional`),"-c":e1(`none`),"--continue":e1(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":e1(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":e1(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":e1(`none`),"--forward-subagent-text":$(`none`),"--from-pr":e1(`optional`),"-h":e1(`none`),"--help":e1(`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":e1(`none`),"--print":e1(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":e1(`optional`),"--resume":e1(`optional`),"--safe-mode":$(`none`),"--session-id":e1(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":e1(`optional`),"--tmux":e1(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":e1(`none`),"--version":e1(`none`),"-w":e1(`optional`),"--worktree":e1(`optional`)},n1={resume:`--resume`,fresh:`--session-id`};function r1(e){return[n1[e.kind],e.sessionId]}const i1=e=>e.startsWith(`-`)&&e!==`-`;function a1(e,t){let n=c1(t);return n===null?{dir:e??t,args:[]}:e!==null&&o1(e,n.top)?{dir:e,args:[]}:{dir:e===null||c1(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const o1=(e,t)=>e===t||e.startsWith(t+s.sep);function s1(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!i1(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=t1[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=>!i1(e)):o.arity===`variadic`?l1(n.slice(r),e=>!i1(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 c1(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 l1(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const u1=`candybar-band@cc-candybar`,d1=s.join(`bin`,`cc-candybar-native`),f1=`@cc-candybar-bar-pane`,p1=$M(`/reload-plugins`),m1=e=>({kind:`done`,said:e});function h1(e){let t=bZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const g1={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${j_.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,d1);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${u1} from ${r}`,finished:_1(e,r,n)}},off:()=>m1(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=h1(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${j_.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:b1(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>m1(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=h1(e),i=n.barPanes(r);return i.length>0?m1(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):m1(`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=bZ(e.hints.tmux);if(r.kind===`refused`)return m1(`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 m1(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>m1(`the daemon draws ${h1(e).pane}'s bar in its status line`),off:()=>m1(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function _1(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,u1],r);let i=xZ(n.claudeInput,e.hints.tmux,p1);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 ${u1} from ${t} and typed /reload-plugins into ${i.pane}`}const v1=new Set([ya,Q$,...Mt]);function y1(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function b1(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${j_.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=T1(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${j_.statusline.label} off and on again`);let s=x1(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=s1(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=y1(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])=>v1.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...r1(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=S1(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(a1(null,i.cwd),_))}let y=m(a1(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}\`, ${C1[g.kind](e.sessionId)}, and its statusline follows lane B`}function x1(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 S1(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const C1={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},w1={"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 T1(e){let t=hZ(e);return t.kind===`ready`?vZ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:gZ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:w1[t.kind]}const E1={switches:Object.fromEntries(M_.map(e=>[e,!1])),revision:0};var D1=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??E1;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of M_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),JJ(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=g1[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function O1(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 k1(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function A1(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function j1(e,t,n){let r=O1(`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 M1=2e3;function N1(e,t,n){let r=SU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function P1(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 F1(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 I1=`#{pane_id} #{${f1}}`;function L1(e,t){return e.split(`
|
|
505
|
-
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const
|
|
506
|
-
`);async function V1(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=P1(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,B1,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function H1(e,t){return P1(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function U1(e){let t=await CU(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 H1(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function W1(e){let{panePid:t,cwd:n,foreground:r}=await U1(e),i=await H1(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await V1(r),o=fY(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:z1(i,r,t)}}function G1(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function K1(e){return{claudeInput:EZ(),barPanes:e=>L1(N1(e,[`list-panes`,`-a`,`-F`,I1]),e.pane),openBarPane:(e,t,n)=>{let r=N1(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 N1(e,[`set-option`,`-p`,`-t`,r,f1,e.pane]),r},closePane:(e,t)=>void N1(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void P1(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:G1(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:tB,paneClaude:W1,paneDir:async(e,t)=>{let n=Date.now()+M1;for(;;){let r=await U1(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 ${M1/1e3} s`);await ge(100)}},launcherNode:e=>j1(e,e=>k1(e,p.constants.X_OK),A1),onPath:(e,t)=>{let n=O1(e,t,e=>k1(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?F1(r.stdout):null;return i===null?(P1(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void N1(e,wZ(e.pane,`cc-candybar-lane`,[]),t)}}function q1(e,t){return M_.filter(n=>e[n]&&j_[n].elsewhere!==null&&t.has(n))}function J1(e,t){let n=`the bar is drawn in ${t.map(e=>j_[e].elsewhere).join(` and `)}`,r=Hr([{verb:Dr,args:[e,...t.map(e=>j_[e].setting)]}]);return{channels:[{severity:cy,message:n,lines:[[ly(n,Hr([{verb:gr,args:[n]}])),ly(`[⟲ draw it here]`,r)]]}]}}const Y1={order:-1/0,text:null,failure:null};var X1=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??Y1;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??Y1;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function Z1(e,t){for(let n of Object.entries(t))e.push(n)}const Q1={ok:`info`,"bad-request":`warn`,threw:`error`};function $1(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function e0(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...$1(t)];return{level:Q1[t.kind],line:`render${r.map(([e,t])=>` ${e}=${OM(t)}`).join(``)}`}}const t0=new dq,n0=new tZ,r0=new lj,i0=i(import.meta.url),a0=dX(gt());st(t0.launchStats);const o0=new dO({counters:t0,logger:M}),s0=VU({watchers:o0,logger:M}),{gitProvider:c0,usageStore:l0,mementoProvider:u0}=s0,d0=new mq,f0=new CJ(d0,M),p0=new KJ,m0=new Wv,h0=[t.execPath,...t.execArgv],g0=new D1({edge:K1(e=>v0.following(e)),host:{bundle:i0,node:h0,socket:vt(),preload:$a(i0)},state:d0,log:M,now:()=>CO(new Date),defer:e=>void pe(e)}),_0=new Z$({edge:{run:(e,t,n)=>CU({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>SU({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>v0.subscribe(e,t),sessionInPane:(e,t)=>v0.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${je(vt())}`,...[...h0,i0].map(je),`url-handle`].join(` `),owner:vt(),defer:e=>void pe(e),log:M}),v0=new s$({render:(e,t)=>a2(e,t),watch:(e,t)=>(0,Db.reaction)(()=>d0.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>s2(e),shown:e=>y0.shown(e.hints.tmux),watching:()=>y0.follow(),periods:e$,now:()=>performance.now(),log:M}),y0=new m$({listPanes:e=>CU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,l$]),listClients:e=>CU({socket:e},`frames.visibility`,[`list-clients`,`-F`,u$]),sockets:()=>new Set(v0.watched().flatMap(({req:e})=>b0(e))),onAnswer:(e,t)=>_0.answered(e,t),onChange:e=>v0.wakeWhere(t=>b0(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function b0({hints:{tmux:e}}){return e==null?[]:[e.socket]}const x0=new X1(At()),S0=new lq({gitService:c0,sessionState:d0,watchers:o0,log:M},{budgetBytes:()=>(F0(),$K(O0)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),C0=60*1e3,w0=nH({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:C0,stat:p.statSync,exit:()=>B0(0),log:M}),T0=$V({entryUrl:import.meta.url,intervalMs:C0,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>w0.checkNow(),log:M});let E0=null,D0=null,O0=0;function k0(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),B0(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),B0(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),B0(0)});try{I0(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),B0(1);return}E0=Oo(t.pid);let e=Ro(Bo(E0));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),B0(1);return}D0=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),d0.useStorage(new gq(wt(),500,M)),f0.useStorage(WJ(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),B0(0)}}),A0(E.createServer({allowHalfOpen:!1},e=>{V0(e)}),vt(),!1)}function A0(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),B0(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}j0(e,n)}),e.listen(n,()=>M0(n))}function j0(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),B0(1);return}}A0(e,n,!0)}function M0(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),B0(0);return}L0(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(O0)}MB`),nr();let r=x0.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),w0.arm(),T0.arm(),F0().arm(),N0(e,n.identity)}function N0(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>B0(e),log:M}).arm()}let P0=null;function F0(){if(P0===null)throw Error(`daemon: limits not yet established`);return P0}function I0(e){O0=Pn(e),P0=Vn(qn(t0.startedAt.getTime(),e=>B0(e),{limitBytes:O0}))}function L0(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:E0});n!==null&&M(`warn`,`lease write failed: ${n}`)}let R0=0,z0=!1;function B0(e){if(!z0){z0=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{_0.restoreAll(),c0.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{l0.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{o0.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{d0.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),D0!==null&&zo(D0,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function V0(e){R0++,t0.inFlight=R0;let t=!1,n=!0,r=()=>{n&&(n=!1,R0=Math.max(0,R0-1),t0.inFlight=R0)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>B0(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,t0.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,H0)},200),s=$t(e=>{Y0(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(K0(e),null,H0)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,H0)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=c$(e),c=v0.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(TH[i](e,t))),refused:t=>e.end(Zt(t)),drawing:()=>!0});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const H0=()=>{},U0=e=>({resp:e,exitAfterFlush:null,delivered:H0}),W0=e=>({kind:`reply`,...e}),G0={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},K0=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),q0=(e,t)=>W0(U0({ok:!1,error:t,code:e,daemonV:3}));function J0(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return q0(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return q0(`VERSION_MISMATCH`,`this client's subscribe names no lane (${M_.join(`, `)}): it predates the lane toggles — update it`);let t=z_(e.lane);return t===null?q0(`BAD_REQUEST`,`subscribe needs a lane, one of ${M_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function Y0(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?q0(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?J0(e):typeof e.kind!=`string`||!Object.hasOwn(G0,e.kind)?q0(`BAD_REQUEST`,`unknown kind`):W0(await X0(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:H0})}async function X0(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:H0};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return U0(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:v0.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return U0({ok:!0,stats:t0.snapshot({gitCache:c0.getStats(),usageCache:l0.getStats(),transcriptReads:ua(),renderCache:S0.stats,effectCache:m0.getStats(),sessionState:{sessions:d0.size(),observers:d0.observers(),revision:d0.latestRevision()},frameFeeds:v0.getStats(),tmuxStatus:_0.stats(),watchersActive:o0.size(),nextRestartReason:F0().describeNextRestart(),handlerProbes:n0.list(),clients:r0.list(CO(new Date)),bundle:i0,daemon:F0().serving(),doctorStores:fX(a0)})});if(e.kind===`render`){let n=new Date,r=CO(n),i=n.getTime(),a=[],o=++t0.requestsTotal,s=c2(e),c=(e,t)=>r0.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:aj(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),v0.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await m2(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?H0:()=>YJ(d0,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:K0(e),delivered:H0})):l2(s.problems);l.outcome.kind!==`ok`&&t0.requestsErrored++,Z1(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=e0(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return U0(r2(e.verb,e.value,{via:`link`,handler:Xt(e.clientVersion)}));if(e.kind===`debug`){if(!QQ(e.what))return U0({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${ZQ.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=S0.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?t2(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??lv(`colorCompatibility`)):e2};return U0({ok:!0,debug:BQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function Z0(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:xz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const Q0={sessionState:d0,dlog:M,applyUpdate:()=>T0.act(),doctor:SX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];S0.reload(...t);let n=S0.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:a0,probes:n0,clients:r0,bundle:i0,serving:()=>F0().serving(),memento:u0,claudeInput:EZ(),history:f0,navigation:p0,configFor:e=>S0.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>S0.reload(e.projectDir,e.cwd,e.configFile??void 0)};Q0.reloadConfig;const $0={endcaps:lv(`endcaps`),colorCompatibility:lv(`colorCompatibility`),wrap:lv(`autoWrap`),padding:lv(`padding`),width:1/0},e2=new Map;function t2(e,t){let n=new Map;for(let[r,i]of e)n.set(r,ry(i,{...$0,colorCompatibility:t}));return n}const n2={...s0,history:e=>f0.depth(e),feeds:e=>v0.feedsOf(e)};function r2(e,t,n){if(e===`tmux-status-click`)return i2(t);let r=MQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...Q0,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function i2(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=_0.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=fo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):r2(e.verb,e.value,{via:`tmux-status`})}let i=ut({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}async function a2(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await u2(e,CO(n),r,{by:`feed`,fps:t}),s=x0.linkFor(e.hookData.session_id,f2(i)),c=e.hookData.session_id,l=d2(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:h2(c,i,s,l,q1(o,v0.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=e0(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=K0(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function o2(e,t){return YB(t.config,t=>d0.get(e,t),e=>t.authoredRoots.has(e))}function s2(e){try{var t=na();let n=e.hookData.session_id,r=WZ(e.requested,d0,n);return qB(o2(n,t.u(S0.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function c2(e){let{report:t}=IQ(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=Z0(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:ij(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const l2=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:H0});async function u2(e,t,n,r){try{var i=na();Z1(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);Z1(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=WZ(e.requested,d0,a),{entry:u,state:d}=i.u(S0.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=$Q(f??120),m=iy(o.termRows);Z1(n,{width:String(p)});let h=t=>d0.get(e.hookData.session_id,t),g=o2(a,d),_=qB(g);Z1(n,{lanes:M_.filter(e=>_[e]).join(`,`)||`-`}),g0.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:nj(e.hookData)},_,f0.revision(a)),_0.observe(a,o.tmux,_.tmuxStatus);let v=await mW(e.hookData,t,{...n2,navigation:e=>p0.depth(e,d0,jV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...vV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});Z1(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:ZU(v.git),feeds:n$(v.feeds)});let y=[],b=JU(g,p),ee=m0.of(a),x=BK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=ZJ(d0,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
|
|
507
|
-
`),re=
|
|
508
|
-
`)),T=
|
|
509
|
-
`}function
|
|
510
|
-
`);return}t.stdout.write(
|
|
511
|
-
`;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?``:` ${
|
|
502
|
+
`)){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 E$=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${w(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:w$(t.stdout,C$(n.stdout)),status:T$(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),!D$(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 D$(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 O$=`@cc-candybar-status-prior`,k$=`@cc-candybar-status-wrote`,A$=`@cc-candybar-binding-prior`,j$=[`-T`,`root`,`MouseDown1Status`],M$=Array.from({length:5},(e,t)=>t),N$=e=>`@cc-candybar-row-${e}`,P$=e=>`#[fill=terminal]#{${N$(e)}}`,F$=e=>`status-format[${e}]`;function I$(e){return e===0?`off`:e===1?`on`:String(e)}function L$(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 R$(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 z$(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function B$(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function V$(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function H$(e){return e.map(e=>e.map(V$).join(` `)).join(` ; `)}const U$=`ccb:separator`;function W$(e){return B$(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,U$],e]))}function G$(e,t){let n=e.split(`${U$}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const K$=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],q$=e=>[`show-options`,`-g`,`-q`,`-v`,e],J$=e=>[[`show-options`,`-t`,e],K$(e,`status`),...M$.map(t=>K$(e,F$(t)))];function Y$(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
503
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of M$)i.includes(F$(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 X$(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,F$(Number(t)),z$(n)])]}const Z$=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...J$(e),...M$.map(e=>q$(F$(e))),K$(e,O$),K$(e,k$)];function Q$(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:L$(t)}catch(e){return{kind:`theirs`,why:`${O$} 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 $$(e,t,n){let[r=``,...i]=t,a=Y$(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return Q$(s,c,n);let l=L$(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,P$(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,O$,JSON.stringify(f)],...X$(e,d)]}}const e1=e=>[...J$(e),K$(e,k$)];function t1(e,t,n){let r=Y$(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(R$(r.formats,t.wrote))a.push(...X$(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,F$(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,z$(t.status)]):o.push(`status`)),a.push(...M$.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,N$(t)]),[`set-option`,`-q`,`-u`,`-t`,e,O$],[`set-option`,`-q`,`-u`,`-t`,e,k$]),{commands:a,kept:o}}const n1=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,r1=[[`list-keys`,`-T`,`root`]];function i1(e){let t=n1.exec(e);return t===null?null:{line:t[0],command:t[1]}}const a1=`cc-candybar://tmux-status-click/`,o1=e=>`${a1}${Br([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,s1=e=>e?.command.includes(a1)??!1;function c1(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,A$]};return s1(i1(t))?{steps:[e===null?{command:[`unbind-key`,...j$]}:{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 l1=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),this.deps.defer(()=>{this.held.get(e)===a&&(a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=IH(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,e1(n));if(i===null)continue;let a=t1(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,r1);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let[t,n,r,...i]=Vr(e);if(t===void 0||n===void 0||r===void 0||i.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let a=[...this.held.values()].find(e=>e.socket===t&&e.pane===`%${n}`)?.frame?.links[r];return a===void 0?{kind:`refused`,reason:`pane %${n}'s status line draws no link ${r} now`}:{kind:`link`,url:a}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${O$}}\t#{${k$}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
|
|
504
|
+
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=Q$(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,[q$(`@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)} ${A$} 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,Z$(n));if(r===null||this.closed)return null;let i=$$(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,N$(r),e])}),i!==n.status){let e=I$(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,k$,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,H$(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,e1(n));if(i===null)return;let a=t1(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,r1);if(r===null||this.closed)return;let i=i1(r[0]??``);if(n.kind===`none`&&s1(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`&&s1(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...j$,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${V$(`${this.deps.handler} ${o1(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,r1);if(r===null)return;let i=c1(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=c1(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,W$(t));return n.kind===`ok`?G$(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,W$(t)));return n.kind===`ok`?G$(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,B$(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,B$(t),n)))}};const u1=`CC_CANDYBAR_CONFIG`;function d1(e,t){return Nz(t,e[u1])}const $=e=>({arity:e,keep:!0}),f1=e=>({arity:e,keep:!1}),p1={"--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":f1(`none`),"--background":f1(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":f1(`optional`),"-c":f1(`none`),"--continue":f1(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":f1(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":f1(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":f1(`none`),"--forward-subagent-text":$(`none`),"--from-pr":f1(`optional`),"-h":f1(`none`),"--help":f1(`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":f1(`none`),"--print":f1(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":f1(`optional`),"--resume":f1(`optional`),"--safe-mode":$(`none`),"--session-id":f1(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":f1(`optional`),"--tmux":f1(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":f1(`none`),"--version":f1(`none`),"-w":f1(`optional`),"--worktree":f1(`optional`)},m1={resume:`--resume`,fresh:`--session-id`};function h1(e){return[m1[e.kind],e.sessionId]}const g1=e=>e.startsWith(`-`)&&e!==`-`;function _1(e,t){let n=b1(t);return n===null?{dir:e??t,args:[]}:e!==null&&v1(e,n.top)?{dir:e,args:[]}:{dir:e===null||b1(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const v1=(e,t)=>e===t||e.startsWith(t+s.sep);function y1(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!g1(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=p1[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=>!g1(e)):o.arity===`variadic`?x1(n.slice(r),e=>!g1(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 b1(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 x1(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const S1=`candybar-band@cc-candybar`,C1=s.join(`bin`,`cc-candybar-native`),w1=`@cc-candybar-bar-pane`,T1=dN(`/reload-plugins`),E1=e=>({kind:`done`,said:e});function D1(e){let t=MZ(e.hints.tmux);if(t.kind===`refused`)throw new J(t.reason);return t.hint}const O1={band:{on:(e,t,n)=>{let r=Je(t.bundle);if(r===null)throw new J(`${j_.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,C1);if(!n.fileExists(i))throw new J(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${S1} from ${r}`,finished:k1(e,r,n)}},off:()=>E1(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=D1(e),i=Pe(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new J(`${j_.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:M1(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>E1(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=D1(e),i=n.barPanes(r);return i.length>0?E1(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):E1(`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=MZ(e.hints.tmux);if(r.kind===`refused`)return E1(`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 E1(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>E1(`the daemon draws ${D1(e).pane}'s bar in its status line`),off:()=>E1(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function k1(e,t,n){let r=e.hints.claudeConfigDir;await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,S1],r);let i=NZ(n.claudeInput,e.hints.tmux,T1);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 ${S1} from ${t} and typed /reload-plugins into ${i.pane}`}const A1=new Set([ya,u1,...Mt]);function j1(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function M1(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Fe(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${j_.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=L1(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${j_.statusline.label} off and on again`);let s=N1(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=y1(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=j1(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])=>A1.has(e)),m=(e,t)=>Re(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...h1(t)]});if(r.terminate(i.pid),!await r.exited(i.pid,15e3))throw Error(`Claude Code in ${t.pane} did not exit within ${15e3/1e3} s of SIGTERM, so it was not restarted under the attach launcher`);let h=(e,n)=>Error(`Claude Code in ${t.pane} exited, but ${e}, so it was not started again — start it with \`${n}\``),g=P1(e,r.presence(e.transcript)),_=g.kind===`unchecked`?{kind:`resume`,sessionId:e.sessionId}:g,v;try{v=await r.paneDir(t,i.parent)}catch(e){throw h(`the directory it was started in could not be read (${e.message})`,m(_1(null,i.cwd),_))}let y=m(_1(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}\`, ${F1[g.kind](e.sessionId)}, and its statusline follows lane B`}function N1(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function P1(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const F1={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},I1={"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 L1(e){let t=DZ(e);return t.kind===`ready`?AZ(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:OZ(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:I1[t.kind]}const R1={switches:Object.fromEntries(M_.map(e=>[e,!1])),revision:0};var z1=class{seen=new Map;queued=new Map;constructor(e){this.deps=e}observe(e,t,n){let r=this.seen.get(e.sessionId)??R1;this.seen.delete(e.sessionId),this.seen.set(e.sessionId,{switches:t,revision:n});for(let[e]of this.seen){if(this.seen.size<=1024)break;this.seen.delete(e)}if(r.revision!==n)for(let n of M_){if(r.switches[n]===t[n])continue;let i=t[n];this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,n,i)))}}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n){let r=`(session=${e.sessionId})`,i=i=>{let a=`lane: ${t} ${n?`on`:`off`}: ${i instanceof Error?i.message:String(i)}`;this.deps.log(`warn`,`${a} ${r}`),oY(this.deps.state,e.sessionId,a,this.deps.now())},a;try{a=O1[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return i(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${a.said} ${r}`),a.kind===`underway`?a.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${r}`),i):Promise.resolve()}};function B1(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 V1(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function H1(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function U1(e,t,n){let r=B1(`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 W1=2e3;function G1(e,t,n){let r=PU(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function K1(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 q1(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 J1=`#{pane_id} #{${w1}}`;function Y1(e,t){return e.split(`
|
|
505
|
+
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const X1=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Z1(e,t,n){for(let r of TY(wY(e),t)){if(r.command.split(` `).some(e=>X1.test(e)))return!0;if(r.pid===n)return!1}return!1}const Q1=[`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(`
|
|
506
|
+
`);async function $1(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=K1(`reading process ${e}'s arguments`,await lt({bin:`python3`,args:[`-c`,Q1,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function e0(e,t){return K1(e,await lt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function t0(e){let t=await FU(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 e0(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function n0(e){let{panePid:t,cwd:n,foreground:r}=await t0(e),i=await e0(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await $1(r),o=wY(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:Z1(i,r,t)}}function r0(e){let{CLAUDE_CONFIG_DIR:t,...n}=process.env;return e===void 0?n:{...n,CLAUDE_CONFIG_DIR:e}}function i0(e){return{claudeInput:RZ(),barPanes:e=>Y1(G1(e,[`list-panes`,`-a`,`-F`,J1]),e.pane),openBarPane:(e,t,n)=>{let r=G1(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 G1(e,[`set-option`,`-p`,`-t`,r,w1,e.pane]),r},closePane:(e,t)=>void G1(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void K1(`claude ${e.join(` `)}`,await lt({bin:`claude`,args:[...e],env:r0(t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:pB,paneClaude:n0,paneDir:async(e,t)=>{let n=Date.now()+W1;for(;;){let r=await t0(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 ${W1/1e3} s`);await ge(100)}},launcherNode:e=>U1(e,e=>V1(e,p.constants.X_OK),H1),onPath:(e,t)=>{let n=B1(e,t,e=>V1(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await ge(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await lt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?q1(r.stdout):null;return i===null?(K1(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Mo(e);){if(Date.now()>n)return!1;await ge(100)}return!0},typeShellLine:(e,t)=>void G1(e,IZ(e.pane,`cc-candybar-lane`,[]),t)}}function a0(e,t){return M_.filter(n=>e[n]&&j_[n].elsewhere!==null&&t.has(n))}function o0(e,t){let n=`the bar is drawn in ${t.map(e=>j_[e].elsewhere).join(` and `)}`,r=Hr([{verb:Dr,args:[e,...t.map(e=>j_[e].setting)]}]);return{channels:[{severity:cy,message:n,lines:[[ly(n,Hr([{verb:gr,args:[n]}])),ly(`[⟲ draw it here]`,r)]]}]}}const s0={order:-1/0,text:null,failure:null};var c0=class{synced=new Map;constructor(e){this.dir=e}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??s0;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??s0;return n.text===t?n.failure===null?{kind:`file`,path:this.pathFor(e)}:{kind:`unavailable`,reason:n.failure}:{kind:`unavailable`,reason:`the file holds another render's text until the session's next statusline request`}}forgetOldestClean(){let e=0;for(let t of this.synced.values())t.text===null&&t.failure===null&&e++;for(let[t,n]of this.synced){if(e<=256)return;n.text!==null||n.failure!==null||(this.synced.delete(t),e--)}}write(e,t){let n=this.pathFor(e);try{return t===null?p.rmSync(n,{force:!0}):(p.mkdirSync(this.dir,{recursive:!0,mode:448}),p.writeFileSync(n,t,{mode:384})),null}catch(e){return`${n}: ${e.message}`}}reset(){this.synced.clear();try{return p.rmSync(this.dir,{recursive:!0,force:!0}),null}catch(e){return`${this.dir}: ${e.message}`}}};function l0(e,t){for(let n of Object.entries(t))e.push(n)}const u0={ok:`info`,"bad-request":`warn`,threw:`error`};function d0(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,w(e.error)]]}}function f0(e,t,n){let r=[...e,[`took`,`${n}ms`],[`outcome`,t.kind],...d0(t)];return{level:u0[t.kind],line:`render${r.map(([e,t])=>` ${e}=${BM(t)}`).join(``)}`}}const p0=new Cq,m0=new pZ,h0=new xj,g0=i(import.meta.url),_0=CX(gt());st(p0.launchStats);const v0=new pO({counters:p0,logger:M}),y0=$U({watchers:v0,logger:M}),{gitProvider:b0,usageStore:x0,mementoProvider:S0}=y0,C0=new Eq,w0=new FJ(C0,M),T0=new iY,E0=new Wv,D0=[t.execPath,...t.execArgv],O0=new z1({edge:i0(e=>A0.following(e)),host:{bundle:g0,node:D0,socket:vt(),preload:$a(g0)},state:C0,log:M,now:()=>FO(new Date),defer:e=>void pe(e)}),k0=new l1({edge:{run:(e,t,n)=>FU({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>PU({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>A0.subscribe(e,t),sessionInPane:(e,t)=>A0.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${je(vt())}`,...[...D0,g0].map(je),`url-handle`].join(` `),owner:vt(),defer:e=>void pe(e),log:M}),A0=new y$({render:(e,t)=>_2(e,t),watch:(e,t)=>(0,Db.reaction)(()=>C0.revision(e),t,{scheduler:e=>pe(e)}),lanes:e=>y2(e),shown:e=>j0.shown(e.hints.tmux),watching:()=>j0.follow(),periods:f$,now:()=>performance.now(),log:M}),j0=new E$({listPanes:e=>FU({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,x$]),listClients:e=>FU({socket:e},`frames.visibility`,[`list-clients`,`-F`,S$]),sockets:()=>new Set(A0.watched().flatMap(({req:e})=>M0(e))),onAnswer:(e,t)=>k0.answered(e,t),onChange:e=>A0.wakeWhere(t=>M0(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function M0({hints:{tmux:e}}){return e==null?[]:[e.socket]}const N0=new c0(At()),P0=new xq({gitService:b0,sessionState:C0,watchers:v0,log:M},{budgetBytes:()=>(q0(),dq(B0)),observers:{onReload:e=>M(`info`,`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`)}}),F0=60*1e3,I0=mH({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:F0,stat:p.statSync,exit:()=>Q0(0),log:M}),L0=dH({entryUrl:import.meta.url,intervalMs:F0,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>I0.checkNow(),log:M});let R0=null,z0=null,B0=0;function V0(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),Q0(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),Q0(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),Q0(0)});try{J0(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),Q0(1);return}R0=Oo(t.pid);let e=Ro(Bo(R0));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Q0(1);return}z0=e.registryPath,p.mkdirSync(_t(),{recursive:!0}),xt(vt()),C0.useStorage(new Oq(wt(),500,M)),w0.useStorage(nY(Tt(),M)),jo({anchor:Ao(t.env),isAlive:Mo,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),Q0(0)}}),H0(E.createServer({allowHalfOpen:!1},e=>{$0(e)}),vt(),!1)}function H0(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),Q0(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}U0(e,n)}),e.listen(n,()=>W0(n))}function U0(e,n){let r=vo(yo(St(n)),(e,t)=>Do(e,t,{readStartTime:Eo,pidAlive:Mo}));if(r.kind===`attach-and-exit`){M(`info`,`EADDRINUSE: ${r.reason} — exiting`),t.exit(0);return}M(`warn`,`EADDRINUSE: ${r.reason} — unlinking stale socket and rebinding`);try{p.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`){M(`error`,`cannot unlink stale socket ${n}: ${e.message}`),Q0(1);return}}H0(e,n,!0)}function W0(e){let n=So(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Q0(0);return}Y0(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${Nn(se.getHeapStatistics().heap_size_limit)}MB memoryLimit=${Nn(B0)}MB`),nr();let r=N0.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),I0.arm(),L0.arm(),q0().arm(),G0(e,n.identity)}function G0(e,n){To({bound:n,myPid:t.pid,readIdentity:()=>So(e),readLease:()=>yo(St(e)),shutdown:e=>Q0(e),log:M}).arm()}let K0=null;function q0(){if(K0===null)throw Error(`daemon: limits not yet established`);return K0}function J0(e){B0=Pn(e),K0=Vn(qn(p0.startedAt.getTime(),e=>Q0(e),{limitBytes:B0}))}function Y0(e){let n=bo(St(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:R0});n!==null&&M(`warn`,`lease write failed: ${n}`)}let X0=0,Z0=!1;function Q0(e){if(!Z0){Z0=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);try{k0.restoreAll(),b0.close()}catch(e){M(`warn`,`gitService close failed: ${e.message}`)}try{x0.close()}catch(e){M(`warn`,`usageStore close failed: ${e.message}`)}try{v0.closeAll()}catch(e){M(`warn`,`watcherRegistry close failed: ${e.message}`)}try{C0.flush()}catch(e){M(`warn`,`sessionState flush failed: ${e.message}`)}xo(Ct(),t.pid),z0!==null&&zo(z0,t.pid,Io,e=>p.unlinkSync(e)),t.exit(e)}}function $0(e){X0++,p0.inFlight=X0;let t=!1,n=!0,r=()=>{n&&(n=!1,X0=Math.max(0,X0-1),p0.inFlight=X0)},i=(n,r,i)=>{if(t){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}t=!0;let a=r===null?void 0:()=>Q0(r);try{e.end(Zt(n),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},a=!1,o=setTimeout(()=>{a=!0,p0.requestsTimedOut++,i({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,e2)},200),s=$t(e=>{s2(e,()=>a).then(e=>e.kind===`reply`?i(e.resp,e.exitAfterFlush,e.delivered):c(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${w(e)}`),i(i2(e),null,e2)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),i({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,e2)}),c=(n,i)=>{if(t||e.destroyed)return;clearTimeout(o),r(),e.off(`data`,s);let a=b$(e),c=A0.subscribe(n,{lane:i,frame:(e,t)=>a(Qt(LH[i](e,t))),refused:t=>e.end(Zt(t)),drawing:()=>!0});t=!0,e.on(`close`,c)};e.on(`data`,s),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(o),r()})}const e2=()=>{},t2=e=>({resp:e,exitAfterFlush:null,delivered:e2}),n2=e=>({kind:`reply`,...e}),r2={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},i2=e=>({ok:!1,error:e instanceof Error?e.message:w(e),code:`RENDER_FAILED`,daemonV:3}),a2=(e,t)=>n2(t2({ok:!1,error:t,code:e,daemonV:3}));function o2(e){if(typeof e.sessionId!=`string`||e.sessionId===``)return a2(`BAD_REQUEST`,`subscribe needs a non-empty string sessionId`);if(e.lane===void 0)return a2(`VERSION_MISMATCH`,`this client's subscribe names no lane (${M_.join(`, `)}): it predates the lane toggles — update it`);let t=z_(e.lane);return t===null?a2(`BAD_REQUEST`,`subscribe needs a lane, one of ${M_.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:e.sessionId,lane:t}}async function s2(e,t){return!e||typeof e!=`object`||typeof e.v!=`number`?a2(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?o2(e):typeof e.kind!=`string`||!Object.hasOwn(r2,e.kind)?a2(`BAD_REQUEST`,`unknown kind`):n2(await c2(e,t)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:e2})}async function c2(e,t){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:e2};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return t2(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:A0.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return t2({ok:!0,stats:p0.snapshot({gitCache:b0.getStats(),usageCache:x0.getStats(),transcriptReads:ua(),renderCache:P0.stats,effectCache:E0.getStats(),sessionState:{sessions:C0.size(),observers:C0.observers(),revision:C0.latestRevision()},frameFeeds:A0.getStats(),tmuxStatus:k0.stats(),watchersActive:v0.size(),nextRestartReason:q0().describeNextRestart(),handlerProbes:m0.list(),clients:h0.list(FO(new Date)),bundle:g0,daemon:q0().serving(),doctorStores:wX(_0)})});if(e.kind===`render`){let n=new Date,r=FO(n),i=n.getTime(),a=[],o=++p0.requestsTotal,s=b2(e),c=(e,t)=>h0.see(e.hookData.session_id,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:_j(e.hookData),frame:t},r,o);s.ok&&(c(s.req,`drawing`),A0.note(s.req.hookData.session_id,s.req,o));let l=s.ok?await E2(s.req,o,r,a).then(({answer:e,motion:t,clickShown:n})=>(c(s.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?e2:()=>sY(C0,s.req.hookData.session_id,n)}),e=>(c(s.req,`failed`),{outcome:{kind:`threw`,error:e},resp:i2(e),delivered:e2})):x2(s.problems);l.outcome.kind!==`ok`&&p0.requestsErrored++,l0(a,{timedOut:t()?`Y`:`N`});let{level:u,line:d}=f0(a,l.outcome,Date.now()-i);return M(u,d),{resp:l.resp,exitAfterFlush:null,delivered:l.delivered}}if(e.kind===`click`)return t2(h2(e.verb,e.value,{via:`link`,handler:Xt(e.clientVersion)}));if(e.kind===`debug`){if(!u$(e.what))return t2({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${l$.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=P0.firstState(),n=t===null?null:{store:t.store,registry:t.registry,config:t.config,compiled:t.compiled,lastRenderBySegment:e.what===`segments`?p2(t.lastRenderCellsBySegment,t.config.globals.colorCompatibility??lv(`colorCompatibility`)):f2};return t2({ok:!0,debug:QQ(e.what,n)})}throw Error(`no reply for request ${w(e)}`)}function l2(e,t){let{tokens:n}=T({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:Nz(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const u2={sessionState:C0,dlog:M,applyUpdate:()=>L0.act(),doctor:PX(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];P0.reload(...t);let n=P0.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:_0,probes:m0,clients:h0,bundle:g0,serving:()=>q0().serving(),memento:S0,claudeInput:RZ(),history:w0,navigation:T0,configFor:e=>P0.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>P0.reload(e.projectDir,e.cwd,e.configFile??void 0)};u2.reloadConfig;const d2={endcaps:lv(`endcaps`),colorCompatibility:lv(`colorCompatibility`),wrap:lv(`autoWrap`),padding:lv(`padding`),width:1/0},f2=new Map;function p2(e,t){let n=new Map;for(let[r,i]of e)n.set(r,ry(i,{...d2,colorCompatibility:t}));return n}const m2={...y0,history:e=>w0.depth(e),feeds:e=>A0.feedsOf(e)};function h2(e,t,n){if(e===`tmux-status-click`)return g2(t);let r=WQ.get(e);if(!r)return{ok:!1,error:`unknown click verb: ${e}`,code:`BAD_REQUEST`,daemonV:3};try{return r(t,{...u2,arrival:n}),{ok:!0,output:``}}catch(e){let t=e instanceof J?`BAD_REQUEST`:`RENDER_FAILED`;return{ok:!1,error:String(e instanceof Error?e.message:e),code:t,daemonV:3}}}function g2(e){let n=e=>({ok:!1,error:e,code:`BAD_REQUEST`,daemonV:3}),r=k0.linkAt(e);if(r.kind===`refused`)return n(r.reason);if(M(`info`,`tmux-status: click ${JSON.stringify(r.url)}`),r.url.startsWith(`cc-candybar://`)){let e=fo(r.url);return e.verb===`tmux-status-click`?n(`a status-line link names another status-line click`):h2(e.verb,e.value,{via:`tmux-status`})}let i=ut({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[r.url],category:`click.open`});return i.ok?{ok:!0,output:``}:{ok:!1,error:`opening ${r.url} failed (${i.error??i.reason})`,code:`RENDER_FAILED`,daemonV:3}}async function _2(e,t){let n=new Date,r=[];try{let{drawn:i,motion:a,lanes:o}=await S2(e,FO(n),r,{by:`feed`,fps:t}),s=N0.linkFor(e.hookData.session_id,w2(i)),c=e.hookData.session_id,l=C2(i,s);return{resp:{ok:!0,output:l},statusline:{ok:!0,output:D2(c,i,s,l,a0(o,A0.following(c)))},moves:a===`moves`,failure:null}}catch(e){let{level:t,line:i}=f0(r,{kind:`threw`,error:e},Date.now()-n.getTime()),a=i2(e);return{resp:a,statusline:a,moves:!1,failure:{level:t,line:`frame ${i}`}}}}function v2(e,t){return sV(t.config,t=>C0.get(e,t),e=>t.authoredRoots.has(e))}function y2(e){try{var t=na();let n=e.hookData.session_id,r=nQ(e.requested,C0,n);return aV(v2(n,t.u(P0.hold(r.projectDir,r.cwd,r.configFile??void 0)).state))}catch(e){t.e=e}finally{t.d()}}function b2(e){let{report:t}=JQ(e.hookData);for(let e of t.unknownTopLevelFields)M(`info`,`schema: unknown field '${e}' — Anthropic may have added it`);let n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);if((typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`),n.length>0)return{ok:!1,problems:n};let r=zt(e),{configFile:i,refusedArgs:a}=l2(e.args,e.cwd);return{ok:!0,req:{...e,hints:r,rateLimits:gj(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:i??r.configEnv??null},refusedArgs:a}}}const x2=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:e2});async function S2(e,t,n,r){try{var i=na();l0(n,{sid:e.hookData.session_id,at:t.toFixed(3)});let a=e.hookData.session_id,o=e.hints,s=Bt(e,o),c=Vt(s);l0(n,{termCols:String(o.termCols??`?`),termRows:String(o.termRows??`?`),refused:s.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:o.client?.kind??`unreported`,rateLimits:e.rateLimits});let l=nQ(e.requested,C0,a),{entry:u,state:d}=i.u(P0.hold(l.projectDir,l.cwd,l.configFile??void 0)),f=o.termCols,p=d$(f??120),m=iy(o.termRows);l0(n,{width:String(p)});let h=t=>C0.get(e.hookData.session_id,t),g=v2(a,d),_=aV(g);l0(n,{lanes:M_.filter(e=>_[e]).join(`,`)||`-`}),O0.observe({sessionId:a,hints:o,origin:l,transcript:e.hookData.transcript_path,answered:mj(e.hookData)},_,w0.revision(a)),k0.observe(a,o.tmux,_.tmuxStatus);let v=await EW(e.hookData,t,{...m2,holds:d.registry.holds,navigation:e=>T0.depth(e,C0,UV(d.config))},e.cwd,d.neededInputPaths(g.preset),g,o,{...AV(d.config,d.fileHeldSettings,h),configPath:u.configLayers.includes(u.configHome)?u.configHome:null});l0(n,{prompts:String(v.metrics?.messageCount??`-`),nonPrompts:String(v.metrics?.nonPrompts??`-`),pr:lW(v.git),feeds:m$(v.feeds)});let y=[],b=oW(g,p),ee=E0.of(a),x=QK(d.config,d.compiled,d.store,d.registry,{...v,drawing:r},t,b,{perSegmentSink:d.lastRenderCellsBySegment,onRenderWarning:e=>y.push(e)},{...g,effects:ee}),S=lY(C0,a,t,r.by),te=S.kind===`held`||S.kind===`owed`?S.error:null,ne=te?.text??null,C=[Ut(e.refusedArgs),c,u.lastError,ne].filter(Boolean).join(`
|
|
507
|
+
`),re=L0.notice({sessionId:a,dismissed:C0.get(a,YV),enabled:g.updateNotice}),ie=u.lastError===null?null:u.failedFile,ae=[...u.lastWarning===null?[]:[{kind:`load`,message:u.lastWarning}],...y],w=uy(C,re,ae.map(e=>e.message).join(`
|
|
508
|
+
`)),T=b0.getStats(),oe=x0.getStats(),E=ee.lastFrame(),se=E.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ce=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,le=ae.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return l0(n,{git:`${T.size}/${T.hits}h/${T.misses}m`,usage:`${oe.size}/${oe.hits}h/${oe.misses}m`,effect:E.effect,effectT:E.t.toFixed(3),effectRows:`${E.made}made/${E.reused}reused`,effectOwn:se,fadeBasis:E.basis,stateRev:String(E.revision),fades:ce(E.fades),leaves:ce(E.leaves),motion:x.motion,err:C?`Y`:`N`,clickError:S.kind===`none`?`-`:S.kind,upd:String(re.length),warn:le}),{drawn:{body:x.text,diagnostics:w,failedConfigFile:ie,geometry:{width:p,rowCap:m,colorCompatibility:g.colorCompatibility}},motion:x.motion,clickShown:te,lanes:_}}catch(e){i.e=e}finally{i.d()}}function C2(e,t){return py(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
|
|
509
|
+
`}function w2(e){return e.diagnostics===null?null:fy(e.diagnostics)}function T2(e){let t=e.hookData.session_id,{client:n,...r}=e.hints,i=JSON.stringify(r);C0.get(t,`client-hints`)!==i&&C0.set(t,OQ,i);let a=rQ(e.requested);C0.get(t,`render-origin`)!==a&&C0.set(t,tQ,a)}async function E2(e,t,n,r){T2(e);let{drawn:i,motion:a,clickShown:o,lanes:s}=await S2(e,n,r,N_),{link:c,failure:l}=N0.sync(e.hookData.session_id,t,w2(i));l0(r,{dumpFailed:l===null?`-`:JSON.stringify(l)});let u=C2(i,c),d=e.hookData.session_id,f=a0(s,A0.following(d)),p=D2(d,i,c,u,f),m=bj(e.hints.client??null)===`statusline`;return l0(r,{handoff:(m?f:[]).join(`,`)||`-`}),{answer:m?p:u,motion:a,clickShown:o}}function D2(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:C2({...t,body:my(o0(e,[a,...o]),t.geometry)},n)}const O2={connectMs:200,budgetMs:500};async function k2(e,n){let r=n.includes(`--json`),i=await A2(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${ln(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
510
|
+
`);return}t.stdout.write(j2(i.value))}function A2(e){return nn({kind:`debug`,what:e},O2,e=>`debug`in e?e.debug:void 0)}function j2(e){switch(e.what){case`vars`:return M2(e.vars);case`segments`:return N2(e.segments);case`config`:return P2(e.config);default:return e}}function M2(e){if(e.length===0)return`no variables (DSL not active)
|
|
511
|
+
`;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?``:` ${I2(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${F2(a.value)}${e}${o}`)}return t.join(`
|
|
512
512
|
`)+`
|
|
513
|
-
`}function
|
|
513
|
+
`}function N2(e){if(e.length===0)return`no segments (DSL not active)
|
|
514
514
|
`;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(`
|
|
515
515
|
`)+`
|
|
516
|
-
`}function
|
|
516
|
+
`}function P2(e){return e===null?`config: DSL not active
|
|
517
517
|
`:JSON.stringify(e,null,2)+`
|
|
518
|
-
`}function
|
|
518
|
+
`}function F2(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function I2(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function L2(){let e=z2();return e===null?null:p.readFileSync(e,`utf-8`)}function R2(){let e;try{e=L2()}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 z2(){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 B2=5e3;function V2(e,t,n){let r=`/home/tester`,i=Math.floor(n),a=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,o={current_dir:`${r}/code/cc-candybar/src`,project_dir:`${r}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:a,version:`1.15.0`,home:r,cwd:`${r}/code/cc-candybar/src`,transcript_path:`${r}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:o,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,timeSinceCommit:780},session:{cost:.39,tokens:241400},today:{cost:12.5,tokens:34e5},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:i+2*3600},weekly:{percentage:21,resetsAt:i+5*86400},cache:{expiresAt:i+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:yN(4e5,1e6),...sW(e),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:bv(()=>!0),themeDefault:e.theme.kind===`decided`?{differs:!0,theme:e.theme.name}:{differs:!1},resumeCommand:aW(o,a,void 0),configPath:t??`${r}/.config/cc-candybar/config.json5`}}function H2(e,t){let n=_B(e,e),r=bB(n);return r!==null&&t.push(r),n.kind===`chain`?n.layers:[]}async function U2(e,n=t.cwd()){let r=[],i=Nz(n,e)??null,a=i===null?H2(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=SB(n,n);o!==null&&r.push(o);try{return{kind:`clean`,layers:a,warnings:r,rendered:await K2(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 Jg&&r.push(...e.warnings),{kind:`fatal`,layers:a,message:e instanceof Jg||e instanceof Error?e.message:String(e),warnings:r})}}async function W2(e,t,n){let r=AB(e,$B,{entered:()=>{},warned:e=>n.push(...e)},{projectDir:t,cwd:t}),{config:i}=r,a=new uq,o=new ak(a,i.globals.default_empty_value??``,void 0,new Eq);try{let s=RK(i,o,{cwd:t});n.push(...s.loadWarnings);let c=await o.settled(B2);return c.length>0&&n.push(`source${c.length===1?``:`s`} still running after ${B2} ms, rendered with fallback values: ${c.join(`, `)}`),{layers:e,droppedPlugins:[...r.installed.dropped,...r.layers.flatMap(e=>e.plugins.dropped)],config:i,compiled:s,store:a,registry:o}}catch(e){throw o.dispose(),e}}function G2({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set;return{rendered:ZK(t,n,r,i,V2(a,e.at(-1)??null,s),s,oW(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}}},a),failures:c,advisories:l}}async function K2(e,t,n){let r=await W2(e,t,n),{config:i}=r,a=FO(new Date);try{let e=uH();try{UV(i),eI(i)}finally{e()}let t=Uy(null,i.globals.preset,i.presets),o=(e,t)=>{let n=sV(i,t=>t===`preset`?e:null,()=>t),o;try{o=G2(r,n,200,a)}catch(e){o={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...o}},s=o(t,!1),c=[s,o(t,!0),...Hy(i.presets).filter(e=>e!==t).flatMap(e=>[o(e,!1),o(e,!0)])],l=e=>{let n=new Map;for(let t of c)for(let r of e(t)){let e=n.get(r)??new Map;e.set(t.preset,(e.get(t.preset)??new Set).add(t.customized)),n.set(r,e)}return[...n].map(([e,n])=>n.get(t)?.has(!1)?e:`${e} (under ${[...n].map(([e,n])=>[...e===t?[]:[`preset "${e}"`],...n.has(!1)?[]:[`.preset.customized = true`]].join(`, `)).join(`; `)})`)};n.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=s.rendered,f=r.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
|
|
519
519
|
`)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
|
|
520
|
-
`));return d}finally{r.registry.dispose()}}function
|
|
521
|
-
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${
|
|
522
|
-
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
523
|
-
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:
|
|
520
|
+
`));return d}finally{r.registry.dispose()}}function q2(e){return e.map(e=>`warning: ${e}\n`).join(``)}function J2(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:q2(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:q2(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 Y2=`--render`,X2=`Usage: cc-candybar check [${Y2}] [config-file]\n`;function Z2(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==Y2);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${X2}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${X2}`}:{kind:`run`,target:n[0],render:t.includes(Y2)}}async function Q2(e){let n=Z2(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:J2(await U2(n.target??d1(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const $2=/^[a-z][a-z0-9+.-]*:\/\//i,e4=/^[^@\s/]+@[^:\s/]+:/,t4=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function n4(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function r4(e,t,n){let r=Mz(t,e);if(n(r))return{kind:`path`,dir:r};if($2.test(e)||e4.test(e))return{kind:`git`,url:e,shown:n4(e)};let i=t4.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 i4(e,t){let n=s.join(e,cB),r=dB(n);if(`error`in r)throw Error(`${t}: could not list ${cB}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${cB}/<name>/${Iz}`);return r.folders.map(e=>s.join(n,e,Iz))}function a4(e,t,n){let r=(n,...r)=>{let i=ut({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
|
|
521
|
+
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${cB}/`)}function o4(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 a4(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function s4(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 c4(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,Iz),s.join(t,Iz));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function l4(e,t,n){let r=i4(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,Iz))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=OB(a.map(e=>s.join(e,Iz)),$B,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(cB,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,cB))}`).join(`
|
|
522
|
+
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:s4(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)c4(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,Iz),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function u4(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=r4(n,process.cwd(),ZO);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=o4(i,t=>l4(t,sB(),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 d4(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 f4=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function p4(e,t,n){return{termCols:d4(e.COLUMNS,n.columns),termRows:d4(e.LINES,n.rows),ssh:f4.some(t=>(e[t]??``)!==``),tmux:fj(e),configEnv:d1(e,t),claudeConfigDir:ba(e,t),mementoEnv:Nt(e,t),terminalEnv:Ft(e)}}function m4(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function h4(e){let t=nZ(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=m4(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:tn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const g4=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},_4=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 v4(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 y4(e){let t=nZ(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=v4(n?.postMortems,e=>Array.isArray(e)&&e.every(g4)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&_4(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 b4(e,t,n){let r=nZ(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=m4(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 x4=e=>yj.includes(e.role),S4=e=>b4(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&hj.includes(e.rateLimits),`the rate-limit windows they carried`),C4=e=>b4(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`),w4=e=>b4(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&x4(e)&&vj.includes(e.frame),`what they drew and from which project`),T4=e=>b4(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&x4(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function E4(e,t,n){let r=e.doctorStores?.[t],i=v4(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 D4(e){let t=nZ(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:E4(e,`marks`,pY),clicked:E4(e,`clicked`,gY),postMortemsRead:E4(e,`postMortemsRead`,vX)}}async function O4(){let e=await tZ();if(e.kind!==`ok`){let t={kind:`failed`,reason:ln(e).split(`
|
|
523
|
+
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:h4(e.value),rateLimits:S4(e.value),transcripts:C4(e.value),frames:w4(e.value),widths:T4(e.value),serving:y4(e.value),stores:D4(e.value)}}const k4=` (fix: click the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,A4=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Jr} by default) › 🧰 tools › 🩺 doctor`;function j4({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:k4}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${A4}\n`)}function M4(e){let t={sessionState:new Eq},n=yq(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??bq(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 N4(e,t,n){return n.kind===`failed`?n:SX(e,n.value.bundle,xY(t,n.value.clients).map(({client:e})=>e))}function P4(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:xY(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function F4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:xY(e,t.value).map(e=>e.transcript)}}function I4(e,t){return t.kind===`failed`?t:{kind:`ok`,value:CY(e,t.value)}}function L4(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:XX(e.sessionId,xY(e,t.value))}async function R4(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=p4(r,i,a()),u=bY(r.CLAUDE_CODE_SESSION_ID);s={...ZX(e,l,{projectDir:SY(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:Nz(i,o)??d1(r,i)??null},()=>null,c.serving,P4(u,c.rateLimits,xa(l.claudeConfigDir)),F4(u,c.transcripts),u,I4(u,c.frames),L4(u,c.widths,l.termCols??null),c.stores),urlHandler:await vZ(t),install:N4(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=LM(s);return{stdout:c.map(j4).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function z4(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new _e(e),{columns:r}=n;return n.destroy(),{columns:r}}async function B4(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
|
|
524
524
|
Usage: cc-candybar doctor [config-file]
|
|
525
|
-
`),t.exit(2));let n=t.cwd(),r=await
|
|
526
|
-
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const
|
|
527
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
525
|
+
`),t.exit(2));let n=t.cwd(),r=await R4(PX(M4),SZ(),O4,t.env,n,z4,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function V4(e){return!e.ok&&e.code!==`RENDER_FAILED`}function H4(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=E.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Zt(c))),s.on(`data`,$t(e=>{let t=e;V4(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 U4(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function W4(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 G4(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=H4(e,t,n,e=>{s=U4(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=W4(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&&Jn();let e=s;s=U4(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function K4(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function q4(e,n){let{values:r,tokens:i}=T({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=z_(r.lane);c===null&&(s(`--lane needs one of ${M_.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=b$(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{K4(p,e)&&t(),p=e},h=async e=>{let r=await mn(e,a,o,{...p4(t.env,o,t.stderr),client:Lt(`frames`,n)});r.kind!==`ok`&&(s(ln(r)),r.kind===`transient`&&Jn())},g=e=>{f?.close(),f=G4(vt(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of ve({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function J4(e){let t=e.replace(/\n+$/,``).split(`
|
|
526
|
+
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const Y4=5e3,X4=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function Z4(e,t,n,r){let i=e.split(`
|
|
527
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?w$(e,C$(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function Q4(e,t){let[n,r]=await Promise.all([FU(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,x$]),FU(e,`bar-pane.tmux`,[`list-clients`,`-F`,S$])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:Z4(n.stdout,r.stdout,t,e.pane)}:r:n}function $4(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>Y4)throw Error(`tmux has not answered for ${Y4/1e3} s: ${t.reason}`)}}function e3(e){let{positionals:t}=(()=>{try{return T({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${X4}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(X4);return{pane:n}}async function t3(e){try{return await n3(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function n3(e){let{pane:n}=e3(e),r=fj(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 Q4(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=$4(),f=async()=>{if(a.kind!==`shown`)return;let e=J4(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await FU(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:G4(vt(),e,`pane`,{frame:e=>n(vH(pn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=$4();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await hn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${vt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(Jn(),u=``),c=ln(e))}h(),await ge(500);let e=await Q4(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const r3=i(import.meta.url),i3=e=>e.some(e=>t.argv.includes(e));function a3(){console.log(lj);let e=$a(r3),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 ${j_.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Re(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const o3={install:async e=>{await go(e,r3),t.exit(0)},"install-url-handler":async()=>{uo(r3),t.exit(0)},"url-handle":async e=>{await po(e[0])},daemon:async()=>{V0()},"daemon-stats":async e=>{await eZ(e),t.exit(0)},frames:async()=>{await q4(t.argv,r3)},check:async e=>{await Q2(e)},lint:async e=>{await Q2(e)},plugin:async e=>{t.exit(u4(e))},schema:async()=>{R2()},doctor:async e=>{await B4(e)},"bar-pane":async e=>{t.exit(await t3(e))},...Object.fromEntries(l$.map(e=>[e,async n=>{await k2(e,n),t.exit(0)}]))};async function s3(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(o3,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),i3(qA.help)&&(a3(),t.exit(0)),i3(qA.version)&&(console.log(`cc-candybar ${qe}`),t.exit(0)),n!==null){await o3[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
528
528
|
|
|
529
529
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
530
530
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -540,4 +540,4 @@ Add to ~/.claude/settings.json:
|
|
|
540
540
|
Run with --help for more options.
|
|
541
541
|
|
|
542
542
|
To test output manually:
|
|
543
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
543
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),D(`Working directory: ${t.cwd()}`),D(`Process args:`,t.argv);let r=await o(t.stdin);D(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),a3(),t.exit(1));let i=vH(await mn(r,t.argv.slice(1),t.cwd(),{...p4(t.env,t.cwd(),t.stderr),client:Lt(`node`,r3)}));i.debug!==null&&D(i.debug),i.kick&&Jn(),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)}}s3();export{};
|