@promptctl/cc-candybar 1.160.10 → 1.161.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as T,spawnSync as oe}from"node:child_process";import{inspect as E,parseArgs as se,types as ce}from"node:util";import le from"node:net";import ue from"node:v8";import{open as de,readFile as fe,readdir as pe,stat as me}from"node:fs/promises";import{clearInterval as he,setImmediate as ge,setInterval as _e}from"node:timers";import{get as ve}from"node:https";import{setTimeout as ye}from"node:timers/promises";import{WriteStream as be}from"node:tty";import{createInterface as xe}from"node:readline";var Se=Object.create,Ce=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyNames,Ee=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Oe=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Te(t),a=0,o=i.length,s;a<o;a++)s=i[a],!De.call(e,s)&&s!==n&&Ce(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=we(t,s))||r.enumerable});return e},Ae=(e,t,n)=>(n=e==null?{}:Se(Ee(e)),ke(t||!e||!e.__esModule?Ce(n,`default`,{value:e,enumerable:!0}):n,e));const je=()=>!!process.env.CC_CANDYBAR_DEBUG;function Me(e){return je()?`[DEBUG] ${e()}\n`:``}function D(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}const Ne=(e,t)=>D(t),Pe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Fe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ie(e){return Pe.test(e)?e:Fe(e)}function Le(e){return`${e.dir===void 0?``:`cd ${Ie(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Ie(t)} `).join(``)}${[e.program,...e.args].map(Ie).join(` `)}`}const Re=`cc-extra`;function ze(e){return s.join(s.dirname(e),Re,`src`,`bun-attach.js`)}function Be(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ve=`attach-preload.cjs`;function He(e){return s.join(s.dirname(e),Ve)}function Ue(e,t){return Le({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const We=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ge(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ke(e,t,n=We){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()?Ke(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Ge(r,i)]]})}function qe(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 Je(e){return qe(Ke(e,e))}const Ye=[`Cargo.toml`,`Cargo.lock`,`src`];function Xe(e){return qe(Ke(e,e,e=>Ye.includes(e)))}const Ze=e=>e.slice(0,7),Qe=`1.160.10`;function $e(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function et(){let e=tt();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Qe,digest:e}}function tt(){return`28bdde4cf52fbbaac897b1e942d33157785e6bd309b721f3e6aadf60d0556172`}function nt(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 rt(e,t){try{let n=$e(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Je(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:nt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function it(e,t){return ce.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const at={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},ot=new Map;function st(e){let t=at[e];if(t===void 0)return{allowed:!0};let n=ot.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 ct(e){ot.set(e,Date.now())}function lt(e){return e.env??process.env}function ut(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 dt=null;function ft(e){dt=e}function pt(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function mt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();return dt?.onStart(e.category),new Promise(t=>{let r;try{r=T(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){dt?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(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),dt?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{pt(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:it(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 ht(e){let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();dt?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=oe(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});dt?.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:it(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 dt?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(t,e.cwd)}}}function gt(e){let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();dt?.onStart(e.category);let r=_t(e);return dt?.onEnd(e.category,Date.now()-n),r}function _t(e){let t;try{t=T(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(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=vt(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 vt(e){return yt(e).at(-1)}function yt(e){let t=[e];for(let e=0;e<bt;e++){let e=t[t.length-1],n;try{n=p.lstatSync(e)}catch(e){let{code:n}=e;if(n===`ENOENT`||n===`ENOTDIR`)return t;throw e}if(!n.isSymbolicLink())return t;t.push(s.resolve(p.realpathSync(s.dirname(e)),p.readlinkSync(e)))}throw Error(`${e}: more than ${bt} symbolic links`)}const bt=40;function xt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function St(e=process.env){let t=xt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function Ct(){let e=xt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function wt(){return St()}function Tt(){return process.env.CC_CANDYBAR_SOCKET||Et()}function Et(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Dt(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 Ot(e){Dt(s.dirname(e));for(let t of[e,kt(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function kt(e){return`${e}.lease`}function At(){return kt(Tt())}function jt(){return s.join(St(),`session-state.json`)}function Mt(){return s.join(St(),`settings-history.json`)}function Nt(){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 Pt(){return s.join(St(),`spawn.lock`)}function Ft(){return s.join(St(),`spawn.cooldown`)}function It(){return s.join(St(),`spawn.backoff`)}function Lt(){return s.join(St(),`diagnostics`)}function Rt(e=process.env){return s.join(St(e),`daemon.log`)}const zt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Bt(e){return Object.fromEntries(zt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Vt=[`native`,`node`,`frames`];function Ht(e,t){return{kind:e,bundle:t,source:null}}const Ut=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Wt(e){let t=A(e.termCols),n=A(e.termRows),r=Qt(e.ssh),i=Xt(e.tmux),a=Yt(e.configEnv),o=Yt(e.claudeConfigDir),s=Jt(e.terminalEnv),c=on(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Gt(e,t){return Ut.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function k(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 Kt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function qt(e){let t=Object.keys(Kt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Kt[t](n.join(`, `))]});return t.length===0?null:t.join(`
2
+ import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as T,spawnSync as oe}from"node:child_process";import{inspect as E,parseArgs as se,types as ce}from"node:util";import le from"node:net";import ue from"node:v8";import{open as de,readFile as fe,readdir as pe,stat as me}from"node:fs/promises";import{clearInterval as he,setImmediate as ge,setInterval as _e}from"node:timers";import{get as ve}from"node:https";import{setTimeout as ye}from"node:timers/promises";import{WriteStream as be}from"node:tty";import{createInterface as xe}from"node:readline";var Se=Object.create,Ce=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyNames,Ee=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Oe=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Te(t),a=0,o=i.length,s;a<o;a++)s=i[a],!De.call(e,s)&&s!==n&&Ce(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=we(t,s))||r.enumerable});return e},Ae=(e,t,n)=>(n=e==null?{}:Se(Ee(e)),ke(t||!e||!e.__esModule?Ce(n,`default`,{value:e,enumerable:!0}):n,e));const je=()=>!!process.env.CC_CANDYBAR_DEBUG;function Me(e){return je()?`[DEBUG] ${e()}\n`:``}function D(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}const Ne=(e,t)=>D(t),Pe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Fe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Ie(e){return Pe.test(e)?e:Fe(e)}function Le(e){return`${e.dir===void 0?``:`cd ${Ie(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Ie(t)} `).join(``)}${[e.program,...e.args].map(Ie).join(` `)}`}const Re=`cc-extra`;function ze(e){return s.join(s.dirname(e),Re,`src`,`bun-attach.js`)}function Be(e){return s.join(s.dirname(e),`bun-graph.js`)}const Ve=`attach-preload.cjs`;function He(e){return s.join(s.dirname(e),Ve)}function Ue(e,t){return Le({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const We=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ge(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ke(e,t,n=We){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()?Ke(e,r):[[s.relative(e,r).split(s.sep).join(`/`),Ge(r,i)]]})}function qe(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 Je(e){return qe(Ke(e,e))}const Ye=[`Cargo.toml`,`Cargo.lock`,`src`];function Xe(e){return qe(Ke(e,e,e=>Ye.includes(e)))}const Ze=e=>e.slice(0,7),Qe=`1.161.0`;function $e(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function et(){let e=tt();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Qe,digest:e}}function tt(){return`c8b1fb598e713a325284a7d3860cc7db68e1fa03ab0ebe129906eb28d70ddfe0`}function nt(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 rt(e,t){try{let n=$e(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Je(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:nt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function it(e,t){return ce.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const at={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},ot=new Map;function st(e){let t=at[e];if(t===void 0)return{allowed:!0};let n=ot.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 ct(e){ot.set(e,Date.now())}function lt(e){return e.env??process.env}function ut(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 dt=null;function ft(e){dt=e}function pt(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function mt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();return dt?.onStart(e.category),new Promise(t=>{let r;try{r=T(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){dt?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(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),dt?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{pt(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:it(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 ht(e){let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();dt?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=oe(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});dt?.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:it(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 dt?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(t,e.cwd)}}}function gt(e){let t=st(e.category);if(!t.allowed)return ut(e.category,t.minIntervalMs,t.sinceLastMs);ct(e.category);let n=Date.now();dt?.onStart(e.category);let r=_t(e);return dt?.onEnd(e.category,Date.now()-n),r}function _t(e){let t;try{t=T(e.bin,e.args??[],{cwd:e.cwd,env:lt(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:it(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=vt(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 vt(e){return yt(e).at(-1)}function yt(e){let t=[e];for(let e=0;e<bt;e++){let e=t[t.length-1],n;try{n=p.lstatSync(e)}catch(e){let{code:n}=e;if(n===`ENOENT`||n===`ENOTDIR`)return t;throw e}if(!n.isSymbolicLink())return t;t.push(s.resolve(p.realpathSync(s.dirname(e)),p.readlinkSync(e)))}throw Error(`${e}: more than ${bt} symbolic links`)}const bt=40;function xt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function St(e=process.env){let t=xt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function Ct(){let e=xt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function wt(){return St()}function Tt(){return process.env.CC_CANDYBAR_SOCKET||Et()}function Et(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function Dt(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 Ot(e){Dt(s.dirname(e));for(let t of[e,kt(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function kt(e){return`${e}.lease`}function At(){return kt(Tt())}function jt(){return s.join(St(),`session-state.json`)}function Mt(){return s.join(St(),`settings-history.json`)}function Nt(){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 Pt(){return s.join(St(),`spawn.lock`)}function Ft(){return s.join(St(),`spawn.cooldown`)}function It(){return s.join(St(),`spawn.backoff`)}function Lt(){return s.join(St(),`diagnostics`)}function Rt(e=process.env){return s.join(St(e),`daemon.log`)}const zt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Bt(e){return Object.fromEntries(zt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Vt=[`native`,`node`,`frames`];function Ht(e,t){return{kind:e,bundle:t,source:null}}const Ut=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Wt(e){let t=A(e.termCols),n=A(e.termRows),r=Qt(e.ssh),i=Xt(e.tmux),a=Yt(e.configEnv),o=Yt(e.claudeConfigDir),s=Jt(e.terminalEnv),c=on(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Gt(e,t){return Ut.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function k(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 Kt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function qt(e){let t=Object.keys(Kt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Kt[t](n.join(`, `))]});return t.length===0?null:t.join(`
3
3
  `)}function Jt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=zt.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 Yt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function Xt(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 Zt=1e4;function A(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Zt?Zt:t}function Qt(e){return typeof e==`boolean`?e:void 0}function $t(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var en=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function tn(e){return nn(JSON.stringify(e))}function nn(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function rn(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 en(`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 en(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function an(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=rn(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(tn(t))})}function on(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Yt(n);return Vt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function sn(e,t,n){let r=null;try{r=await fn(Tt(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await an(r,{v:3,...a},i);return un(a.kind,o,n)}catch(e){return dn(e)}finally{r&&r.destroy()}}function cn(e,t){return typeof e==`string`?e:t}function ln(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function un(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=cn(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:ln(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 dn(e){if(e instanceof en||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 fn(e,t){return new Promise((n,r)=>{let i=le.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 pn(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 mn={connectMs:50,budgetMs:150},hn={connectMs:50,budgetMs:200};function gn(e){let t=e.output;return typeof t==`string`?t:void 0}function _n(e){return un(`render`,e,gn)}function vn(e,t,n,r){return sn(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),mn,gn)}function yn(e,t){return sn(()=>({kind:`pane-session`,socket:e,pane:t}),hn,e=>`paneSession`in e?e.paneSession:void 0)}function bn(e,t){return sn(()=>({kind:`click`,verb:e,value:t,clientVersion:Qe}),hn,gn)}let xn=null;function Sn(){if(xn!==null){try{p.closeSync(xn.fd)}catch{}xn=null}}async function Cn(e){let t=await p.promises.stat(e).catch(()=>null);if(xn!==null&&xn.path===e&&t!==null&&xn.id===wn(t))return{held:xn,size:t.size};Sn(),await p.promises.mkdir(s.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>p.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>p.fstat(n,(n,r)=>n===null?e(r):t(n)));return xn={path:e,fd:n,id:wn(r)},{held:xn,size:r.size}}function wn(e){return`${e.dev}:${e.ino}`}function Tn(e,t){return new Promise((n,r)=>p.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function En(e){for(let t=2;t>=1;t--)await p.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await p.promises.rename(e,`${e}.1`).catch(()=>{})}let Dn=[],j=0,On=0,kn=0,An=null,jn=!1;const Mn=[];let Nn=!1,Pn=!1;function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;if(Pn||(Pn=!0,process.on(`exit`,()=>{Nn=!0,Vn(!0,zn)})),Dn.push(n),j+=Buffer.byteLength(n),j>4194304){let e=0;for(;j>4194304/2&&e<Dn.length-1;){let t=Buffer.byteLength(Dn[e]);j-=t,kn+=t,e++}Dn.splice(0,e),On+=e}Nn?Vn(!0,zn):jn||In()}function Fn(){Vn(!1,Bn)}async function In(){jn=!0;try{for(;Dn.length>0;){let e=Ln();An={bytes:Buffer.from(e),state:{kind:`taken`}};try{await Rn(Rt(),An)}catch(t){Sn(),An.state.kind!==`landed`&&Un(e,t)}finally{An=null}}}finally{jn=!1;for(let e of Mn.splice(0))e()}}function Ln(){let e=(On===0?``:`${new Date().toISOString()} [warn] log: ${On} earlier line(s) dropped (${kn} bytes): more than 4194304 bytes were waiting for the disk\n`)+Dn.join(``);return Dn=[],j=0,On=0,kn=0,e}async function Rn(e,t){let{held:n,size:r}=await Cn(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await Tn(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){Sn();let e=await p.promises.stat(n.path).catch(()=>null);e!==null&&wn(e)===n.id&&await En(n.path)}}const zn=1e3,Bn=2e3;function Vn(e,t){let n=An,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=Hn(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Un(n.bytes.toString(),t)}}if(r.length===0&&Dn.length===0)return;let a=Buffer.concat([r,Buffer.from(Ln())]);try{let e=Rt();p.mkdirSync(s.dirname(e),{recursive:!0}),p.appendFileSync(e,a),i!==null&&n!==null&&wn(p.fstatSync(i.fd))===wn(p.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Un(a.toString(),e)}}function Hn(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=p.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Un(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Wn=5e3;function Gn(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 Kn=`/usr/bin/footprint`;function qn(e,t){return e===`darwin`?[Zn(Kn,[`-p`,String(t)]),Zn(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Qn(`/proc/self/smaps_rollup`),Qn(`/proc/self/status`)]:[]}function Jn(e,t){return e===`darwin`?Yn(t,e=>mt({bin:Kn,args:e,timeoutMs:Wn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Yn(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}`}${$n(r.stderr)}`};let i=Xn(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 Xn(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Zn(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=ht({bin:e,args:[...t],timeoutMs:Wn,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}`}${$n(n.stderr)}`}}}}function Qn(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 $n(e){let t=e.split(`
5
5
  `).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const er=`CC_CANDYBAR_RSS_LIMIT_MB`;function tr(e){let t=e[er];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${er} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function nr(e){return tr(e)*2}const rr=1024*1024,N=e=>Math.round(e/rr);function ir(e){return tr(e)*rr}const ar={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function or(e,t){return e>t}function sr(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const cr=.75;function lr(e,t){return e>t*cr}function ur(e,t,n){let{prefix:r,suffix:i}=ar[t];return s.join(e,`${r}${n}${i}`)}function dr(e){for(let t of Object.keys(ar)){let{prefix:n,suffix:r}=ar[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function fr(e){let t=e.limitBytes??1024*rr,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=sr(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${hr(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${pr(s)} > limit ${N(t)} MB (rss ${N(a)} MB, v8 heap ${N(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return gr(e.log,`memory report`,()=>{let t=ur(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),gr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=ur(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),gr(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of _r(e.listArtifacts()).slice(n))for(let n of Object.values(t))gr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&lr(i.charge.bytes,t)?`${pr(i.charge)} approaching limit ${N(t)} MB (v8 heap ${N(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:_r(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 pr(e){return e.kind===`charged`?`${e.measure} ${N(e.bytes)} MB`:`rss ${N(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${N(e.gap)} MB gap`} (standing in: ${e.unread})`}function mr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function hr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${N(e.gap)}MB`:``;return`measure=${mr(e)} charge=${N(e.bytes)}MB rss=${N(t)}MB heap=${N(n)}MB limit=${N(r)}MB${i}`}function gr(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function _r(e){let t=new Map;for(let n of e){let e=s.basename(n),r=dr(e);if(r===null)continue;let{prefix:i,suffix:a}=ar[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(ar);return[...t].sort(([e],[t])=>or(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function vr(e,t,n={}){let r=wt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Jn(process.platform,process.pid),captureMemoryReport:()=>Gn(qn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>ue.writeHeapSnapshot(e),writeLogNow:Fn,listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>dr(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function yr(e={}){if(Fr()!==null)return;let n=e.spawn??Lr,r=Mr();if(r.kind===`contended`){let e=xr();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),br(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),br(n);return}try{br(n)}finally{Pr()}}function br(e){Or()&&Sr(e)}function xr(){try{let e=p.statSync(Pt());return Date.now()-e.mtimeMs}catch{return null}}function Sr(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
@@ -187,18 +187,18 @@ Config tooling:
187
187
  `,1)[0]??``}function VW(e,t){if(e.kind!==`ok`)return e;let n=t(e.value);return n===null?I:F(n)}function HW(e){if(e.kind!==`ok`)return e;let t=e.value.trim();return t?F(t):I}const UW={github:`gh`,gitlab:`glab`};function WW(e){return!e.ok&&e.reason===`spawn-error`&&/ENOENT/i.test(e.error??``)}const GW=/^[A-Za-z]:[\\/]/;function KW(e){let t=e.trim();if(GW.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 qW(e){return KW(e)?.host||null}function JW(e){let t=qW(e);return t?t===`github.com`||t.endsWith(`.github.com`)?`github`:/(^|\.)gitlab\./.test(t)?`gitlab`:null:null}const YW=[`config`,`--local`,`--get-regexp`,`^remote\\..*\\.url$`];function XW(e){let t=RW(`git config --get-regexp remote url`,e,1);return t.kind===`failed`?t:{kind:`ok`,value:t.kind===`ok`?ZW(t.value):[]}}function ZW(e){let t=new Map;for(let n of e.split(`
188
188
  `)){let e=n.match(/^remote\.(.+)\.url\s+(\S.*)$/);if(!e)continue;let r=t.get(e[1])??[];r.push(e[2].trim()),t.set(e[1],r)}return[...t].map(([e,t])=>({name:e,urls:t}))}function QW(e){return e.urls.find(e=>rG(e)!==null)??e.urls[0]??null}function $W(e){return e.find(e=>e.name===`origin`)??e[0]??null}function eG(e){let t=$W(e);return t?QW(t):null}function tG(e){let t=$W(e);return t?t.urls.find(e=>JW(e)!==null)??QW(t):null}function nG(e){let t=(KW(e)?.path??e.replace(/[\\/]+$/,``)).split(`/`);return(t[t.length-1]??``).replace(/\.git$/,``)||null}function rG(e){let t=KW(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 iG(e){let t=eG(e);return t===null?null:rG(t)}function aG(e,t,n,r){return t.ok?r(t.stdout):WW(t)||t.reason===`non-zero`&&n.test(t.stderr)?I:L(`${e}: ${[t.reason,t.exitCode==null?null:`exit ${t.exitCode}`,t.error??BW(t.stderr)].filter(Boolean).join(`, `)}`)}function oG(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sG(e){let t=`detached`,n=I,r=I,i=I,a=0,o=0,s=0,c=0;for(let l of e.split(`
189
189
  `)){if(!l)continue;if(l.startsWith(`# `)){let e=l.slice(2);if(e.startsWith(`branch.oid `)){let t=e.slice(11).trim();n=t===`(initial)`?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 cG(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(!oG(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=FW(`gh pr view`,NW,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function lG(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(!oG(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=FW(`glab mr view`,PW,r);return o.kind===`ok`?F({number:n,state:o.value,url:i,head:a}):o}function uG(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var dG=class{isGitRepo(e){return KV(e)}async execGitAsync(e,t){return mt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?F(e):t&&this.isGitRepo(t)?F(t):this.isGitRepo(e)?F(e):this.findGitRoot(e)}findGitRoot(e){let t=qV(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=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=VW(a.value.oid,e=>e.slice(0,7))),t.showUpstream&&(o.upstream=a.value.upstream),t.showTag&&(o.tag=await this.getNearestTagAsync(r)),t.showCommittedAt&&(o.committedAt=await this.committedAt(r,a.value.oid)),t.showStashCount&&(o.stashCount=this.getStashCount(r));let s=t.showRepoName||t.showRepoUrl?await this.getRemotesAsync(r):void 0;return s!==void 0&&t.showRepoName&&(o.repoName=VW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=VW(s,iG)),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 HW(RW(`git describe --tags`,await this.execGitAsync([`describe`,`--tags`,`--abbrev=0`],{cwd:e,timeout:2e3}),`absent`))}async committedAt(e,t){return t.kind===`ok`?this.commitTimestamp(e,t.value):t}commitTimes=new Map;async commitTimestamp(e,t){let n=this.commitTimes.get(t);if(n!==void 0)return this.commitTimes.delete(t),this.commitTimes.set(t,n),n;let r=this.readCommitTimestamp(e,t);for(this.commitTimes.set(t,r),r.then(e=>{e.kind!==`ok`&&this.commitTimes.get(t)===r&&this.commitTimes.delete(t)},()=>{this.commitTimes.get(t)===r&&this.commitTimes.delete(t)});this.commitTimes.size>256;){let e=this.commitTimes.keys().next().value;if(e===void 0)break;this.commitTimes.delete(e)}return r}async readCommitTimestamp(e,t){let n=HW(RW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?L(`git log -1: unparseable timestamp "${n.value}"`):F(r)}resolveCommonGitDir(e){try{let t=p.readFileSync(s.join(e,`commondir`),`utf-8`).trim();if(t)return s.resolve(e,t)}catch{}return e}getStashCount(e){let t=s.join(this.resolveCommonGitDir(this.resolveGitDir(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(`
190
- `).length:0)}async getRemotesAsync(e){let t=uG(s.join(this.resolveCommonGitDir(this.resolveGitDir(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 XW(await this.execGitAsync(YW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=eG(e);return(n===null?null:nG(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=tG(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return mt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JW(t);return n===`github`?aG(`gh pr view`,await this.execForgeAsync(UW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,cG):n===`gitlab`?aG(`glab mr view`,await this.execForgeAsync(UW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,lG):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=RW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(sG(t.value)):t}};const fG=(e,t)=>D(t);function pG(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const mG=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var hG=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??fG}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:t.dirs.map(e=>({path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}follow(e,t,n){return e!==null&&e.key===t.key?{watch:e,move:`kept`}:(e?.handle.release(),{watch:{key:t.key,handle:this.acquire(t.key,t.targets,n)},move:`rebound`})}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=pG(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1,recursive:r.recursive===!0},(e,n)=>{i&&(!n||!i.has(n))||t(mG(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};const gG=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},_G=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,vG=e=>e===`gone`?`gone`:`${e.dev}:${e.ino}:${e.birthtimeNs}`,yG=e=>{try{return gG(e)}catch(e){return{unreadable:e.code??String(e)}}},bG=e=>typeof e==`string`||`ino`in e?vG(e):`unreadable:${e.unreadable}`;function xG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var SG=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function CG(){return J.observable.box(wG(`unread`),{deep:!1})}function wG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function TG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function EG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(wG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function DG(e,t){e.reading.get().kind===`pending`&&TG(e,t)}function OG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function kG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function AG(e){for(;;){let t=e();if(!OG(t))return t;await t.landed}}function jG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function MG(e){return{current:()=>e}}function NG(e){return AG(()=>e.current())}const PG=`pass`,FG={okMs:5*6e4,failedMs:45e3};function IG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function LG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function RG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function zG(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:s.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>yG(e.path));return{spec:{key:`git:${e}:${r.map((e,t)=>`${e.path}@${bG(i[t])}`).join(`|`)}`,targets:{dirs:r}},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function BG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function VG(e){e.missed=!0,EG(e,`unread`)}function HG(e,t){return e.missed&&e.reading.get().kind===`pending`&&TG(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function UG(e,t){let n=kG(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:kG(t)})}function WG(e){return t=>L(`${e} threw: ${String(t)}`)}var GG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new dG,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Ne;let t=e.ledger??new Bk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new hG({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return MG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>UG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new Rk,watch:this.followWatch(e,null).watch,period:new SG(()=>{n.refresh.share(PG,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),{spec:r,unbound:i}=zG(e,n,this.inner.resolveCommonGitDir(n));if(t!==null&&i)return{watch:t,move:`kept`};let a=this.watchers.follow(t,r,()=>this.changed(e));return a.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} refused=${a.watch.handle.refused.length}`),a}changedPass(e,t){e.asked.add(t),e.refresh.run(PG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&VG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(PG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:CG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=RG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(LG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(WG(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,TG(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of LW(n.value))c.add(e)});let l=BG(o),u=a===null||i.length===0?`-`:l===void 0?HG(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,IG(n),c.size===0?F(null):L([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new SG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:CG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(WG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(VG(t),`owed`):(EG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,TG(t,a.outcome),t.period.landed(xG(FG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(WG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${cs(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(TG(t,i),t.period.landed(xG(FG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())DG(n,t);e.pr!==null&&DG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},KG=class{static CACHE_DIR=Ct();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 ye(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 ye(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 ye(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 qG={"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 JG=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 KG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await KG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ve({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(qG).length} models`),this.executionCache=qG,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(qG).length} models`),qG)}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 YG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function XG(e){if(typeof e==`string`)return YG.exec(e)?.[1]}function ZG(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 QG(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 $G(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=ZG(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`?XG(QG(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 eK(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function tK(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await nK(Ra(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function nK(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function rK(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Ra(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 Wa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=dK(i,t,s.value);let c=cK(Ga(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 iK(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(oK(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=QG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||aK.test(r)?`claude-code`:`prompt`}const aK=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function oK(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function sK(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=iK(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:$G(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 cK(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 lK(e){let t=cK(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return sK(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function uK(e){let t=[];for(let n of e.split(`
190
+ `).length:0)}async getRemotesAsync(e){let t=uG(s.join(this.resolveCommonGitDir(this.resolveGitDir(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 XW(await this.execGitAsync(YW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=eG(e);return(n===null?null:nG(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=tG(t.value);return n===null?I:F(n)}async execForgeAsync(e,t,n){return mt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=JW(t);return n===`github`?aG(`gh pr view`,await this.execForgeAsync(UW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,cG):n===`gitlab`?aG(`glab mr view`,await this.execForgeAsync(UW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,lG):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=RW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?F(sG(t.value)):t}};const fG=(e,t)=>D(t);function pG(e,t){return t.kind===`failed`?t:e.kind===`changed`?t.kind===`unknown`?t:{kind:`changed`,names:new Set([...e.names,...t.names])}:e}const mG=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var hG=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??fG}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:t.dirs.map(e=>({path:e.path,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}follow(e,t,n){return e!==null&&e.key===t.key?{watch:e,move:`kept`}:(e?.handle.release(),{watch:{key:t.key,handle:this.acquire(t.key,t.targets,n)},move:`rebound`})}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=pG(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1,recursive:r.recursive===!0},(e,n)=>{i&&(!n||!i.has(n))||t(mG(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}watchedDirs(){return[...this.slots.values()].flatMap(e=>e.targets.dirs.map(e=>e.path))}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};const gG=e=>{try{let t=p.statSync(e,{bigint:!0});return{dev:t.dev,ino:t.ino,birthtimeNs:t.birthtimeNs}}catch(e){let t=e.code;if(t===`ENOENT`||t===`ENOTDIR`)return`gone`;throw e}},_G=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,vG=e=>e===`gone`?`gone`:`${e.dev}:${e.ino}:${e.birthtimeNs}`,yG=e=>{try{return gG(e)}catch(e){return{unreadable:e.code??String(e)}}},bG=e=>typeof e==`string`||`ino`in e?vG(e):`unreadable:${e.unreadable}`;function xG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var SG=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};function CG(){return J.observable.box(wG(`unread`),{deep:!1})}function wG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function TG(e,t){let n=e.reading.get();n.kind===`read`&&(0,J.compareStructural)(n.outcome,t)||((0,J.runInAction)(()=>e.reading.set({kind:`read`,outcome:t})),n.kind===`pending`&&n.land())}function EG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(wG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function DG(e,t){e.reading.get().kind===`pending`&&TG(e,t)}function OG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function kG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function AG(e){for(;;){let t=e();if(!OG(t))return t;await t.landed}}function jG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function MG(e){return{current:()=>e}}function NG(e){return AG(()=>e.current())}const PG=`pass`,FG={okMs:5*6e4,failedMs:45e3};function IG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function LG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function RG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function zG(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:s.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>yG(e.path));return{spec:{key:`git:${e}:${r.map((e,t)=>`${e.path}@${bG(i[t])}`).join(`|`)}`,targets:{dirs:r}},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function BG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function VG(e){e.missed=!0,EG(e,`unread`)}function HG(e,t){return e.missed&&e.reading.get().kind===`pending`&&TG(e,t.size>0?L([...t].join(`; `)):I),`unkeyed`}function UG(e,t){let n=kG(e);return t===null||n.kind!==`ok`?n:F({...n.value,pullRequest:kG(t)})}function WG(e){return t=>L(`${e} threw: ${String(t)}`)}var GG=class{repos=new Map;resolutions=new Map;hits=0;misses=0;changes=0;gitRefreshes;prRefreshes;inner;periodMs;maxRepos;watchers;ownsWatchers;logger;constructor(e={}){this.inner=e.inner??new dG,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Ne;let t=e.ledger??new Bk(this.logger);this.gitRefreshes=t.declare({name:`git`,scope:`repo`,refresh:[`first`,`period`,`change`]}),this.prRefreshes=t.declare({name:`pr`,scope:`repo`,refresh:[`first`,`period`]}),e.watchers?(this.watchers=e.watchers,this.ownsWatchers=!1):(this.watchers=new hG({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=L(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return MG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>UG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new Rk,watch:this.followWatch(e,null).watch,period:new SG(()=>{n.refresh.share(PG,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),{spec:r,unbound:i}=zG(e,n,this.inner.resolveCommonGitDir(n));if(t!==null&&i)return{watch:t,move:`kept`};let a=this.watchers.follow(t,r,()=>this.changed(e));return a.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} refused=${a.watch.handle.refused.length}`),a}changedPass(e,t){e.asked.add(t),e.refresh.run(PG,()=>this.refreshPass(e))}async refreshPass(e){try{await this.pass(e)}catch(t){this.logger(`error`,`git refresh threw (${e.root}): ${String(t)}`)}finally{e.period.landed(this.periodMs)}}hold(e,t,n){return e.holders++,n!==null&&(n.holders++,t.missed&&VG(n),n.missed&&e.asked.add(`owed`)),t.readers++,t.missed&&e.asked.add(`resume`),this.held(e),this.evict(),()=>{e.holders--,t.readers--,n!==null&&n.holders--,this.held(e)}}queue(e,t){e.asked.size>t&&e.refresh.run(PG,()=>this.refreshPass(e))}held(e){e.period.hold(e.holders>0),e.pr?.period.hold(e.pr.holders>0&&!e.pr.missed)}valueOf(e,t,n){let r=e.values.get(t);if(r!==void 0)return r;let i={options:n,reading:CG(),readers:0,missed:!1};return e.values.set(t,i),e.asked.add(`first`),i}ask(e,t,n,r){let i=e.asked.size,a=RG(n),o=this.valueOf(e,a,n);r&&e.pr===null&&(e.pr=this.prSource(e),e.asked.add(`pr`));let s=r?e.pr:null;return t.take(LG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(WG(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,TG(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of LW(n.value))c.add(e)});let l=BG(o),u=a===null||i.length===0?`-`:l===void 0?HG(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,IG(n),c.size===0?F(null):L([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new SG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:I,reading:CG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(WG(`git remote`))}movePr(e,t,n,r){let i=`${n}|${r.kind===`ok`?r.value:r.kind}`;if(i===t.key&&!t.missed)return`kept`;t.key=i,t.remote=r;let a=t.seen.get(i);return a===void 0?t.holders===0?(VG(t),`owed`):(EG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,TG(t,a.outcome),t.period.landed(xG(FG,a.outcome),a.at),`recalled`)}readPr(e,t,n){let r=t.key;if(t.inFlight?.key===r)return t.inFlight.done;let i=t.remote,a=Date.now(),o=(i.kind===`ok`?this.inner.resolvePullRequest(e.root,i.value).catch(WG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:I)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${cs(r)}`,n,i,Date.now()-a);let o=Date.now();t.seen.delete(r),t.seen.set(r,{outcome:i,at:o});for(let e of t.seen.keys()){if(t.seen.size<=16)break;t.seen.delete(e)}t.key!==r||t.missed||(TG(t,i),t.period.landed(xG(FG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=L(`git state dropped: ${e.root}`);for(let n of e.values.values())DG(n,t);e.pr!==null&&DG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},KG=class{static CACHE_DIR=Ct();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 ye(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 ye(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 ye(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 qG={"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 JG=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 KG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await KG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ve({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(qG).length} models`),this.executionCache=qG,D(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(qG).length} models`),qG)}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 YG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function XG(e){if(typeof e==`string`)return YG.exec(e)?.[1]}function ZG(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 QG(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 $G(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=ZG(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`?XG(QG(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 eK(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function tK(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await nK(Ra(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function nK(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function rK(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Ra(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 Wa(t,void 0,void 0);if(s.kind!==`ok`){D(`Failed to check agent file ${t}`);continue}i=dK(i,t,s.value);let c=cK(Ga(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 iK(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(oK(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=QG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||aK.test(r)?`claude-code`:`prompt`}const aK=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function oK(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function sK(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=iK(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:$G(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 cK(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 lK(e){let t=cK(e);if(t.kind===`unparsed`)return D(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return sK(t.value)}catch(e){return D(`Failed to project JSONL line: ${e}`),null}}function uK(e){let t=[];for(let n of e.split(`
191
191
  `)){let e=lK(n);e&&t.push(e)}return t}function dK(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function fK(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function pK(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Wa(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=dK(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,Ga(c,e=>uK(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 mK=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}},hK=class{entries=new Map;refreshes;constructor(e){this.spec=e,this.refreshes=e.ledger.declare({name:e.name,scope:e.scope,refresh:e.every===null?[`first`,`change`,`supersede`]:[`first`,`period`,`change`,`supersede`]})}declare(e,t){let n=this.spec.keyOf(t),r=this.touched(n)??this.firstRead(this.created(n,t));return e.take(`${this.spec.name}:${n}`,()=>this.hold(r)),{current:()=>kG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,EG(n,`superseded`),n.flight=null,n.changed=!1,this.evict();let r=!1;return()=>{r||(r=!0,n.superseding--,this.entries.get(n.key)===n&&this.refresh(n,`supersede`))}}changed(e){for(let t of this.entries.values())t.holders>0&&e(t.input)&&this.refresh(t,`change`)}isHeld(e){for(let t of this.entries.values())if(t.holders>0&&e(t.input))return!0;return!1}stats(){let e=0;for(let t of this.entries.values())t.holders>0&&e++;let{refreshes:t,failures:n,lastMs:r}=this.refreshes.record();return{entries:this.entries.size,held:e,refreshes:t,failures:n,lastMs:r}}close(){for(let e of[...this.entries.values()])this.drop(e)}touched(e){let t=this.entries.get(e);if(t!==void 0)return this.entries.delete(e),this.entries.set(e,t),t}created(e,t){let n={key:e,input:t,reading:CG(),holders:0,flight:null,changed:!1,superseding:0,revisit:gK(this.spec.every,{period:()=>this.refresh(n,`period`),holdReturned:()=>this.refresh(n,`change`)})};return this.entries.set(e,n),n}firstRead(e){return this.refresh(e,`first`),e}refresh(e,t){if(e.superseding>0)return;if(e.flight!==null){e.changed||=t===`change`;return}let n={};e.flight=n;let r=Date.now();vK(()=>this.spec.read(e.input)).then(i=>{let a=e.flight===n;try{this.refreshes.recorded(`${this.spec.fields(e.input)} stored=${a?`Y`:`N`}`,t,i,Date.now()-r)}finally{a&&this.store(e,i)}}).catch(t=>{this.spec.logger(`error`,`${this.spec.name} refresh threw (${this.spec.fields(e.input)}): ${String(t)}`)})}store(e,t){e.flight=null;try{TG(e,t)}finally{e.revisit.landed(t),e.changed&&(e.changed=!1,this.refresh(e,`change`))}}hold(e){return e.holders++,e.revisit.hold(!0),this.evict(),()=>{e.holders--,e.revisit.hold(e.holders>0)}}evict(){for(let e of[...this.entries.values()]){if(this.entries.size<=this.spec.maxEntries)return;e.holders===0&&e.superseding===0&&this.drop(e)}}drop(e){this.entries.delete(e.key),e.flight=null,e.revisit.dispose(),DG(e,L(`${this.spec.name} entry dropped`))}};function gK(e,t){if(e===null)return new _K(t.holdReturned);let n=new SG(t.period);return{landed:t=>n.landed(xG(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var _K=class{state=`released`;answered=!1;constructor(e){this.reread=e}landed(){this.answered=!0}hold(e){if(this.state===`disposed`)return;let t=e&&this.state===`released`&&this.answered;this.state=e?`held`:`released`,t&&this.reread()}dispose(){this.state=`disposed`}};function vK(e){let t=e=>L(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function yK(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 bK={okMs:60*1e3,failedMs:10*1e3},xK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},SK={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function CK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function wK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function TK(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const EK={entries:0,cost:0,breakdown:TK(),days:new Map};async function DK(e,t){let n=CK(new Date(wK())),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 JG.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=CK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...xK};l.cost+=s,l.input+=t.input_tokens||0,l.output+=t.output_tokens||0,l.cacheCreation+=t.cache_creation_input_tokens||0,l.cacheRead+=t.cache_read_input_tokens||0,o.set(c,l)}return{entries:r,cost:i,breakdown:a,days:o}}function OK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function kK(e){let t=0,n=0,r=TK(),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)??{...xK};OK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:SK,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function AK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function jK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!AK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...xK};OK(r,t),n.set(e,r)}return n}async function MK(e,t,n){let r=0,i=async()=>{for(;r<e.length;){let t=e[r++];await n(t)}},a=Math.min(t,e.length);await Promise.all(Array.from({length:a},i))}function NK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function PK(e,t){(0,J.runInAction)(()=>e.set(t))}var FK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new mK;scans;daySets=new Map;speedFlight=new mK;requestFlight=new mK;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Ne,this.ledger=e.ledger??new Bk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new hK({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${cs(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??bK,maxEntries:8,logger:this.log,ledger:this.ledger});let t=e.sweepIntervalMs??3e5;t>0&&(this.sweepTimer=setInterval(()=>this.sweepStale(),t),this.sweepTimer.unref())}getStats(){return{size:this.sessions.size,hits:this.renderTally.hits,misses:this.renderTally.misses,sweeps:this.sweeps}}scanStats(){return this.scans.stats()}getUsageInfo(e,t){return this.request(e,t?.transcript_path).usage(t)}request(e,t){let n=null,r=()=>{if(n!==null)return n;let r=Pa(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:F(NK(t.kind===`ok`?t.value.sessionInfo:SK,e))},speed:t=>this.observed(e,r,t),today:async e=>{await NG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return ja;let r=n.failure.get();return r===null?F(NK(n.record?.sessionInfo??SK,t)):L(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${cs(e)}`,`request`,a,Date.now()-i),PK(this.hold(e).failure,a.kind===`failed`?a.reason:null),a})}refreshToday(e,t){return this.request(t?.session_id??``,t?.transcript_path).today(e)}declareToday(e,t){let n=eK(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?F({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return L(i);let a=CK(mk(n)),o={...xK},s=e.sums.get(a);s!==void 0&&OK(o,s);let c=AK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&OK(o,c),s===void 0&&c===void 0?I:F({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return I;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return PK(this.hold(e).speed,t),t;let r=yK(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=F({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return PK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??ja:I}async ingest(e,t,n,r){if(!e)return I;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,F(i);if(!t)return i?F(i):I;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return L(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),F(c)):l===void 0?F(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new fS(`today over ${e.join(`,`)}`,()=>jK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await rK(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of fK(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 pK(e,r,EK,DK);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 fK(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return F({files:i,...kK(i),mainStamp:a})}async scan(e){try{let t=wK(),n=await tK(e),r=[];for(let e of n){let n=await nK(Ra(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await nK(za(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Fa(a)})}}let i=[],a={hits:0,misses:0};return await MK(r,8,async e=>{let t=await this.ingest(e.sessionId,e.path,a,e.stamp);t.kind===`failed`&&(i.push(t.reason),this.log(`warn`,`usageStore scan: ${t.reason}`))}),this.log(`info`,`usageStore scan dirs=${cs(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?L(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):F({sessions:r.length,read:a.misses})}catch(e){return L(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=CK(new Date(e)),n=0,r=0,i=0;return(0,J.runInAction)(()=>{for(let[a,{lastSeenAt:o,record:s}]of[...this.sessions])if(!(e-o<=this.staleAgeMs)){if(s?.days.has(t)){r++;continue}this.sessions.delete(a),n++,s===void 0&&i++}}),n>0&&this.sweeps++,(n>0||r>0)&&this.log(`info`,`usageStore sweep dropped=${n} noRecord=${i} held=${r}`),n}close(){this.sweepTimer&&=(clearInterval(this.sweepTimer),null),this.scans.close(),(0,J.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},IK=class{values=J.observable.map(void 0,{deep:!1});order=new Set;constructor(e){this.max=e}get(e){return this.values.get(e)}get size(){return this.order.size}touch(e){this.order.delete(e)&&this.order.add(e)}set(e,t){this.order.delete(e),this.order.add(e),(0,J.runInAction)(()=>{this.values.set(e,t);for(let e of this.order){if(this.order.size<=this.max)break;this.order.delete(e),this.values.delete(e)}})}},LK=class{sessions;constructor(e,t,n,r=Ne,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new IK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Pa(t);if(n?.folded&&i!==``&&n.folded.cursor.stamp===i){let{folded:t,answer:r}=n;return r.kind===`ok`&&r.value===t.value?(this.sessions.touch(e),r):this.store(e,t,{kind:`ok`,value:t.value})}let a=Date.now(),o=await pK(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${cs(e)}`,`request`,o,Date.now()-a),o.kind===`failed`)return this.store(e,r,o);if(o.kind===`absent`)return this.store(e,r,{kind:`ok`,value:r?.value??this.empty});let{folded:s,longLines:c}=o.value;for(let e of fK(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??ja}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function RK(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 zK=class{fold;constructor(e={}){let t=e.logger??Ne;this.fold=new LK(void 0,RK,(e.ledger??new Bk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return 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){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?F(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,BK(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return F(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,BK(e))}contextFrom(e,t){if(e.kind===`failed`)return L(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(D(`No main chain entries with usage data found`),I):(D(`Most recent main chain context: ${n} tokens (limit: ${t})`),F({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function BK(e){return e.context_window?.context_window_size??2e5}const VK={messageCount:0,nonPrompts:0,recent:[]},HK=new Set([`turn`,`interrupt`,`claude-code`]);function UK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!HK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function WK(e){let t=null,n=null;for(let r of e){let e=r.type||r.message?.role||r.message?.type;if(r.userEntry===`prompt`||r.userEntry===`turn`)t=r.timestamp;else if(e===`assistant`&&t){let e=(r.timestamp.getTime()-t.getTime())/1e3;e>.1&&e<300&&(n=e)}}return n}var GK=class{fold;constructor(e={}){let t=e.logger??Ne;this.fold=new LK(VK,UK,(e.ledger??new Bk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){D(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?KK(e,n,await this.fold.read(e,t.transcript_path)):I}metricsOf(e,t){let n=t.cost;if(!n)return I;let r=this.fold.answer(e);return r.kind===`pending`?r:KK(e,n,r)}};function KK(e,t,n){return n.kind===`failed`?L(`metrics (${e}): ${n.reason}`):F({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:WK(n.value.recent),sessionDuration:t.total_duration_ms/1e3,messageCount:n.value.messageCount,nonPrompts:n.value.nonPrompts,linesAdded:t.total_lines_added,linesRemoved:t.total_lines_removed})}const qK={command:null,todos:[],pending:[],done:[]};function JK(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 YK(e,t){switch(t.userEntry){case`prompt`:return{...e,command:t.activity?.command??null,pending:[],done:[]};case`interrupt`:return{...e,pending:[]};case`turn`:case`tool-result`:case`claude-code`:case void 0:return e}}function XK(e,t){if(t.isSidechain)return e;let n=YK(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=JK(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 ZK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>JK(e,t.name),[]),done:e.done}}var QK=class{fold;constructor(e={}){let t=e.logger??Ne;this.fold=new LK(qK,XK,(e.ledger??new Bk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return $K(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:$K(e,t)}};function $K(e,t){return t.kind===`failed`?L(`activity (${e}): ${t.reason}`):F(ZK(t.value))}function eq(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function tq(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 nq(e,t,n,r){return tq(ht(eq(e,t,n,r)),n)}async function rq(e,t,n,r){return tq(await mt(eq(e,t,n,r)),n)}const iq=3e4;var aq=class{names;constructor(e={}){let t=e.logger??Ne;this.names=new hK({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${cs(e.pane)} socket=${cs(e.socket)}`,read:oq,every:{okMs:iq,failedMs:iq},maxEntries:64,logger:t,ledger:e.ledger??new Bk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function oq(e){let t=await rq(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return L(t.reason);let n=t.stdout.trim();return n?F(n):I}const sq=6e4,cq={okMs:sq,failedMs:sq};function lq(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function uq(e,t){try{let e=t();return Promise.resolve(e===``?I:F(e))}catch(t){return Promise.resolve(L(`host.${e}: ${String(t)}`))}}var dq=class{name;user;constructor(e={}){let t=e.logger??Ne,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:cq,maxEntries:1,logger:t,ledger:e.ledger??new Bk(t)};this.name=new hK({...n,name:`host.name`,read:()=>uq(`name`,()=>lq(C.hostname()))}),this.user=new hK({...n,name:`host.user`,read:()=>uq(`user`,()=>C.userInfo().username)})}declareName(e){return this.name.declare(e,null)}declareUser(e){return this.user.declare(e,null)}held(){return this.name.stats().held+this.user.stats().held}close(){this.name.close(),this.user.close()}},fq=class{known=new IK(64);refreshes;constructor(e=Ne,t=new Bk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=pq(e),n=this.known.get(e);if(n!==void 0&&n.stamp===t)return this.known.touch(e),n.outcome;let r=Date.now(),i=wP(e);return this.refreshes.recorded(`path=${cs(e)} stamp=${cs(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??ja}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function pq(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Fa(t)}catch(e){return`unread:${e.code??`error`}`}}const mq=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function hq(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t.message?.usage;if(!((n?.cache_read_input_tokens??0)>0||(n?.cache_creation_input_tokens??0)>0))return null;let r=t.timestamp==null?NaN:Date.parse(t.timestamp);return Number.isNaN(r)?null:r}var gq=class{known=new IK(256);refreshes;constructor(e=Ne,t=new Bk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Pa(t),r=this.known.get(e);if(r!==void 0&&n!==``&&r.stamp===n&&r.outcome.kind!==`failed`)return this.known.touch(e),r.outcome;let i=await this.read(e,t,n);return this.known.set(e,{stamp:n,outcome:i}),i}expiryOf(e){return this.known.get(e)?.outcome??ja}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}async read(e,t,n){let r=Date.now(),i=await _q(t);return this.refreshes.recorded(`sid=${cs(e)} stamp=${cs(n)}`,`request`,i,Date.now()-r),i}};async function _q(e){let t=await vq(e);return t.kind===`ok`?F(Math.floor((t.value+36e5)/1e3)):t}async function vq(e){for(let t of[65536,1048576]){let n=await Ja(e,t);if(n.kind!==`ok`)return n;let r=yq(n.value.buf,n.value.fromStart);if(r!=null)return F(r);if(n.value.fromStart)return I}return I}function yq(e,t){let n=e.toString(`utf8`).split(`
192
- `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!mq.test(t))continue;let r=hq(t);if(r!=null)return r}return null}var bq=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const xq=e=>dV(e),Sq=e=>s.join(e.storage.folder,xq(e.sessionId)),Cq=e=>JSON.stringify([e.folder,e.generation]),wq=(e,t)=>e.folder===t.folder&&e.generation===t.generation,Tq=(e,t)=>`cannot refresh: ${e.folder}: its watch has delivered no event since ${new Date(t).toISOString()}, not even for the files the daemon wrote there to test it; the OS is not delivering its file events`;var Eq=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;stalls=0;probes=0;probeFailures=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??gG,this.sessions=new hK({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${cs(Sq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Bk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!_G(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${cs(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(Cq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost,stalled:[...this.watched.values()].filter(e=>e.health.kind!==`faulted`&&e.delivery.kind===`stalled`).length,stalls:this.stalls,probes:this.probes,probeFailures:this.probeFailures}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${Cq(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),probe:setInterval(()=>void this.tick(i),3e4),health:{kind:`watching`},delivery:{kind:`delivering`,unreported:[]}};i.sweep.unref(),i.probe.unref(),this.watched.set(Cq(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return this.sweep(e),this.tick(i),i}closed(e){let t=Cq(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),clearInterval(e.probe),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>wq(e.storage,n);switch(t.kind!==`failed`&&this.delivered(e),t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(xq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&_G(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${cs(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>wq(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${cs(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>wq(e.storage,r)))}async tick(e){if(this.judged(e,()=>this.stalled(e)),e.health.kind!==`watching`)return;let t=Date.now();this.awaiting(e,e=>[...e,t]);try{await p.promises.writeFile(s.join(e.key.folder,`.cc-candybar-watch-probe`),String(t)),this.probes++}catch(n){this.awaiting(e,e=>e.filter(e=>e!==t)),this.probeFailures++,this.logger(`warn`,`plugin storage probe failed folder=${cs(e.key.folder)} generation=${e.key.generation} reason=${JSON.stringify(n.message)}`)}}awaiting(e,t){let{delivery:n}=e;n.kind!==`stalled`&&(e.delivery={kind:`delivering`,unreported:t(n.unreported)})}stalled(e){let{delivery:t}=e;if(t.kind===`stalled`||t.unreported.length<2)return;let n=t.unreported[0];e.delivery={kind:`stalled`,since:n},this.stalls++,this.logger(`warn`,`plugin storage stalled folder=${cs(e.key.folder)} generation=${e.key.generation} since=${new Date(n).toISOString()}`),this.sessions.changed(t=>wq(t.storage,e.key))}delivered(e){let{delivery:t}=e;e.delivery={kind:`delivering`,unreported:[]},t.kind===`stalled`&&(this.logger(`info`,`plugin storage recovered folder=${cs(e.key.folder)} generation=${e.key.generation} stalled=${Date.now()-t.since}ms`),this.sessions.changed(t=>wq(t.storage,e.key)))}standing(e){let t=this.watched.get(Cq(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:return t.delivery.kind===`stalled`?Tq(e,t.delivery.since):null;case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t);let n=Sq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=Lk(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${cs(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&xq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function Dq(e){let{logger:t,ledger:n}=e;return{hostService:new dq({logger:t,ledger:n}),gitProvider:new GG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new FK({logger:t,ledger:n}),contextProvider:new zK({logger:t,ledger:n}),metricsProvider:new GK({logger:t,ledger:n}),activityProvider:new QK({logger:t,ledger:n}),tmuxService:new aq({logger:t,ledger:n}),autoCompact:new fq(t,n),cacheExpiry:new gq(t,n),managedStorage:new Eq({watchers:e.watchers,logger:t,ledger:n}),faults:new bq,log:e.logger}}function Oq(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 kq=`repo-configs.json`;function Aq(e=St()){return s.join(e,kq)}const jq=(e=St())=>Oq(e,kq,{},eH);function Mq(e,t,n){return{sessionId:e,action:fi,declaration:t,evaluated:n}}function Nq(e,t,n){return e.awaiting.map(e=>{let r=`${e} has a cc-candybar config — run it?`,i=XV.map(r=>wb(`[${r===`approved`?`approve`:`decline`}]`,gi([{verb:fi,args:[t,e,r,n.sign(Mq(t,e,r))]}])));return{severity:Sb,message:r,lines:[[wb(r,gi([{verb:Kr,args:[r]}])),...i]]}})}function Pq(e){return Math.max(1,e-2)}function Fq(e,t,n){return Le({dir:e.project_dir,env:n===void 0?[]:[[Xa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function Iq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function Lq(e){return{...Object.fromEntries(_y.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:KH(e.preset)}}}const Rq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function zq(e,t){if(!t)return`-`;if(Ma(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return Ma(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const Bq=10*1e3;function Vq(e,t){if(!(t<60))return e*3600/t}function Hq(e,t,n,r){let i=r-t;if(i<50||i>Bq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Uq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Hq(t.input,t.atMs,n.input,n.atMs),i=Hq(t.output,t.atMs,n.output,n.atMs),a=Hq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function Wq(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>Bq)continue;let o=Hq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Gq(e,t){let n=cx(e,t),r=[...qg.flatMap(e=>{let t=n[e];return Jg(t)?[t]:[]})];for(let n of A_(sx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...Kq(e,n.name));return Jq(e,r)}function Kq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function qq(e,t,n){return Jq(e,[...Kq(e,t),...n])}function Jq(e,t){let n=pB(e),r=new Map(Jx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=dB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Yq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=Gq(e,n);return t.set(n,i),i}}function Xq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Zq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(Rq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Qq=new WeakMap;function $q(e){let t=Qq.get(e);return t===void 0&&(t=eJ(e),Qq.set(e,t)),t}function eJ(e){let t=t=>Xq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function tJ(e){return Pq(e.termCols??120)}function nJ(e){return $a(Qa(e.claudeConfigDir))}function rJ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function iJ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=$q(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${E(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(mk(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(nJ(a)))])}function aJ(e,t){return[...t.keys()].filter(t=>e.has(t))}function oJ(e,t){let n=MG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function sJ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Zq(n),t.workspace?.project_dir]}function cJ(e,t,n,r,i){let a=$q(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return MG(I);try{return n()}catch(t){return s.push(`${e}: ${E(t)}`),MG(L(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...sJ(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(aJ(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function lJ(e){let{hookData:t,deps:n}=e,r=$q(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return I;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${E(t)}`),L(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(nJ(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function uJ(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function dJ(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=$q(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return ja;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?ja:wJ(n.git,()=>ja),m=n.tmuxSession.kind===`pending`?ja:d(n.tmuxSession),h=n.hostName.kind===`pending`?ja:d(n.hostName),g=n.hostUser.kind===`pending`?ja:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?ja:yJ(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?ja:mJ(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,hJ),x=u(n.usage,e=>SJ({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>SJ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,bJ),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=CJ(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:CJ(r.workspace.current_dir)??``,project_dir:CJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>CJ(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...Lq(a),history:t.history,navigation:{back:t.back},term:{cols:tJ(i)},...c,...s!==null&&{configPath:s},resumeCommand:Fq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:pJ(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?ja:t})}}function fJ(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function pJ(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function mJ(e,t){let n=e!=null&&t!=null?Vq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function hJ(e){let t=Uq(e),n=Wq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function gJ(e,t){return dJ(e,t,lJ(e))}function _J({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return ja;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${E(e)}`),I}})();return s.kind===`pending`?ja:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function vJ(e,t,n){await iJ(e,t,n),await AG(()=>{let t=uJ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function yJ(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return TP(e.value,t)}}function bJ(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=xJ(e.running),i=xJ(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 xJ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function SJ(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 CJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function wJ(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(jW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:MW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function TJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const EJ={kind:`hidden`},DJ={kind:`shown`};function OJ(e,t){try{return TJ(e,t)?DJ:EJ}catch(e){let t=lS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function kJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function AJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function jJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function MJ({text:e,placement:t,lead:n,trail:r}){return{text:NJ(e),placement:t,...n!==void 0&&{lead:NJ(n)},...r!==void 0&&{trail:NJ(r)}}}function NJ(e){let t=e.blankCopy(e.plain);t.style=Ky(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Ky(i).clearMetaAndLinks(),n,r);return t}function PJ(e){let t=jJ(e);if(t.length===1)return e.text;let n=kJ(t);return n.style=e.text.style,n}function FJ(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=kJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:kJ([d,...c],a)},...l.length>0&&{trail:kJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(AJ(u,n,p),[{text:u,...f}])}const IJ=RegExp(`\\x1b\\[[0-9;]*m|${tf.source}`,`g`);function LJ(e){return Math.max(0,...e.split(`
193
- `).map(e=>Ks(e.replace(IJ,``))))}function RJ(e,t){let n=()=>e.map(e=>({owner:PJ(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=_b(e.map(PJ),t).split(`
194
- `);if(i.length>1)return n();let a=Math.max(0,t.width-LJ(i[0]??``)),o=Math.floor(a/r.length),s=a-o*r.length;return r.forEach(({at:t,how:n},i)=>{let a=o+(i===r.length-1?s:0),{text:c}=e[t];AJ(c,c.cellLength+a,n)}),n()}function zJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=BJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Ky(a.style)};if(e.style.link){i();let r=BJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function BJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>VJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function VJ(e,t){let n=e.copy();return n.style=t,n}function HJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function UJ(e,t){let{look:n}=HJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function WJ(e,t){let{layout:n}=HJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function GJ(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 KJ(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,qJ(e,t,o,n,r,i));return i}function qJ(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=mx(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=jy.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=mx(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=mx(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:XJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:XJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:vx(n),argv:n.run.map(n=>XJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,XJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:XJ(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 JJ(e){return e.kind===`do`?JJ(e.head):e}function YJ(e){switch(JJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function XJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function ZJ(e,t){return e.has(t)?aS(e.read(t)):``}function QJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function $J(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function eY(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Ky(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Ky(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function tY(e,t){return Math.max(e.members.indexOf(ZJ(t,e.stateVar)),0)}function nY(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=ZJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=ZJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=ZJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(tY(e,r)+1)%e.members.length];return{effects:[{verb:Br,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Vr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Hr,args:[QJ(e.text,kk(r))]}],active:!1};case`open`:return{effects:[{verb:Ur,args:[QJ(e.target,kk(r))]}],active:!1};case`persist-literal`:{let t=ZJ(r,e.stateVar);return{effects:[{verb:Jr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=ZJ(r,e.stateVar);return{effects:[{verb:Jr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(tY(e,r)+1)%e.members.length];return{effects:[{verb:Jr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Yr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ei,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ni,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ri,args:[i]}],active:!1};case`back`:return{effects:[{verb:ii,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ai,args:[i]}],active:!1};case`save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Zr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Qr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:$r,args:[i,QJ(e.name,kk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:si,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ci,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:li,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:di,args:[i,e.line]}],active:!1};case`run`:{let t=kk(r),n=JSON.stringify({run:e.argv.map(e=>QJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,QJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:ti,args:[i,e.key,HI(e.op)]}],active:!1};case`do`:{let o=nY(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>nY(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:ti,args:[i,e.key,HI(r)]}],active:!1}}}}function rY(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:wi(`action "${e}"`,n,t.members.length,tY(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 iY(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=HJ(n,`action "${e}"`).store,{display:a,boundValue:o}=rY(e,JJ(r),t,i),s=ZJ(i,`session.id`),{effects:c,active:l}=nY(r,a.plain,o,i,s,n.signer);return eY(a,gi(c),l)}function aY(e){return{action:{fn:(t,...n)=>iY(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function oY(e,t){return $J(`✕`,gi([{verb:Br,args:[ZJ(e,`session.id`),t,P]}]),!1)}function sY(e,t,n){return new V({bgcolor:B.fromRgba(t),color:B.fromRgba(eg(e,t,n))})}function cY({tint:e,text:t}){return new V({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function lY(e,t,n){return new V({color:B.fromRgba(zl(Wh(e,`warning`),t,$h,n))})}function uY(e,t,n){return V.combine([sY(e,t,n),lY(e,t,n)])}function dY(e,t,n){return sY(e.palette,Dg(e.palette,e.disclosure,t,n),n)}function fY(e){let t=B.fromRgba(Wh(e,`background`)),n=W.fromFragments(vh.map(n=>new W(`▀`,{style:new V({color:B.fromRgba(Wh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const pY=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},mY=e=>new V({bold:e});function hY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>pY(a,V.combine([dY(e,{...n,distribution:t},i),mY(o)]));let o=sY(e.palette,a,i);return(e,t,i,a)=>gY(i,V.combine([o,mY(a)]),r(t,n))}const gY=(e,t,n)=>pY(W.fromFragments([pY(e,t),pY(` `,t),fY(n)]));function _Y(e,t){return t===void 0?(e,t,n)=>pY(n):(n,r,i)=>gY(i,void 0,t(r,e))}function vY(e,t,n,r,i){let a=sY(e.palette,i,r);return(e,r,i,o)=>pY(W.fromFragments([pY(o?`[`:` `,a),fY(n(r,t)),pY(o?`]`:` `,a)]))}function yY(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=>bY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function bY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function xY(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function SY(e){return{current:null,drawnAt:e}}function CY(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 wY(e,t,n){return EY(e,()=>n(CY(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function TY(e,t){return EY(e,()=>(e.current=null,t()))}function EY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function DY(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 OY(e){return new W(e).cellLength}function kY(e){let{width:t,chromeCols:n,padding:r}=HJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function AY(e){let{padding:t,seamCols:n}=HJ(e,`a row fit`);return Math.max(1,kY(e)-(OY(`✕`)+2*t+n))}function jY(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 MY(e,t,n){let r=OY(`←`)+1+OY(`→`)+1,i=jY(e,t,n);return(i.length>1?jY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function NY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function PY(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 FY(e,t,n){let r=e.compiled.get(t),i=r&&JJ(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 IY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=HJ(a,`picker`).store,d=ZJ(u,`session.id`),f=`stateVar`in t?ZJ(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`?AY(a):kY(a):1/0,h=(r.kind===`led`?0:OY(`✕`)+1)+c.reduce((e,t)=>e+OY(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?MY(_.map(e=>e.cellLength),m,h):yY(g.entries,g.groups,i),y=parseInt(ZJ(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=>gi([{verb:Br,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Br,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>gi([...nY(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>eY(e,ie(t.options[n])),C=r.kind===`led`?[]:[$J(`✕`,gi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>$J(e,gi([...nY(l,r,r,u,d,a.signer).effects,{verb:Br,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push($J(`←`,te(x-1),!1));let w=x<v.length-1?[$J(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[NY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let T=new V({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new W(`${S[0].label}${oe}`,{style:T})]:[],se=[NY([...C,...E,...w],i)];for(let e of S){S.length>1&&se.push(NY([new W(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>OY(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:Ly(a),s=` `.repeat(n-OY(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(NY([ae(p(r,xY(c,m)),r)],i))}}return se}function LY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ok(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=PY(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=FY(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=DY(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]=IY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,hY(u,Nh(void 0),UJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),lY(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function RY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function zY(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 BY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=HJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=ZJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return NY([],!0);let d=ZJ(o,t.stateVar),f=RY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=gi(nY(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=eY(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):eY(_Y(UJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),gi(nY(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=zY(e=>v(e).cellLength,u,OY(`◀`)+1+y.cellLength+1+OY(`▶`),AY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return NY([...ee(-1).reverse(),$J(`◀`,h(-1),!1),y,$J(`▶`,h(1),!1),...ee(1)],!0)}function VY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ok(`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&&YJ(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=FY(e,n,`carousel`),l=DY(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 BY(n,c,e,hY(l,Nh(void 0),UJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function HY(e,t,n){let r=FY(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 UY(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 WY(e,t,n,r){let i=HY(e,t,n),a=r??ZJ(HJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,UJ(e,`{{ ${n} }}`))}function GY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ok(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return fY(WY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function KY(e,t,n){return{swatches:{fn:(r,i)=>{let a=HY(e,r,`swatches`),o=PY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=DY(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]=IY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,vY(s,UJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),lY(s.palette,s.bg,c),u===0?[]:(()=>{let t=RY(l,ZJ(HJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[UY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const qY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function JY(e,t,n,r){let i=mg(e,n,r),a=(t,n)=>({text:t,colour:n,ink:eg(e,n,r)});return[[Oh(t).map((n,i)=>{let a=Gh(e,n);return{text:qY[i%qY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Wh(e,`warning`)),a(`error`,Wh(e,`error`))]]]}function YY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:cY({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function XY(e,t,n,r,i){let a=JY(e,t,n,r).map(e=>YY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
195
- `),...e]));return o.overflow=`ignore`,o.end=``,o}function ZY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ok(`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}=UJ(e,`{{ themePreview }}`);return XY(r===void 0?a:WY(e,r,`themePreview`),o,{...DY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),AY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const QY=e=>e.slice(e.lastIndexOf(`.`)+1),$Y=(e,t)=>{let n=new W(QY(e));return n.truncate(t,{marker:`…`}),n.plain};function eX(e,t){let n=e.map(e=>e.map(({name:e})=>OY(QY(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 tX(e,t,n,r){let i=eX(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${$Y(s,i)} `,{style:cY(Lg(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
- `),...e]));return o.overflow=`ignore`,o.end=``,o}const nX=`layoutPreview`;function rX(e,t){return{[nX]:{fn:()=>tX(WJ(e,`{{ layoutPreview }}`),UJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),AY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function iX(e,t,n,r){let i=DY(r.activeSegment,`{{ menu }}`),a=r.action,o=jA(i.placementId,e,n.key),s=PA(o),c=AA(e),l=HJ(a,`menu`).store,u=ZJ(l,o)===c,d=ZJ(l,`session.id`),f=u?P:c,p=$J(wi(`{{ menu "${e}" }}`,t,2,+!!u),gi([{verb:Br,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=mg(i.palette,i.disclosure,t).plane,l=FY(a,e,`menu`);return IY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,P],[s,`0`]],onPick:n.closeOnPick},n.paged,a,hY(i,n.distribution,UJ(a,`{{ menu }}`),l.paletteOf,t,c),lY(i.palette,c,t))})():[]),p}const aX=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function oX(e,t){let n=t[t.length-1],r=aX(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:RA(r??{})}}function sX(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=oX(t,n);return iX(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function cX(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=lX(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function lX(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 uX(e){let t={fn:(()=>{let t=DY(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:(()=>DY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=DY(e,`{{ keptOn }}`),i=Al(r,t),a=Al(r,n),o=bc(Vl(i,z.TRUECOLOR),Vl(a,z.TRUECOLOR)),s=Math.min($h,Math.max(o,3));return(Bl(i,e.drawnAt(),(e,t)=>bc(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=WO(()=>DY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...dX(s)];return cX({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 dX(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 fX(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>Dk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const pX={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},mX=new WeakMap;function hX(e){let t=mX.get(e);return t===void 0&&(t=gX(e),mX.set(e,t)),t}function gX(e){let t=new Map(Jx(e)),n=pB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:pX[t.kind]])),i=new Map([...t].map(([e,t])=>[e,fX(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function _X(e){let t=[],n=[];for(let r of e){if(!r.contains(`
192
+ `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!mq.test(t))continue;let r=hq(t);if(r!=null)return r}return null}var bq=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:L(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const xq=e=>dV(e),Sq=e=>s.join(e.storage.folder,xq(e.sessionId)),Cq=e=>JSON.stringify([e.folder,e.generation]),wq=(e,t)=>e.folder===t.folder&&e.generation===t.generation,Tq=(e,t)=>`cannot refresh: ${e.folder}: its watch has delivered no event since ${new Date(t).toISOString()}, not even for the files the daemon wrote there to test it; the OS is not delivering its file events`;var Eq=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;stalls=0;probes=0;probeFailures=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??gG,this.sessions=new hK({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${cs(Sq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Bk(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{p.mkdirSync(e,{recursive:!0}),n=this.identityOf(e)}catch(e){t.unusable=`could not be created or read: ${e.message}`}return(t.lost||t.identity!==null&&(n===`gone`||!_G(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${cs(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(Cq(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost,stalled:[...this.watched.values()].filter(e=>e.health.kind!==`faulted`&&e.delivery.kind===`stalled`).length,stalls:this.stalls,probes:this.probes,probeFailures:this.probeFailures}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${Cq(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),probe:setInterval(()=>void this.tick(i),3e4),health:{kind:`watching`},delivery:{kind:`delivering`,unreported:[]}};i.sweep.unref(),i.probe.unref(),this.watched.set(Cq(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return this.sweep(e),this.tick(i),i}closed(e){let t=Cq(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),clearInterval(e.probe),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>wq(e.storage,n);switch(t.kind!==`failed`&&this.delivered(e),t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(xq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{health:n}=e;if(n.kind!==`watching`)return;let{key:r,folder:i}=e,a;try{a=this.identityOf(r.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let o=e.identity;if(a!==`gone`&&o!==`gone`&&_G(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${cs(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>wq(e.storage,r)))}faulted(e,t,n){let{key:r,folder:i}=e;e.health.kind===`watching`&&(e.health={kind:`faulted`,reason:n},this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${cs(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>wq(e.storage,r)))}async tick(e){if(this.judged(e,()=>this.stalled(e)),e.health.kind!==`watching`)return;let t=Date.now();this.awaiting(e,e=>[...e,t]);try{await p.promises.writeFile(s.join(e.key.folder,`.cc-candybar-watch-probe`),String(t)),this.probes++}catch(n){this.awaiting(e,e=>e.filter(e=>e!==t)),this.probeFailures++,this.logger(`warn`,`plugin storage probe failed folder=${cs(e.key.folder)} generation=${e.key.generation} reason=${JSON.stringify(n.message)}`)}}awaiting(e,t){let{delivery:n}=e;n.kind!==`stalled`&&(e.delivery={kind:`delivering`,unreported:t(n.unreported)})}stalled(e){let{delivery:t}=e;if(t.kind===`stalled`||t.unreported.length<2)return;let n=t.unreported[0];e.delivery={kind:`stalled`,since:n},this.stalls++,this.logger(`warn`,`plugin storage stalled folder=${cs(e.key.folder)} generation=${e.key.generation} since=${new Date(n).toISOString()}`),this.sessions.changed(t=>wq(t.storage,e.key))}delivered(e){let{delivery:t}=e;e.delivery={kind:`delivering`,unreported:[]},t.kind===`stalled`&&(this.logger(`info`,`plugin storage recovered folder=${cs(e.key.folder)} generation=${e.key.generation} stalled=${Date.now()-t.since}ms`),this.sessions.changed(t=>wq(t.storage,e.key)))}standing(e){let t=this.watched.get(Cq(e));if(t===void 0)return null;let{health:n}=t;switch(n.kind){case`faulted`:return`cannot refresh: ${e.folder} ${n.reason}; reload the config or restart the daemon`;case`watching`:case`lost`:return t.delivery.kind===`stalled`?Tq(e,t.delivery.since):null;case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return L(t);let n=Sq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?I:L(`${n}: ${t.message}`)}if(r.trim()===``)return I;let i=Lk(r);return i.kind===`failed`?L(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${cs(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await p.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=s.join(e.folder,a.name);try{let{mtimeMs:r}=await p.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&xq(t.sessionId)===a.name);if(r>=n||o)continue;await p.promises.unlink(t),i++}catch(e){if(e.code!==`ENOENT`)throw e}}this.logger(`info`,a())}catch(e){this.logger(`warn`,`${a()} outcome=failed reason=${JSON.stringify(e.message)}`)}}};function Dq(e){let{logger:t,ledger:n}=e;return{hostService:new dq({logger:t,ledger:n}),gitProvider:new GG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new FK({logger:t,ledger:n}),contextProvider:new zK({logger:t,ledger:n}),metricsProvider:new GK({logger:t,ledger:n}),activityProvider:new QK({logger:t,ledger:n}),tmuxService:new aq({logger:t,ledger:n}),autoCompact:new fq(t,n),cacheExpiry:new gq(t,n),managedStorage:new Eq({watchers:e.watchers,logger:t,ledger:n}),faults:new bq,log:e.logger}}function Oq(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 kq=`repo-configs.json`;function Aq(e=St()){return s.join(e,`repo-configs`)}function jq(e=St()){return s.join(Aq(e),kq)}const Mq=(e=St())=>{let t=Oq(Aq(e),kq,{},eH),n=Oq(e,kq,{},eH),r=()=>p.existsSync(jq(e));return{read:()=>(r()?t:n).read(),update:e=>{if(r())return t.update(e);let i=n.read();return i.kind===`failed`?i:t.update(()=>e(i.value))}}};function Nq(e,t,n){return{sessionId:e,action:fi,declaration:t,evaluated:n}}function Pq(e,t,n){return e.awaiting.map(e=>{let r=`${e} has a cc-candybar config — run it?`,i=XV.map(r=>wb(`[${r===`approved`?`approve`:`decline`}]`,gi([{verb:fi,args:[t,e,r,n.sign(Nq(t,e,r))]}])));return{severity:Sb,message:r,lines:[[wb(r,gi([{verb:Kr,args:[r]}])),...i]]}})}function Fq(e){return Math.max(1,e-2)}function Iq(e,t,n){return Le({dir:e.project_dir,env:n===void 0?[]:[[Xa,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function Lq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function Rq(e){return{...Object.fromEntries(_y.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:KH(e.preset)}}}const zq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function Bq(e,t){if(!t)return`-`;if(Ma(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return Ma(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const Vq=10*1e3;function Hq(e,t){if(!(t<60))return e*3600/t}function Uq(e,t,n,r){let i=r-t;if(i<50||i>Vq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Wq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Uq(t.input,t.atMs,n.input,n.atMs),i=Uq(t.output,t.atMs,n.output,n.atMs),a=Uq(t.total,t.atMs,n.total,n.atMs);if(!(r===void 0&&i===void 0&&a===void 0))return{...r!==void 0&&{input:r},...i!==void 0&&{output:i},...a!==void 0&&{total:a}}}function Gq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>Vq)continue;let o=Uq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Kq(e,t){let n=cx(e,t),r=[...qg.flatMap(e=>{let t=n[e];return Jg(t)?[t]:[]})];for(let n of A_(sx(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...qq(e,n.name));return Yq(e,r)}function qq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function Jq(e,t,n){return Yq(e,[...qq(e,t),...n])}function Yq(e,t){let n=pB(e),r=new Map(Jx(e)),i=t.flatMap(e=>n.ofTemplate(e).flatMap(({reaches:e})=>e)),a=new Set,o=new Set;for(;i.length>0;){let e=i.pop();if(a.has(e))continue;a.add(e);let t=r.get(e),s=dB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Xq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=Kq(e,n);return t.set(n,i),i}}function Zq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Qq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(zq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const $q=new WeakMap;function eJ(e){let t=$q.get(e);return t===void 0&&(t=tJ(e),$q.set(e,t)),t}function tJ(e){let t=t=>Zq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function nJ(e){return Fq(e.termCols??120)}function rJ(e){return $a(Qa(e.claudeConfigDir))}function iJ(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function aJ(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=eJ(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${E(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(mk(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(rJ(a)))])}function oJ(e,t){return[...t.keys()].filter(t=>e.has(t))}function sJ(e,t){let n=MG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function cJ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Qq(n),t.workspace?.project_dir]}function lJ(e,t,n,r,i){let a=eJ(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return MG(I);try{return n()}catch(t){return s.push(`${e}: ${E(t)}`),MG(L(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...cJ(n,r))),tmux:c(`tmux`,a.tmux&&o!==null,()=>e.tmuxService.declare(t,o)),hostName:c(`host.name`,a.hostName,()=>e.hostService.declareName(t)),hostUser:c(`host.user`,a.hostUser,()=>e.hostService.declareUser(t)),today:c(`today`,a.today,()=>e.usageStore.declareToday(t,n.hints.claudeConfigDir)),sources:new Map(oJ(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function uJ(e){let{hookData:t,deps:n}=e,r=eJ(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return I;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${E(t)}`),L(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(rJ(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function dJ(e){let t=e.git.current(),n=t.kind===`ok`?t.value.pullRequest:void 0;return[t,e.tmux.current(),e.hostName.current(),e.hostUser.current(),e.today.current(),...[...e.sources.values()].map(e=>e.current()),...n===void 0?[]:[n]].flatMap(e=>e.kind===`pending`&&e.why===`unread`?[e.landed]:[])}function fJ(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=eJ(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return ja;case`failed`:case`absent`:return;case`ok`:return t(e.value)}},d=e=>e.kind===`ok`?e.value:void 0,f=i.tmux??null,p=n.git.kind===`pending`?ja:TJ(n.git,()=>ja),m=n.tmuxSession.kind===`pending`?ja:d(n.tmuxSession),h=n.hostName.kind===`pending`?ja:d(n.hostName),g=n.hostUser.kind===`pending`?ja:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?ja:bJ(n.autoCompact,d(n.context)?.maxTokens),v=r.rate_limits?.five_hour,y=r.rate_limits?.seven_day,b=l.burn?n.usage.kind===`pending`||n.metrics.kind===`pending`?ja:hJ(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,gJ),x=u(n.usage,e=>CJ({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>CJ({lastResponseTime:e.lastResponseTime,responseTime:e.responseTime,sessionDuration:e.sessionDuration,messageCount:e.messageCount,nonPrompts:e.nonPrompts,linesAdded:e.linesAdded,linesRemoved:e.linesRemoved})),te=u(n.activity,xJ),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=wJ(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:wJ(r.workspace.current_dir)??``,project_dir:wJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>wJ(e)??e)}:r.workspace,C=r.session_id;return{...r,...ae!==void 0&&{workspace:ae},...ie!==void 0&&{home:ie},...p!==void 0&&{git:p},...f!==null&&{tmux:{pane:f.pane,...m!==void 0&&{session:m}}},host:{...h!==void 0&&{name:h},...g!==void 0&&{user:g},...i.ssh!==void 0&&{ssh:i.ssh}},...Rq(a),history:t.history,navigation:{back:t.back},term:{cols:nJ(i)},...c,...s!==null&&{configPath:s},resumeCommand:Iq(ae,C,i.claudeConfigDir),...x!==void 0&&{session:x},...b!==void 0&&{burn:b},...ee!==void 0&&{speed:ee},...l.block&&v!==void 0&&{block:{nativeUtilization:v.used_percentage,resetsAt:v.resets_at}},...y!==void 0&&{weekly:{percentage:y.used_percentage,resetsAt:y.resets_at}},...re!==void 0&&{cache:re},...ne!==void 0&&{context:ne},...S!==void 0&&{metrics:S},...te!==void 0&&{activity:te},..._!==void 0&&{autocompact:_},plugins:mJ(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?ja:t})}}function pJ(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function mJ(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function hJ(e,t){let n=e!=null&&t!=null?Hq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function gJ(e){let t=Wq(e),n=Gq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function _J(e,t){return fJ(e,t,uJ(e))}function vJ({usageStore:e,faults:t,log:n},r,i,a){if(t.of(i.session_id,`today`)!==void 0)return;let o=r.current();if(o.kind===`pending`)return ja;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${E(e)}`),I}})();return s.kind===`pending`?ja:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function yJ(e,t,n){await aJ(e,t,n),await AG(()=>{let t=dJ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function bJ(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return TP(e.value,t)}}function xJ(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=SJ(e.running),i=SJ(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 SJ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function CJ(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 wJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function TJ(e,t){if(e.kind!==`ok`)return;let n=e.value,r=e=>e?.kind===`ok`?e.value:void 0,i=r(n.aheadBehind),a=r(n.sha),o=r(n.operation),s=r(n.committedAt),c=r(n.stashCount),l=r(n.upstream),u=n.upstream===void 0?void 0:r(jW(n.upstream,n.aheadBehind)),d=r(n.repoName),f=r(n.repoUrl),p=n.pullRequest===void 0?void 0:n.pullRequest.kind===`pending`?n.pullRequest:MW(n.pullRequest,n.head),m={};switch(p?.kind){case`pending`:{let e=t(`git.pr`);m={prNumber:e,prState:e,prUrl:e,prError:e,prEarlier:e};break}case`ok`:m={prNumber:p.value.number,prState:p.value.state,prUrl:p.value.url};break;case`failed`:m={prError:p.reason};break;case`earlier`:m={prEarlier:p.value.state};break;case`absent`:case void 0:break}return{branch:n.branch,status:n.status,...i!==void 0&&{ahead:i.ahead,behind:i.behind},...n.workingTree!==void 0&&{staged:n.workingTree.staged,unstaged:n.workingTree.unstaged,untracked:n.workingTree.untracked,conflicts:n.workingTree.conflicts},...a!==void 0&&{sha:a},...o!==void 0&&{operation:o},...s!==void 0&&{committedAt:s},...c!==void 0&&{stash:c},...l!==void 0&&{upstream:l},...u!==void 0&&{tracking:u},...d!==void 0&&{repoName:d},...f!==void 0&&{repoUrl:f},...m}}function EJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const DJ={kind:`hidden`},OJ={kind:`shown`};function kJ(e,t){try{return EJ(e,t)?OJ:DJ}catch(e){let t=lS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function AJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function jJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function MJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function NJ({text:e,placement:t,lead:n,trail:r}){return{text:PJ(e),placement:t,...n!==void 0&&{lead:PJ(n)},...r!==void 0&&{trail:PJ(r)}}}function PJ(e){let t=e.blankCopy(e.plain);t.style=Ky(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Ky(i).clearMetaAndLinks(),n,r);return t}function FJ(e){let t=MJ(e);if(t.length===1)return e.text;let n=AJ(t);return n.style=e.text.style,n}function IJ(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=AJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:AJ([d,...c],a)},...l.length>0&&{trail:AJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(jJ(u,n,p),[{text:u,...f}])}const LJ=RegExp(`\\x1b\\[[0-9;]*m|${tf.source}`,`g`);function RJ(e){return Math.max(0,...e.split(`
193
+ `).map(e=>Ks(e.replace(LJ,``))))}function zJ(e,t){let n=()=>e.map(e=>({owner:FJ(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=_b(e.map(FJ),t).split(`
194
+ `);if(i.length>1)return n();let a=Math.max(0,t.width-RJ(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];jJ(c,c.cellLength+a,n)}),n()}function BJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=VJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Ky(a.style)};if(e.style.link){i();let r=VJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function VJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>HJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function HJ(e,t){let n=e.copy();return n.style=t,n}function UJ(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 WJ(e,t){let{look:n}=UJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function GJ(e,t){let{layout:n}=UJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function KJ(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 qJ(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,JJ(e,t,o,n,r,i));return i}function JJ(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=mx(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=jy.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=mx(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=mx(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:ZJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:ZJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:vx(n),argv:n.run.map(n=>ZJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,ZJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:ZJ(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 YJ(e){return e.kind===`do`?YJ(e.head):e}function XJ(e){switch(YJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function ZJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function QJ(e,t){return e.has(t)?aS(e.read(t)):``}function $J(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function eY(e,t,n,r){let i=new W(e,{style:V.combine([r,new V({link:t,bold:n})])});return i.overflow=`ignore`,i.end=``,i}function tY(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Ky(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Ky(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function nY(e,t){return Math.max(e.members.indexOf(QJ(t,e.stateVar)),0)}function rY(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=QJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=QJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=QJ(r,e.stateVar);return{effects:[{verb:Br,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(nY(e,r)+1)%e.members.length];return{effects:[{verb:Br,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:Vr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Hr,args:[$J(e.text,kk(r))]}],active:!1};case`open`:return{effects:[{verb:Ur,args:[$J(e.target,kk(r))]}],active:!1};case`persist-literal`:{let t=QJ(r,e.stateVar);return{effects:[{verb:Jr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=QJ(r,e.stateVar);return{effects:[{verb:Jr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(nY(e,r)+1)%e.members.length];return{effects:[{verb:Jr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:Yr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:ei,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ni,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ri,args:[i]}],active:!1};case`back`:return{effects:[{verb:ii,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ai,args:[i]}],active:!1};case`save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Zr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Qr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:$r,args:[i,$J(e.name,kk(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:si,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:ci,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:li,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:di,args:[i,e.line]}],active:!1};case`run`:{let t=kk(r),n=JSON.stringify({run:e.argv.map(e=>$J(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,$J(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:ti,args:[i,e.key,HI(e.op)]}],active:!1};case`do`:{let o=rY(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>rY(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:ti,args:[i,e.key,HI(r)]}],active:!1}}}}function iY(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:wi(`action "${e}"`,n,t.members.length,nY(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 aY(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=UJ(n,`action "${e}"`).store,{display:a,boundValue:o}=iY(e,YJ(r),t,i),s=QJ(i,`session.id`),{effects:c,active:l}=rY(r,a.plain,o,i,s,n.signer);return tY(a,gi(c),l)}function oY(e){return{action:{fn:(t,...n)=>aY(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function sY(e,t){return eY(`✕`,gi([{verb:Br,args:[QJ(e,`session.id`),t,P]}]),!1)}function cY(e,t,n){return new V({bgcolor:B.fromRgba(t),color:B.fromRgba(eg(e,t,n))})}function lY({tint:e,text:t}){return new V({bgcolor:B.fromRgba(e),color:B.fromRgba(t)})}function uY(e,t,n){return new V({color:B.fromRgba(zl(Wh(e,`warning`),t,$h,n))})}function dY(e,t,n){return V.combine([cY(e,t,n),uY(e,t,n)])}function fY(e,t,n){return cY(e.palette,Dg(e.palette,e.disclosure,t,n),n)}function pY(e){let t=B.fromRgba(Wh(e,`background`)),n=W.fromFragments(vh.map(n=>new W(`▀`,{style:new V({color:B.fromRgba(Wh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const mY=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},hY=e=>new V({bold:e});function gY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>mY(a,V.combine([fY(e,{...n,distribution:t},i),hY(o)]));let o=cY(e.palette,a,i);return(e,t,i,a)=>_Y(i,V.combine([o,hY(a)]),r(t,n))}const _Y=(e,t,n)=>mY(W.fromFragments([mY(e,t),mY(` `,t),pY(n)]));function vY(e,t){return t===void 0?(e,t,n)=>mY(n):(n,r,i)=>_Y(i,void 0,t(r,e))}function yY(e,t,n,r,i){let a=cY(e.palette,i,r);return(e,r,i,o)=>mY(W.fromFragments([mY(o?`[`:` `,a),pY(n(r,t)),mY(o?`]`:` `,a)]))}function bY(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=>xY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function xY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function SY(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function CY(e){return{current:null,drawnAt:e}}function wY(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 TY(e,t,n){return DY(e,()=>n(wY(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function EY(e,t){return DY(e,()=>(e.current=null,t()))}function DY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function OY(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 kY(e){return new W(e).cellLength}function AY(e){let{width:t,chromeCols:n,padding:r}=UJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function jY(e){let{padding:t,seamCols:n}=UJ(e,`a row fit`);return Math.max(1,AY(e)-(kY(`✕`)+2*t+n))}function MY(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 NY(e,t,n){let r=kY(`←`)+1+kY(`→`)+1,i=MY(e,t,n);return(i.length>1?MY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function PY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function FY(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 IY(e,t,n){let r=e.compiled.get(t),i=r&&YJ(r);if(!i||i.kind!==`set-option`&&i.kind!==`persist-option`&&i.kind!==`layout-op-option`)throw Error(`${n} references action "${t}" which must be a set-option, persist-option, or layout-op-option action ({ set, from }, { persist, from }, or { persist, insertSegmentFrom, anchor, relation }), got ${i?`a ${i.kind} action`:`no such action`}`);return i}function LY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=UJ(a,`picker`).store,d=QJ(u,`session.id`),f=`stateVar`in t?QJ(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`?jY(a):AY(a):1/0,h=(r.kind===`led`?0:kY(`✕`)+1)+c.reduce((e,t)=>e+kY(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?NY(_.map(e=>e.cellLength),m,h):bY(g.entries,g.groups,i),y=parseInt(QJ(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=>gi([{verb:Br,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Br,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>gi([...rY(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>tY(e,ie(t.options[n])),C=r.kind===`led`?[]:[eY(`✕`,gi(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>eY(e,gi([...rY(l,r,r,u,d,a.signer).effects,{verb:Br,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(eY(`←`,te(x-1),!1));let w=x<v.length-1?[eY(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[PY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let T=new V({bold:!0}),oe=v.length>1?` ${x+1}/${v.length}`:``,E=S.length===1?[new W(`${S[0].label}${oe}`,{style:T})]:[],se=[PY([...C,...E,...w],i)];for(let e of S){S.length>1&&se.push(PY([new W(e.label,{style:T})],i));let n=Math.max(...e.indices.map(e=>kY(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:Ly(a),s=` `.repeat(n-kY(e)+2),c=o===void 0?e:`${e}${s}${o}`;se.push(PY([ae(p(r,SY(c,m)),r)],i))}}return se}function RY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{ok(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=FY(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=IY(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=OY(t,`{{ picker }}`);if(u.bg===void 0)throw Error(`{{ picker }} is not available while segments.${u.segName}'s own "bg:" is being evaluated — a picker is drawn on that background`);let[d]=LY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,gY(u,Nh(void 0),WJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),uY(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function zY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function BY(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 VY(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=UJ(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=QJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return PY([],!0);let d=QJ(o,t.stateVar),f=zY(l,d),p=e=>l[f(e)],m=new Map,h=e=>{let t=m.get(e);if(t!==void 0)return t;let r=gi(rY(s,p(e),p(e),o,c,n.signer).effects);return m.set(e,r),r},g=e=>r({index:f(e),count:u},p(e),p(e),p(e)===d),_=new Map,v=e=>{let t=_.get(e);if(t!==void 0)return t;let n=tY(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):tY(vY(WJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),gi(rY(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=BY(e=>v(e).cellLength,u,kY(`◀`)+1+y.cellLength+1+kY(`▶`),jY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return PY([...ee(-1).reverse(),eY(`◀`,h(-1),!1),y,eY(`▶`,h(1),!1),...ee(1)],!0)}function HY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(ok(`carousel "${n}"`,[`neighbours`,`centre`],o),i!==void 0&&!(Number.isInteger(i)&&i>=0))throw Error(`carousel "${n}": neighbours must be a whole number ≥ 0 (0 shows only ◀ CURRENT ▶), got ${String(i)}`);if(a!==void 0&&!(typeof a==`string`&&e.compiled.has(a)))throw Error(`carousel "${n}": centre must name a declared action, got ${JSON.stringify(a)}`);if(a!==void 0&&XJ(e.compiled.get(a)))throw Error(`carousel "${n}": centre "${a}" writes a value the template binds, and the centre binds none — name an action that writes a fixed value, a cycle, or a do of them`);let s=i??1/0,c=IY(e,n,`carousel`),l=OY(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 VY(n,c,e,gY(l,Nh(void 0),WJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function UY(e,t,n){let r=IY(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 WY(e,t,n){let r=Math.imul(e^e>>>16,73244475);return r=Math.imul(r^r>>>16,73244475),r^=r>>>16,(n+1+(r>>>0)%Math.max(t-1,1))%t}function GY(e,t,n,r){let i=UY(e,t,n),a=r??QJ(UJ(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,WJ(e,`{{ ${n} }}`))}function KY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(ok(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return pY(GY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function qY(e,t,n){return{swatches:{fn:(r,i)=>{let a=UY(e,r,`swatches`),o=FY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=OY(t,`{{ swatches }}`);if(s.bg===void 0)throw Error(`{{ swatches }} is not available while segments.${s.segName}'s own "bg:" is being evaluated — a swatch row is drawn on that background`);let c=t.drawnAt(),{options:l}=a,u=l.length,[d]=LY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,yY(s,WJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),uY(s.palette,s.bg,c),u===0?[]:(()=>{let t=zY(l,QJ(UJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[WY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const JY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function YY(e,t,n,r){let i=mg(e,n,r),a=(t,n)=>({text:t,colour:n,ink:eg(e,n,r)});return[[Oh(t).map((n,i)=>{let a=Gh(e,n);return{text:JY[i%JY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Wh(e,`warning`)),a(`error`,Wh(e,`error`))]]]}function XY(e,t){let n=e.flatMap((e,t)=>e.map(({text:e,colour:n,ink:r},i)=>({gap:t>0&&i===0?` `:``,cell:new W(` ${e} `,{style:lY({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function ZY(e,t,n,r,i){let a=YY(e,t,n,r).map(e=>XY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
195
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}function QY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(ok(`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}=WJ(e,`{{ themePreview }}`);return ZY(r===void 0?a:GY(e,r,`themePreview`),o,{...OY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),jY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const $Y=e=>e.slice(e.lastIndexOf(`.`)+1),eX=(e,t)=>{let n=new W($Y(e));return n.truncate(t,{marker:`…`}),n.plain};function tX(e,t){let n=e.map(e=>e.map(({name:e})=>kY($Y(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 nX(e,t,n,r){let i=tX(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${eX(s,i)} `,{style:lY(Lg(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
196
+ `),...e]));return o.overflow=`ignore`,o.end=``,o}const rX=`layoutPreview`;function iX(e,t){return{[rX]:{fn:()=>nX(GJ(e,`{{ layoutPreview }}`),WJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),jY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function aX(e,t,n,r){let i=OY(r.activeSegment,`{{ menu }}`),a=r.action,o=jA(i.placementId,e,n.key),s=PA(o),c=AA(e),l=UJ(a,`menu`).store,u=QJ(l,o)===c,d=QJ(l,`session.id`),f=u?P:c,p=eY(wi(`{{ menu "${e}" }}`,t,2,+!!u),gi([{verb:Br,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=mg(i.palette,i.disclosure,t).plane,l=IY(a,e,`menu`);return LY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,P],[s,`0`]],onPick:n.closeOnPick},n.paged,a,gY(i,n.distribution,WJ(a,`{{ menu }}`),l.paletteOf,t,c),uY(i.palette,c,t))})():[]),p}const oX=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function sX(e,t){let n=t[t.length-1],r=oX(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:RA(r??{})}}function cX(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=sX(t,n);return aX(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function lX(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=uX(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new W(t?i:a,{style:l===void 0?void 0:new V({color:l})}))}let l=W.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function uX(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 dX(e){let t={fn:(()=>{let t=OY(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:(()=>OY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=OY(e,`{{ keptOn }}`),i=Al(r,t),a=Al(r,n),o=bc(Vl(i,z.TRUECOLOR),Vl(a,z.TRUECOLOR)),s=Math.min($h,Math.max(o,3));return(Bl(i,e.drawnAt(),(e,t)=>bc(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=WO(()=>OY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...fX(s)];return lX({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 fX(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 pX(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>Dk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const mX={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},hX=new WeakMap;function gX(e){let t=hX.get(e);return t===void 0&&(t=_X(e),hX.set(e,t)),t}function _X(e){let t=new Map(Jx(e)),n=pB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:mX[t.kind]])),i=new Map([...t].map(([e,t])=>[e,pX(t,n)]));for(let e=!0;e;){e=!1;for(let[t,n]of i)r.get(t)!==`view`&&n.some(e=>e===null||r.get(e)!==`directory`)&&(r.set(t,`view`),e=!0)}return r}function vX(e){let t=[],n=[];for(let r of e){if(!r.contains(`
197
197
  `)){n.push(r);continue}let e=r.split(`
198
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function vX(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const yX=e=>e.kind===`failed`?EJ:e;function bX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function xX(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function SX(e){return{...e,cells:e.cells.map(MJ)}}function CX(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,...wX(e,r)]}function wX(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 TX(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:CX(e.direction,e.children.map((t,i)=>n(t,[...r,EX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function EX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:T_[e.direction]}}const DX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Nh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,j_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),CX(e.direction,e.children.map((n,r)=>t.renderChild(n,yX(t.gate),EX(e,r))))}},OX={drop:e=>e.place,above:()=>`above`},kX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},AX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:E_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Di(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,M_(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,jX(e,t))};function jX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=jk(t.scope,e.settings);if(t.gate.kind===`failed`)return LX(e,r,t,t.gate.message);try{let i=t.placement(e),a=bX(t.gate,i.gate());if(a.kind===`failed`)return LX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return LX(e,r,t,s.message);let c=Lb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Xj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?MX(f.variable):NX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?PX(p.segment,u):FX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:EJ,h.disclosure).map(e=>({...e,place:OX[v.placement](e)})),b=(e,t,n)=>FJ(zJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?kX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(IX(jJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(jJ)),[...ie,...re]}catch(n){return LX(e,r,t,n.message??String(n))}}const MX=e=>({kind:`waiting`,variable:e});function NX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=lS(e);if(t===void 0)throw e;return MX(t.variable)}}function PX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:_X(zJ(r,c)).map((e,t)=>({cells:FJ(e,{...l,lead:t===0?zJ(i,c):[],trail:t===0?zJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:FJ(zJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function FX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=zJ(RX(e.lead,e,t,n),l),d=zJ(RX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return FJ(zJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function IX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function LX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:FJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Xj(n.palette)},lead:RX(e.lead,e,t,n),trail:RX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function RX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=lS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const zX={container:DX,segment:AX};function BX(e){return zX[e]}var VX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?HX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const HX={kind:`hidden`},UX={palette:`theme`,style:`style`,effect:`effect`},WX=jy.get(`colorCompatibility`),GX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function KX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function qX(e){if(e.ok)return e.value;throw e.error}const JX=e=>({read:()=>e}),YX=gh({basePalette:hh,palette:hh,decor:Ag});var XX=class{evaluated=0;memory=new VX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&YX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=kk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(WX);return typeof e==`string`&&m_(e)?e:`truecolor`});let i=(0,J.observable)(GX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return TX(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=PI(e);return i===void 0?[]:[{name:i,address:n,palette:Lb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>h_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=_A(e);return t===void 0?hA(e)===void 0?iA(this.view.get().payload(),e):iA(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[UX[e]];if(t.kind===`decided`)return $X(t.name,null,null);let r=tZ(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=nZ(this.source,e,i.name,r.where,e=>{t=e}),$X(n,t,null)}case`pending`:return $X(n??t_[e],null,i.variable);case`failed`:return n=t_[e],$X(n,n_(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!eZ(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??t_[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return OJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>TY(this.source.activeSegment,()=>OJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new rZ(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:GJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=lS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:KX(e)}),qX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:PI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function ZX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new XX(t,n,e,r);return e.views.set(t,a),a}function QX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const $X=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),eZ=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function tZ(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function nZ(e,t,n,r,i){switch(t){case`palette`:return Hb(n,r,i).name;case`style`:return Qg(n,e.styles).name;case`effect`:return c_(n).name}}var rZ=class{where=iZ(gh({palette:hh,region:Og}));ground=iZ(gh({colours:oZ,bodyOpen:hh}));opened=iZ(gh({colours:oZ,open:hh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=jk(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?JX(DJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>TY(r,()=>OJ(a,i))),this.open=d===void 0?JX(EJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>TY(r,()=>OJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return lZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return uZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?JX(fZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return dZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),mZ(n,r,this.affixes.read())}};function iZ(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const aZ=(e,t)=>e.hex===t.hex,oZ=gh({palette:hh,drawnAt:hh,tint:aZ,text:aZ,bg:aZ,disclosure:jg});function sZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const cZ=e=>mg(e.palette,e.disclosure,e.drawnAt);function lZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Lg(n,r,i)};return wY(e,sZ(t,c),e=>{let t=Qj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function uZ(e,t,n,r,i,a){return wY(e,sZ(t,n),e=>(e.bg=i?cZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function dZ(e,t,n,r,i,a,o){return wY(e,sZ(t,n),e=>(e.bg=r?cZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const fZ={lead:[],trail:[],drops:[]};function pZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return sY(t,cZ(e).state,n)},get band(){return sY(t,cZ(e).plane,n)},get close(){return uY(t,cZ(e).state,n)},disclosure:r}}function mZ(e,t,n){return{styles:pZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?cZ(e).shortfalls:[]}}function hZ(e,t,n,r,i,a,o){let s=lZ(e,t,n,r,i,void 0,void 0,o);return mZ(s,uZ(e,t,s,a,!1,o),fZ)}function gZ(e,t,n,r,i){return pZ(lZ(e,t,n,r,i,void 0,void 0,{}))}function _Z(e,t){return{payload:()=>e,selections:()=>t}}function vZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Wk(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 yZ(e,t){switch(F_(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 bZ(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:vZ(n.cache),parse:yZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:vZ(n.cache),parse:yZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function xZ(e,t){let n=ZS.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 SZ(e,t,n){let{compiled:r,loadWarnings:i}=wZ(e,t,n.cwd,CZ(n.signer),OZ);return{...r,loadWarnings:i}}const CZ=e=>(t,n)=>kZ(n,e);function wZ(e,t,n,r,i=OZ){let a=TZ(e),o=EZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:DZ(e,t,n,i)}}function TZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of My)n in t&&r.set(e,n);for(let[t,n]of V_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[..._B(e)].sort(([e],[t])=>e<t?-1:1)}}function EZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function DZ(e,t,n,r){let i=hX(e),a=_B(e),o=[];for(let[s,c]of Jx(e))if(r.has(i.get(s)))try{bZ(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const OZ=new Set([`directory`,`view`]);function kZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>HJ(i,`drawnAt`).registry.drawnAt(),o=SY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=ix(e.presets),u=CI(e),d=[e=>KY(i,o,e.now)],f=Ok({extraFuncs:{...aY(i),...GY(i),...LY(i,o),...VY(i,o),...ZY(i,o),...rX(i,o),...sX(s),...uX(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=xZ(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=KJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=G_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Z_(t,e,a,t=>String(HJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return BX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=sx(e,t);S.set(t,x(n,r))}let te=new Map(qg.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of yB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:MZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:uB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:Tk(d)},re=SB(ne),ie=[...S.values()].flatMap(jZ(y)).some(e=>re(m.get(e))),ae=ie?SB({...ne,clock:new Set([...ne.clock,nX])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function AZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const jZ=e=>t=>{let n=[];return TX(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function MZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const NZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function PZ(e,t,n,r,i){let a=FZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function FZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??t_[e];case`failed`:return r({kind:`rule`,slot:e,message:n_(t.where,e,`the rule failed — ${n.error}`)}),t_[e]}}function IZ(e){return LZ(e).filter(e=>!e.name.startsWith(TA)).map(e=>e.id)}function LZ(e){return e.kind===`container`?e.children.flatMap(LZ):[e,...e.opens===void 0?[]:LZ(e.opens.body)]}function RZ(e,t,n,r,i,a,o,s,c=$H(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return ZX(t,n,r,_Z(l,c)),BZ(e,t,n,r,l,a,o,s,c)}function zZ(...e){return RZ(...e).text}function BZ(e,t,n,r,i,a,o,s,c){try{var l=Na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new rb(``),g=h.clockAt(a,i_[c.animationSpeed]);l.u(gk(a,g.anim));let _=QX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:db(v),padding:v.padding,seamCols:fb(v),preset:c.preset},i);let y=_.evaluated;l.u(GJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Dh[c.variation],shade:Th[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,xX),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=nZ(t,e,PZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:T,effect:oe}=_.selections(),E=w.kind===`decided`?w:Hb(C(`palette`),``,NZ),se=T.kind===`decided`?T:Qg(C(`style`),e.styles),ce=oe.kind===`decided`?oe:c_(C(`effect`)),le=E.value,ue=zb(le,se.value);_.publishLook({basePalette:le,palette:ue,decor:x});let de=c.idleSince===void 0?null:Qv(c.idleSince,c.menuTimeout,a),fe=Wh(ue,`warning`),pe=de===null?null:{t:de,fill:fe,text:eg(ue,fe,r.drawnAt())},me=h.motion(ce.value,g,{transitions:ee,source:S,last:ne,returned:xX,hold:SX},pe);u?.clear();let he=t=>e.segments[t],ge=e=>{for(let t of e.shortfalls)m.add(t);return e},_e=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>ge(t.evaluate(e,n))}},ve=(e,i,a)=>{let o=i.kind===`hidden`?i:bX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${IZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ue,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:_e,evaluateOnce:(e,n,i,o)=>ge(hZ(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:he,renderChild:(e,t,n)=>ve(e,t,Fg(a,n)),renderBody:(e,t,n)=>ve(e,t,Ig(n)),closeDisclosure:e=>oY(n,e),placed:(e,t)=>te.placed(e,me.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>gZ(t.activeSegment,e,n,a,r.drawnAt())};return BX(e.kind).render(e,c)},ye=t.roots.get(b);if(ye===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${nx}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let be=vX(ve(ye,DJ,Pg(x))).map(({line:e,row:t})=>{let n=RJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...gb(n.map(e=>e.owner),v,me.row(t,r,n))}});me.drawn(),te.commit();let xe=be.filter(e=>e.kind===`menu`).length,Se=be.some(e=>e.moves)?`moves`:xe>0||_.selections().effect.kind===`expression`||ee||LZ(ye).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:be.map(e=>e.text).join(`
199
- `),motion:Se,menuRows:xe,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*VZ(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*HZ(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 ix(e.presets)){for(let n of A_(sx(e,t).node))n.when!==void 0&&(yield n.when);let n=cx(e,t);for(let e of qg){let t=n[e];Jg(t)&&(yield t)}}for(let[,t]of VZ(e))for(let[,e]of R_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of yx(t))yield e}function UZ(e,t){let n=pB(t),r=new Set,i=new Set,a=new Set;for(let e of HZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Bx(e,t.helpers))i.add(n);for(let n of Gx(e,t.helpers))a.add(n)}for(let[,e]of VZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of ix(t.presets))for(let n of A_(sx(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!DA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(VZ(e));return[...d(`variable`,f.keys(),e=>l(e,f.get(e))),...d(`action`,Object.keys(e.actions??{}),e=>o.has(e)),...d(`helper`,Object.keys(e.helpers??{}),e=>a.has(e)),...d(`segment`,Object.keys(e.segments??{}),e=>c.has(e))]}var WZ=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function GZ(e){return Math.floor(Math.max(e/4,e*cr-67108864))}const KZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function qZ(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=cV(e),r=t===void 0?void 0:n.variables[uV(t)];return r?.kind===`file`?r.path:`none`},d=o.flatMap(e=>{let t=cV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>gV(e)(t)&&t!==uV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${e.join(` < `)||`<default>`}: projections=${[..._B(n).keys()].join(`,`)||`-`} instantSegments=${AZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}function JZ(e){let t=e=>e.join(`,`)||`-`;return`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} awaiting=${t(e.repos.awaiting)} declined=${t(e.repos.declined)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function YZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function XZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function ZZ(e,t){return new Set(ix(e.presets).filter(n=>sx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function QZ(e){let t=[],n=e=>{try{return yt(e)}catch(n){return t.push({path:e,reason:n.message}),[e]}},r=new Map,{loaded:i,dropped:a,unreached:o}=e.state.plugins,c=[...new Set([...e.state.plugins.roots,s.join(e.projectDir,VV)])];for(let t of[...iH(e.projectDir,e.cwd,e.configFile),...c,...i,...[...a,...o].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))].flatMap(n)){let{dir:e,name:n}=$x(t),i=r.has(e)?r.get(e):new Set;i?.add(n),r.set(e,i)}for(let e of c){let{dir:t,name:n,leaf:i}=$x(s.join(e,`_`));i&&n===`_`&&r.set(t,null)}return{targets:{dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},unresolved:t}}function $Z(e){return e.filter(Boolean).join(`
200
- `)||null}function eQ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=xH(t.layers,WH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??WH,l=a.find(e=>e.path===t.home)?.raw??{},u=new SS,d=new cA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=wZ(o,d,e,r.compile??CZ(r.signer),iQ),n.push(...f.loadWarnings);let t=d.view();n.push(...DZ(o,t,e,aQ)),t.dispose(),FU(o),rL(o),p=tQ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Yq(o),authoredRoots:ZZ(c,l),fileHeldSettings:xU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>UZ(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:p}}function tQ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function nQ(e,t,n,r){let i=performance.now(),a=oH(jq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[pH(e,t),dH(a),tH(o)],l,u=null;try{l=eQ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof tv&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:$Z(c),state:null,error:e instanceof tv||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:$Z(c),state:l,error:null}}function rQ(e,t,n){return eQ(e,{layers:[],home:``,repo:t},[],n)}const iQ=new Set([`directory`]),aQ=new Set([`view`]);function oQ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new WZ;DZ(e.config,l,t,aQ);let d=()=>QH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),oJ(L(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});ZX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var sQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ne,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{};let{dir:n,name:r}=$x(Aq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??kZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=XZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,qZ(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??rQ(t,a.repos.plugins,this.deps),watch: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=${N(this.accountedBytes())}/${N(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=Na();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(XZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=oQ(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return nQ(e,t,n,this.deps)}drop(e,t,n){t.watch?.handle.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${N(this.accountedBytes())}/${N(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,YZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,qZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let{targets:n,unresolved:r}=QZ(e),i=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`,{watch:a,move:o}=this.deps.watchers.follow(e.watch,{key:i,targets:n},()=>this.onConfigChanged(e));if(e.watch=a,o!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${n.dirs.map(e=>e.path).join(`,`)} refused=${a.handle.refused.length}`);for(let{path:t,reason:n}of r)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const cQ=16384;var lQ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<cQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%cQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0,probes:0,probeFailures:0,stalled:0,stalls:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Qe,sourceDigest:tt(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function uQ(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 dQ={load:()=>({}),save:()=>{},flush:()=>{}};var fQ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=dQ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,J.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,J.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,J.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function pQ(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 mQ=class{timer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Ne){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return pQ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await p.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await p.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Math.round(performance.now()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.rmSync(this.writingPath,{force:!0}),p.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const hQ=new Set([`1`,`true`]),gQ=new Set([`0`,`false`,``]);function _Q(e,t){let n=HQ(e),r=n.scope===`segment-palette`?`string`:Cy(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(hQ.has(t))return`true`;if(gQ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function vQ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function yQ(e,t,n){try{if(t===null){p.rmSync(vt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function bQ(e){return/^\s*$/.test(e)?null:Ki(e)}function xQ(e,t){return e!==null&&Ji(e,t)!==void 0}function SQ(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(SQ),...i}}return e}function CQ(e){if(!Jb(e))return SQ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,SQ(t)])),...n}}const wQ=HH,TQ=wQ.segments,EQ=wQ.presets,DQ=wQ.root;function OQ(e,t,n,r){if(!xQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function kQ(e,t){let n=Ej(t);return t.scope===`segment-palette`&&OQ(e,[`segments`,t.segment],TQ[t.segment],n.join(`.`)),n}function AQ(e){return Ki(na(e))}function jQ(){return Object.entries(DQ.rows).map(([e,t])=>{let n=SQ(t);return{path:[`root`],fragment:AQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function MQ(e,t){let n=e===null?void 0:Ji(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function NQ(e,t){if(t===void 0)return null;let n=CQ(t);return{path:e,fragment:AQ(n),unit:{path:e,value:n}}}function PQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=EQ[t];OQ(e,n,i,r.join(`.`));let a=MQ(e,r)??NQ(r,i?.root);return a!==null&&Ca(a.fragment)?a:null}function FQ(e,t){let n=Sa(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 IQ(e,t){return[...jQ(),MQ(e,[`root`]),PQ(e,t)].filter(e=>e!==null).reduce(FQ,new Map)}function LQ(e,t,n){for(let{node:r,...i}of IQ(e,t).values())if(Ta(r,n))return i;throw new q(`${RQ(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 RQ(e,t){return PQ(e,t)?.path??[`root`]}function zQ(e,t){return t.scope===`preset-root`?RQ(e,t.preset):Ej(t)}function BQ(e,{unit:t}){return t===null?e:ga(e,t.path,na(t.value),ea)}function VQ(e){let t=Tj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function HQ(e){let t=VQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function UQ(e,t,n,r,i){i(t,n,e$(t,r)),yQ(t.path,r,e.logger),e.record(t.path,n,r)}function WQ(e,t,n){let r=qQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const GQ=()=>{};function KQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function qQ(e,t,n){let r=JQ(e,t);if(r===null)return[];let i=new Set(QQ(ZQ(r),ZQ(n)));return QQ(XQ(e,r),XQ(e,n)).filter(e=>!i.has(e))}function JQ(e,t){try{return YQ(e,t)}catch(e){if(e instanceof tv)return null;throw e}}function YQ(e,t){return xH(t===null?e.above:[e.path,...e.above],WH,{entered:()=>{},warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function XQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function ZQ(e){return e.layers.at(-1)?.config??e.base}function QQ(e,t,n=``){return!$Q(e)||!$Q(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>QQ(e[r],t[r],n===``?r:`${n}.${r}`))}function $Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function e$(e,t){try{return YQ(e,t)}catch(e){throw e instanceof tv?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function t$(e,t){let n=HQ(t),r=bQ(vQ(e)??``),i=r===null?void 0:Ji(r,Ej(n));return i!==void 0&&`value`in i?i.value:void 0}function n$(e,t,n){r$(e,t,n,[])}function r$(e,t,n,r){let i=vQ(t.path),a=n.reduce((e,[t,n])=>ga(e,kQ(bQ(e),HQ(t)),_Q(t,n),ea),i??``);UQ(e,t,i,KQ(t,()=>i$(a,t.path,r,e=>e)),WQ)}function i$(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=LQ(bQ(s),n,i),l=ka(BQ(s,c),c.path,i,a,na(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function a$(e,t,n){let r=bQ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of IQ(r,t)){if(!Ta(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Xi(e,c):na(s.value);if(a!==`#`)return ga(e,[...i,`rows`,a],l,ea);if(PQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ga(e,i,l,ea)}return e}function o$(e,t){return va(e,t,t[0]===`presets`&&t.length>2&&!KH(t[1])?2:0)}function s$(e,t,n){let r=n.map(VQ),i=vQ(t.path);if(i===null)return;let a=r.reduce((e,t)=>o$(e,zQ(bQ(e),t)),i);a!==i&&UQ(e,t,i,a,GQ)}function c$(e){let t=e===null?void 0:Ji(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function l$(e,t){let n=new Set([...GH,...c$(e),...t.above.flatMap(e=>Object.keys(zi.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(xA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(xA(e)))}function u$(e,t,n,r,i,a){let o=vQ(t.path),s=bQ(o??``),c=l$(s,t),l=[`presets`,c],u=KQ(t,()=>PQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Xi(o??``,u.fragment):na(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],na(r)]]],f=i.map(([e,t])=>{let n=wj(c,e);return[kQ(s,HQ(n)),_Q(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ga(e,t,n,ea),ga(o??``,l,`{}`,ea));return UQ(e,t,o,KQ(t,()=>i$(p,t.path,a.map(e=>({...e,preset:c})),a$)),WQ),c}function d$(e,t,n,r){let i=vQ(t.path);UQ(e,t,i,ga(i??``,[`themeDefaults`,n],na(r),ea),WQ)}function f$(e,t,n){if(KH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=vQ(t.path),a=bQ(i??``);if(i===null||a===null||Ji(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ji(a,[`globals`,`preset`]);UQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>o$(e,t),i),GQ)}function p$(e,t,n,r){let i=VQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=vQ(t.path),o=r.op===`remove`?r.target:r.anchor,s=KQ(t,()=>LQ(bQ(a??``),i.preset,o)),c=BQ(a??``,s),{after:l,placed:u}=m$(c,s.path,r,()=>{let e=e$(t,c).config;return ix(e.presets).map(t=>sx(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return UQ(e,t,a,l,WQ),u}function m$(e,t,n,r){switch(n.op){case`remove`:return{after:Da(e,t,n.target),placed:null};case`insert`:{let i=WI(n.segment,n.anchor,r());return{after:Oa(e,t,i,n.anchor,n.relation),placed:i}}}}const h$={load:()=>({}),save:()=>{}},g$=new Set(Oy.map(e=>e.sessionKey)),_$=e=>g$.has(e)||e.startsWith(Rj),v$=8*1024*1024,y$={past:[],future:[]},b$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var x$=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=h$){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)??y$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??y$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(b$(n));r.set(b$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:uQ(this.sessionState,e=>_$(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:k$(i,n),o=r.get(e),s=o===void 0?a:N$(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,j$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(b$)),a=n.net.filter(e=>!i.has(b$(e))),o=w$(P$(M$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(I$).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new q(`redo: nothing to redo`);let a=[...n,i],o=w$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...E$(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(b$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:P$(n,t),future:P$(i,t),...a!==void 0&&{savepoint:{at:P$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(b$(e))),below:P$(a.below,t)}}}),new q(`${r}: ${o.map(I$).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):vQ(t.file)}write(e,t,n){t.kind===`file`?yQ(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||S$(n)>v$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,C$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${v$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function S$(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 C$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...E$(n,1,[])}:{past:e,future:t.slice(1),...E$(n,0,[])}}function w$(e){return e.slice(-50)}const T$=e=>e===Bj.member;function E$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:D$(e.net,n),below:e.below}}}function D$(e,t){let n=new Map(e.map(e=>[b$(e),e]));for(let e of t){let t=n.get(b$(e));n.set(b$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const O$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function k$(e,t){let n=[...e.past,t],r=w$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...E$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...A$(e.future,a),...i.below]},n.length-r.length,t)}}function A$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function j$(e,t){return{past:e.past.slice(0,-1),future:w$([...e.future,t]),...E$(e.savepoint,0,O$(t))}}function M$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...A$(r,t.at-i.length),...t.below]}function N$(e,t){if(T$(t.after)&&!T$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!T$(t.after)&&T$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function P$(e,t){return e.map(e=>e.filter(e=>!t.has(b$(e)))).filter(e=>e.length>0)}function F$(e){return e.map(I$).join(`, `)}function I$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function L$(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function R$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(L$))}function z$(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(L$)&&R$(t.below)}function B$(e){if(typeof e!=`object`||!e)return!1;let t=e;return R$(t.past)&&R$(t.future)&&(t.savepoint===void 0||z$(t.savepoint))}function V$(e,t){let n=e=>e.kind===`file`||_$(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function H$(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(B$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,V$(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 U$=e=>!_$(e)&&!pP(e)&&e!==`update.dismissed`;var W$=class{past=J.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:uQ(e,U$,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,J.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const G$={inside:()=>[],defaultOf:()=>P,menus:[]},K$=e=>`${e.key}\0${e.member}`;function q$(e){let t=new Map,n=n=>{let r=`${n.name}\0${E_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:az(a,E_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(K$(e))??new Map;n.set(K$(t),t),o.set(K$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(K$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of ix(e.presets))d(sx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Pi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(K$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(K$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(K$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const J$=new WeakMap;function Y$(e){let t=J$.get(e);if(t!==void 0)return t;let n=q$(e);return J$.set(e,n),n}function X$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function Z$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function Q$(e,t,n){let r=(r,i,a)=>{let o=X$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const $$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function e1(e,t){let n={...e};for(let e of $$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const t1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function n1(e){let t=e=>({kind:`failed`,reason:e});if(!t1(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!t1(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!eN.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${eN.join(` or `)}`)}return{kind:`ok`,value:e}}function r1(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const i1=e=>Oq(e,`doctor-marks.json`,{},n1),a1=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},o1=(e,t)=>e.includes(t)?e:[...e,t],s1=e=>Oq(e,`doctor-clicked-terminals.json`,[],a1);var c1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const l1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},u1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),d1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=u1(e,t);return r===void 0?n:r.projectDir},f1=(e,t)=>u1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function p1(e){let t=new Map;for(let n of e.split(`
201
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*m1(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 h1={pullRequests:e=>Zq(e).showPullRequest===!0,rateLimits:e=>Xq(e,`block`)||Xq(e,`weekly`)};function g1(e,t){let n=new Map;for(let r of A_(sx(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=>B_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,qq(e,t,n.get(t))])),a=e=>r.filter(t=>h1[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
198
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function yX(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const bX=e=>e.kind===`failed`?DJ:e;function xX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function SX(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function CX(e){return{...e,cells:e.cells.map(NJ)}}function wX(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,...TX(e,r)]}function TX(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 EX(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:wX(e.direction,e.children.map((t,i)=>n(t,[...r,DX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function DX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:T_[e.direction]}}const OX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Nh(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,j_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),wX(e.direction,e.children.map((n,r)=>t.renderChild(n,bX(t.gate),DX(e,r))))}},kX={drop:e=>e.place,above:()=>`above`},AX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},jX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:E_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Di(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,M_(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,MX(e,t))};function MX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=jk(t.scope,e.settings);if(t.gate.kind===`failed`)return RX(e,r,t,t.gate.message);try{let i=t.placement(e),a=xX(t.gate,i.gate());if(a.kind===`failed`)return RX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return RX(e,r,t,s.message);let c=Lb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:Xj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?NX(f.variable):PX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?FX(p.segment,u):IX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:DJ,h.disclosure).map(e=>({...e,place:kX[v.placement](e)})),b=(e,t,n)=>IJ(BJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?AX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(LX(MJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(MJ)),[...ie,...re]}catch(n){return RX(e,r,t,n.message??String(n))}}const NX=e=>({kind:`waiting`,variable:e});function PX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=lS(e);if(t===void 0)throw e;return NX(t.variable)}}function FX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:vX(BJ(r,c)).map((e,t)=>({cells:IJ(e,{...l,lead:t===0?BJ(i,c):[],trail:t===0?BJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:IJ(BJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function IX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=BJ(zX(e.lead,e,t,n),l),d=BJ(zX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return IJ(BJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function LX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function RX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:IJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:Xj(n.palette)},lead:zX(e.lead,e,t,n),trail:zX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function zX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=lS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const BX={container:OX,segment:jX};function VX(e){return BX[e]}var HX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?UX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const UX={kind:`hidden`},WX={palette:`theme`,style:`style`,effect:`effect`},GX=jy.get(`colorCompatibility`),KX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function qX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function JX(e){if(e.ok)return e.value;throw e.error}const YX=e=>({read:()=>e}),XX=gh({basePalette:hh,palette:hh,decor:Ag});var ZX=class{evaluated=0;memory=new HX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&XX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=kk(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(GX);return typeof e==`string`&&m_(e)?e:`truecolor`});let i=(0,J.observable)(KX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return EX(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=PI(e);return i===void 0?[]:[{name:i,address:n,palette:Lb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>h_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=_A(e);return t===void 0?hA(e)===void 0?iA(this.view.get().payload(),e):iA(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[WX[e]];if(t.kind===`decided`)return eZ(t.name,null,null);let r=nZ(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=rZ(this.source,e,i.name,r.where,e=>{t=e}),eZ(n,t,null)}case`pending`:return eZ(n??t_[e],null,i.variable);case`failed`:return n=t_[e],eZ(n,n_(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!tZ(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??t_[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return kJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>EY(this.source.activeSegment,()=>kJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new iZ(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:KJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=lS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:qX(e)}),JX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:PI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function QX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new ZX(t,n,e,r);return e.views.set(t,a),a}function $X(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const eZ=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),tZ=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function nZ(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function rZ(e,t,n,r,i){switch(t){case`palette`:return Hb(n,r,i).name;case`style`:return Qg(n,e.styles).name;case`effect`:return c_(n).name}}var iZ=class{where=aZ(gh({palette:hh,region:Og}));ground=aZ(gh({colours:sZ,bodyOpen:hh}));opened=aZ(gh({colours:sZ,open:hh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=jk(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?YX(OJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>EY(r,()=>kJ(a,i))),this.open=d===void 0?YX(DJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>EY(r,()=>kJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return uZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return dZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?YX(pZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return fZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),hZ(n,r,this.affixes.read())}};function aZ(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const oZ=(e,t)=>e.hex===t.hex,sZ=gh({palette:hh,drawnAt:hh,tint:oZ,text:oZ,bg:oZ,disclosure:jg});function cZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const lZ=e=>mg(e.palette,e.disclosure,e.drawnAt);function uZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Lg(n,r,i)};return TY(e,cZ(t,c),e=>{let t=Qj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function dZ(e,t,n,r,i,a){return TY(e,cZ(t,n),e=>(e.bg=i?lZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function fZ(e,t,n,r,i,a,o){return TY(e,cZ(t,n),e=>(e.bg=r?lZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const pZ={lead:[],trail:[],drops:[]};function mZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return cY(t,lZ(e).state,n)},get band(){return cY(t,lZ(e).plane,n)},get close(){return dY(t,lZ(e).state,n)},disclosure:r}}function hZ(e,t,n){return{styles:mZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?lZ(e).shortfalls:[]}}function gZ(e,t,n,r,i,a,o){let s=uZ(e,t,n,r,i,void 0,void 0,o);return hZ(s,dZ(e,t,s,a,!1,o),pZ)}function _Z(e,t,n,r,i){return mZ(uZ(e,t,n,r,i,void 0,void 0,{}))}function vZ(e,t){return{payload:()=>e,selections:()=>t}}function yZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Wk(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 bZ(e,t){switch(F_(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 xZ(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:yZ(n.cache),parse:bZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:yZ(n.cache),parse:bZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function SZ(e,t){let n=ZS.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 CZ(e,t,n){let{compiled:r,loadWarnings:i}=TZ(e,t,n.cwd,wZ(n.signer),kZ);return{...r,loadWarnings:i}}const wZ=e=>(t,n)=>AZ(n,e);function TZ(e,t,n,r,i=kZ){let a=EZ(e),o=DZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:OZ(e,t,n,i)}}function EZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of My)n in t&&r.set(e,n);for(let[t,n]of V_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[..._B(e)].sort(([e],[t])=>e<t?-1:1)}}function DZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function OZ(e,t,n,r){let i=gX(e),a=_B(e),o=[];for(let[s,c]of Jx(e))if(r.has(i.get(s)))try{xZ(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const kZ=new Set([`directory`,`view`]);function AZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>UJ(i,`drawnAt`).registry.drawnAt(),o=CY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=ix(e.presets),u=CI(e),d=[e=>qY(i,o,e.now)],f=Ok({extraFuncs:{...oY(i),...KY(i),...RY(i,o),...HY(i,o),...QY(i,o),...iX(i,o),...cX(s),...dX(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=SZ(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=qJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=G_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Z_(t,e,a,t=>String(UJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return VX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=sx(e,t);S.set(t,x(n,r))}let te=new Map(qg.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of yB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:NZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:uB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:Tk(d)},re=SB(ne),ie=[...S.values()].flatMap(MZ(y)).some(e=>re(m.get(e))),ae=ie?SB({...ne,clock:new Set([...ne.clock,rX])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function jZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const MZ=e=>t=>{let n=[];return EX(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function NZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const PZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function FZ(e,t,n,r,i){let a=IZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function IZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??t_[e];case`failed`:return r({kind:`rule`,slot:e,message:n_(t.where,e,`the rule failed — ${n.error}`)}),t_[e]}}function LZ(e){return RZ(e).filter(e=>!e.name.startsWith(TA)).map(e=>e.id)}function RZ(e){return e.kind===`container`?e.children.flatMap(RZ):[e,...e.opens===void 0?[]:RZ(e.opens.body)]}function zZ(e,t,n,r,i,a,o,s,c=$H(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return QX(t,n,r,vZ(l,c)),VZ(e,t,n,r,l,a,o,s,c)}function BZ(...e){return zZ(...e).text}function VZ(e,t,n,r,i,a,o,s,c){try{var l=Na();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new rb(``),g=h.clockAt(a,i_[c.animationSpeed]);l.u(gk(a,g.anim));let _=$X(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:db(v),padding:v.padding,seamCols:fb(v),preset:c.preset},i);let y=_.evaluated;l.u(KJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:Dh[c.variation],shade:Th[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,SX),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=rZ(t,e,FZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:T,effect:oe}=_.selections(),E=w.kind===`decided`?w:Hb(C(`palette`),``,PZ),se=T.kind===`decided`?T:Qg(C(`style`),e.styles),ce=oe.kind===`decided`?oe:c_(C(`effect`)),le=E.value,ue=zb(le,se.value);_.publishLook({basePalette:le,palette:ue,decor:x});let de=c.idleSince===void 0?null:Qv(c.idleSince,c.menuTimeout,a),fe=Wh(ue,`warning`),pe=de===null?null:{t:de,fill:fe,text:eg(ue,fe,r.drawnAt())},me=h.motion(ce.value,g,{transitions:ee,source:S,last:ne,returned:SX,hold:CX},pe);u?.clear();let he=t=>e.segments[t],ge=e=>{for(let t of e.shortfalls)m.add(t);return e},_e=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>ge(t.evaluate(e,n))}},ve=(e,i,a)=>{let o=i.kind===`hidden`?i:xX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${LZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:ue,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:_e,evaluateOnce:(e,n,i,o)=>ge(gZ(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:he,renderChild:(e,t,n)=>ve(e,t,Fg(a,n)),renderBody:(e,t,n)=>ve(e,t,Ig(n)),closeDisclosure:e=>sY(n,e),placed:(e,t)=>te.placed(e,me.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>_Z(t.activeSegment,e,n,a,r.drawnAt())};return VX(e.kind).render(e,c)},ye=t.roots.get(b);if(ye===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${nx}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let be=yX(ve(ye,OJ,Pg(x))).map(({line:e,row:t})=>{let n=zJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...gb(n.map(e=>e.owner),v,me.row(t,r,n))}});me.drawn(),te.commit();let xe=be.filter(e=>e.kind===`menu`).length,Se=be.some(e=>e.moves)?`moves`:xe>0||_.selections().effect.kind===`expression`||ee||RZ(ye).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:be.map(e=>e.text).join(`
199
+ `),motion:Se,menuRows:xe,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*HZ(e){yield*Object.entries(e.variables??{});for(let[t,n]of Object.entries(e.segments??{}))for(let[e,r]of Object.entries(n.vars??{}))yield[`${t}.${e}`,r]}function*UZ(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 ix(e.presets)){for(let n of A_(sx(e,t).node))n.when!==void 0&&(yield n.when);let n=cx(e,t);for(let e of qg){let t=n[e];Jg(t)&&(yield t)}}for(let[,t]of HZ(e))for(let[,e]of R_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of yx(t))yield e}function WZ(e,t){let n=pB(t),r=new Set,i=new Set,a=new Set;for(let e of UZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Bx(e,t.helpers))i.add(n);for(let n of Gx(e,t.helpers))a.add(n)}for(let[,e]of HZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of ix(t.presets))for(let n of A_(sx(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!DA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(HZ(e));return[...d(`variable`,f.keys(),e=>l(e,f.get(e))),...d(`action`,Object.keys(e.actions??{}),e=>o.has(e)),...d(`helper`,Object.keys(e.helpers??{}),e=>a.has(e)),...d(`segment`,Object.keys(e.segments??{}),e=>c.has(e))]}var GZ=class{held=new Map;declaring=null;closed=!1;take(e,t){if(this.closed)throw Error(`hold taken after close: ${e}`);this.declaring?.taken.add(e),!this.held.has(e)&&(this.held.set(e,t()),this.declaring!==null&&this.declaring.acquired++)}declare(e){if(this.declaring!==null)throw Error(`declaration within one`);let t={taken:new Set,acquired:0};this.declaring=t;let n;try{n=e()}finally{this.declaring=null}let r=0;for(let[e,n]of this.held)t.taken.has(e)||(this.held.delete(e),n(),r++);return{result:n,acquired:t.acquired,released:r}}close(){this.closed=!0;let e=this.held.size;for(let e of this.held.values())e();return this.held.clear(),e}get size(){return this.held.size}};function KZ(e){return Math.floor(Math.max(e/4,e*cr-67108864))}const qZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function JZ(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=cV(e),r=t===void 0?void 0:n.variables[uV(t)];return r?.kind===`file`?r.path:`none`},d=o.flatMap(e=>{let t=cV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>gV(e)(t)&&t!==uV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${e.join(` < `)||`<default>`}: projections=${[..._B(n).keys()].join(`,`)||`-`} instantSegments=${jZ(r).join(`,`)||`-`} instantTemplates=${r.instant.size} plugins loaded=${o.length} sources=${f} pluginVariables=${p} dropped=${s.length} unplaced=${c.length} checkout=${l} ms=${i}`+o.map(e=>` +${e} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}function YZ(e){let t=e=>e.join(`,`)||`-`;return`config loaded projectDir=${e.projectDir} cwd=${e.cwd} files=${e.configLayers.join(` < `)||`<bundled default>`} awaiting=${t(e.repos.awaiting)} declined=${t(e.repos.declined)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function XZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function ZZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function QZ(e,t){return new Set(ix(e.presets).filter(n=>sx(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function $Z(e){let t=[],n=e=>{try{return yt(e)}catch(n){return t.push({path:e,reason:n.message}),[e]}},r=new Map,{loaded:i,dropped:a,unreached:o}=e.state.plugins,c=[...new Set([...e.state.plugins.roots,s.join(e.projectDir,VV)])];for(let t of[...iH(e.projectDir,e.cwd,e.configFile),...c,...i,...[...a,...o].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))].flatMap(n)){let{dir:e,name:n}=$x(t),i=r.has(e)?r.get(e):new Set;i?.add(n),r.set(e,i)}for(let e of c){let{dir:t,name:n,leaf:i}=$x(s.join(e,`_`));i&&n===`_`&&r.set(t,null)}return{targets:{dirs:[...r.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})},unresolved:t}}function eQ(e){return e.filter(Boolean).join(`
200
+ `)||null}function tQ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=xH(t.layers,WH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??WH,l=a.find(e=>e.path===t.home)?.raw??{},u=new SS,d=new cA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=TZ(o,d,e,r.compile??wZ(r.signer),aQ),n.push(...f.loadWarnings);let t=d.view();n.push(...OZ(o,t,e,oQ)),t.dispose(),FU(o),rL(o),p=nQ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Xq(o),authoredRoots:QZ(c,l),fileHeldSettings:xU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>WZ(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:p}}function nQ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function rQ(e,t,n,r){let i=performance.now(),a=oH(Mq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[pH(e,t),dH(a),tH(o)],l,u=null;try{l=tQ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof tv&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:eQ(c),state:null,error:e instanceof tv||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:eQ(c),state:l,error:null}}function iQ(e,t,n){return tQ(e,{layers:[],home:``,repo:t},[],n)}const aQ=new Set([`directory`]),oQ=new Set([`view`]);function sQ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new GZ;OZ(e.config,l,t,oQ);let d=()=>QH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),sJ(L(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});QX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var cQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Ne,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},p.mkdirSync(Aq(),{recursive:!0});let{dir:n,name:r}=$x(jq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??AZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=ZZ(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`,JZ(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??iQ(t,a.repos.plugins,this.deps),watch: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=${N(this.accountedBytes())}/${N(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=Na();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(ZZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=sQ(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return rQ(e,t,n,this.deps)}drop(e,t,n){t.watch?.handle.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${N(this.accountedBytes())}/${N(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,XZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,JZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let{targets:n,unresolved:r}=$Z(e),i=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`,{watch:a,move:o}=this.deps.watchers.follow(e.watch,{key:i,targets:n},()=>this.onConfigChanged(e));if(e.watch=a,o!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${n.dirs.map(e=>e.path).join(`,`)} refused=${a.handle.refused.length}`);for(let{path:t,reason:n}of r)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const lQ=16384;var uQ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<lQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%lQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0,probes:0,probeFailures:0,stalled:0,stalls:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Qe,sourceDigest:tt(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function dQ(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 fQ={load:()=>({}),save:()=>{},flush:()=>{}};var pQ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=fQ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,J.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,J.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,J.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function mQ(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 hQ=class{timer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Ne){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return mQ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=this.writingPath;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}let c=!1;if(t===this.generation)try{await p.promises.rename(i,this.filePath),c=!0}catch(e){if(e.code!==`ENOENT`||t===this.generation)throw e}if(t!==this.generation){c||await p.promises.rm(i,{force:!0}),this.logger(`info`,`session-state write superseded by a flush landed=${c} took=${Math.round(performance.now()-n)}ms held=${Math.round(a)}ms`);return}this.saved(r,e,n,a),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.rmSync(this.writingPath,{force:!0}),p.renameSync(n,this.filePath),this.generation++,this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const gQ=new Set([`1`,`true`]),_Q=new Set([`0`,`false`,``]);function vQ(e,t){let n=UQ(e),r=n.scope===`segment-palette`?`string`:Cy(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(gQ.has(t))return`true`;if(_Q.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function yQ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function bQ(e,t,n){try{if(t===null){p.rmSync(vt(e),{force:!0});return}O(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function xQ(e){return/^\s*$/.test(e)?null:Ki(e)}function SQ(e,t){return e!==null&&Ji(e,t)!==void 0}function CQ(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(CQ),...i}}return e}function wQ(e){if(!Jb(e))return CQ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,CQ(t)])),...n}}const TQ=HH,EQ=TQ.segments,DQ=TQ.presets,OQ=TQ.root;function kQ(e,t,n,r){if(!SQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function AQ(e,t){let n=Ej(t);return t.scope===`segment-palette`&&kQ(e,[`segments`,t.segment],EQ[t.segment],n.join(`.`)),n}function jQ(e){return Ki(na(e))}function MQ(){return Object.entries(OQ.rows).map(([e,t])=>{let n=CQ(t);return{path:[`root`],fragment:jQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function NQ(e,t){let n=e===null?void 0:Ji(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function PQ(e,t){if(t===void 0)return null;let n=wQ(t);return{path:e,fragment:jQ(n),unit:{path:e,value:n}}}function FQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=DQ[t];kQ(e,n,i,r.join(`.`));let a=NQ(e,r)??PQ(r,i?.root);return a!==null&&Ca(a.fragment)?a:null}function IQ(e,t){let n=Sa(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function LQ(e,t){return[...MQ(),NQ(e,[`root`]),FQ(e,t)].filter(e=>e!==null).reduce(IQ,new Map)}function RQ(e,t,n){for(let{node:r,...i}of LQ(e,t).values())if(Ta(r,n))return i;throw new q(`${zQ(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 zQ(e,t){return FQ(e,t)?.path??[`root`]}function BQ(e,t){return t.scope===`preset-root`?zQ(e,t.preset):Ej(t)}function VQ(e,{unit:t}){return t===null?e:ga(e,t.path,na(t.value),ea)}function HQ(e){let t=Tj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function UQ(e){let t=HQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function WQ(e,t,n,r,i){i(t,n,t$(t,r)),bQ(t.path,r,e.logger),e.record(t.path,n,r)}function GQ(e,t,n){let r=JQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const KQ=()=>{};function qQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function JQ(e,t,n){let r=YQ(e,t);if(r===null)return[];let i=new Set($Q(QQ(r),QQ(n)));return $Q(ZQ(e,r),ZQ(e,n)).filter(e=>!i.has(e))}function YQ(e,t){try{return XQ(e,t)}catch(e){if(e instanceof tv)return null;throw e}}function XQ(e,t){return xH(t===null?e.above:[e.path,...e.above],WH,{entered:()=>{},warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function ZQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function QQ(e){return e.layers.at(-1)?.config??e.base}function $Q(e,t,n=``){return!e$(e)||!e$(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>$Q(e[r],t[r],n===``?r:`${n}.${r}`))}function e$(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function t$(e,t){try{return XQ(e,t)}catch(e){throw e instanceof tv?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function n$(e,t){let n=UQ(t),r=xQ(yQ(e)??``),i=r===null?void 0:Ji(r,Ej(n));return i!==void 0&&`value`in i?i.value:void 0}function r$(e,t,n){i$(e,t,n,[])}function i$(e,t,n,r){let i=yQ(t.path),a=n.reduce((e,[t,n])=>ga(e,AQ(xQ(e),UQ(t)),vQ(t,n),ea),i??``);WQ(e,t,i,qQ(t,()=>a$(a,t.path,r,e=>e)),GQ)}function a$(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=RQ(xQ(s),n,i),l=ka(VQ(s,c),c.path,i,a,na(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function o$(e,t,n){let r=xQ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of LQ(r,t)){if(!Ta(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Xi(e,c):na(s.value);if(a!==`#`)return ga(e,[...i,`rows`,a],l,ea);if(FQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ga(e,i,l,ea)}return e}function s$(e,t){return va(e,t,t[0]===`presets`&&t.length>2&&!KH(t[1])?2:0)}function c$(e,t,n){let r=n.map(HQ),i=yQ(t.path);if(i===null)return;let a=r.reduce((e,t)=>s$(e,BQ(xQ(e),t)),i);a!==i&&WQ(e,t,i,a,KQ)}function l$(e){let t=e===null?void 0:Ji(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function u$(e,t){let n=new Set([...GH,...l$(e),...t.above.flatMap(e=>Object.keys(zi.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(xA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(xA(e)))}function d$(e,t,n,r,i,a){let o=yQ(t.path),s=xQ(o??``),c=u$(s,t),l=[`presets`,c],u=qQ(t,()=>FQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Xi(o??``,u.fragment):na(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],na(r)]]],f=i.map(([e,t])=>{let n=wj(c,e);return[AQ(s,UQ(n)),vQ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ga(e,t,n,ea),ga(o??``,l,`{}`,ea));return WQ(e,t,o,qQ(t,()=>a$(p,t.path,a.map(e=>({...e,preset:c})),o$)),GQ),c}function f$(e,t,n,r){let i=yQ(t.path);WQ(e,t,i,ga(i??``,[`themeDefaults`,n],na(r),ea),GQ)}function p$(e,t,n){if(KH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=yQ(t.path),a=xQ(i??``);if(i===null||a===null||Ji(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ji(a,[`globals`,`preset`]);WQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>s$(e,t),i),KQ)}function m$(e,t,n,r){let i=HQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=yQ(t.path),o=r.op===`remove`?r.target:r.anchor,s=qQ(t,()=>RQ(xQ(a??``),i.preset,o)),c=VQ(a??``,s),{after:l,placed:u}=h$(c,s.path,r,()=>{let e=t$(t,c).config;return ix(e.presets).map(t=>sx(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return WQ(e,t,a,l,GQ),u}function h$(e,t,n,r){switch(n.op){case`remove`:return{after:Da(e,t,n.target),placed:null};case`insert`:{let i=WI(n.segment,n.anchor,r());return{after:Oa(e,t,i,n.anchor,n.relation),placed:i}}}}const g$={load:()=>({}),save:()=>{}},_$=new Set(Oy.map(e=>e.sessionKey)),v$=e=>_$.has(e)||e.startsWith(Rj),y$=8*1024*1024,b$={past:[],future:[]},x$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var S$=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=g$){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)??b$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??b$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(x$(n));r.set(x$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:dQ(this.sessionState,e=>v$(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:A$(i,n),o=r.get(e),s=o===void 0?a:P$(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,M$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(x$)),a=n.net.filter(e=>!i.has(x$(e))),o=T$(F$(N$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(L$).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new q(`redo: nothing to redo`);let a=[...n,i],o=T$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...D$(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(x$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:F$(n,t),future:F$(i,t),...a!==void 0&&{savepoint:{at:F$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(x$(e))),below:F$(a.below,t)}}}),new q(`${r}: ${o.map(L$).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):yQ(t.file)}write(e,t,n){t.kind===`file`?bQ(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||C$(n)>y$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,w$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${y$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function C$(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 w$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...D$(n,1,[])}:{past:e,future:t.slice(1),...D$(n,0,[])}}function T$(e){return e.slice(-50)}const E$=e=>e===Bj.member;function D$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:O$(e.net,n),below:e.below}}}function O$(e,t){let n=new Map(e.map(e=>[x$(e),e]));for(let e of t){let t=n.get(x$(e));n.set(x$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const k$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function A$(e,t){let n=[...e.past,t],r=T$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...D$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...j$(e.future,a),...i.below]},n.length-r.length,t)}}function j$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function M$(e,t){return{past:e.past.slice(0,-1),future:T$([...e.future,t]),...D$(e.savepoint,0,k$(t))}}function N$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...j$(r,t.at-i.length),...t.below]}function P$(e,t){if(E$(t.after)&&!E$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!E$(t.after)&&E$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function F$(e,t){return e.map(e=>e.filter(e=>!t.has(x$(e)))).filter(e=>e.length>0)}function I$(e){return e.map(L$).join(`, `)}function L$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function R$(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 z$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(R$))}function B$(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(R$)&&z$(t.below)}function V$(e){if(typeof e!=`object`||!e)return!1;let t=e;return z$(t.past)&&z$(t.future)&&(t.savepoint===void 0||B$(t.savepoint))}function H$(e,t){let n=e=>e.kind===`file`||v$(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 U$(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(V$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,H$(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 W$=e=>!v$(e)&&!pP(e)&&e!==`update.dismissed`;var G$=class{past=J.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:dQ(e,W$,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,J.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const K$={inside:()=>[],defaultOf:()=>P,menus:[]},q$=e=>`${e.key}\0${e.member}`;function J$(e){let t=new Map,n=n=>{let r=`${n.name}\0${E_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:az(a,E_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(q$(e))??new Map;n.set(q$(t),t),o.set(q$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(q$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of ix(e.presets))d(sx(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Pi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(q$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(q$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(q$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const Y$=new WeakMap;function X$(e){let t=Y$.get(e);if(t!==void 0)return t;let n=J$(e);return Y$.set(e,n),n}function Z$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function Q$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function $$(e,t,n){let r=(r,i,a)=>{let o=Z$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const e1=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function t1(e,t){let n={...e};for(let e of e1)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const n1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function r1(e){let t=e=>({kind:`failed`,reason:e});if(!n1(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!n1(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!eN.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${eN.join(` or `)}`)}return{kind:`ok`,value:e}}function i1(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const a1=e=>Oq(e,`doctor-marks.json`,{},r1),o1=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},s1=(e,t)=>e.includes(t)?e:[...e,t],c1=e=>Oq(e,`doctor-clicked-terminals.json`,[],o1);var l1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const u1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},d1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),f1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=d1(e,t);return r===void 0?n:r.projectDir},p1=(e,t)=>d1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function m1(e){let t=new Map;for(let n of e.split(`
201
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*h1(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 g1={pullRequests:e=>Qq(e).showPullRequest===!0,rateLimits:e=>Zq(e,`block`)||Zq(e,`weekly`)};function _1(e,t){let n=new Map;for(let r of A_(sx(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=>B_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,Jq(e,t,n.get(t))])),a=e=>r.filter(t=>g1[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
202
202
  /*!
203
203
  * Copyright (c) Squirrel Chat et al., All rights reserved.
204
204
  * SPDX-License-Identifier: BSD-3-Clause
@@ -226,9 +226,9 @@ Config tooling:
226
226
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
227
227
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
228
228
  */
229
- function _1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function v1(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+=`
229
+ function v1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function y1(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
230
230
  `,e===t&&(i+=` `.repeat(a+n+2),i+=`^
231
- `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=_1(t.toml,t.ptr),i=v1(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})}};
231
+ `))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=v1(t.toml,t.ptr),i=y1(t.toml,n,r);super(`Invalid TOML document: ${e}\n\n${i}`,t),this.line=n,this.column=r,this.codeblock=i}static x(t,n,r){throw new e(t,{toml:n.s,ptr:r??n.p})}};
232
232
  /*!
233
233
  * Copyright (c) Squirrel Chat et al., All rights reserved.
234
234
  * SPDX-License-Identifier: BSD-3-Clause
@@ -256,7 +256,7 @@ function _1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
256
256
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
257
257
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
258
258
  */
259
- function y1(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+=`
259
+ function b1(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCodeAt(e.p)&&n===e.s.charCodeAt(e.p+1);a&&((n=e.s.charCodeAt(e.p+=2))===10?e.p++:n===13&&e.s.charCodeAt(e.p+1)===10&&(e.p+=2));let o=``,s=e.p,c=0;for(;e.p<e.s.length;e.p++)if(n=e.s.charCodeAt(e.p),a&&(n===10||n===13&&e.s.charCodeAt(e.p+1)===10))c&&=3;else if(n<32&&n!==9||n===127)Q.x(`control characters are not allowed in strings`,e);else if((!c||c===3)&&n===r&&(!a||e.s.charCodeAt(e.p+1)===r&&e.s.charCodeAt(e.p+2)===r)){if(a&&(e.s.charCodeAt(e.p+3)===r&&e.p++,e.s.charCodeAt(e.p+3)===r&&e.p++),!c){let t=e.s.slice(s,e.p);o=o?o+t:t}return e.p+=a?3:1,o}else if(!c)!i&&n===92&&(o+=e.s.slice(s,s=e.p),c=1);else if(c===1)if(n===120||n===117||n===85){let t=e.p++-1,r=0,i=n===120?2:n===117?4:8;for(let t=0;t<i;t++,e.p++){let t=e.s.charCodeAt(e.p),n=t>=48&&t<=57?t-48:t>=65&&t<=70?t-65+10:t>=97&&t<=102?t-97+10:-1;n<0&&Q.x(`invalid non-hex character in unicode escape`,e),r=r<<4|n}(r<0||r>1114111||r>=55296&&r<=57343)&&Q.x(`invalid unicode escape`,e,t),o+=String.fromCodePoint(r),s=e.p--,c=0}else a&&(n===32||n===9)?c=2:(n===98?o+=`\b`:n===116?o+=` `:n===110?o+=`
260
260
  `:n===102?o+=`\f`:n===114?o+=`\r`:n===101?o+=`\x1B`:n===34?o+=`"`:n===92?o+=`\\`:Q.x(`unrecognised escape sequence`,e),s=e.p+1,c=0);else n!==32&&n!==9&&(c===2&&Q.x(`invalid escape: only line-ending whitespace may be escaped`,e,s),c=+(!i&&n===92),s=e.p);Q.x(`unfinished string`,e,t)}
261
261
  /*!
262
262
  * Copyright (c) Squirrel Chat et al., All rights reserved.
@@ -285,7 +285,7 @@ function y1(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
285
285
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
286
286
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
287
287
  */
288
- let b1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var x1=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(b1);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}};
288
+ let x1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var S1=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(x1);t?(t[1]||(r=!1,e=`0000-01-01T${e}`),i=!!t[2],i&&e[10]===` `&&(e=e.replace(` `,`T`)),t[2]&&+t[2]>23?e=``:(a=t[3]||null,!a&&i&&(e+=`Z`))):e=``}super(e),isNaN(this.getTime())||(this.#e=r,this.#t=i,this.#n=a)}isDateTime(){return this.#e&&this.#t}isLocal(){return!this.#e||!this.#t||!this.#n}isDate(){return this.#e&&!this.#t}isTime(){return this.#t&&!this.#e}isValid(){return this.#e||this.#t}toISOString(){let e=super.toISOString();if(this.isDate())return e.slice(0,10);if(this.isTime())return e.slice(11,23);if(this.#n===null)return e.slice(0,-1);if(this.#n===`Z`||this.#n===`z`)return e;let t=this.#n.slice(1,3)*60+ +this.#n.slice(4,6);return t=this.#n[0]===`-`?t:-t,new Date(this.getTime()-t*6e4).toISOString().slice(0,-1)+this.#n}static wrapAsOffsetDateTime(t,n=`Z`){let r=new e(t);return r.#n=n,r}static wrapAsLocalDateTime(t){let n=new e(t);return n.#n=null,n}static wrapAsLocalDate(t){let n=new e(t);return n.#t=!1,n.#n=null,n}static wrapAsLocalTime(t){let n=new e(t);return n.#e=!1,n.#n=null,n}};
289
289
  /*!
290
290
  * Copyright (c) Squirrel Chat et al., All rights reserved.
291
291
  * SPDX-License-Identifier: BSD-3-Clause
@@ -313,7 +313,7 @@ let b1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
313
313
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
314
314
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
315
315
  */
316
- function S1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function C1(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function w1(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?F1(e):P1(e);return e.d++,t}return r===34||r===39?y1(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?T1(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?O1(e,r,t):e.s.charCodeAt(e.p+2)===58?k1(e,r,t):T1(e,e.p,r,0,t)}function T1(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||C1(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return E1(e,t,16,i);if(a===98)return E1(e,t,2,i);if(a===111)return E1(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else S1(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!C1(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:S1(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):D1(e,c,10,t)}function E1(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!C1(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):S1(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(`_`,``)),D1(e,o,n,t)}function D1(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 O1(e,t,n){let r=e.p++,i;if(!S1(t)||!S1(e.s.charCodeAt(e.p++))||!S1(e.s.charCodeAt(e.p++))||!S1(e.s.charCodeAt(e.p++)))return T1(e,e.p=r,t,0,n);if(e.p+=5,S1(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,!S1(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return A1(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(;S1(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return A1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return A1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return A1(e,e.s.slice(r,e.p),2,i,r)}function k1(e,t,n){let r=e.p;if(!S1(t)||!S1(e.s.charCodeAt(++e.p)))return T1(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;S1(e.s.charCodeAt(++e.p)););return A1(e,e.s.slice(r,e.p),4,!1,r)}function A1(e,t,n,r,i,a){if(e.ld){let a=new x1(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)}}
316
+ function C1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function w1(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function T1(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?I1(e):F1(e);return e.d++,t}return r===34||r===39?b1(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?E1(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?k1(e,r,t):e.s.charCodeAt(e.p+2)===58?A1(e,r,t):E1(e,e.p,r,0,t)}function E1(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||w1(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return D1(e,t,16,i);if(a===98)return D1(e,t,2,i);if(a===111)return D1(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else C1(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!w1(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:C1(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):O1(e,c,10,t)}function D1(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!w1(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):C1(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(`_`,``)),O1(e,o,n,t)}function O1(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 k1(e,t,n){let r=e.p++,i;if(!C1(t)||!C1(e.s.charCodeAt(e.p++))||!C1(e.s.charCodeAt(e.p++))||!C1(e.s.charCodeAt(e.p++)))return E1(e,e.p=r,t,0,n);if(e.p+=5,C1(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,!C1(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return j1(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(;C1(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return j1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return j1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return j1(e,e.s.slice(r,e.p),2,i,r)}function A1(e,t,n){let r=e.p;if(!C1(t)||!C1(e.s.charCodeAt(++e.p)))return E1(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;C1(e.s.charCodeAt(++e.p)););return j1(e,e.s.slice(r,e.p),4,!1,r)}function j1(e,t,n,r,i,a){if(e.ld){let a=new S1(t,n,r);return a.isValid()||Q.x(`invalid date`,e,i),a}try{switch(a&&(t+=a),n){case 1:return Temporal.ZonedDateTime.from(t);case 2:return Temporal.PlainDateTime.from(t);case 3:return Temporal.PlainDate.from(t);case 4:return Temporal.PlainTime.from(t)}}catch(t){Q.x(t instanceof Error?t.message:``+t,e,i)}}
317
317
  /*!
318
318
  * Copyright (c) Squirrel Chat et al., All rights reserved.
319
319
  * SPDX-License-Identifier: BSD-3-Clause
@@ -341,7 +341,7 @@ function S1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
341
341
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
342
342
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
343
343
  */
344
- function j1(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 M1(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;j1(e)}}
344
+ function M1(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 N1(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;M1(e)}}
345
345
  /*!
346
346
  * Copyright (c) Squirrel Chat et al., All rights reserved.
347
347
  * SPDX-License-Identifier: BSD-3-Clause
@@ -369,7 +369,7 @@ function j1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
369
369
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
370
370
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
371
371
  */
372
- function N1(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(y1(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 P1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(M1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=N1(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),M1(e,!0,!0);let l=w1(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),M1(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 F1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(M1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(w1(e,93)),M1(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)}
372
+ function P1(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(b1(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 F1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(N1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=P1(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),N1(e,!0,!0);let l=T1(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),N1(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 I1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(N1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(T1(e,93)),N1(e),(r=e.s.charCodeAt(e.p++))===93)return n;r!==44&&Q.x(`expected comma or end of structure`,e,e.p-1)}Q.x(`unfinished array`,e,t)}
373
373
  /*!
374
374
  * Copyright (c) Squirrel Chat et al., All rights reserved.
375
375
  * SPDX-License-Identifier: BSD-3-Clause
@@ -397,7 +397,7 @@ function N1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
397
397
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
398
398
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
399
399
  */
400
- function I1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(a=c?a[s]:a[s]=Object.create(null),o=(l=o[s]).c,i===0&&(l.t===1||l.t===2))return null;if(l.t===2){let e=a.length-1;a=a[e],o=o[e].c}}if(s=t[n],(c=Object.hasOwn(a,s))&&o[s]?.t===0&&o[s]?.d)return null;if(!c){let r=s===`__proto__`;if(e.uk&&(r||s===`constructor`))return!1;r&&(Object.defineProperty(a,s,{enumerable:!0,configurable:!0,writable:!0}),Object.defineProperty(o,s,{enumerable:!0,configurable:!0,writable:!0})),o[s]={t:n<t.length-1&&i===2?3:i,d:!1,i:0,c:Object.create(null)}}}if(l=o[s],l.t!==i&&!(i===1&&l.t===3)||(i===2&&(l.d||(l.d=!0,a[s]=[]),a[s].push(a=Object.create(null)),l.c[l.i++]=l={t:1,d:!1,i:0,c:Object.create(null)}),l.d))return null;if(l.d=!0,i===1)a=c?a[s]:a[s]=Object.create(null);else if(i===0&&c)return null;return[s,a,l.c]}function L1(e,t,n){(t===null||e.uk===2)&&Q.x(t===null?`trying to redefine an already defined table or value`:`document contains an unsafe property`,e,n)}function R1(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++,M1(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=N1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=I1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(L1(n,u,a),o=!0)}else{a=n.p;let e=I1(n,N1(n),s,c,0);!e&&!o&&L1(n,e,a),M1(n,!0,!0);let t=w1(n,void 0);e&&!o&&(e[1][e[0]]=t)}M1(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),M1(n)}return r}``.isWellFormed;
400
+ function L1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if(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 R1(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 z1(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++,N1(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=P1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=L1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(R1(n,u,a),o=!0)}else{a=n.p;let e=L1(n,P1(n),s,c,0);!e&&!o&&R1(n,e,a),N1(n,!0,!0);let t=T1(n,void 0);e&&!o&&(e[1][e[0]]=t)}N1(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),N1(n)}return r}``.isWellFormed;
401
401
  /*!
402
402
  * Copyright (c) Squirrel Chat et al., All rights reserved.
403
403
  * SPDX-License-Identifier: BSD-3-Clause
@@ -425,7 +425,7 @@ function I1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
425
425
  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
426
426
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
427
427
  */
428
- const z1=e=>e.codePointAt(0).toString(16).toUpperCase(),B1=String.raw`
428
+ const B1=e=>e.codePointAt(0).toString(16).toUpperCase(),V1=String.raw`
429
429
  ObjC.import("AppKit");
430
430
  ObjC.import("CoreText");
431
431
  function lacksOf(font, points) {
@@ -472,48 +472,48 @@ function run(argv) {
472
472
  : iterm(argv[1], points),
473
473
  );
474
474
  }
475
- `;function V1(e){let t=ht({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,B1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new c1(`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 H1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),U1=e=>[...e].map(z1).join(`,`);function W1(e,t){let n=V1([`font`,e.kind,e.name,U1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:H1(r)}}}function G1(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=>!LM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const K1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function q1(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=>G1(e,n));if(t!==null)return r[0];let i=r.find(e=>!K1(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 J1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=V1([`iterm`,r??``,U1(n)]);return i.kind===`failed`?i:q1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:H1(e.lacks)})),r,e)}function Y1(e,t){let n=e.split(`
476
- `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const X1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function Z1(e,t){let n=ht({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
477
- `,`:family=${X1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new c1(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return Y1(n.stdout,t)}function Q1(e,t){return process.platform===`darwin`?W1(e,t):Z1(e.name,t)}function $1(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 e0(e){return e===`darwin`?`Menlo`:`monospace`}const t0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function n0(e){let t=t0(e.font)?e.font:{},n=t0(t.normal)?t.normal:{},r=(t0(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 r0(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=R1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=n0(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=r0(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function i0(e,t){let n=C.homedir(),r=$1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:r0(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??e0(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=Q1({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 a0={iterm2:J1,alacritty:(e,t,n)=>i0(t,n)};function o0(e,t,n){return a0[e.name](e.version,t,n)}function s0(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 c0=e=>Oq(e,`doctor-post-mortems-read.json`,{through:null},s0);function l0(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const u0={realpath:e=>l0(()=>p.realpathSync(e)),checkoutOf:$e,digest:e=>l0(()=>Xe(e)),nativeShipped:xo(process.platform,process.arch)};function d0(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 f0=e=>({marks:i1(e),clicked:s1(e),postMortemsRead:c0(e)}),p0=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function m0(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 h0=/^(sshd|mosh-server)\b/;function g0(e,t){let n=p1(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of m1(n,t))if(h0.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function _0(e){let t=ht({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new c1(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return g0(t.stdout,e)}const v0=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function y0(e,t){let n=[];for(let r of e.split(`
478
- `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function b0(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=v0.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function x0(){let e=ht({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:y0(e.stdout,b0)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function S0(e){let t=nq(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 c1(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:m0(t.stdout)}function C0(e){return{probeTmux:S0,remoteLogin:_0,fontInUse:o0,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ao(process.platform),install:u0,daemons:x0,forge:O0,transcript:T0}}function w0(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
475
+ `;function H1(e){let t=ht({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,V1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new l1(`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 U1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),W1=e=>[...e].map(B1).join(`,`);function G1(e,t){let n=H1([`font`,e.kind,e.name,W1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:U1(r)}}}function K1(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=>!LM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const q1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function J1(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=>K1(e,n));if(t!==null)return r[0];let i=r.find(e=>!q1(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 Y1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=H1([`iterm`,r??``,W1(n)]);return i.kind===`failed`?i:J1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:U1(e.lacks)})),r,e)}function X1(e,t){let n=e.split(`
476
+ `).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const Z1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function Q1(e,t){let n=ht({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
477
+ `,`:family=${Z1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new l1(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return X1(n.stdout,t)}function $1(e,t){return process.platform===`darwin`?G1(e,t):Q1(e.name,t)}function e0(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 t0(e){return e===`darwin`?`Menlo`:`monospace`}const n0=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function r0(e){let t=n0(e.font)?e.font:{},n=n0(t.normal)?t.normal:{},r=(n0(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 i0(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=z1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=r0(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=i0(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function a0(e,t){let n=C.homedir(),r=e0(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:i0(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??t0(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=$1({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 o0={iterm2:Y1,alacritty:(e,t,n)=>a0(t,n)};function s0(e,t,n){return o0[e.name](e.version,t,n)}function c0(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 l0=e=>Oq(e,`doctor-post-mortems-read.json`,{through:null},c0);function u0(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const d0={realpath:e=>u0(()=>p.realpathSync(e)),checkoutOf:$e,digest:e=>u0(()=>Xe(e)),nativeShipped:xo(process.platform,process.arch)};function f0(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 p0=e=>({marks:a1(e),clicked:c1(e),postMortemsRead:l0(e)}),m0=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function h0(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 g0=/^(sshd|mosh-server)\b/;function _0(e,t){let n=m1(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of h1(n,t))if(g0.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function v0(e){let t=ht({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new l1(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return _0(t.stdout,e)}const y0=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function b0(e,t){let n=[];for(let r of e.split(`
478
+ `)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function x0(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=y0.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function S0(){let e=ht({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:b0(e.stdout,x0)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function C0(e){let t=nq(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 l1(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:h0(t.stdout)}function w0(e){return{probeTmux:C0,remoteLogin:v0,fontInUse:s0,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ao(process.platform),install:d0,daemons:S0,forge:k0,transcript:E0}}function T0(e,t){let n=e.toString(`utf-8`),r=t?0:n.indexOf(`
479
479
  `)+1,i=n.lastIndexOf(`
480
480
  `)+1,a=0,o=0;for(let e of n.slice(r,i).split(`
481
- `)){let t=cK(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function T0(e){let t=Ya(e,tN+1);return t.kind===`ok`?F(w0(t.value.buf,t.value.fromStart)):t}function E0(e,t){if(t.kind===`failed`)return t;let n=new Map;for(let{path:e,answered:r}of t.value)n.set(e,r||(n.get(e)??!1));return{kind:`ok`,value:[...n].map(([t,n])=>({path:t,answered:n,read:e.transcript(t)}))}}const D0={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function O0(e){if(qV(e)===void 0)return{kind:`ok`,value:null};let t=XW(ht({bin:`git`,args:[...YW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=tG(t.value);if(n===null)return{kind:`ok`,value:null};let r=JW(n);if(r===null)return{kind:`ok`,value:null};let i=UW[r],a=D0[r],o=a.loginHost(qW(n)),s=ht({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return k0(i,o,a.nonZero,s)}function k0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):WW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:BW(r.stderr)}):{kind:`failed`,reason:zW(e,r)}}function A0(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
482
- `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const j0=e=>l0(()=>so(e));function M0(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:$a(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:j0(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 N0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function P0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:WM(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:UM(t),tmuxClient:t}}}}function F0(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(NM(s))return{kind:`bundling`,name:s,version:c};if(!PM(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 I0(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 L0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function R0(e,t,n,r){return{pullRequests:L0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:L0(t.rateLimits,()=>r)}}function z0(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 B0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=$H(d.config,r,()=>!1),p=N0(e,t.tmux),m=P0(p,t.terminalEnv),h=[...new Set([...hb(f),...mb(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:F0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:A0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:R0(e,g1(d.config,f.preset),n,a),transcripts:E0(e,o),claudeSettings:M0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:$a(Qa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function V0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;O(e,ga(no(e),t.path,JSON.stringify(t.value),ta));let r=e=>({...e,sources:j0(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||or(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 H0={connectMs:200,budgetMs:500};async function U0(e){return W0(await G0(),e.includes(`--json`))}function W0(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${pn(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
483
- `:null,r=K0(e.value);return r===null?{stdout:n??e2(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function G0(){return sn(()=>({kind:`stats`}),H0,e=>`stats`in e?e.stats:void 0)}function K0(e,t=q0){let n=lQ.referenceSnapshot(),r=J0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=X0(e.version,e.sourceDigest??null),a=X0(Qe,tt());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 q0=Object.keys(lQ.referenceSnapshot());function J0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!Y0(e))return[];if(!Y0(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(...J0(e[i],t[i],a)):r.push(a)}return r}function Y0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function X0(e,t){return`${e} [${t===null?`no digest`:Ze(t)}]`}function Z0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function Q0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function $0(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 e2(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${X0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${$0(e.uptimeSec)}`),t.push(` rss ${Z0(e.rssBytes)}`),t.push(` heapUsed ${Z0(e.heapUsedBytes)}`),t.push(` heapTotal ${Z0(e.heapTotalBytes)}`),t.push(` external ${Z0(e.externalBytes)}`),t.push(` arrayBuffers ${Z0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${Q0(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${Q0(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} probes=${i.probes} probeFailures=${i.probeFailures} stalled=${i.stalled} stalls=${i.stalls} faults ${a}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${Z0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${Z0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${Z0(e.renderCache.accountedBytes)} / ${Z0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
481
+ `)){let t=cK(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function E0(e){let t=Ya(e,tN+1);return t.kind===`ok`?F(T0(t.value.buf,t.value.fromStart)):t}function D0(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 O0={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function k0(e){if(qV(e)===void 0)return{kind:`ok`,value:null};let t=XW(ht({bin:`git`,args:[...YW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=tG(t.value);if(n===null)return{kind:`ok`,value:null};let r=JW(n);if(r===null)return{kind:`ok`,value:null};let i=UW[r],a=O0[r],o=a.loginHost(qW(n)),s=ht({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return A0(i,o,a.nonZero,s)}function A0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):WW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:BW(r.stderr)}):{kind:`failed`,reason:zW(e,r)}}function j0(e){let t={layers:e.layers,warnings:e.warning===null?[]:e.warning.split(`
482
+ `)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const M0=e=>u0(()=>so(e));function N0(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:$a(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:M0(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 P0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function F0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:WM(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:UM(t),tmuxClient:t}}}}function I0(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(NM(s))return{kind:`bundling`,name:s,version:c};if(!PM(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 L0(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 R0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function z0(e,t,n,r){return{pullRequests:R0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:R0(t.rateLimits,()=>r)}}function B0(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 V0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=$H(d.config,r,()=>!1),p=P0(e,t.tmux),m=F0(p,t.terminalEnv),h=[...new Set([...hb(f),...mb(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:I0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:j0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:z0(e,_1(d.config,f.preset),n,a),transcripts:D0(e,o),claudeSettings:N0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:$a(Qa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function H0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;O(e,ga(no(e),t.path,JSON.stringify(t.value),ta));let r=e=>({...e,sources:M0(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||or(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 U0={connectMs:200,budgetMs:500};async function W0(e){return G0(await K0(),e.includes(`--json`))}function G0(e,t){if(e.kind!==`ok`)return{stdout:``,stderr:`daemon-stats: ${pn(e)}\n`,code:1};let n=t?JSON.stringify(e.value,null,2)+`
483
+ `:null,r=q0(e.value);return r===null?{stdout:n??t2(e.value),stderr:``,code:0}:{stdout:n??``,stderr:`daemon-stats: ${r}\n`,code:1}}function K0(){return sn(()=>({kind:`stats`}),U0,e=>`stats`in e?e.stats:void 0)}function q0(e,t=J0){let n=uQ.referenceSnapshot(),r=Y0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=Z0(e.version,e.sourceDigest??null),a=Z0(Qe,tt());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 J0=Object.keys(uQ.referenceSnapshot());function Y0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!X0(e))return[];if(!X0(t))return[n||`<snapshot>`];if(`kind`in e)return[];let r=[];for(let i of Object.keys(e)){let a=n===``?i:`${n}.${i}`;i in t?r.push(...Y0(e[i],t[i],a)):r.push(a)}return r}function X0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Z0(e,t){return`${e} [${t===null?`no digest`:Ze(t)}]`}function Q0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function $0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function e2(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 t2(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${Z0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${e2(e.uptimeSec)}`),t.push(` rss ${Q0(e.rssBytes)}`),t.push(` heapUsed ${Q0(e.heapUsedBytes)}`),t.push(` heapTotal ${Q0(e.heapTotalBytes)}`),t.push(` external ${Q0(e.externalBytes)}`),t.push(` arrayBuffers ${Q0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${$0(e.gitCache.hits,e.gitCache.misses)} (${e.gitCache.hits} / ${e.gitCache.hits+e.gitCache.misses})`),t.push(` changes ${e.gitCache.changes}`),t.push(``),t.push(`usageCache`),t.push(` size ${e.usageCache.size}`),t.push(` hit rate ${$0(e.usageCache.hits,e.usageCache.misses)} (${e.usageCache.hits} / ${e.usageCache.hits+e.usageCache.misses})`),t.push(` sweeps ${e.usageCache.sweeps}`),t.push(``),t.push(`sources`);for(let n of e.sources.records){let e=Object.entries(n.refreshes).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` ${`${n.scope}/${n.name}`.padEnd(24)} failures=${n.failures} last=${n.lastMs===null?`-`:`${n.lastMs}ms`} refreshes ${e}`)}let n=Object.entries(e.sources.homes).map(([e,t])=>`${e}:${t}`).join(` `),r=Object.entries(e.sources.held).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` homes ${n}`),t.push(` held ${r}`);let i=e.sources.pluginStorage,a=Object.entries(i.faults).map(([e,t])=>`${e}:${t}`).join(` `);t.push(` plugin storage folders=${i.folders} lost=${i.lost} probes=${i.probes} probeFailures=${i.probeFailures} stalled=${i.stalled} stalls=${i.stalls} faults ${a}`),t.push(``),t.push(`transcriptReads`),t.push(` reads ${e.transcriptReads.reads}`),t.push(` bytes ${Q0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${Q0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${Q0(e.renderCache.accountedBytes)} / ${Q0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
484
484
  `)+`
485
- `}const t2=e=>({kind:`ok`,value:e}),n2=e=>({kind:`failed`,reason:e});var r2=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const i2=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function a2(e){return i2.test(e)?e:null}function o2(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return t2(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return t2({app:n,missing:n2(`its script could not be read (${r.reason})`)});let i=Mo(r.value);return t2({app:n,missing:i===null?n2("its script is not one `cc-candybar install` wrote"):t2([i.node,i.script].filter(t=>!e.exists(t)))})}async function s2(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 c2(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(`${Rr}://${ui}/${n}`);return(r===null?await s2(e,n):null)??{kind:`lost`,unopened:r,opener:o2(e)}}function l2(e,t,n){let r=ht({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?t2(r.stdout):n2(r.stderr.trim()||r.error||r.reason)}const u2=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Rr}://probe"));u.isNil() ? "" : u.path.js`;async function d2(){let e=await G0();if(e.kind!==`ok`)return n2(pn(e).split(`
486
- `).join(` — `));let t=K0(e.value,[`handlerProbes`]);if(t!==null)return n2(t);let{version:n,handlerProbes:r}=e.value;return t2({version:n,arrivals:r})}function f2(){return{platform:process.platform,sockets:{own:Tt(),handler:Et()},now:Date.now,nonce:ie,daemon:d2,open:e=>{let t=l2(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=l2(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,u2]);if(e.kind===`failed`)return e;let t=e.value.trim();return t2(t===``?null:t)},script:e=>l2(`doctor.osadecompile`,`/usr/bin/osadecompile`,[No(e)]),exists:p.existsSync}}const p2=/^─{20,}/,m2=/^❯(\s|$)/,h2=/›\s*stashed$/;function g2(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>p2.test(e)?[t]:[]).at(-2);return n===void 0||!m2.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function _2(e){if(e.inMode)return{kind:`in-mode`};let t=g2(e);return t===null?{kind:`no-prompt`}:h2.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function v2(e){return/^❯\s*\S/u.test(g2(e)?.prompt??``)}const y2=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function b2(e){return e.screen.some(e=>y2.test(e))}const x2={"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 S2(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 C2(e,t,n){let r=S2(t);if(r.kind===`refused`)return r;let i=r.hint,a=_2(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:x2[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function w2(e,t,n,r){let i=nq(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function T2(e){let t=w2(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
487
- `);return{inMode:n!==`0`,screen:r}}function E2(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 D2(e,t){let n=w2(e,`claude-input.type`,E2(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 O2(){return{read:T2,type:D2}}function k2(e){let t=AW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function A2(e){return Pb(()=>decodeURIComponent(e))}function j2(e,t,n){let r=ht(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function M2(e,t){j2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const N2=(e,t)=>M2(A2(e),t),P2=(e,t)=>j2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,A2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),F2=(e,t)=>M2(A2(e),t),I2=(e,t)=>M2(A2(e),t),L2=(e,t)=>{let n=k2(A2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},R2=(e,t)=>{let[n=``,...r]=Pb(()=>mi(e)),i=k2(n),a=FU($2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}H2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},z2=/^-?\d+$/;function B2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const V2=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=k2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!z2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=$2(t,a),c=FU(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&z2.test(u)?U2(l,parseInt(u,10)):W2(`step-state`,r,l,RU(s,e=>t.sessionState.get(a,e),r)),f=B2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);H2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function H2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Rj));if(i.length===0)return;let a=mU($2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function U2(e,t){return Math.max(e.min,Math.min(e.max,t))}function W2(e,t,n,r){if(r===null)return n.min;if(!z2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return U2(n,parseInt(r,10))}const G2=`render-origin`;function K2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function q2(e){return JSON.stringify(e)}function J2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function Y2(e,t){let n=Z2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function X2(e,t){let n=e.sessionState.get(t,G2);return n===null?null:J2(n)}function Z2(e,t){let n=X2(e,t);return n===null?null:K2(n,e.sessionState,t)}function Q2(e,t,n){let r=Z2(e,t);if(r===null)return;let{path:i}=n4(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function $2(e,t){return e.configFor(Y2(e,t))}function e4(e,t){let n=X2(e,t);if(n===null)return null;let r=()=>e.lanes.of(K2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function t4(e,t){let n=Z2(e,t);return n===null?G$:Y$(e.configFor(n))}function n4(e){return uH(jq().read(),e.projectDir,e.cwd,e.configFile??void 0)}function r4(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const i4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=k2(n),o=Y2(t,a),s=t.configFor(o),c=rL(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=n4(o),d=fU(s,e=>t.sessionState.get(a,e),r);n$(r4(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},a4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=k2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!z2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=Y2(t,a),c=t.configFor(s),l=rL(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=n4(s),f=fU(c,e=>t.sessionState.get(a,e),r),p=t$(d.path,f.key),m=typeof p==`number`?U2(u,p):W2(`step-config`,r,u,aL(f.globals,r)),h=B2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);n$(r4(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})`)},o4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=k2(n),i=Y2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=uU(a,o),c=pU(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=FU(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});c4(`save`,l,c);let d=n4(i);r$(r4(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(s4)].join(` `)} → ${d.path} (session=${r})`)},s4=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Y_(e.value)}`;function c4(e,t,n){for(let r of n){let n=t.validate(r.key,Y_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const l4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=k2(n),i=Y2(t,r),a=t.configFor(i),o=_U(a,e=>t.sessionState.get(r,e)),s=FU(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});c4(`save-preset`,s,o.placements);let l=n4(i),u=u$(r4(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Oy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Ey.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(s4)].join(` `)} → ${l.path} (session=${r})`)},u4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=k2(n),i=Y2(t,r),a=yU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=n4(i);d$(r4(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(uU(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=yy.map(e=>Ey[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} ${yy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},d4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=k2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=Y2(t,i),o=n4(a);f$(r4(t,i),o,r),t.reloadConfig(a);let s=Ey.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},f4=(e,t)=>{let[n=``,...r]=Pb(()=>mi(e)),i=k2(n),a=Y2(t,i),o=rL(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=n4(a),l=r.map(bU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);s$(r4(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 p4(e,t){let n=(e,t)=>[...A_(sx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(ix(t.presets).flatMap(e=>n(t,e).map(t=>zj(xA(e),E_(t)))));return ix(e.presets).flatMap(t=>n(e,t).map(e=>({member:zj(xA(t),E_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function m4(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Fj]:[]])}const h4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=k2(n),o=Y2(t,a),s=t.configFor(o),c=rL(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=UI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=n4(o),f=p$(r4(t,a),d,r,u);t.reloadConfig(o);let p=m4(p4(s,t.configFor(o)),t.sessionState.get(a,Fj)).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})`)},g4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=k2(n);t.journal.commit();let i=t.history.undo(r);Q2(t,r,i),t.dlog(`info`,`undo: restored ${F$(i)} (session=${r})`)},_4=(e,t)=>{let n=k2(A2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,FU($2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},v4=(e,t)=>{let n=k2(A2(e));t.journal.commit();let r=t.history.rewind(n);Q2(t,n,r),t.dlog(`info`,`rewind: put back ${F$(r)||`nothing`} as edit mode found it (session=${n})`)},y4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=k2(n);t.journal.commit();let i=t.history.redo(r);Q2(t,r,i),t.dlog(`info`,`redo: re-applied ${F$(i)} (session=${r})`)},b4=(e,t)=>{k2(A2(e)),t.applyUpdate()},x4=`client-hints`;function S4(e,t){let n=e.sessionState.get(t,x4);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Wt(r)}function C4(e,t,n){let r=GN(n);e.sessionState.setBatch(t,sP(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${aP(n.nerdFont,n.marks)} ${YN(n.terminal,n.clicked)} ${XN(n.terminal,n.width)} ${ZN(n.install)} ${$N(n.daemon)} ${eP(n.data)} ${iP(n.transcripts)} ${tP(n.frames,n.claudeSettings)} ${rP(n.claudeSettings.origin.sources)} (session=${t})`)}function w4(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,pk(new Date)),i;try{i=B0(e.doctor,S4(e,t),Y2(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:f1(n,r)},z0(t,r),p0(e.doctorStores))}catch(e){throw e instanceof c1?new q(e.message):e}return{...i,urlHandler:I0(e.arrival),install:d0(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:T4(e,i)}}function T4(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?GM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>o1(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 E4=(e,t)=>{let n=k2(A2(e));C4(t,n,w4(t,n))},D4=(e,t)=>{let n=a2(A2(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},O4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=k2(n),a=KN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=w4(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=V0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${rN(s.fix)} (session=${i})`),C4(t,i,c.value)},k4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=k2(n),o=KN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!eN.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${eN.join(` or `)}`);let s=w4(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>r1(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),C4(t,a,{...s,marks:u})},A4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=k2(n),a=Object.values(t.configFor(Y2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=C2(t.claudeInput,S4(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function j4([e=``,t=``,n=``,r=``],i){let a=k2(e),o=Y2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=vx(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...e1(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:S4(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const M4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=Pb(()=>mi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=j4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},N4=(e,t)=>{let[n=``,r=``,i=``,a=``]=Pb(()=>mi(e)),o=k2(n),s=i;if(!t.links.verify(Mq(o,r,s),a))throw new q(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=jq().update(e=>$V(e,r,s));if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.dlog(`info`,`repo-config: ${r} ${s} (session=${o})`),t.reloadConfig(Y2(t,o))},P4=`config-override`,F4=new Map([[Hr,N2],[qr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=k2(Pb(()=>decodeURIComponent(e.slice(0,n)))),i=Pb(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,P4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,P4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ur,P2],[Br,R2],[Vr,V2],[Jr,i4],[Yr,a4],[ei,f4],[Xr,o4],[Zr,l4],[Qr,u4],[$r,d4],[ti,h4],[ni,g4],[ri,y4],[ii,_4],[ai,v4],[Gr,F2],[Kr,I2],[Wr,L2],[oi,b4],[si,E4],[ci,O4],[li,k4],[ui,D4],[di,A4],[`run`,M4],[fi,N4]]),I4=new Set([Br,Vr,Jr,Yr,ei,Xr,Zr,Qr,$r,ti,ni,ri,ii,ai,Wr,oi,si,ci,li,di,`run`,fi,qr]);function L4(e,t){return R4(e===`dispatch`?_i(t):[{verb:e,value:t}])}function R4(e){let t=e.find(e=>I4.has(e.verb)),n=t===void 0?``:Pb(()=>hi(t.value));return n===``?null:AW(n)}const z4=(e,t)=>{let n=[],r=!1,i=_i(e),a=R4(i);for(let{verb:e,value:a}of yi(i)){let i=F4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a?.ok&&ns(t.sessionState,a.id,n.join(`
488
- `),pk(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function B4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:e4(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>Q$(e,e=>t4(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=Z2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const V4=new Map([...F4,[zr,z4]].map(([e,t])=>[e,B4(t,t=>{let n=L4(e,t);return n?.ok?n.id:null})]));Object.freeze([...V4.keys()]);function H4(e,t,n){B4((n,r)=>{let i=Z$(t4(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:P}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const U4=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`]),W4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],G4=[[`workspace.added_dirs`,`string-list`]];function K4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of W4){let i=Y4(n,e);if(i==null)t.missingRequired.push(e);else{let n=q4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of G4){let i=Y4(n,e),a=i===void 0?r:J4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))U4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function q4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function J4(e){return Array.isArray(e)&&e.every(e=>q4(e)===`string`)?`string-list`:q4(e)}function Y4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function X4(e,t){switch(e){case`vars`:return{what:e,vars:Z4(t)};case`segments`:return{what:e,segments:n3(t)};case`config`:return{what:e,config:o3(t)}}}function Z4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=e3(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=Q4(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:$4(r.lastUpdatedMs())})}return o}function Q4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function $4(e){return e===null?null:Math.max(0,Date.now()-e)}function e3(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,t3(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}`,t3(i));return t}function t3(e){return e.kind}function n3(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=i3(n),o=r3(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:a3(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function r3(e){let t=new Map;for(let n of ix(e.presets))for(let r of A_(sx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=E_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function i3(e){let t=[],n=new Set;for(let r of A_(Zb(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 a3(e,t,n){let r=new Set([...Ix(e,t).keys()].flatMap(e=>Yx(e,n)));return Array.from(r).sort()}function o3(e){return e===null?null:e.config}const s3=[`vars`,`segments`,`config`];function c3(e){return typeof e==`string`&&s3.includes(e)}function l3(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>$H(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return gJ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...SU(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const u3={moving:1e3/30,still:1e3},d3=[`data`,`state`,`reload`,`visibility`];function f3(e){return zv.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 p3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const m3=e=>({resp:e,bytes:JSON.stringify(e)}),h3=(e,t)=>Rv[t].elsewhere===null?e.statusline:e.bar,g3=e=>Math.round(1e3/e);var _3=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Gv;let r=t-1,i=this.shown(n);return Wv(e=>{let a=n.rates.get(e);if(a===void 0)return Hv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:g3(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${E(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=g3(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:m3(t.resp),statusline:m3(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||h3(i,n).bytes!==h3(r,n).bytes)&&p3(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=h3(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:pM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=zk.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps achieved=${a} evaluated=${e.evaluated} woke=${d3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function v3(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 y3=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,b3=`#{session_id} #{client_control_mode} #{pane_id}`;function x3(e){let t=new Set;for(let n of e.split(`
489
- `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function S3(e,t){let n=new Set;for(let r of e.split(`
490
- `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function C3(e,t){let n=new Map;for(let t of e.split(`
485
+ `}const n2=e=>({kind:`ok`,value:e}),r2=e=>({kind:`failed`,reason:e});var i2=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const a2=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function o2(e){return a2.test(e)?e:null}function s2(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return n2(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return n2({app:n,missing:r2(`its script could not be read (${r.reason})`)});let i=Mo(r.value);return n2({app:n,missing:i===null?r2("its script is not one `cc-candybar install` wrote"):n2([i.node,i.script].filter(t=>!e.exists(t)))})}async function c2(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 l2(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(`${Rr}://${ui}/${n}`);return(r===null?await c2(e,n):null)??{kind:`lost`,unopened:r,opener:s2(e)}}function u2(e,t,n){let r=ht({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?n2(r.stdout):r2(r.stderr.trim()||r.error||r.reason)}const d2=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Rr}://probe"));u.isNil() ? "" : u.path.js`;async function f2(){let e=await K0();if(e.kind!==`ok`)return r2(pn(e).split(`
486
+ `).join(` — `));let t=q0(e.value,[`handlerProbes`]);if(t!==null)return r2(t);let{version:n,handlerProbes:r}=e.value;return n2({version:n,arrivals:r})}function p2(){return{platform:process.platform,sockets:{own:Tt(),handler:Et()},now:Date.now,nonce:ie,daemon:f2,open:e=>{let t=u2(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=u2(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,d2]);if(e.kind===`failed`)return e;let t=e.value.trim();return n2(t===``?null:t)},script:e=>u2(`doctor.osadecompile`,`/usr/bin/osadecompile`,[No(e)]),exists:p.existsSync}}const m2=/^─{20,}/,h2=/^❯(\s|$)/,g2=/›\s*stashed$/;function _2(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>m2.test(e)?[t]:[]).at(-2);return n===void 0||!h2.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function v2(e){if(e.inMode)return{kind:`in-mode`};let t=_2(e);return t===null?{kind:`no-prompt`}:g2.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function y2(e){return/^❯\s*\S/u.test(_2(e)?.prompt??``)}const b2=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function x2(e){return e.screen.some(e=>b2.test(e))}const S2={"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 C2(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 w2(e,t,n){let r=C2(t);if(r.kind===`refused`)return r;let i=r.hint,a=v2(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:S2[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function T2(e,t,n,r){let i=nq(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function E2(e){let t=T2(e,`claude-input.read`,[`display`,`-p`,`-t`,e.pane,`#{pane_in_mode}`,`;`,`capture-pane`,`-p`,`-t`,e.pane]);if(t.kind===`rate-limited`)throw Error(t.reason);let[n=``,...r]=t.stdout.split(`
487
+ `);return{inMode:n!==`0`,screen:r}}function D2(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 O2(e,t){let n=T2(e,`claude-input.type`,D2(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 k2(){return{read:E2,type:O2}}function A2(e){let t=AW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function j2(e){return Pb(()=>decodeURIComponent(e))}function M2(e,t,n){let r=ht(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function N2(e,t){M2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const P2=(e,t)=>N2(j2(e),t),F2=(e,t)=>M2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,j2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),I2=(e,t)=>N2(j2(e),t),L2=(e,t)=>N2(j2(e),t),R2=(e,t)=>{let n=A2(j2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},z2=(e,t)=>{let[n=``,...r]=Pb(()=>mi(e)),i=A2(n),a=FU(e4(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}U2(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})`)},B2=/^-?\d+$/;function V2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const H2=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=A2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!B2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=e4(t,a),c=FU(s),l=c.rangeParamsFor(r);if(!l)throw new q(`step-state: key "${r}" is not a bounded (range) state key (have keys: ${c.listKeys().join(`, `)})`);let u=t.sessionState.get(a,r),d=u&&B2.test(u)?W2(l,parseInt(u,10)):G2(`step-state`,r,l,RU(s,e=>t.sessionState.get(a,e),r)),f=V2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);U2(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 U2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Rj));if(i.length===0)return;let a=mU(e4(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function W2(e,t){return Math.max(e.min,Math.min(e.max,t))}function G2(e,t,n,r){if(r===null)return n.min;if(!B2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return W2(n,parseInt(r,10))}const K2=`render-origin`;function q2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function J2(e){return JSON.stringify(e)}function Y2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function X2(e,t){let n=Q2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function Z2(e,t){let n=e.sessionState.get(t,K2);return n===null?null:Y2(n)}function Q2(e,t){let n=Z2(e,t);return n===null?null:q2(n,e.sessionState,t)}function $2(e,t,n){let r=Q2(e,t);if(r===null)return;let{path:i}=r4(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function e4(e,t){return e.configFor(X2(e,t))}function t4(e,t){let n=Z2(e,t);if(n===null)return null;let r=()=>e.lanes.of(q2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function n4(e,t){let n=Q2(e,t);return n===null?K$:X$(e.configFor(n))}function r4(e){return uH(Mq().read(),e.projectDir,e.cwd,e.configFile??void 0)}function i4(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const a4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=A2(n),o=X2(t,a),s=t.configFor(o),c=rL(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=r4(o),d=fU(s,e=>t.sessionState.get(a,e),r);r$(i4(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},o4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=A2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!B2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=X2(t,a),c=t.configFor(s),l=rL(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=r4(s),f=fU(c,e=>t.sessionState.get(a,e),r),p=n$(d.path,f.key),m=typeof p==`number`?W2(u,p):G2(`step-config`,r,u,aL(f.globals,r)),h=V2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);r$(i4(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})`)},s4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=A2(n),i=X2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=uU(a,o),c=pU(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=FU(a),u=s.map(e=>{let t=l.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save: ${t.reason}`);return[e.target,t.value]});l4(`save`,l,c);let d=r4(i);i$(i4(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(c4)].join(` `)} → ${d.path} (session=${r})`)},c4=e=>`${e.preset}/${e.id}.settings.${e.setting}=${Y_(e.value)}`;function l4(e,t,n){for(let r of n){let n=t.validate(r.key,Y_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const u4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=A2(n),i=X2(t,r),a=t.configFor(i),o=_U(a,e=>t.sessionState.get(r,e)),s=FU(a),c=o.picks.map(e=>{let t=s.validate(e.sessionKey,e.value);if(!t.ok)throw new q(`save-preset: ${t.reason}`);return[e.configKey,t.value]});l4(`save-preset`,s,o.placements);let l=r4(i),u=d$(i4(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Oy.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Ey.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(c4)].join(` `)} → ${l.path} (session=${r})`)},d4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=A2(n),i=X2(t,r),a=yU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=r4(i);f$(i4(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(uU(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=yy.map(e=>Ey[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} ${yy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},f4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=A2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=X2(t,i),o=r4(a);p$(i4(t,i),o,r),t.reloadConfig(a);let s=Ey.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},p4=(e,t)=>{let[n=``,...r]=Pb(()=>mi(e)),i=A2(n),a=X2(t,i),o=rL(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=r4(a),l=r.map(bU),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);c$(i4(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 m4(e,t){let n=(e,t)=>[...A_(sx(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(ix(t.presets).flatMap(e=>n(t,e).map(t=>zj(xA(e),E_(t)))));return ix(e.presets).flatMap(t=>n(e,t).map(e=>({member:zj(xA(t),E_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function h4(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Fj]:[]])}const g4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=A2(n),o=X2(t,a),s=t.configFor(o),c=rL(s);if(!r)throw new q(`apply-layout-op: <key>/<op> is required (have: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`apply-layout-op: ${l.reason}`);let u=UI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=r4(o),f=m$(i4(t,a),d,r,u);t.reloadConfig(o);let p=h4(m4(s,t.configFor(o)),t.sessionState.get(a,Fj)).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})`)},_4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=A2(n);t.journal.commit();let i=t.history.undo(r);$2(t,r,i),t.dlog(`info`,`undo: restored ${I$(i)} (session=${r})`)},v4=(e,t)=>{let n=A2(j2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,FU(e4(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},y4=(e,t)=>{let n=A2(j2(e));t.journal.commit();let r=t.history.rewind(n);$2(t,n,r),t.dlog(`info`,`rewind: put back ${I$(r)||`nothing`} as edit mode found it (session=${n})`)},b4=(e,t)=>{let[n=``]=Pb(()=>mi(e)),r=A2(n);t.journal.commit();let i=t.history.redo(r);$2(t,r,i),t.dlog(`info`,`redo: re-applied ${I$(i)} (session=${r})`)},x4=(e,t)=>{A2(j2(e)),t.applyUpdate()},S4=`client-hints`;function C4(e,t){let n=e.sessionState.get(t,S4);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Wt(r)}function w4(e,t,n){let r=GN(n);e.sessionState.setBatch(t,sP(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${aP(n.nerdFont,n.marks)} ${YN(n.terminal,n.clicked)} ${XN(n.terminal,n.width)} ${ZN(n.install)} ${$N(n.daemon)} ${eP(n.data)} ${iP(n.transcripts)} ${tP(n.frames,n.claudeSettings)} ${rP(n.claudeSettings.origin.sources)} (session=${t})`)}function T4(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,pk(new Date)),i;try{i=V0(e.doctor,C4(e,t),X2(e,t),n=>e.sessionState.get(t,n),{kind:`ok`,value:e.serving()},{kind:`ok`,value:r.map(e=>e.rateLimits)},{kind:`ok`,value:r.map(e=>e.transcript)},n,{kind:`ok`,value:p1(n,r)},B0(t,r),m0(e.doctorStores))}catch(e){throw e instanceof l1?new q(e.message):e}return{...i,urlHandler:L0(e.arrival),install:f0(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:E4(e,i)}}function E4(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?GM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>s1(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 D4=(e,t)=>{let n=A2(j2(e));w4(t,n,T4(t,n))},O4=(e,t)=>{let n=o2(j2(e));if(n===null)throw new q(`doctor-probe: the value is not a probe nonce`);if(t.arrival.via!==`link`)throw new q(`doctor-probe: a probe arrives only as a link`);let{handler:r}=t.arrival;t.probes.arrive({nonce:n,handler:r}),t.dlog(`info`,`doctor-probe: arrived nonce=${n} handler=${r??`unreported`}`)},k4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=A2(n),a=KN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=T4(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=H0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${rN(s.fix)} (session=${i})`),w4(t,i,c.value)},A4=(e,t)=>{let[n=``,r=``,i=``]=Pb(()=>mi(e)),a=A2(n),o=KN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!eN.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${eN.join(` or `)}`);let s=T4(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>i1(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),w4(t,a,{...s,marks:u})},j4=(e,t)=>{let[n=``,r=``]=Pb(()=>mi(e)),i=A2(n),a=Object.values(t.configFor(X2(t,i)).actions).filter(e=>`slash`in e),o=a.find(e=>e.slash===r);if(o===void 0)throw new q(`${JSON.stringify(r)} is not a command this config declares (it declares: ${[...new Set(a.map(e=>e.slash))].join(`, `)||`none`})`);let s=w2(t.claudeInput,C4(t,i).tmux,o.slash);if(s.kind===`refused`)throw t.dlog(`warn`,`slash: ${r} refused — ${s.reason} (session=${i})`),new q(`${r} was not typed: ${s.reason}`);t.dlog(`info`,`slash: typed ${r} into ${s.pane} (session=${i})`)};function M4([e=``,t=``,n=``,r=``],i){let a=A2(e),o=X2(i,a),s=i.configFor(o).actions,c=Object.hasOwn(s,t)?s[t]:void 0;if(c===void 0||!(`run`in c))throw new q(`"${t}" is not a run action this session's config declares`);let l=vx(c);if(!i.links.verify({sessionId:a,action:t,declaration:l,evaluated:n},r))throw new q(`the link's signature does not match what it carries: it was not drawn by this daemon, or its action has been edited since it was drawn`);let u;try{u=JSON.parse(n)}catch{throw new q(`run ${t}: what the link carries is not JSON`)}let[d,...f]=u.run;if(d===void 0||d===``)throw new q(`run ${t}: the program evaluated to nothing`);let p=i.sourcesFor(o);return{sessionId:a,action:t,argv:[d,...f],env:{...t1(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:C4(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const N4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=Pb(()=>mi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=M4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},P4=(e,t)=>{let[n=``,r=``,i=``,a=``]=Pb(()=>mi(e)),o=A2(n),s=i;if(!t.links.verify(Nq(o,r,s),a))throw new q(`the answer's signature does not match what it carries: it was not drawn by this daemon`);let c=Mq().update(e=>$V(e,r,s));if(c.kind===`failed`)throw Error(`${r} was not ${s}: ${c.reason}`);t.dlog(`info`,`repo-config: ${r} ${s} (session=${o})`),t.reloadConfig(X2(t,o))},F4=`config-override`,I4=new Map([[Hr,P2],[qr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=A2(Pb(()=>decodeURIComponent(e.slice(0,n)))),i=Pb(()=>decodeURIComponent(e.slice(n+1))).trim();if(i!==``){if(!i.startsWith(`/`))throw new q(`load-config: path must be absolute, got "${i}"`);if(!/\.(json5?|json)$/.test(i))throw new q(`load-config: path must end with .json5 or .json, got "${i}"`)}i===``?(t.sessionState.clear(r,F4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,F4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Ur,F2],[Br,z2],[Vr,H2],[Jr,a4],[Yr,o4],[ei,p4],[Xr,s4],[Zr,u4],[Qr,d4],[$r,f4],[ti,g4],[ni,_4],[ri,b4],[ii,v4],[ai,y4],[Gr,I2],[Kr,L2],[Wr,R2],[oi,x4],[si,D4],[ci,k4],[li,A4],[ui,O4],[di,j4],[`run`,N4],[fi,P4]]),L4=new Set([Br,Vr,Jr,Yr,ei,Xr,Zr,Qr,$r,ti,ni,ri,ii,ai,Wr,oi,si,ci,li,di,`run`,fi,qr]);function R4(e,t){return z4(e===`dispatch`?_i(t):[{verb:e,value:t}])}function z4(e){let t=e.find(e=>L4.has(e.verb)),n=t===void 0?``:Pb(()=>hi(t.value));return n===``?null:AW(n)}const B4=(e,t)=>{let n=[],r=!1,i=_i(e),a=z4(i);for(let{verb:e,value:a}of yi(i)){let i=I4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a?.ok&&ns(t.sessionState,a.id,n.join(`
488
+ `),pk(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function V4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:t4(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>$$(e,e=>n4(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=Q2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const H4=new Map([...I4,[zr,B4]].map(([e,t])=>[e,V4(t,t=>{let n=R4(e,t);return n?.ok?n.id:null})]));Object.freeze([...H4.keys()]);function U4(e,t,n){V4((n,r)=>{let i=Q$(n4(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:P}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const W4=new Set([`hook_event_name`,`session_id`,`session_name`,`transcript_path`,`cwd`,`model`,`workspace`,`version`,`output_style`,`cost`,`context_window`,`exceeds_200k_tokens`,`effort`,`thinking`,`rate_limits`,`vim`,`agent`,`worktree`]),G4=[[`session_id`,`string`],[`transcript_path`,`string`],[`cwd`,`string`],[`model`,`object`],[`model.id`,`string`],[`model.display_name`,`string`],[`workspace`,`object`],[`workspace.current_dir`,`string`],[`workspace.project_dir`,`string`]],K4=[[`workspace.added_dirs`,`string-list`]];function q4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of G4){let i=X4(n,e);if(i==null)t.missingRequired.push(e);else{let n=J4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of K4){let i=X4(n,e),a=i===void 0?r:Y4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))W4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function J4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function Y4(e){return Array.isArray(e)&&e.every(e=>J4(e)===`string`)?`string-list`:J4(e)}function X4(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n))return;n=n[e]}return n}function Z4(e,t){switch(e){case`vars`:return{what:e,vars:Q4(t)};case`segments`:return{what:e,segments:r3(t)};case`config`:return{what:e,config:s3(t)}}}function Q4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=t3(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=$4(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:e3(r.lastUpdatedMs())})}return o}function $4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function e3(e){return e===null?null:Math.max(0,Date.now()-e)}function t3(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,n3(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}`,n3(i));return t}function n3(e){return e.kind}function r3(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=a3(n),o=i3(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:o3(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function i3(e){let t=new Map;for(let n of ix(e.presets))for(let r of A_(sx(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=E_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function a3(e){let t=[],n=new Set;for(let r of A_(Zb(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 o3(e,t,n){let r=new Set([...Ix(e,t).keys()].flatMap(e=>Yx(e,n)));return Array.from(r).sort()}function s3(e){return e===null?null:e.config}const c3=[`vars`,`segments`,`config`];function l3(e){return typeof e==`string`&&c3.includes(e)}function u3(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>$H(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return _J({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...SU(n.config,n.fileHeldSettings,a),configPath:n.configPath},history:e.history(t),back:e.navigation(t,n.config)})});return{payload:()=>s.read(),effective:()=>o.read(),selections:()=>o.read()}}}const d3={moving:1e3/30,still:1e3},f3=[`data`,`state`,`reload`,`visibility`];function p3(e){return zv.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 m3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const h3=e=>({resp:e,bytes:JSON.stringify(e)}),g3=(e,t)=>Rv[t].elsewhere===null?e.statusline:e.bar,_3=e=>Math.round(1e3/e);var v3=class{requests=new Map;feeds=new Map;stopWatching=null;drawn=0;pushed=0;refused=0;lookups=0;found=0;constructor(e){this.deps=e}note(e,t,n){let r=this.requests.get(e);if(r!==void 0&&r.order>n)return;this.requests.delete(e),this.requests.set(e,{req:t,order:n});for(let e of this.requests.keys()){if(this.requests.size<=256)break;this.feeds.has(e)||this.requests.delete(e)}let i=this.feeds.get(e);i!==void 0&&i.noted++}subscribe(e,t){let n=this.deps.lanes(e);if(n!==null&&!n[t.lane])return this.refuse(e,t),()=>{};let r=this.feeds.get(e),i=r??this.open(e);return i.followers.set(t,null),i.rates.has(t.lane)||i.rates.set(t.lane,[]),r!==void 0&&this.send(i,t),this.hasten(i),this.deps.log(`info`,`feed sid=${JSON.stringify(e)} subscribed lane=${t.lane} subscribers=${i.followers.size} view=${n===null?`N`:`Y`}`),()=>this.unsubscribe(i,t)}following(e){return new Set([...this.feeds.get(e)?.followers.keys()??[]].filter(e=>e.drawing()).map(e=>e.lane))}wake(e,t){let n=this.feeds.get(e);n!==void 0&&(n.woke[t]++,this.hasten(n)||n.coalesced++)}wakeWhere(e,t){for(let{sessionId:n,req:r}of this.watched())t(r)&&this.wake(n,e)}newestWhere(e){let t=null;for(let[n,{req:r,order:i}]of this.requests)e(r)&&(t===null||i>t.order)&&(t={sessionId:n,order:i});return this.lookups++,t!==null&&this.found++,t?.sessionId??null}latest(e){return this.requests.get(e)?.req??null}watched(){return[...this.feeds.keys()].flatMap(e=>{let t=this.requests.get(e);return t===void 0?[]:[{sessionId:e,req:t.req}]})}feedsOf(e,t){let n=this.feeds.get(e);if(n===void 0)return Gv;let r=t-1,i=this.shown(n);return Wv(e=>{let a=n.rates.get(e);if(a===void 0)return Hv;let o=0;for(let t of n.followers.keys())t.lane===e&&o++;let s=0;for(let e of a)e>r&&e<=t&&s++;return{subscribers:o,fps:s,shown:i}})}getStats(){let e=0;for(let t of this.feeds.values())e+=t.followers.size;return{feeds:this.feeds.size,subscribers:e,drawn:this.drawn,pushed:this.pushed,refused:this.refused,lookups:this.lookups,found:this.found}}open(e){let t=this.deps.now(),n={sessionId:e,followers:new Map,rates:new Map,unwatch:this.deps.watch(e,()=>this.wake(e,`state`)),unpin:this.deps.pin(e),phase:{kind:`waiting`},lastStart:-1/0,last:null,since:t,drawn:0,noted:0,noView:0,moving:0,unseen:0,failed:0,pushed:0,pace:_3(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${E(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=_3(a),this.arm(e,n+a)}spacingOf(e){return this.shown(e)?this.deps.periods.moving:this.deps.periods.still}hasten(e){let{phase:t}=e;if(t.kind===`drawing`)return!1;let n=Math.max(this.deps.now(),e.lastStart+this.spacingOf(e));return t.kind===`due`&&t.at<=n?!1:(this.arm(e,n),!0)}arm(e,t){e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.phase={kind:`due`,at:t,timer:setTimeout(()=>this.draw(e),Math.max(0,t-this.deps.now()))}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t){let n=this.deps.lanes(e.sessionId);if(n!==null)for(let t of[...e.followers.keys()])n[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;let r={bar:h3(t.resp),statusline:h3(t.statusline)};if(e.last?.answers.bar.bytes===r.bar.bytes&&e.last.answers.statusline.bytes===r.statusline.bytes)return;let i=e.last?.answers??null;e.last={answers:r},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[n,a]of e.rates)(i===null||g3(i,n).bytes!==g3(r,n).bytes)&&m3(a,t.at);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let{resp:n,bytes:r}=g3(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:pM(t.lane),code:`SWITCHED_OFF`,daemonV:3})}summarize(e,t){let n=this.deps.now(),r=this.deps.refreshes(),i=(n-e.since)/1e3,a=i===0?`-`:`${(e.drawn/i).toFixed(1)}fps`,o=zk.map(t=>`${t}:${r[t]-e.refreshesAtOpen[t]}`).join(`,`);this.deps.log(`info`,`feed sid=${JSON.stringify(e.sessionId)} ${t} subscribers=${e.followers.size} lanes=${[...e.followers.keys()].map(e=>e.lane).join(`,`)||`-`} for=${Math.round(i)}s drawn=${e.drawn} noted=${e.noted} noView=${e.noView} moving=${e.moving} unseen=${e.unseen} failed=${e.failed} pushed=${e.pushed} pace=${e.pace}fps achieved=${a} evaluated=${e.evaluated} woke=${f3.map(t=>`${t}:${e.woke[t]}`).join(`,`)} coalesced=${e.coalesced} daemonRefreshed=${o} meanDraw=${e.drawn===0?`-`:(e.drawMs/e.drawn).toFixed(2)}ms`),e.summarizedAt=n}};function y3(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 b3=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,x3=`#{session_id} #{client_control_mode} #{pane_id}`;function S3(e){let t=new Set;for(let n of e.split(`
489
+ `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function C3(e,t){let n=new Set;for(let r of e.split(`
490
+ `)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function w3(e,t){let n=new Map;for(let t of e.split(`
491
491
  `)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
492
- `)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var w3=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: ${E(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:S3(t.stdout,x3(n.stdout)),status:C3(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),!T3(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 T3(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 E3=`@cc-candybar-status-prior`,D3=`@cc-candybar-status-wrote`,O3=`@cc-candybar-binding-prior`,k3=[`-T`,`root`,`MouseDown1Status`],A3=Array.from({length:5},(e,t)=>t),j3=e=>`@cc-candybar-row-${e}`,M3=e=>`#[fill=terminal]#{${j3(e)}}`,N3=e=>`status-format[${e}]`;function P3(e){return e===0?`off`:e===1?`on`:String(e)}function F3(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 I3(e,t){if(e===null)return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>e[Number(n)]===t[Number(n)])}function L3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function R3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function z3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function B3(e){return e.map(e=>e.map(z3).join(` `)).join(` ; `)}const V3=`ccb:separator`;function H3(e){return R3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,V3],e]))}function U3(e,t){let n=e.split(`${V3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const W3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],G3=e=>[`show-options`,`-g`,`-q`,`-v`,e],K3=e=>[[`show-options`,`-t`,e],W3(e,`status`),...A3.map(t=>W3(e,N3(t)))];function q3(e){let[t=``,n=``,...r]=e,i=t.split(`
493
- `).map(e=>e.split(` `)[0]??``),a={};for(let e of A3)i.includes(N3(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 J3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,N3(Number(t)),L3(n)])]}const Y3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...K3(e),...A3.map(e=>G3(N3(e))),W3(e,E3),W3(e,D3)];function X3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:F3(t)}catch(e){return{kind:`theirs`,why:`${E3} 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 Z3(e,t,n){let[r=``,...i]=t,a=q3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return X3(s,c,n);let l=F3(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,M3(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,E3,JSON.stringify(f)],...J3(e,d)]}}const Q3=e=>[...K3(e),W3(e,D3)];function $3(e,t,n){let r=q3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(I3(r.formats,t.wrote))a.push(...J3(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,N3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,L3(t.status)]):o.push(`status`)),a.push(...A3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,j3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,E3],[`set-option`,`-q`,`-u`,`-t`,e,D3]),{commands:a,kept:o}}const e6=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,t6=[[`list-keys`,`-T`,`root`]];function n6(e){let t=e6.exec(e);return t===null?null:{line:t[0],command:t[1]}}const r6=`cc-candybar://tmux-status-click/`,i6=e=>`${r6}${pi([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,a6=e=>e?.command.includes(r6)??!1;function o6(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,O3]};return a6(n6(t))?{steps:[e===null?{command:[`unbind-key`,...k3]}:{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 s6=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=OW(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,Q3(n));if(i===null)continue;let a=$3(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,t6);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let t=c6(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${E3}}\t#{${D3}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
494
- `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=X3(i,a,this.deps.owner);o.kind===`ours`?t.layouts.set(n,{prior:o.prior,rows:[],status:o.status}):this.leave(e,t,n,o.why)}let r=(await this.ask(e,[G3(`@cc-candybar-binding-prior`)]))?.[0]??``;if(r!==``)try{let e=JSON.parse(r);e.owner===this.deps.owner&&(t.binding={kind:`adopted`,prior:e.prior})}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${O3} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,Y3(n));if(r===null||this.closed)return null;let i=Z3(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,j3(r),e])}),i!==n.status){let e=P3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,D3,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,B3(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,Q3(n));if(i===null)return;let a=$3(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,t6);if(r===null||this.closed)return;let i=n6(r[0]??``);if(n.kind===`none`&&a6(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`&&a6(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...k3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${z3(`${this.deps.handler} ${i6(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,t6);if(r===null)return;let i=o6(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=o6(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,H3(t));return n.kind===`ok`?U3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,H3(t)));return n.kind===`ok`?U3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,R3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,R3(t),n)))}};function c6(e){try{return mi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const l6=`CC_CANDYBAR_CONFIG`;function u6(e,t){return rV(t,e[l6])}function d6(e,t,n){return rV(n,e)??u6(t,n)}const $=e=>({arity:e,keep:!0}),f6=e=>({arity:e,keep:!1}),p6={"--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":f6(`none`),"--background":f6(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":f6(`optional`),"-c":f6(`none`),"--continue":f6(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":f6(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":f6(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":f6(`none`),"--forward-subagent-text":$(`none`),"--from-pr":f6(`optional`),"-h":f6(`none`),"--help":f6(`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":f6(`none`),"--print":f6(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":f6(`optional`),"--resume":f6(`optional`),"--safe-mode":$(`none`),"--session-id":f6(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":f6(`optional`),"--tmux":f6(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":f6(`none`),"--version":f6(`none`),"-w":f6(`optional`),"--worktree":f6(`optional`)},m6={resume:`--resume`,fresh:`--session-id`};function h6(e){return[m6[e.kind],e.sessionId]}const g6=e=>e.startsWith(`-`)&&e!==`-`;function _6(e,t){let n=b6(t);return n===null?{dir:e??t,args:[]}:e!==null&&v6(e,n.top)?{dir:e,args:[]}:{dir:e===null||b6(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const v6=(e,t)=>e===t||e.startsWith(t+s.sep);function y6(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!g6(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=p6[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=>!g6(e)):o.arity===`variadic`?x6(n.slice(r),e=>!g6(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 b6(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 x6(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const S6=`candybar-band@cc-candybar`,C6=s.join(`bin`,`cc-candybar-native`),w6=`@cc-candybar-bar-pane`,T6=_P(`/reload-plugins`),E6=e=>({kind:`done`,said:e});function D6(e){let t=S2(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const O6={band:{on:(e,t,n)=>{let r=$e(t.bundle);if(r===null)throw new q(`${Rv.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,C6);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${S6} from ${r}`,finished:k6(e,r,n)}},off:()=>E6(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=D6(e),i=ze(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Rv.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:M6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>E6(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=D6(e),i=n.barPanes(r);return i.length>0?E6(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):E6(`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=S2(e.hints.tmux);if(r.kind===`refused`)return E6(`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 E6(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>E6(`the daemon draws ${D6(e).pane}'s bar in its status line`),off:()=>E6(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function k6(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,S6],r);let i=C2(n.claudeInput,e.hints.tmux,T6);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 ${S6} from ${t} and typed /reload-plugins into ${i.pane}`}const A6=new Set([Xa,l6]);function j6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function M6(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,Be(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}) — ${Rv.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=L6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Rv.statusline.label} off and on again`);let s=N6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=y6(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=j6(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])=>A6.has(e)),m=(e,t)=>Ue(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...h6(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=P6(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(_6(null,i.cwd),_))}let y=m(_6(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}\`, ${F6[g.kind](e.sessionId)}, and its statusline follows lane B`}function N6(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 P6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const F6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},I6={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function L6(e){let t=_2(e);return t.kind===`ready`?b2(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:v2(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:I6[t.kind]}var R6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=zv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),ns(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=O6[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function z6(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 B6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function V6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function H6(e,t,n){let r=z6(`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 U6=2e3;function W6(e,t,n){let r=nq(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function G6(e,t){if(t.ok)return t.stdout;let n=t.error??[t.reason,t.stderr.trim(),t.stdout.trim()].filter(e=>e!==``).join(`: `);throw Error(`${e} failed (${n})`)}function K6(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 q6=`#{pane_id} #{${w6}}`;function J6(e,t){return e.split(`
495
- `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const Y6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function X6(e,t,n){for(let r of m1(p1(e),t)){if(r.command.split(` `).some(e=>Y6.test(e)))return!0;if(r.pid===n)return!1}return!1}const Z6=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
496
- `);async function Q6(e){if(process.platform===`linux`)return{executable:await p.promises.readlink(`/proc/${e}/exe`),argv:(await p.promises.readFile(`/proc/${e}/cmdline`,`utf8`)).split(`\0`).slice(0,-1),env:(await p.promises.readFile(`/proc/${e}/environ`,`utf8`)).split(`\0`).slice(0,-1)};let t=G6(`reading process ${e}'s arguments`,await mt({bin:`python3`,args:[`-c`,Z6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function $6(e,t){return G6(e,await mt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function e8(e){let t=await rq(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 $6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function t8(e){let{panePid:t,cwd:n,foreground:r}=await e8(e),i=await $6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await Q6(r),o=p1(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:X6(i,r,t)}}function n8(e){return{claudeInput:O2(),barPanes:e=>J6(W6(e,[`list-panes`,`-a`,`-F`,q6]),e.pane),openBarPane:(e,t,n)=>{let r=W6(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 W6(e,[`set-option`,`-p`,`-t`,r,w6,e.pane]),r},closePane:(e,t)=>void W6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void G6(`claude ${e.join(` `)}`,await mt({bin:`claude`,args:[...e],env:e1(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:YV,paneClaude:t8,paneDir:async(e,t)=>{let n=Date.now()+U6;for(;;){let r=await e8(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 ${U6/1e3} s`);await ye(100)}},launcherNode:e=>H6(e,e=>B6(e,p.constants.X_OK),V6),onPath:(e,t)=>{let n=z6(e,t,e=>B6(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 ye(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await mt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?K6(r.stdout):null;return i===null?(G6(`reading ${n}'s module graph`,r),{ok:!0}):{ok:!1,reason:i}},terminate:e=>{try{process.kill(e,`SIGTERM`)}catch(t){throw Error(`Claude Code (pid ${e}) could not be sent SIGTERM: ${t instanceof Error?t.message:String(t)}`)}},exited:async(e,t)=>{let n=Date.now()+t;for(;Ds(e);){if(Date.now()>n)return!1;await ye(100)}return!0},typeShellLine:(e,t)=>void W6(e,E2(e.pane,`cc-candybar-lane`,[]),t)}}function r8(e,t){return zv.filter(n=>e[n]&&Rv[n].elsewhere!==null&&t.has(n))}function i8(e,t){let n=`the bar is drawn in ${t.map(e=>Rv[e].elsewhere).join(` and `)}`,r=gi([{verb:ei,args:[e,...t.map(e=>Rv[e].setting)]}]);return{channels:[{severity:Cb,message:n,lines:[[wb(n,gi([{verb:Hr,args:[n]}])),wb(`[⟲ draw it here]`,r)]]}]}}const a8={order:-1/0,text:null,failure:null};var o8=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??a8;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??a8;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}`}}},s8=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?Zv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function c8(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function l8(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function u8(e,t){for(let n of Object.entries(t))e.push(n)}const d8={ok:`info`,"bad-request":`warn`,threw:`error`};function f8(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,E(e.error)]]}}function p8(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...f8(n)];return{level:d8[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${cs(t)}`).join(``)}`}}const m8=new lQ,h8=new r2,g8=new AM,_8=i(import.meta.url),v8=f0(St());ft(m8.launchStats);const y8=new hG({counters:m8,logger:M}),b8=new Bk(M),x8=Dq({watchers:y8,logger:M,ledger:b8}),{gitProvider:S8,usageStore:C8,tmuxService:w8,hostService:T8,managedStorage:E8}=x8,D8=new fQ,O8=new x$(D8,M),k8=new W$,A8=new ib,j8=new s8({now:()=>pk(new Date),close:(e,t)=>H4(e,t,v5),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${E(t)}`)}),M8=Qo(),N8=new fs({supersede:(e,t)=>E8.supersede(e,t),launch:mt,state:D8,log:M,now:()=>pk(new Date)}),P8=[t.execPath,...t.execArgv],F8=new R6({edge:n8(e=>L8.following(e)),host:{bundle:_8,node:P8,socket:Tt(),preload:Ao(_8)},state:D8,log:M,now:()=>pk(new Date),defer:e=>void ge(e)}),I8=new s6({edge:{run:(e,t,n)=>rq({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>nq({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>L8.subscribe(e,t),sessionInPane:(e,t)=>L8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Ie(Tt())}`,...[...P8,_8].map(Ie),`url-handle`].join(` `),owner:Tt(),log:M}),L8=new _3({render:(e,t)=>D5(e,t),watch:(e,t)=>(0,J.reaction)(()=>D8.revision(e),t),lanes:e=>k5(e),pin:e=>V8.pin(e),shown:e=>R8.shown(e.hints.tmux),watching:()=>R8.follow(),refreshes:()=>b8.totals(),periods:u3,now:()=>performance.now(),log:M}),R8=new w3({listPanes:e=>rq({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,y3]),listClients:e=>rq({socket:e},`frames.visibility`,[`list-clients`,`-F`,b3]),sockets:()=>new Set(L8.watched().flatMap(({req:e})=>z8(e))),onAnswer:(e,t)=>I8.answered(e,t),onChange:e=>L8.wakeWhere(`visibility`,t=>z8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function z8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const B8=new o8(Lt(),e=>L8.wake(e,`data`)),V8=new sQ({sessionState:D8,watchers:y8,log:M,storage:E8,signer:M8,ledger:b8,declare:(e,t,n,r)=>cJ(x8,e,t,n,r),source:l3({providers:x8,sessionState:D8,history:e=>O8.depth(e),navigation:(e,t)=>k8.depth(e,D8,FU(t))})},{budgetBytes:()=>(t5(),GZ(q8)),observers:{onReload:(e,t)=>{M(`info`,JZ(e));for(let e of t)L8.wake(e,`reload`)},onViewChanged:e=>L8.wake(e,`data`)}}),H8=60*1e3,U8=oW({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:H8,stat:p.statSync,exit:()=>o5(0),log:M}),W8=rW({entryUrl:import.meta.url,intervalMs:H8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>U8.checkNow(),log:M});let G8=null,K8=null,q8=0;function J8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),o5(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),o5(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),o5(0)});try{n5(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),o5(1);return}G8=Cs(t.pid);let e=Ns(Fs(G8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),o5(1);return}K8=e.registryPath,p.mkdirSync(wt(),{recursive:!0}),Ot(Tt()),D8.useStorage(new mQ(jt(),500,M)),O8.useStorage(H$(Mt(),M)),Es({anchor:Ts(t.env),isAlive:Ds,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),o5(0)}}),X8(le.createServer({allowHalfOpen:!1},e=>{s5(e)}),Tt(),!1)}function Y8(){let e=S8.getStats(),t=w8.getStats(),n=C8.scanStats(),r=E8.stats(),i=V8.stats;return{records:b8.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:C8.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:T8.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost,probes:r.probes,probeFailures:r.probeFailures,stalled:r.stalled,stalls:r.stalls}}}function X8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),o5(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Z8(e,n)}),e.listen(n,()=>Q8(n))}function Z8(e,n){let r=ps(ms(kt(n)),(e,t)=>Ss(e,t,{readStartTime:xs,pidAlive:Ds}));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}`),o5(1);return}}X8(e,n,!0)}function Q8(e){let n=_s(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),o5(0);return}r5(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=${N(ue.getHeapStatistics().heap_size_limit)}MB memoryLimit=${N(q8)}MB`),Dr();let r=B8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),U8.arm(),W8.arm(),t5().arm(),$8(e,n.identity)}function $8(e,n){bs({bound:n,myPid:t.pid,readIdentity:()=>_s(e),readLease:()=>ms(kt(e)),shutdown:e=>o5(e),log:M}).arm()}let e5=null;function t5(){if(e5===null)throw Error(`daemon: limits not yet established`);return e5}function n5(e){q8=ir(e),e5=fr(vr(m8.startedAt.getTime(),e=>o5(e),{limitBytes:q8}))}function r5(e){let n=hs(kt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:G8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let i5=0,a5=!1;function o5(e){if(a5)return;a5=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>I8.restoreAll()],[`gitService close`,()=>S8.close()],[`usageStore close`,()=>C8.close()],[`tmuxService close`,()=>w8.close()],[`hostService close`,()=>T8.close()],[`runs close`,()=>N8.close()],[`managedStorage close`,()=>E8.close()],[`watcherRegistry close`,()=>y8.closeAll()],[`sessionState flush`,()=>D8.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}gs(At(),t.pid),K8!==null&&Ps(K8,t.pid,js,e=>p.unlinkSync(e)),t.exit(e)}function s5(e){let t=performance.now();i5++,m8.inFlight=i5;let n=!1,r=!0,i=()=>{r&&(r=!1,i5=Math.max(0,i5-1),m8.inFlight=i5)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>o5(r);try{e.end(tn(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,m8.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,c5)},200),c=rn(e=>{h5(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${E(e)}`),a(f5(e),null,c5)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,c5)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=v3(e),o=L8.subscribe(t,{lane:r,frame:(e,t)=>a(nn(kW[r](e,t))),refused:t=>e.end(tn(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const c5=()=>{},l5=e=>({resp:e,exitAfterFlush:null,delivered:c5}),u5=e=>({kind:`reply`,...e}),d5={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},f5=e=>({ok:!1,error:e instanceof Error?e.message:E(e),code:`RENDER_FAILED`,daemonV:3}),p5=(e,t)=>u5(l5({ok:!1,error:t,code:e,daemonV:3}));function m5(e){let t=AW(e.sessionId);if(!t.ok)return p5(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return p5(`VERSION_MISMATCH`,`this client's subscribe names no lane (${zv.join(`, `)}): it predates the lane toggles — update it`);let n=Kv(e.lane);return n===null?p5(`BAD_REQUEST`,`subscribe needs a lane, one of ${zv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function h5(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?p5(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?m5(e):typeof e.kind!=`string`||!Object.hasOwn(d5,e.kind)?p5(`BAD_REQUEST`,`unknown kind`):u5(await g5(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:c5})}async function g5(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:c5};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return l5(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:L8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return l5({ok:!0,stats:m8.snapshot({gitCache:S8.getStats(),usageCache:C8.getStats(),sources:Y8(),runs:N8.stats(),transcriptReads:Va(),renderCache:V8.stats,effectCache:A8.getStats(),menuIdle:j8.getStats(),sessionState:{sessions:D8.size(),observers:D8.observers(),revision:D8.latestRevision()},frameFeeds:L8.getStats(),tmuxStatus:I8.stats(),watchersActive:y8.size(),nextRestartReason:t5().describeNextRestart(),handlerProbes:h8.list(),clients:g8.list(pk(new Date)),bundle:_8,daemon:t5().serving(),doctorStores:p0(v8)})});if(e.kind===`render`){let r=new Date,i=pk(r),a=performance.now(),o=Math.round(a-n),s=[],c=++m8.requestsTotal,l=j5(e),u=(e,t)=>g8.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Qa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:EM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),L8.note(l.req.sessionId,l.req,c));let d=l.ok?await V5(l.req,c,i,(e=>{let t=l8(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?c5:()=>rs(D8,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:f5(e),delivered:c5})):M5(l.problems);d.outcome.kind!==`ok`&&m8.requestsErrored++,u8(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=p8(`render`,s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`){let r=performance.now(),i=[[`queued`,`${Math.round(r-n)}ms`]],a=S5(e,i);u8(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=p8(`click`,i,a,Math.round(performance.now()-r));return M(o,s),l5(T5(a))}if(e.kind===`debug`){if(!c3(e.what))return l5({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${s3.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=V8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?x5(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??Sy(`colorCompatibility`)):b5};return l5({ok:!0,debug:X4(e.what,n)})}throw Error(`no reply for request ${E(e)}`)}function _5(e,t){let{tokens:n}=se({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:rV(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const v5={sessionState:D8,dlog:M,applyUpdate:()=>W8.act(),doctor:C0(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];V8.reload(...t);let n=V8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:v8,probes:h8,clients:g8,bundle:_8,serving:()=>t5().serving(),claudeInput:O2(),history:O8,navigation:k8,configFor:e=>V8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>V8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>V8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:M8,runs:N8,lanes:{of:A5,clicked:W5},views:{follow:(e,t)=>V8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};v5.reloadConfig;const y5={endcaps:Sy(`endcaps`),colorCompatibility:Sy(`colorCompatibility`),wrap:Sy(`autoWrap`),padding:Sy(`padding`),width:1/0},b5=new Map;function x5(e,t){let n=new Map;for(let[r,i]of e)n.set(r,_b(i,{...y5,colorCompatibility:t}));return n}function S5(e,t){let{verb:n,value:r}=e;if(typeof n!=`string`||typeof r!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof n} and ${typeof r}`]};try{return w5(n,r,{via:`link`,handler:$t(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const C5={link:`verb`,"tmux-status":`linkVerb`};function w5(e,t,n,r){if(e===`tmux-status-click`)return u8(r,{verb:e}),E5(t,r);let i=V4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};u8(r,{[C5[n.via]]:e});let a=L4(e,t);return a===null?u8(r,{sid:`-`}):a.ok&&(u8(r,{sid:a.id}),j8.clicked(a.id,pk(new Date))),i(t,{...v5,arrival:n}),{kind:`ok`}}function T5(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:return f5(e.error)}}function E5(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=I8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(u8(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=Pb(()=>Ho(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):w5(e.verb,e.value,{via:`tmux-status`},n)}return j2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function D5(e,t){let n=new Date,r=pk(n),i=[];try{try{var a=Na();let n=a.u(F5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=L5(n,{by:`feed`,fps:t}),u=B8.linkFor(e,z5(o)),d=R5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:K5(e,o,u,d,r8(l,L8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=p8(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=f5(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function O5(e,t){return $H(t.config,t=>D8.get(e,t),e=>t.authoredRoots.has(e))}function k5(e){try{var t=Na();let n=t.u(V8.holdView(e));return n===null?null:XH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function A5(e,t){try{var n=Na();return XH(O5(t,n.u(V8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function j5(e){let{report:t}=K4(e.hookData),n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=AW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=c8(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};for(let e of t.unknownTopLevelFields)m8.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Wt(e),{configFile:o,refusedArgs:s}=_5(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:TM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const M5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:c5});function N5(e,t,n){u8(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Gt(e,r),a=k(i);return u8(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function P5(e,t,n){let r=e.sessionId,i=N5(e,t,n),a=K2(e.requested,D8,r);return I5(V8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function F5(e,t,n){let r=V8.holdView(e);if(r===null){let t=V8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=N5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return I5(r,i,a,t,n)}function I5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...x8,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function L5(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=XH(u);u8(i,{lanes:zv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=tJ(f),m=vb(f.termRows);u8(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:L8.feedsOf(a,r),today:_J(x8,c.lanes().today,c.facts().hookData,r)},_=Ma(h.metrics)?void 0:h.metrics;u8(i,fJ(c.lanes().sources)),u8(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:zq(h.git,Zq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:f3(g.feeds)});let v=[],y=Iq(u,p),b=A8.of(a),ee=j8.since(a,r),x=BZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});j8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=j8.since(a,r);u8(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=as(D8,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[qt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
497
- `),ae=W8.notice({sessionId:a,dismissed:D8.get(a,VU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],T=Nq(o.repos,a,M8),oe=Tb(ie,[...ae,...T],w.map(e=>e.message).join(`
498
- `)),E=S8.getStats(),se=C8.getStats(),ce=b.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=w.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return u8(i,{git:`${E.size}/${E.hits}h/${E.misses}m`,usage:`${se.size}/${se.hits}h/${se.misses}m`,effect:ce.effect,effectT:ce.t.toFixed(3),speed:`${ce.speed}x`,effectRows:`${ce.made}made/${ce.reused}reused`,effectOwn:le,fadeBasis:ce.basis,stateRev:String(ce.revision),fades:ue(ce.fades),leaves:ue(ce.leaves),motion:x.motion,evaluated:String(x.evaluated),pending:x.pending.join(`,`)||`-`,rules:[...x.rules].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ie?`Y`:`N`,clickError:te.kind===`none`?`-`:te.kind,upd:String(ae.length),ask:String(T.length),warn:de}),{drawn:{body:x.text,diagnostics:oe,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function R5(e,t){return Ob(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
499
- `}function z5(e){return e.diagnostics===null?null:Db(e.diagnostics)}function B5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);D8.get(t,`client-hints`)!==i&&D8.set(t,x4,i);let a=q2(e.requested);D8.get(t,`render-origin`)!==a&&D8.set(t,G2,a)}async function V5(e,t,n,r,i){return B5(e),G5(e,t,n,r,i)}function H5(e,t){F8.noted(U5(e),t),I8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function U5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:K2(e.requested,D8,t),transcript:e.hookData.transcript_path,answered:CM(e.hookData)}}function W5(e,t,n){let r=L8.latest(e);F8.clicked(e,r===null?null:U5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&I8.observe(e,r.hints.tmux,n.tmuxStatus)}async function G5(e,t,n,r,i){try{var a=Na();let o=a.u(P5(e,n,i));H5(e,XH(o.view.source.effective())),u8(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await jG(e=>Promise.all([vJ(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${E(e)}`)),u=performance.now();u8(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:rJ(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=L5(o,Bv),{link:h,failure:g}=B8.sync(e.sessionId,t,z5(d));u8(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=R5(d,h),v=e.sessionId,y=r8(m,L8.following(v)),b=K5(v,d,h,_,y),ee=kM(e.hints.client??null)===`statusline`;return u8(i,{handoff:(ee?y:[]).join(`,`)||`-`,drew:`${Math.round(performance.now()-u)}ms`}),{answer:ee?b:_,motion:f,clickShown:p}}catch(e){a.e=e}finally{a.d()}}function K5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:R5({...t,body:kb(i8(e,[a,...o]),t.geometry)},n)}const q5={connectMs:200,budgetMs:500};async function J5(e,t){return Y5(e,await X5(e),t.includes(`--json`))}function Y5(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
500
- `:Z5(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${pn(t)}\n`,code:1}}function X5(e){return sn(()=>({kind:`debug`,what:e}),q5,e=>`debug`in e?e.debug:void 0)}function Z5(e){switch(e.what){case`vars`:return Q5(e.vars);case`segments`:return $5(e.segments);case`config`:return e7(e.config);default:return e}}function Q5(e){if(e.length===0)return`no variables (DSL not active)
501
- `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${n7(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${t7(a.value)}${e}${o}`)}return t.join(`
492
+ `)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var T3=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: ${E(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:C3(t.stdout,S3(n.stdout)),status:w3(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),!E3(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 E3(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 D3=`@cc-candybar-status-prior`,O3=`@cc-candybar-status-wrote`,k3=`@cc-candybar-binding-prior`,A3=[`-T`,`root`,`MouseDown1Status`],j3=Array.from({length:5},(e,t)=>t),M3=e=>`@cc-candybar-row-${e}`,N3=e=>`#[fill=terminal]#{${M3(e)}}`,P3=e=>`status-format[${e}]`;function F3(e){return e===0?`off`:e===1?`on`:String(e)}function I3(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 L3(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 R3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function z3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function B3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function V3(e){return e.map(e=>e.map(B3).join(` `)).join(` ; `)}const H3=`ccb:separator`;function U3(e){return z3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,H3],e]))}function W3(e,t){let n=e.split(`${H3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const G3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],K3=e=>[`show-options`,`-g`,`-q`,`-v`,e],q3=e=>[[`show-options`,`-t`,e],G3(e,`status`),...j3.map(t=>G3(e,P3(t)))];function J3(e){let[t=``,n=``,...r]=e,i=t.split(`
493
+ `).map(e=>e.split(` `)[0]??``),a={};for(let e of j3)i.includes(P3(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 Y3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,P3(Number(t)),R3(n)])]}const X3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...q3(e),...j3.map(e=>K3(P3(e))),G3(e,D3),G3(e,O3)];function Z3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:I3(t)}catch(e){return{kind:`theirs`,why:`${D3} 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 Q3(e,t,n){let[r=``,...i]=t,a=J3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return Z3(s,c,n);let l=I3(r),u={};for(let e=0;e<l;e++){let t=a.formats===null?o[e]:a.formats[e];t!==void 0&&t!==``&&(u[e]=t)}let d={...u,...Object.fromEntries(Array.from({length:5-l},(e,t)=>[l+t,N3(t)]))},f={owner:n,base:l,status:a.status,formats:a.formats,wrote:d};return{kind:`lay-out`,prior:f,commands:[[`set-option`,`-t`,e,D3,JSON.stringify(f)],...Y3(e,d)]}}const $3=e=>[...q3(e),G3(e,O3)];function e6(e,t,n){let r=J3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(L3(r.formats,t.wrote))a.push(...Y3(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,P3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,R3(t.status)]):o.push(`status`)),a.push(...j3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,M3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,D3],[`set-option`,`-q`,`-u`,`-t`,e,O3]),{commands:a,kept:o}}const t6=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,n6=[[`list-keys`,`-T`,`root`]];function r6(e){let t=t6.exec(e);return t===null?null:{line:t[0],command:t[1]}}const i6=`cc-candybar://tmux-status-click/`,a6=e=>`${i6}${pi([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,o6=e=>e?.command.includes(i6)??!1;function s6(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,k3]};return o6(r6(t))?{steps:[e===null?{command:[`unbind-key`,...A3]}:{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 c6=class{held=new Map;servers=new Map;closed=!1;writes=0;failedWrites=0;constructor(e){this.deps=e}observe(e,t,n){if(this.closed)return;let r=this.held.get(e),i=n&&t!=null?t:null;if(r!==void 0&&(i===null||r.socket!==i.socket||r.pane!==i.pane)&&this.release(r,`switched off or moved`),i===null||this.held.has(e))return;let a={sessionId:e,socket:i.socket,pane:i.pane,unsubscribe:null,frame:null};this.held.set(e,a),this.serverOf(i.socket),this.deps.log(`info`,`tmux-status: holding sid=${JSON.stringify(e)} pane=${i.pane} socket=${JSON.stringify(i.socket)}`),a.unsubscribe=this.deps.subscribe(e,{lane:`tmuxStatus`,frame:e=>{a.frame=OW(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,$3(n));if(i===null)continue;let a=e6(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,n6);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let t=l6(e),[n,r,i,...a]=t??[];if(t===null||n===void 0||r===void 0||i===void 0||a.length>0)return{kind:`refused`,reason:`tmux-status-click needs <socket>/<pane>/<range>, got ${JSON.stringify(e)}`};let o=[...this.held.values()].find(e=>e.socket===n&&e.pane===`%${r}`)?.frame?.links[i];return o===void 0?{kind:`refused`,reason:`pane %${r}'s status line draws no link ${i} now`}:{kind:`link`,url:o}}stats(){return{sessions:this.held.size,layouts:[...this.servers.values()].reduce((e,t)=>e+t.layouts.size,0),writes:this.writes,failedWrites:this.failedWrites}}async settled(){for(let e of this.servers.values())await e.running}serverOf(e){let t=this.servers.get(e);if(t!==void 0)return t;let n={view:null,adopted:!1,layouts:new Map,left:new Map,binding:{kind:`none`},running:null,again:!1,lastFailure:null};return this.servers.set(e,n),n}release(e,t){e.unsubscribe?.(),this.held.delete(e.sessionId),this.deps.log(`info`,`tmux-status: released sid=${JSON.stringify(e.sessionId)} pane=${e.pane} — ${t}`),this.reconcile(e.socket)}reconcile(e){let t=this.servers.get(e);if(!(t===void 0||this.closed)){if(t.running!==null){t.again=!0;return}t.running=(async()=>{try{do t.again=!1,await this.step(e,t);while(t.again&&!this.closed)}catch(t){this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} reconcile threw: ${String(t)}`)}finally{t.running=null}})()}}async step(e,t){let n=t.view;if(n===null)return;t.adopted||(t.adopted=!0,await this.adopt(e,t));let r=new Map;for(let t of this.held.values()){if(t.socket!==e)continue;let i=n.sessionOf.get(t.pane);i!==void 0&&r.set(i,[...r.get(i)??[],t])}for(let i of new Set([...t.layouts.keys(),...t.left.keys(),...r.keys()])){if(this.closed)return;let a=r.get(i)??[],o=t.layouts.get(i);if(a.length===0){t.left.delete(i),o!==void 0&&await this.restore(e,t,i);continue}if(t.left.has(i))continue;let s=o??await this.install(e,t,i);if(s===null)continue;let c=a.find(e=>e.pane===n.shownBy.get(i))?.frame?.rows.slice(0,5-s.prior.base)??[];await this.draw(e,i,s,c)}this.closed||(t.layouts.size>0?await this.installBinding(e,t):await this.restoreBinding(e,t))}async adopt(e,t){let n=await this.run(e,[`list-sessions`,`-F`,`#{session_id}\t#{${D3}}\t#{${O3}}`]);if(n.kind===`ok`)for(let r of n.stdout.split(`
494
+ `)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=Z3(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,[K3(`@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)} ${k3} does not read (${String(t)}), left as it is`)}(t.layouts.size>0||t.binding.kind===`adopted`)&&this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} took over layouts=${[...t.layouts.keys()].join(`,`)||`-`} binding=${t.binding.kind}`)}leave(e,t,n,r){t.left.set(n,r),this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} session ${n} left as it is: ${r}`)}async install(e,t,n){let r=await this.ask(e,X3(n));if(r===null||this.closed)return null;let i=Q3(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,M3(r),e])}),i!==n.status){let e=F3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,O3,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,V3(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,$3(n));if(i===null)return;let a=e6(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,n6);if(r===null||this.closed)return;let i=r6(r[0]??``);if(n.kind===`none`&&o6(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`&&o6(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...A3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${B3(`${this.deps.handler} ${a6(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,n6);if(r===null)return;let i=s6(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=s6(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,U3(t));return n.kind===`ok`?W3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,U3(t)));return n.kind===`ok`?W3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,z3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,z3(t),n)))}};function l6(e){try{return mi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const u6=`CC_CANDYBAR_CONFIG`;function d6(e,t){return rV(t,e[u6])}function f6(e,t,n){return rV(n,e)??d6(t,n)}const $=e=>({arity:e,keep:!0}),p6=e=>({arity:e,keep:!1}),m6={"--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":p6(`none`),"--background":p6(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":p6(`optional`),"-c":p6(`none`),"--continue":p6(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":p6(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":p6(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":p6(`none`),"--forward-subagent-text":$(`none`),"--from-pr":p6(`optional`),"-h":p6(`none`),"--help":p6(`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":p6(`none`),"--print":p6(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":p6(`optional`),"--resume":p6(`optional`),"--safe-mode":$(`none`),"--session-id":p6(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":p6(`optional`),"--tmux":p6(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":p6(`none`),"--version":p6(`none`),"-w":p6(`optional`),"--worktree":p6(`optional`)},h6={resume:`--resume`,fresh:`--session-id`};function g6(e){return[h6[e.kind],e.sessionId]}const _6=e=>e.startsWith(`-`)&&e!==`-`;function v6(e,t){let n=x6(t);return n===null?{dir:e??t,args:[]}:e!==null&&y6(e,n.top)?{dir:e,args:[]}:{dir:e===null||x6(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const y6=(e,t)=>e===t||e.startsWith(t+s.sep);function b6(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!_6(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=m6[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=>!_6(e)):o.arity===`variadic`?S6(n.slice(r),e=>!_6(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 x6(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 S6(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const C6=`candybar-band@cc-candybar`,w6=s.join(`bin`,`cc-candybar-native`),T6=`@cc-candybar-bar-pane`,E6=_P(`/reload-plugins`),D6=e=>({kind:`done`,said:e});function O6(e){let t=C2(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const k6={band:{on:(e,t,n)=>{let r=$e(t.bundle);if(r===null)throw new q(`${Rv.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,w6);if(!n.fileExists(i))throw new q(`the band mod starts ${i}, which is not built — run \`just install-rust\` in ${r}`);return{kind:`underway`,said:`installing ${C6} from ${r}`,finished:A6(e,r,n)}},off:()=>D6(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=O6(e),i=ze(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Rv.statusline.label} restarts Claude Code under the attach launcher, and ${a} is not there — run \`cc-candybar install\` (in a checkout, \`pnpm build\`)`);return{kind:`underway`,said:`restarting Claude Code in ${r.pane} under the attach launcher`,finished:N6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>D6(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=O6(e),i=n.barPanes(r);return i.length>0?D6(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):D6(`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=C2(e.hints.tmux);if(r.kind===`refused`)return D6(`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 D6(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>D6(`the daemon draws ${O6(e).pane}'s bar in its status line`),off:()=>D6(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function A6(e,t,n){let r={sessionId:e.sessionId,projectDir:e.origin.projectDir,claudeConfigDir:e.hints.claudeConfigDir};await n.claude([`plugin`,`marketplace`,`add`,t],r),await n.claude([`plugin`,`install`,C6],r);let i=w2(n.claudeInput,e.hints.tmux,E6);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 ${C6} from ${t} and typed /reload-plugins into ${i.pane}`}const j6=new Set([Xa,u6]);function M6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function N6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,Be(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}) — ${Rv.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=R6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Rv.statusline.label} off and on again`);let s=P6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=b6(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=M6(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])=>j6.has(e)),m=(e,t)=>Ue(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...g6(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=F6(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(v6(null,i.cwd),_))}let y=m(v6(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}\`, ${I6[g.kind](e.sessionId)}, and its statusline follows lane B`}function P6(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 F6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const I6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},L6={"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 R6(e){let t=v2(e);return t.kind===`ready`?x2(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:y2(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:L6[t.kind]}var z6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=zv.filter(e=>n[e]!==r[e]),a=this.take(e);for(let e of i)a.has(e)||a.set(e,n[e]);let o=e=>i.includes(e)?`click`:`owed`;if(t!==null){this.settle(t,a,r,o);return}for(let[e,t]of a)t===r[e]&&a.delete(e);if(i.length>0){let t=[...a.keys()].map(e=>`${e} ${r[e]?`on`:`off`}`);this.deps.log(`info`,`lane: owed ${t.join(`,`)||`nothing`} (session=${e})`)}a.size>0&&this.owed.set(e,a);for(let[e,t]of this.owed){if(this.owed.size<=1024)break;this.owed.delete(e),this.deps.log(`warn`,`lane: owed dropped sid=${JSON.stringify(e)} lanes=${[...t.keys()].join(`,`)}`)}}noted(e,t){this.settle(e,this.take(e.sessionId),t,()=>`owed`)}take(e){let t=this.owed.get(e)??new Map;return this.owed.delete(e),t}settle(e,t,n,r){for(let[i,a]of t)n[i]===a?this.deps.log(`info`,`lane: ${i} ${a?`on`:`off`} — nothing owed: its switch is back where the lane is by=${r(i)} (session=${e.sessionId})`):this.start(e,i,n[i],r(i))}start(e,t,n,r){this.deps.defer(()=>this.enqueue(e.sessionId,()=>this.sync(e,t,n,r)))}enqueue(e,t){let n=this.queued.get(e);if(n!==void 0){n.push(t);return}let r=[];this.queued.set(e,r);let i=t=>void t().then(()=>{let t=r.shift();t===void 0?this.queued.delete(e):i(t)});i(t)}sync(e,t,n,r){let i=`by=${r} (session=${e.sessionId})`,a=r=>{let a=`lane: ${t} ${n?`on`:`off`}: ${r instanceof Error?r.message:String(r)}`;this.deps.log(`warn`,`${a} ${i}`),ns(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=k6[t][n?`on`:`off`](e,this.deps.host,this.deps.edge)}catch(e){return a(e),Promise.resolve()}return this.deps.log(`info`,`lane: ${t} ${n?`on`:`off`} — ${o.said} ${i}`),o.kind===`underway`?o.finished.then(e=>this.deps.log(`info`,`lane: ${t} ${e} ${i}`),a):Promise.resolve()}};function B6(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 V6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function H6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function U6(e,t,n){let r=B6(`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 W6=2e3;function G6(e,t,n){let r=nq(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function K6(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 q6(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 J6=`#{pane_id} #{${T6}}`;function Y6(e,t){return e.split(`
495
+ `).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const X6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function Z6(e,t,n){for(let r of h1(m1(e),t)){if(r.command.split(` `).some(e=>X6.test(e)))return!0;if(r.pid===n)return!1}return!1}const Q6=[`import ctypes, json, struct, sys`,`libc = ctypes.CDLL(None)`,`mib = (ctypes.c_int * 3)(1, 49, int(sys.argv[1]))`,`size = ctypes.c_size_t(0)`,`if libc.sysctl(mib, 3, None, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`buf = ctypes.create_string_buffer(size.value)`,`if libc.sysctl(mib, 3, buf, ctypes.byref(size), None, 0) != 0: sys.exit('sysctl KERN_PROCARGS2 refused')`,`raw = buf.raw[:size.value]`,`argc = struct.unpack_from('i', raw)[0]`,`rest = raw[4:]`,`end = rest.index(b'\\0')`,`exe = rest[:end].decode('utf-8', 'surrogateescape')`,`rest = rest[end:].lstrip(b'\\0')`,`words = [w.decode('utf-8', 'surrogateescape') for w in rest.split(b'\\0')]`,`end = words.index('', argc) if '' in words[argc:] else len(words)`,`print(json.dumps({'executable': exe, 'argv': words[:argc], 'env': words[argc:end]}))`].join(`
496
+ `);async function $6(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=K6(`reading process ${e}'s arguments`,await mt({bin:`python3`,args:[`-c`,Q6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function e8(e,t){return K6(e,await mt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function t8(e){let t=await rq(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 e8(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function n8(e){let{panePid:t,cwd:n,foreground:r}=await t8(e),i=await e8(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await $6(r),o=m1(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:Z6(i,r,t)}}function r8(e){return{claudeInput:k2(),barPanes:e=>Y6(G6(e,[`list-panes`,`-a`,`-F`,J6]),e.pane),openBarPane:(e,t,n)=>{let r=G6(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 G6(e,[`set-option`,`-p`,`-t`,r,T6,e.pane]),r},closePane:(e,t)=>void G6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void K6(`claude ${e.join(` `)}`,await mt({bin:`claude`,args:[...e],env:t1(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:YV,paneClaude:n8,paneDir:async(e,t)=>{let n=Date.now()+W6;for(;;){let r=await t8(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 ${W6/1e3} s`);await ye(100)}},launcherNode:e=>U6(e,e=>V6(e,p.constants.X_OK),H6),onPath:(e,t)=>{let n=B6(e,t,e=>V6(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 ye(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await mt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?q6(r.stdout):null;return i===null?(K6(`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(;Ds(e);){if(Date.now()>n)return!1;await ye(100)}return!0},typeShellLine:(e,t)=>void G6(e,D2(e.pane,`cc-candybar-lane`,[]),t)}}function i8(e,t){return zv.filter(n=>e[n]&&Rv[n].elsewhere!==null&&t.has(n))}function a8(e,t){let n=`the bar is drawn in ${t.map(e=>Rv[e].elsewhere).join(` and `)}`,r=gi([{verb:ei,args:[e,...t.map(e=>Rv[e].setting)]}]);return{channels:[{severity:Cb,message:n,lines:[[wb(n,gi([{verb:Hr,args:[n]}])),wb(`[⟲ draw it here]`,r)]]}]}}const o8={order:-1/0,text:null,failure:null};var s8=class{synced=new Map;constructor(e,t){this.dir=e,this.changed=t}pathFor(e){return s.join(this.dir,`${encodeURIComponent(e)}.txt`)}sync(e,t,n){let r=this.synced.get(e)??o8;if(t<r.order)return{link:this.linkFor(e,n),failure:null};let i=n===r.text&&r.failure===null?null:this.write(e,n);return this.synced.delete(e),this.synced.set(e,{order:t,text:n,failure:i}),this.forgetOldestClean(),(n!==r.text||i!==r.failure)&&this.changed(e),{link:this.linkFor(e,n),failure:i}}linkFor(e,t){let n=this.synced.get(e)??o8;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}`}}},c8=class{sessions=new Map;constructor(e){this.deps=e}clicked(e,t){this.record(e,t).since=t,this.settle(e)}since(e,t){let n=this.record(e,t);return n.shown?n.since:void 0}observe(e,t,n,r){let i=this.record(e,t);t<i.drawnAt||(i.drawnAt=t,n&&!i.shown&&t>i.since&&(i.since=t),i.shown=n,i.timeoutS=r,this.settle(e))}getStats(){let e=0;for(let t of this.sessions.values())t.timer!==null&&e++;return{sessions:this.sessions.size,armed:e}}dispose(){for(let e of this.sessions.values())this.disarm(e);this.sessions.clear()}record(e,t){let n=this.sessions.get(e)??{since:t,timeoutS:0,shown:!1,drawnAt:t,timer:null};this.sessions.delete(e),this.sessions.set(e,n);for(let[e,t]of this.sessions){if(this.sessions.size<=256)break;this.disarm(t),this.sessions.delete(e)}return n}settle(e){let t=this.sessions.get(e),n=t.shown?Zv(t.since,t.timeoutS):null;if(t.timer?.at===n||(this.disarm(t),n===null))return;let r=setTimeout(()=>this.fire(e),Math.max(0,(n-this.deps.now())*1e3));r.unref(),t.timer={at:n,handle:r}}disarm(e){e.timer!==null&&clearTimeout(e.timer.handle),e.timer=null}fire(e){let t=this.sessions.get(e);t.timer=null;let n=this.deps.now(),r={idleS:n-t.since,timeoutS:t.timeoutS};t.since=n,t.shown=!1;try{this.deps.close(e,r)}catch(t){this.deps.failed(e,t)}}};function l8(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function u8(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function d8(e,t){for(let n of Object.entries(t))e.push(n)}const f8={ok:`info`,"bad-request":`warn`,threw:`error`};function p8(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,E(e.error)]]}}function m8(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...p8(n)];return{level:f8[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${cs(t)}`).join(``)}`}}const h8=new uQ,g8=new i2,_8=new AM,v8=i(import.meta.url),y8=p0(St());ft(h8.launchStats);const b8=new hG({counters:h8,logger:M}),x8=new Bk(M),S8=Dq({watchers:b8,logger:M,ledger:x8}),{gitProvider:C8,usageStore:w8,tmuxService:T8,hostService:E8,managedStorage:D8}=S8,O8=new pQ,k8=new S$(O8,M),A8=new G$,j8=new ib,M8=new c8({now:()=>pk(new Date),close:(e,t)=>U4(e,t,y5),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${E(t)}`)}),N8=Qo(),P8=new fs({supersede:(e,t)=>D8.supersede(e,t),launch:mt,state:O8,log:M,now:()=>pk(new Date)}),F8=[t.execPath,...t.execArgv],I8=new z6({edge:r8(e=>R8.following(e)),host:{bundle:v8,node:F8,socket:Tt(),preload:Ao(v8)},state:O8,log:M,now:()=>pk(new Date),defer:e=>void ge(e)}),L8=new c6({edge:{run:(e,t,n)=>rq({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>nq({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>R8.subscribe(e,t),sessionInPane:(e,t)=>R8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Ie(Tt())}`,...[...F8,v8].map(Ie),`url-handle`].join(` `),owner:Tt(),log:M}),R8=new v3({render:(e,t)=>O5(e,t),watch:(e,t)=>(0,J.reaction)(()=>O8.revision(e),t),lanes:e=>A5(e),pin:e=>H8.pin(e),shown:e=>z8.shown(e.hints.tmux),watching:()=>z8.follow(),refreshes:()=>x8.totals(),periods:d3,now:()=>performance.now(),log:M}),z8=new T3({listPanes:e=>rq({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,b3]),listClients:e=>rq({socket:e},`frames.visibility`,[`list-clients`,`-F`,x3]),sockets:()=>new Set(R8.watched().flatMap(({req:e})=>B8(e))),onAnswer:(e,t)=>L8.answered(e,t),onChange:e=>R8.wakeWhere(`visibility`,t=>B8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function B8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const V8=new s8(Lt(),e=>R8.wake(e,`data`)),H8=new cQ({sessionState:O8,watchers:b8,log:M,storage:D8,signer:N8,ledger:x8,declare:(e,t,n,r)=>lJ(S8,e,t,n,r),source:u3({providers:S8,sessionState:O8,history:e=>k8.depth(e),navigation:(e,t)=>A8.depth(e,O8,FU(t))})},{budgetBytes:()=>(n5(),KZ(J8)),observers:{onReload:(e,t)=>{M(`info`,YZ(e));for(let e of t)R8.wake(e,`reload`)},onViewChanged:e=>R8.wake(e,`data`)}}),U8=60*1e3,W8=oW({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:U8,stat:p.statSync,exit:()=>s5(0),log:M}),G8=rW({entryUrl:import.meta.url,intervalMs:U8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>W8.checkNow(),log:M});let K8=null,q8=null,J8=0;function Y8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),s5(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),s5(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),s5(0)});try{r5(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),s5(1);return}K8=Cs(t.pid);let e=Ns(Fs(K8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),s5(1);return}q8=e.registryPath,p.mkdirSync(wt(),{recursive:!0}),Ot(Tt()),O8.useStorage(new hQ(jt(),500,M)),k8.useStorage(U$(Mt(),M)),Es({anchor:Ts(t.env),isAlive:Ds,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),s5(0)}}),Z8(le.createServer({allowHalfOpen:!1},e=>{c5(e)}),Tt(),!1)}function X8(){let e=C8.getStats(),t=T8.getStats(),n=w8.scanStats(),r=D8.stats(),i=H8.stats;return{records:x8.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:w8.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:E8.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost,probes:r.probes,probeFailures:r.probeFailures,stalled:r.stalled,stalls:r.stalls}}}function Z8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),s5(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}Q8(e,n)}),e.listen(n,()=>$8(n))}function Q8(e,n){let r=ps(ms(kt(n)),(e,t)=>Ss(e,t,{readStartTime:xs,pidAlive:Ds}));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}`),s5(1);return}}Z8(e,n,!0)}function $8(e){let n=_s(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),s5(0);return}i5(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=${N(ue.getHeapStatistics().heap_size_limit)}MB memoryLimit=${N(J8)}MB`),Dr();let r=V8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),W8.arm(),G8.arm(),n5().arm(),e5(e,n.identity)}function e5(e,n){bs({bound:n,myPid:t.pid,readIdentity:()=>_s(e),readLease:()=>ms(kt(e)),shutdown:e=>s5(e),log:M}).arm()}let t5=null;function n5(){if(t5===null)throw Error(`daemon: limits not yet established`);return t5}function r5(e){J8=ir(e),t5=fr(vr(h8.startedAt.getTime(),e=>s5(e),{limitBytes:J8}))}function i5(e){let n=hs(kt(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:K8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let a5=0,o5=!1;function s5(e){if(o5)return;o5=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>L8.restoreAll()],[`gitService close`,()=>C8.close()],[`usageStore close`,()=>w8.close()],[`tmuxService close`,()=>T8.close()],[`hostService close`,()=>E8.close()],[`runs close`,()=>P8.close()],[`managedStorage close`,()=>D8.close()],[`watcherRegistry close`,()=>b8.closeAll()],[`sessionState flush`,()=>O8.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}gs(At(),t.pid),q8!==null&&Ps(q8,t.pid,js,e=>p.unlinkSync(e)),t.exit(e)}function c5(e){let t=performance.now();a5++,h8.inFlight=a5;let n=!1,r=!0,i=()=>{r&&(r=!1,a5=Math.max(0,a5-1),h8.inFlight=a5)},a=(t,r,i)=>{if(n){r!==null&&M(`warn`,`exit-after-flush dropped: an earlier responder settled this socket`);return}n=!0;let a=r===null?void 0:()=>s5(r);try{e.end(tn(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,h8.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,l5)},200),c=rn(e=>{g5(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${E(e)}`),a(p5(e),null,l5)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,l5)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=y3(e),o=R8.subscribe(t,{lane:r,frame:(e,t)=>a(nn(kW[r](e,t))),refused:t=>e.end(tn(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const l5=()=>{},u5=e=>({resp:e,exitAfterFlush:null,delivered:l5}),d5=e=>({kind:`reply`,...e}),f5={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},p5=e=>({ok:!1,error:e instanceof Error?e.message:E(e),code:`RENDER_FAILED`,daemonV:3}),m5=(e,t)=>d5(u5({ok:!1,error:t,code:e,daemonV:3}));function h5(e){let t=AW(e.sessionId);if(!t.ok)return m5(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return m5(`VERSION_MISMATCH`,`this client's subscribe names no lane (${zv.join(`, `)}): it predates the lane toggles — update it`);let n=Kv(e.lane);return n===null?m5(`BAD_REQUEST`,`subscribe needs a lane, one of ${zv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function g5(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?m5(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?h5(e):typeof e.kind!=`string`||!Object.hasOwn(f5,e.kind)?m5(`BAD_REQUEST`,`unknown kind`):d5(await _5(e,t,n)):(e.v>3?M(`info`,`version mismatch: client=${e.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):M(`info`,`version mismatch: client=${e.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${e.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:e.v>3?0:null,delivered:l5})}async function _5(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:l5};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return u5(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:R8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return u5({ok:!0,stats:h8.snapshot({gitCache:C8.getStats(),usageCache:w8.getStats(),sources:X8(),runs:P8.stats(),transcriptReads:Va(),renderCache:H8.stats,effectCache:j8.getStats(),menuIdle:M8.getStats(),sessionState:{sessions:O8.size(),observers:O8.observers(),revision:O8.latestRevision()},frameFeeds:R8.getStats(),tmuxStatus:L8.stats(),watchersActive:b8.size(),nextRestartReason:n5().describeNextRestart(),handlerProbes:g8.list(),clients:_8.list(pk(new Date)),bundle:v8,daemon:n5().serving(),doctorStores:m0(y8)})});if(e.kind===`render`){let r=new Date,i=pk(r),a=performance.now(),o=Math.round(a-n),s=[],c=++h8.requestsTotal,l=M5(e),u=(e,t)=>_8.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Qa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:EM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),R8.note(l.req.sessionId,l.req,c));let d=l.ok?await H5(l.req,c,i,(e=>{let t=u8(e.deadline,n,{epochMs:r.getTime(),monoMs:a});return{stated:e.deadline.kind,ms:t,endsAt:a+t}})(l.req),s).then(({answer:e,motion:t,clickShown:n})=>(u(l.req,t),{outcome:{kind:`ok`},resp:{ok:!0,output:e},delivered:n===null?l5:()=>rs(O8,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:p5(e),delivered:l5})):N5(l.problems);d.outcome.kind!==`ok`&&h8.requestsErrored++,d8(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=m8(`render`,s,d.outcome,Math.round(performance.now()-a));return M(f,p),{resp:d.resp,exitAfterFlush:null,delivered:d.delivered}}if(e.kind===`click`){let r=performance.now(),i=[[`queued`,`${Math.round(r-n)}ms`]],a=C5(e,i);d8(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=m8(`click`,i,a,Math.round(performance.now()-r));return M(o,s),u5(E5(a))}if(e.kind===`debug`){if(!l3(e.what))return u5({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${c3.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=H8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?S5(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??Sy(`colorCompatibility`)):x5};return u5({ok:!0,debug:Z4(e.what,n)})}throw Error(`no reply for request ${E(e)}`)}function v5(e,t){let{tokens:n}=se({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:rV(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const y5={sessionState:O8,dlog:M,applyUpdate:()=>G8.act(),doctor:w0(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];H8.reload(...t);let n=H8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:y8,probes:g8,clients:_8,bundle:v8,serving:()=>n5().serving(),claudeInput:k2(),history:k8,navigation:A8,configFor:e=>H8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>H8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>H8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:N8,runs:P8,lanes:{of:j5,clicked:G5},views:{follow:(e,t)=>H8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};y5.reloadConfig;const b5={endcaps:Sy(`endcaps`),colorCompatibility:Sy(`colorCompatibility`),wrap:Sy(`autoWrap`),padding:Sy(`padding`),width:1/0},x5=new Map;function S5(e,t){let n=new Map;for(let[r,i]of e)n.set(r,_b(i,{...b5,colorCompatibility:t}));return n}function C5(e,t){let{verb:n,value:r}=e;if(typeof n!=`string`||typeof r!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof n} and ${typeof r}`]};try{return T5(n,r,{via:`link`,handler:$t(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const w5={link:`verb`,"tmux-status":`linkVerb`};function T5(e,t,n,r){if(e===`tmux-status-click`)return d8(r,{verb:e}),D5(t,r);let i=H4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};d8(r,{[w5[n.via]]:e});let a=R4(e,t);return a===null?d8(r,{sid:`-`}):a.ok&&(d8(r,{sid:a.id}),M8.clicked(a.id,pk(new Date))),i(t,{...y5,arrival:n}),{kind:`ok`}}function E5(e){switch(e.kind){case`ok`:return{ok:!0,output:``};case`bad-request`:return{ok:!1,error:e.problems.join(`; `),code:`BAD_REQUEST`,daemonV:3};case`threw`:return p5(e.error)}}function D5(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=L8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(d8(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=Pb(()=>Ho(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):T5(e.verb,e.value,{via:`tmux-status`},n)}return M2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function O5(e,t){let n=new Date,r=pk(n),i=[];try{try{var a=Na();let n=a.u(I5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=R5(n,{by:`feed`,fps:t}),u=V8.linkFor(e,B5(o)),d=z5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:q5(e,o,u,d,i8(l,R8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=m8(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=p5(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function k5(e,t){return $H(t.config,t=>O8.get(e,t),e=>t.authoredRoots.has(e))}function A5(e){try{var t=Na();let n=t.u(H8.holdView(e));return n===null?null:XH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function j5(e,t){try{var n=Na();return XH(k5(t,n.u(H8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function M5(e){let{report:t}=q4(e.hookData),n=[];for(let e of t.missingRequired)n.push(`missing required field '${e}'`);for(let{path:e,expected:r,got:i}of t.typeMismatches)n.push(`field '${e}' expected ${r}, got ${i}`);let r=AW(e.hookData?.session_id);r.ok||n.push(`field 'session_id' ${r.problem}`),(typeof e.cwd!=`string`||!u(e.cwd))&&n.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&n.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let i=l8(e.deadline);if(i.kind===`refused`)return{ok:!1,problems:[...n,i.problem]};if(n.length>0||!r.ok)return{ok:!1,problems:n};for(let e of t.unknownTopLevelFields)h8.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Wt(e),{configFile:o,refusedArgs:s}=v5(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:TM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const N5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:l5});function P5(e,t,n){d8(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Gt(e,r),a=k(i);return d8(n,{termCols:String(r.termCols??`?`),termRows:String(r.termRows??`?`),refused:i.map(e=>e.hint).join(`,`)||`-`,badArgs:e.refusedArgs.map(e=>`${e.arg}:${e.why}`).join(`,`)||`-`,client:r.client?.kind??`unreported`,rateLimits:e.rateLimits}),a}function F5(e,t,n){let r=e.sessionId,i=P5(e,t,n),a=q2(e.requested,O8,r);return L5(H8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function I5(e,t,n){let r=H8.holdView(e);if(r===null){let t=H8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=P5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return L5(r,i,a,t,n)}function L5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...S8,lanes:s.lanes},cwd:t.cwd,neededInputPaths:o.neededInputPaths(u.preset),hints:l},[Symbol.dispose]:()=>e[Symbol.dispose]()}}catch(t){throw e[Symbol.dispose](),t}}function R5(e,t){let{req:n,at:r,facts:i,sessionId:a,entry:o,state:s,view:c,hintsError:l}=e,u=c.source.effective(),d=XH(u);d8(i,{lanes:zv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=nJ(f),m=vb(f.termRows);d8(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:R8.feedsOf(a,r),today:vJ(S8,c.lanes().today,c.facts().hookData,r)},_=Ma(h.metrics)?void 0:h.metrics;d8(i,pJ(c.lanes().sources)),d8(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:Bq(h.git,Qq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:p3(g.feeds)});let v=[],y=Lq(u,p),b=j8.of(a),ee=M8.since(a,r),x=VZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});M8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=M8.since(a,r);d8(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=as(O8,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[qt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
497
+ `),ae=G8.notice({sessionId:a,dismissed:O8.get(a,VU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],T=Pq(o.repos,a,N8),oe=Tb(ie,[...ae,...T],w.map(e=>e.message).join(`
498
+ `)),E=C8.getStats(),se=w8.getStats(),ce=b.lastFrame(),le=ce.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,ue=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=w.map(e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`load`:case`band-floor`:case`when`:return e.kind}}).join(`,`)||`-`;return d8(i,{git:`${E.size}/${E.hits}h/${E.misses}m`,usage:`${se.size}/${se.hits}h/${se.misses}m`,effect:ce.effect,effectT:ce.t.toFixed(3),speed:`${ce.speed}x`,effectRows:`${ce.made}made/${ce.reused}reused`,effectOwn:le,fadeBasis:ce.basis,stateRev:String(ce.revision),fades:ue(ce.fades),leaves:ue(ce.leaves),motion:x.motion,evaluated:String(x.evaluated),pending:x.pending.join(`,`)||`-`,rules:[...x.rules].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:ie?`Y`:`N`,clickError:te.kind===`none`?`-`:te.kind,upd:String(ae.length),ask:String(T.length),warn:de}),{drawn:{body:x.text,diagnostics:oe,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function z5(e,t){return Ob(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
499
+ `}function B5(e){return e.diagnostics===null?null:Db(e.diagnostics)}function V5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);O8.get(t,`client-hints`)!==i&&O8.set(t,S4,i);let a=J2(e.requested);O8.get(t,`render-origin`)!==a&&O8.set(t,K2,a)}async function H5(e,t,n,r,i){return V5(e),K5(e,t,n,r,i)}function U5(e,t){I8.noted(W5(e),t),L8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function W5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:q2(e.requested,O8,t),transcript:e.hookData.transcript_path,answered:CM(e.hookData)}}function G5(e,t,n){let r=R8.latest(e);I8.clicked(e,r===null?null:W5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&L8.observe(e,r.hints.tmux,n.tmuxStatus)}async function K5(e,t,n,r,i){try{var a=Na();let o=a.u(F5(e,n,i));U5(e,XH(o.view.source.effective())),d8(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await jG(e=>Promise.all([yJ(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${E(e)}`)),u=performance.now();d8(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:iJ(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=R5(o,Bv),{link:h,failure:g}=V8.sync(e.sessionId,t,B5(d));d8(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=z5(d,h),v=e.sessionId,y=i8(m,R8.following(v)),b=q5(v,d,h,_,y),ee=kM(e.hints.client??null)===`statusline`;return d8(i,{handoff:(ee?y:[]).join(`,`)||`-`,drew:`${Math.round(performance.now()-u)}ms`}),{answer:ee?b:_,motion:f,clickShown:p}}catch(e){a.e=e}finally{a.d()}}function q5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:z5({...t,body:kb(a8(e,[a,...o]),t.geometry)},n)}const J5={connectMs:200,budgetMs:500};async function Y5(e,t){return X5(e,await Z5(e),t.includes(`--json`))}function X5(e,t,n){return t.kind===`ok`?{stdout:n?JSON.stringify(t.value,null,2)+`
500
+ `:Q5(t.value),stderr:``,code:0}:{stdout:``,stderr:`${e}: ${pn(t)}\n`,code:1}}function Z5(e){return sn(()=>({kind:`debug`,what:e}),J5,e=>`debug`in e?e.debug:void 0)}function Q5(e){switch(e.what){case`vars`:return $5(e.vars);case`segments`:return e7(e.segments);case`config`:return t7(e.config);default:return e}}function $5(e){if(e.length===0)return`no variables (DSL not active)
501
+ `;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${r7(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${n7(a.value)}${e}${o}`)}return t.join(`
502
502
  `)+`
503
- `}function $5(e){if(e.length===0)return`no segments (DSL not active)
503
+ `}function e7(e){if(e.length===0)return`no segments (DSL not active)
504
504
  `;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
505
505
  `)+`
506
- `}function e7(e){return e===null?`config: DSL not active
506
+ `}function t7(e){return e===null?`config: DSL not active
507
507
  `:JSON.stringify(e,null,2)+`
508
- `}function t7(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function n7(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function r7(){let e=a7();return e===null?null:p.readFileSync(e,`utf-8`)}function i7(){let e;try{e=r7()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function a7(){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 o7=5e3;function s7(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:TP(4e5,1e6),...Lq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Ny(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:Fq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:pJ(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>I)}}const c7={cost:12.5,tokens:34e5};function l7(e,t){let n=dH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function u7(e,n=t.cwd(),r=o7){let i=[],a=rV(n,e)??null,o=oH(jq().read(),n,n,a??void 0);i.push(...nH(o.repos));let s=a===null?l7(o,i):[a];if(a!==null){let e;try{e=p.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let c=pH(n,n);c!==null&&i.push(c);try{return{kind:`clean`,layers:s,warnings:i,rendered:await p7(s,o.repos.plugins,n,i,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&s.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof tv&&i.push(...e.warnings),{kind:`fatal`,layers:s,message:e instanceof tv||e instanceof Error?e.message:String(e),warnings:i})}}async function d7(e,t,n,r,i,a=o7){let o=xH(e,WH,{entered:()=>{},warned:e=>r.push(...e)},{repo:t,cwd:n}),{config:s}=o,c=new SS,l=new cA(c,s.globals.default_empty_value??``,new fQ);try{let t=SZ(s,l,{cwd:n,signer:Qo()});r.push(...t.loadWarnings);let u=$H(s,()=>null,()=>!1);ZX(t,c,l,_Z({...s7(s,u,e.at(-1)??null,i),today:c7},u));let d=await l.settled(a);return d.length>0&&r.push(`source${d.length===1?``:`s`} still running after ${a} ms, rendered with fallback values: ${d.join(`, `)}`),{layers:e,droppedPlugins:[...o.installed.dropped,...o.layers.flatMap(e=>e.plugins.dropped)],config:s,compiled:t,store:c,registry:l}}catch(e){throw l.dispose(),e}}function f7({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u=e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}};return{rendered:zZ(t,n,r,i,{...s7(t,a,e.at(-1)??null,s),today:c7},s,Iq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function p7(e,t,n,r,i){let a=pk(new Date),o=await d7(e,t,n,r,a,i),{config:s}=o;try{let e=nW();try{FU(s),rL(s)}finally{e()}let t=ax(null,s.globals.preset,s.presets),n=(e,t)=>{let n=$H(s,t=>t===`preset`?e:null,()=>t),r;try{r=f7(o,n,200,a)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},i=n(t,!1),c=[i,n(t,!0),...ix(s.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(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(`; `)})`)};r.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=i.rendered,f=o.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(`
508
+ `}function n7(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function r7(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function i7(){let e=o7();return e===null?null:p.readFileSync(e,`utf-8`)}function a7(){let e;try{e=i7()}catch(e){return{stdout:``,stderr:`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`,code:2}}return e===null?{stdout:``,stderr:"schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n",code:2}:{stdout:e,stderr:``,code:0}}function o7(){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 s7=5e3;function c7(e,t,n,r){let i=`/home/tester`,a=Math.floor(r),o=`test0a1b-2c3d-4e5f-6a7b-8c9d0e1f2a3b`,s={current_dir:`${i}/code/cc-candybar/src`,project_dir:`${i}/code/cc-candybar`,added_dirs:[]};return{hook_event_name:`Status`,session_id:o,version:`1.15.0`,home:i,cwd:`${i}/code/cc-candybar/src`,transcript_path:`${i}/.claude/projects/x/test.jsonl`,model:{id:`claude-opus-4-8`,display_name:`Opus 4.8`},effort:{level:`xhigh`},workspace:s,git:{repoName:`cc-candybar`,repoUrl:`https://github.com/promptctl/cc-candybar`,branch:`main`,sha:`abc1234`,ahead:2,behind:1,staged:3,unstaged:2,untracked:1,conflicts:0,upstream:`origin/main`,tracking:`tracked`,stash:1,status:`dirty`,operation:`rebase`,committedAt:a-780},session:{cost:.39,tokens:241400},context:{totalTokens:48487,contextLeft:24},metrics:{lastResponseTime:8.2,responseTime:4.2,sessionDuration:930,messageCount:8,linesAdded:512,linesRemoved:88},block:{nativeUtilization:63,resetsAt:a+2*3600},weekly:{percentage:21,resetsAt:a+5*86400},cache:{expiresAt:a+900},tmux:{pane:`%0`,session:`work`},host:{name:`tester-box`,user:`tester`,ssh:!0},autocompact:TP(4e5,1e6),...Rq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Ny(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:Iq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:mJ(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>I)}}const l7={cost:12.5,tokens:34e5};function u7(e,t){let n=dH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function d7(e,n=t.cwd(),r=s7){let i=[],a=rV(n,e)??null,o=oH(Mq().read(),n,n,a??void 0);i.push(...nH(o.repos));let s=a===null?u7(o,i):[a];if(a!==null){let e;try{e=p.statSync(a,{throwIfNoEntry:!1})}catch(e){return{kind:`unreadable`,path:a,message:e instanceof Error?e.message:String(e)}}if(e!==void 0&&!e.isFile())return{kind:`unreadable`,path:a,message:`not a file`}}let c=pH(n,n);c!==null&&i.push(c);try{return{kind:`clean`,layers:s,warnings:i,rendered:await m7(s,o.repos.plugins,n,i,r)}}catch(e){let t=e;return typeof t==`object`&&t&&typeof t.code==`string`&&typeof t.path==`string`&&s.includes(t.path)&&typeof t.message==`string`?{kind:`unreadable`,path:t.path,message:t.message}:(e instanceof tv&&i.push(...e.warnings),{kind:`fatal`,layers:s,message:e instanceof tv||e instanceof Error?e.message:String(e),warnings:i})}}async function f7(e,t,n,r,i,a=s7){let o=xH(e,WH,{entered:()=>{},warned:e=>r.push(...e)},{repo:t,cwd:n}),{config:s}=o,c=new SS,l=new cA(c,s.globals.default_empty_value??``,new pQ);try{let t=CZ(s,l,{cwd:n,signer:Qo()});r.push(...t.loadWarnings);let u=$H(s,()=>null,()=>!1);QX(t,c,l,vZ({...c7(s,u,e.at(-1)??null,i),today:l7},u));let d=await l.settled(a);return d.length>0&&r.push(`source${d.length===1?``:`s`} still running after ${a} ms, rendered with fallback values: ${d.join(`, `)}`),{layers:e,droppedPlugins:[...o.installed.dropped,...o.layers.flatMap(e=>e.plugins.dropped)],config:s,compiled:t,store:c,registry:l}}catch(e){throw l.dispose(),e}}function p7({layers:e,config:t,compiled:n,store:r,registry:i},a,o,s){let c=new Map,l=new Set,u=e=>{switch(e.kind){case`rule`:c.set(`${e.slot} rule`,e.message);return;case`when`:c.set(e.where,e.error);return;case`refresh`:c.set(`variable "${e.variable}"`,`cannot refresh: ${e.error}`);return;case`band-floor`:l.add(e.message);return;default:}};return{rendered:BZ(t,n,r,i,{...c7(t,a,e.at(-1)??null,s),today:l7},s,Lq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function m7(e,t,n,r,i){let a=pk(new Date),o=await f7(e,t,n,r,a,i),{config:s}=o;try{let e=nW();try{FU(s),rL(s)}finally{e()}let t=ax(null,s.globals.preset,s.presets),n=(e,t)=>{let n=$H(s,t=>t===`preset`?e:null,()=>t),r;try{r=p7(o,n,200,a)}catch(e){r={failures:new Map([[`render`,e instanceof Error?e.message:String(e)]]),advisories:new Set}}return{preset:e,customized:t,...r}},i=n(t,!1),c=[i,n(t,!0),...ix(s.presets).filter(e=>e!==t).flatMap(e=>[n(e,!1),n(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(`; `)})`)};r.push(...l(e=>e.advisories));let u=l(e=>[...e.failures].map(([e,t])=>`${e}: ${t}`)),d=i.rendered,f=o.droppedPlugins.length,p=[...f>0?[`${f} plugin${f===1?``:`s`} did not load (named in the warnings)`]:[],...u.length>0||d===void 0?[`config renders with ${u.length} render error${u.length===1?``:`s`} (the daemon would show them on the bar):\n`+u.map(e=>` ${e}`).join(`
509
509
  `)]:[]];if(p.length>0||d===void 0)throw Error(p.join(`
510
- `));return d}finally{o.registry.dispose()}}function m7(e){return e.map(e=>`warning: ${e}\n`).join(``)}function h7(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:m7(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:m7(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 g7=`--render`,_7=`Usage: cc-candybar check [${g7}] [config-file]\n`;function v7(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==g7);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${_7}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${_7}`}:{kind:`run`,target:n[0],render:t.includes(g7)}}async function y7(e){let n=v7(e),r=t.cwd();return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:h7(await u7(d6(n.target,t.env,r),r),n.render)}const b7=/^[a-z][a-z0-9+.-]*:\/\//i,x7=/^[^@\s/]+@[^:\s/]+:/,S7=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function C7(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function w7(e,t,n){let r=nV(t,e);if(n(r))return{kind:`path`,dir:r};if(b7.test(e)||x7.test(e))return{kind:`git`,url:e,shown:C7(e)};let i=S7.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 T7(e,t){let n=s.join(e,VV),r=WV(n);if(`error`in r)throw Error(`${t}: could not list ${VV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${VV}/<name>/${oV}`);return r.folders.map(e=>s.join(n,e,oV))}function E7(e,t,n){let r=(n,...r)=>{let i=ht({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
511
- `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${VV}/`)}function D7(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 E7(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function O7(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 k7(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,oV),s.join(t,oV));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function A7(e,t,n){let r=T7(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,oV))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=yH(a.map(e=>s.join(e,oV)),WH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(VV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,VV))}`).join(`
512
- `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:O7(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)k7(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,oV),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function j7(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=w7(n,process.cwd(),Qk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=D7(i,t=>A7(t,BV(),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 M7(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 N7=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function P7(e,t,n){return{termCols:M7(e.COLUMNS,n.columns),termRows:M7(e.LINES,n.rows),ssh:N7.some(t=>(e[t]??``)!==``),tmux:xM(e),configEnv:u6(e,t),claudeConfigDir:Za(e,t),terminalEnv:Bt(e)}}function F7(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function I7(e){let t=K0(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=F7(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:on(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 L7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},R7=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 z7(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 B7(e){let t=K0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=z7(n?.postMortems,e=>Array.isArray(e)&&e.every(L7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&R7(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 V7(e,t,n){let r=K0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=F7(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 H7=e=>OM.includes(e.role),U7=e=>V7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&wM.includes(e.rateLimits),`the rate-limit windows they carried`),W7=e=>V7(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`),G7=e=>V7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&H7(e)&&DM.includes(e.frame),`what they drew and from which project`),K7=e=>V7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&H7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function q7(e,t,n){let r=e.doctorStores?.[t],i=z7(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 J7(e){let t=K0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:q7(e,`marks`,n1),clicked:q7(e,`clicked`,a1),postMortemsRead:q7(e,`postMortemsRead`,s0)}}async function Y7(){let e=await G0();if(e.kind!==`ok`){let t={kind:`failed`,reason:pn(e).split(`
513
- `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:I7(e.value),rateLimits:U7(e.value),transcripts:W7(e.value),frames:G7(e.value),widths:K7(e.value),serving:B7(e.value),stores:J7(e.value)}}const X7=` (fix: click the settings menu (${Si} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,Z7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Si} by default) › 🧰 tools › 🩺 doctor`;function Q7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:X7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${Z7}\n`)}function $7(e){let t={sessionState:new fQ,storage:KZ,signer:Qo()},n=nQ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??rQ(e.cwd,n.repos.plugins,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function e9(e,t,n){return n.kind===`failed`?n:d0(e,n.value.bundle,u1(t,n.value.clients).map(({client:e})=>e))}function t9(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:u1(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function n9(e,t){return t.kind===`failed`?t:{kind:`ok`,value:u1(e,t.value).map(e=>e.transcript)}}function r9(e,t){return t.kind===`failed`?t:{kind:`ok`,value:f1(e,t.value)}}function i9(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:z0(e.sessionId,u1(e,t.value))}async function a9(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=P7(r,i,a()),u=l1(r.CLAUDE_CODE_SESSION_ID);s={...B0(e,l,{projectDir:d1(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:d6(o,r,i)??null},()=>null,c.serving,t9(u,c.rateLimits,Qa(l.claudeConfigDir)),n9(u,c.transcripts),u,r9(u,c.frames),i9(u,c.widths,l.termCols??null),c.stores),urlHandler:await c2(t),install:e9(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=GN(s);return{stdout:c.map(Q7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function o9(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new be(e),{columns:r}=n;return n.destroy(),{columns:r}}const s9=`Usage: cc-candybar doctor [config-file]
514
- `;function c9(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`));return t.length>0?{kind:`usage`,message:`doctor: unknown option ${t.join(` `)}\n${s9}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${s9}`}:{kind:`run`,configFile:n[0]}}async function l9(e){let n=c9(e);return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:await a9(C0($7),f2(),Y7,t.env,t.cwd(),o9,n.configFile)}function u9(e){return!e.ok&&e.code!==`RENDER_FAILED`}function d9(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=le.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(tn(c))),s.on(`data`,rn(e=>{let t=e;u9(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 f9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function p9(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 m9(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=d9(e,t,n,e=>{s=f9(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=p9(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&&yr();let e=s;s=f9(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function h9(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function g9(e,n){let{values:r,tokens:i}=se({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=Kv(r.lane);c===null&&(s(`--lane needs one of ${zv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=v3(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{h9(p,e)&&t(),p=e},h=async e=>{let r=await vn(e,a,o,{...P7(t.env,o,t.stderr),client:Ht(`frames`,n)});r.kind!==`ok`&&(s(pn(r)),r.kind===`transient`&&yr())},g=e=>{f?.close(),f=m9(Tt(),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 xe({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 _9(e){let t=e.replace(/\n+$/,``).split(`
515
- `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const v9=5e3,y9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function b9(e,t,n,r){let i=e.split(`
516
- `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?S3(e,x3(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function x9(e,t){let[n,r]=await Promise.all([rq(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,y3]),rq(e,`bar-pane.tmux`,[`list-clients`,`-F`,b3])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:b9(n.stdout,r.stdout,t,e.pane)}:r:n}function S9(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>v9)throw Error(`tmux has not answered for ${v9/1e3} s: ${t.reason}`)}}function C9(e){let{positionals:t}=(()=>{try{return se({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${y9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(y9);return{pane:n}}async function w9(e){try{return await T9(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function T9(e){let{pane:n}=C9(e),r=xM(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 x9(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=S9(),f=async()=>{if(a.kind!==`shown`)return;let e=_9(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await rq(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:m9(Tt(),e,`pane`,{frame:e=>n(uW(_n(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=S9();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await yn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${Tt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(yr(),u=``),c=pn(e))}h(),await ye(500);let e=await x9(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const E9=(e,t)=>new Promise((n,r)=>{let i=t=>{t?t.code===`EPIPE`?n():r(t):(e.off(`error`,i),n())};e.once(`error`,i),e.write(t,i)});async function D9(e){let n=Me(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),r=[];for(let[i,a]of[[t.stdout,e.stdout],[t.stderr,e.stderr+n]])await E9(i,a).catch(e=>r.push(e));if(r.length>0)throw r[0];t.exit(e.code)}const O9=i(import.meta.url),k9=e=>e.some(e=>t.argv.includes(e));function A9(){console.log(vM);let e=Ao(O9),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 ${Rv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Ue(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const j9={install:async e=>{await Ko(e,O9),t.exit(0)},"install-url-handler":async()=>{Vo(O9),t.exit(0)},"url-handle":async e=>{await Uo(e[0])},daemon:async()=>{J8()},"daemon-stats":async e=>{await D9(await U0(e))},frames:async()=>{await g9(t.argv,O9)},check:async e=>{await D9(await y7(e))},lint:async e=>{await D9(await y7(e))},plugin:async e=>{t.exit(j7(e))},schema:async()=>{await D9(i7())},doctor:async e=>{await D9(await l9(e))},"bar-pane":async e=>{t.exit(await w9(e))},...Object.fromEntries(s3.map(e=>[e,async t=>{await D9(await J5(e,t))}]))};async function M9(){let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(n!==null&&!Object.hasOwn(j9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),k9(nM.help)&&(A9(),t.exit(0)),k9(nM.version)&&(console.log(`cc-candybar ${Qe}`),t.exit(0)),n!==null){await j9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
510
+ `));return d}finally{o.registry.dispose()}}function h7(e){return e.map(e=>`warning: ${e}\n`).join(``)}function g7(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:h7(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:h7(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 _7=`--render`,v7=`Usage: cc-candybar check [${_7}] [config-file]\n`;function y7(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==_7);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${v7}`}:n.length>1?{kind:`usage`,message:`check: expected at most one path\n${v7}`}:{kind:`run`,target:n[0],render:t.includes(_7)}}async function b7(e){let n=y7(e),r=t.cwd();return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:g7(await d7(f6(n.target,t.env,r),r),n.render)}const x7=/^[a-z][a-z0-9+.-]*:\/\//i,S7=/^[^@\s/]+@[^:\s/]+:/,C7=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function w7(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function T7(e,t,n){let r=nV(t,e);if(n(r))return{kind:`path`,dir:r};if(x7.test(e)||S7.test(e))return{kind:`git`,url:e,shown:w7(e)};let i=C7.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 E7(e,t){let n=s.join(e,VV),r=WV(n);if(`error`in r)throw Error(`${t}: could not list ${VV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${VV}/<name>/${oV}`);return r.folders.map(e=>s.join(n,e,oV))}function D7(e,t,n){let r=(n,...r)=>{let i=ht({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
511
+ `))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${VV}/`)}function O7(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 D7(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function k7(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 A7(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,oV),s.join(t,oV));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function j7(e,t,n){let r=E7(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,oV))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=yH(a.map(e=>s.join(e,oV)),WH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(VV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,VV))}`).join(`
512
+ `));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:k7(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)A7(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,oV),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function M7(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=T7(n,process.cwd(),Qk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=O7(i,t=>j7(t,BV(),e));for(let{path:n,placed:r}of t)console.log(`${r} plugin ${s.basename(s.dirname(n))} → ${n} (from ${e})`);return 0}catch(e){return console.error(`plugin install: ${e.message}`),1}}function N7(e,t){if(e!==void 0&&/^\+?\d+$/.test(e)){let t=Number(e);if(t>0&&t<=4294967295)return t}if(t&&t>0)return t}const P7=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function F7(e,t,n){return{termCols:N7(e.COLUMNS,n.columns),termRows:N7(e.LINES,n.rows),ssh:P7.some(t=>(e[t]??``)!==``),tmux:xM(e),configEnv:d6(e,t),claudeConfigDir:Za(e,t),terminalEnv:Bt(e)}}function I7(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function L7(e){let t=q0(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=I7(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:on(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 R7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},z7=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 B7(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 V7(e){let t=q0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=B7(n?.postMortems,e=>Array.isArray(e)&&e.every(R7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&z7(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 H7(e,t,n){let r=q0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=I7(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 U7=e=>OM.includes(e.role),W7=e=>H7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&wM.includes(e.rateLimits),`the rate-limit windows they carried`),G7=e=>H7(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`),K7=e=>H7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&U7(e)&&DM.includes(e.frame),`what they drew and from which project`),q7=e=>H7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&U7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function J7(e,t,n){let r=e.doctorStores?.[t],i=B7(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 Y7(e){let t=q0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:J7(e,`marks`,r1),clicked:J7(e,`clicked`,o1),postMortemsRead:J7(e,`postMortemsRead`,c0)}}async function X7(){let e=await K0();if(e.kind!==`ok`){let t={kind:`failed`,reason:pn(e).split(`
513
+ `).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:L7(e.value),rateLimits:W7(e.value),transcripts:G7(e.value),frames:K7(e.value),widths:q7(e.value),serving:V7(e.value),stores:Y7(e.value)}}const Z7=` (fix: click the settings menu (${Si} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,Q7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${Si} by default) › 🧰 tools › 🩺 doctor`;function $7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:Z7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${Q7}\n`)}function e9(e){let t={sessionState:new pQ,storage:qZ,signer:Qo()},n=rQ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??iQ(e.cwd,n.repos.plugins,t);return r.registry.dispose(),{layers:n.layers,error:n.error,warning:n.warning,unused:r.unused,config:r.config}}function t9(e,t,n){return n.kind===`failed`?n:f0(e,n.value.bundle,d1(t,n.value.clients).map(({client:e})=>e))}function n9(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:d1(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function r9(e,t){return t.kind===`failed`?t:{kind:`ok`,value:d1(e,t.value).map(e=>e.transcript)}}function i9(e,t){return t.kind===`failed`?t:{kind:`ok`,value:p1(e,t.value)}}function a9(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:B0(e.sessionId,d1(e,t.value))}async function o9(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=F7(r,i,a()),u=u1(r.CLAUDE_CODE_SESSION_ID);s={...V0(e,l,{projectDir:f1(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:f6(o,r,i)??null},()=>null,c.serving,n9(u,c.rateLimits,Qa(l.claudeConfigDir)),r9(u,c.transcripts),u,i9(u,c.frames),a9(u,c.widths,l.termCols??null),c.stores),urlHandler:await l2(t),install:t9(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=GN(s);return{stdout:c.map($7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function s9(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new be(e),{columns:r}=n;return n.destroy(),{columns:r}}const c9=`Usage: cc-candybar doctor [config-file]
514
+ `;function l9(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`));return t.length>0?{kind:`usage`,message:`doctor: unknown option ${t.join(` `)}\n${c9}`}:n.length>1?{kind:`usage`,message:`doctor: expected at most one config file\n${c9}`}:{kind:`run`,configFile:n[0]}}async function u9(e){let n=l9(e);return n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:await o9(w0(e9),p2(),X7,t.env,t.cwd(),s9,n.configFile)}function d9(e){return!e.ok&&e.code!==`RENDER_FAILED`}function f9(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=le.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(tn(c))),s.on(`data`,rn(e=>{let t=e;d9(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 p9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function m9(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 h9(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=f9(e,t,n,e=>{s=p9(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=m9(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&&yr();let e=s;s=p9(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function g9(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function _9(e,n){let{values:r,tokens:i}=se({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=Kv(r.lane);c===null&&(s(`--lane needs one of ${zv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=y3(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{g9(p,e)&&t(),p=e},h=async e=>{let r=await vn(e,a,o,{...F7(t.env,o,t.stderr),client:Ht(`frames`,n)});r.kind!==`ok`&&(s(pn(r)),r.kind===`transient`&&yr())},g=e=>{f?.close(),f=h9(Tt(),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 xe({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 v9(e){let t=e.replace(/\n+$/,``).split(`
515
+ `);return{bytes:t.map((e,t)=>`\x1b[${t+1}H${e}`).join(``)+`\x1B[J`,rows:t.length}}const y9=5e3,b9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function x9(e,t,n,r){let i=e.split(`
516
+ `).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?C3(e,S3(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function S9(e,t){let[n,r]=await Promise.all([rq(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,b3]),rq(e,`bar-pane.tmux`,[`list-clients`,`-F`,x3])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:x9(n.stdout,r.stdout,t,e.pane)}:r:n}function C9(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>y9)throw Error(`tmux has not answered for ${y9/1e3} s: ${t.reason}`)}}function w9(e){let{positionals:t}=(()=>{try{return se({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${b9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(b9);return{pane:n}}async function T9(e){try{return await E9(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function E9(e){let{pane:n}=w9(e),r=xM(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 S9(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=C9(),f=async()=>{if(a.kind!==`shown`)return;let e=v9(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await rq(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:h9(Tt(),e,`pane`,{frame:e=>n(uW(_n(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=C9();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await yn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${Tt()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(yr(),u=``),c=pn(e))}h(),await ye(500);let e=await S9(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const D9=(e,t)=>new Promise((n,r)=>{let i=t=>{t?t.code===`EPIPE`?n():r(t):(e.off(`error`,i),n())};e.once(`error`,i),e.write(t,i)});async function O9(e){let n=Me(()=>`delivered stdout=${Buffer.byteLength(e.stdout)} stderr=${Buffer.byteLength(e.stderr)} code=${e.code}`),r=[];for(let[i,a]of[[t.stdout,e.stdout],[t.stderr,e.stderr+n]])await D9(i,a).catch(e=>r.push(e));if(r.length>0)throw r[0];t.exit(e.code)}const k9=i(import.meta.url),A9=e=>e.some(e=>t.argv.includes(e));function j9(){console.log(vM);let e=Ao(k9),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 ${Rv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${Ue(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const M9={install:async e=>{await Ko(e,k9),t.exit(0)},"install-url-handler":async()=>{Vo(k9),t.exit(0)},"url-handle":async e=>{await Uo(e[0])},daemon:async()=>{Y8()},"daemon-stats":async e=>{await O9(await W0(e))},frames:async()=>{await _9(t.argv,k9)},check:async e=>{await O9(await b7(e))},lint:async e=>{await O9(await b7(e))},plugin:async e=>{t.exit(M7(e))},schema:async()=>{await O9(a7())},doctor:async e=>{await O9(await u9(e))},"bar-pane":async e=>{t.exit(await T9(e))},...Object.fromEntries(c3.map(e=>[e,async t=>{await O9(await Y5(e,t))}]))};async function N9(){let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;try{if(n!==null&&!Object.hasOwn(M9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),A9(nM.help)&&(j9(),t.exit(0)),A9(nM.version)&&(console.log(`cc-candybar ${Qe}`),t.exit(0)),n!==null){await M9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
517
517
 
518
518
  cc-candybar is designed to be used as a Claude Code statusLine command.
519
519
  It reads hook data from stdin and outputs formatted statusline.
@@ -529,4 +529,4 @@ Add to ~/.claude/settings.json:
529
529
  Run with --help for more options.
530
530
 
531
531
  To test output manually:
532
- 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 e=await o(t.stdin);D(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),A9(),t.exit(1));let r=uW(await vn(e,t.argv.slice(1),t.cwd(),{...P7(t.env,t.cwd(),t.stderr),client:Ht(`node`,O9)}));r.debug!==null&&D(r.debug),r.kick&&yr(),await D9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await D9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}M9();export{};
532
+ 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 e=await o(t.stdin);D(`Received hook data:`,JSON.stringify(e,null,2)),e||(console.error(`Error: No input data received from stdin`),j9(),t.exit(1));let r=uW(await vn(e,t.argv.slice(1),t.cwd(),{...F7(t.env,t.cwd(),t.stderr),client:Ht(`node`,k9)}));r.debug!==null&&D(r.debug),r.kick&&yr(),await O9({stdout:r.output,stderr:``,code:0})}catch(e){let t=e instanceof Error?e.message:String(e);await O9({stdout:``,stderr:`cc-candybar ${n??`statusline`}: ${t}\n`,code:1})}}N9();export{};