@promptctl/cc-candybar 1.160.0 → 1.160.2
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 +53 -53
- package/package.json +5 -5
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.160.0`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`e839d098ff514ef8fd321458c6dac850d41f33a2a8d5a249449641fdecf883aa`}function tt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:rt(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:rt(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function gt(e,t,n){let r=_t(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function _t(e){let t=e;for(let e=0;e<O;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
2
|
+
import{createRequire as e}from"node:module";import t from"node:process";import{URL as n,URLSearchParams as r,fileURLToPath as i,pathToFileURL as a}from"node:url";import{json as o}from"node:stream/consumers";import s,{basename as c,dirname as l,isAbsolute as u,join as d,sep as f}from"node:path";import p,{closeSync as m,constants as h,existsSync as g,fstatSync as _,openSync as v,readSync as y,realpathSync as b,statSync as ee,watch as x}from"node:fs";import S,{createHash as te,createHmac as ne,randomBytes as re,randomUUID as ie,timingSafeEqual as ae}from"node:crypto";import C,{homedir as w}from"node:os";import{spawn as oe,spawnSync as se}from"node:child_process";import{inspect as T,parseArgs as ce,types as le}from"node:util";import ue from"node:net";import de from"node:v8";import{open as fe,readFile as pe,readdir as me,stat as he}from"node:fs/promises";import{clearInterval as ge,setImmediate as _e,setInterval as ve}from"node:timers";import{get as ye}from"node:https";import{setTimeout as be}from"node:timers/promises";import{WriteStream as xe}from"node:tty";import{createInterface as Se}from"node:readline";var Ce=Object.create,we=Object.defineProperty,Te=Object.getOwnPropertyDescriptor,Ee=Object.getOwnPropertyNames,De=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty,ke=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),Ae=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ee(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Oe.call(e,s)&&s!==n&&we(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Te(t,s))||r.enumerable});return e},je=(e,t,n)=>(n=e==null?{}:Ce(De(e)),Ae(t||!e||!e.__esModule?we(n,`default`,{value:e,enumerable:!0}):n,e));function E(e,...t){process.env.CC_CANDYBAR_DEBUG&&console.error(`[DEBUG] ${e}`,...t)}const Me=(e,t)=>E(t),Ne=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Pe(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Fe(e){return Ne.test(e)?e:Pe(e)}function Ie(e){return`${e.dir===void 0?``:`cd ${Fe(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Fe(t)} `).join(``)}${[e.program,...e.args].map(Fe).join(` `)}`}const Le=`cc-extra`;function Re(e){return s.join(s.dirname(e),Le,`src`,`bun-attach.js`)}function ze(e){return s.join(s.dirname(e),`bun-graph.js`)}const Be=`attach-preload.cjs`;function Ve(e){return s.join(s.dirname(e),Be)}function He(e,t){return Ie({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ue=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function We(e,t){return t.isSymbolicLink()?Buffer.from(p.readlinkSync(e)):p.readFileSync(e)}function Ge(e,t,n=Ue){return p.readdirSync(t).filter(n).sort().flatMap(n=>{let r=s.join(t,n),i=p.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?Ge(e,r):[[s.relative(e,r).split(s.sep).join(`/`),We(r,i)]]})}function Ke(e){let t=S.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function qe(e){return Ke(Ge(e,e))}const Je=[`Cargo.toml`,`Cargo.lock`,`src`];function Ye(e){return Ke(Ge(e,e,e=>Je.includes(e)))}const Xe=e=>e.slice(0,7),Ze=`1.160.2`;function Qe(e){let t=s.dirname(s.dirname(e));return p.existsSync(s.join(t,`src`))?t:null}function $e(){let e=et();if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:Ze,digest:e}}function et(){return`8ba9b94ce9fc13696cd5cf5b95beec2df37c1a872fe3bdf3e7b5fc7d7a582f30`}function tt(e){let t=JSON.parse(p.readFileSync(s.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${s.join(e,`package.json`)} has no version string`);return n}function nt(e,t){try{let n=Qe(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=qe(s.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:tt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function rt(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!g(t)?`working directory does not exist: ${t}`:e.message:String(e)}const it={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3},at=new Map;function ot(e){let t=it[e];if(t===void 0)return{allowed:!0};let n=at.get(e);if(n===void 0)return{allowed:!0};let r=Date.now()-n;return r>=t?{allowed:!0}:{allowed:!1,minIntervalMs:t,sinceLastMs:r}}function st(e){at.set(e,Date.now())}function ct(e){return e.env??process.env}function lt(e,t,n){return{ok:!1,reason:`rate-limited`,stdout:``,stderr:``,exitCode:null,signal:null,error:`rate-limited: ${e} min interval ${t}ms, last start ${n}ms ago`}}let ut=null;function dt(e){ut=e}function ft(e,t){try{process.kill(-e,t)}catch(e){if(e.code!==`ESRCH`)throw e}}async function pt(e){if(e.signal?.aborted)return{ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null};let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();return ut?.onStart(e.category),new Promise(t=>{let r;try{r=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(r){ut?.onEnd(e.category,Date.now()-n),t({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(r,e.cwd)});return}let i=``,a=``,o=!1,s=null,c=null,l=null,u=()=>m(`aborted`),d=t=>{o||(o=!0,s&&clearTimeout(s),c&&clearTimeout(c),e.signal?.removeEventListener(`abort`,u),ut?.onEnd(e.category,Date.now()-n),t())},f=e=>d(()=>t(e)),p=(e,t)=>{try{ft(e,t)}catch(e){f({ok:!1,reason:`signal-refused`,stdout:i,stderr:a,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)})}},m=t=>{l=t,s&&clearTimeout(s),e.signal?.removeEventListener(`abort`,u);let n=r.pid;n!==void 0&&(c=setTimeout(()=>p(n,`SIGKILL`),250),p(n,`SIGTERM`))};r.stdout?.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr?.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,t=>{f({ok:!1,reason:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:null,error:rt(t,e.cwd)})}),r.on(`close`,(e,t)=>{if(l!==null){f({ok:!1,reason:l,stdout:i,stderr:a,exitCode:e,signal:t});return}if(e===0){f({ok:!0,stdout:i,stderr:a,exitCode:e});return}f({ok:!1,reason:t?`signal`:`non-zero`,stdout:i,stderr:a,exitCode:e,signal:t})}),e.timeoutMs&&e.timeoutMs>0&&(s=setTimeout(()=>m(`timeout`),e.timeoutMs)),e.signal?.addEventListener(`abort`,u,{once:!0}),e.stdinInput!==void 0&&r.stdin?r.stdin.end(e.stdinInput):r.stdin&&r.stdin.end()})}function D(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=[`pipe`,`pipe`,`pipe`];try{let t=se(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),input:e.stdinInput,timeout:e.timeoutMs&&e.timeoutMs>0?e.timeoutMs:void 0,stdio:r,encoding:`utf8`});ut?.onEnd(e.category,Date.now()-n);let i=typeof t.stdout==`string`?t.stdout:``,a=typeof t.stderr==`string`?t.stderr:``;if(t.error)return{ok:!1,reason:t.error.code===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:i,stderr:a,exitCode:null,signal:t.signal??null,error:rt(t.error,e.cwd)};if(t.status===0)return{ok:!0,stdout:i,stderr:a,exitCode:t.status};let o=e.timeoutMs!==void 0&&e.timeoutMs>0;return{ok:!1,reason:t.signal?o&&t.signal===`SIGTERM`?`timeout`:`signal`:`non-zero`,stdout:i,stderr:a,exitCode:t.status,signal:t.signal??null}}catch(t){return ut?.onEnd(e.category,Date.now()-n),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}}function mt(e){let t=ot(e.category);if(!t.allowed)return lt(e.category,t.minIntervalMs,t.sinceLastMs);st(e.category);let n=Date.now();ut?.onStart(e.category);let r=ht(e);return ut?.onEnd(e.category,Date.now()-n),r}function ht(e){let t;try{t=oe(e.bin,e.args??[],{cwd:e.cwd,env:ct(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:rt(t,e.cwd)}}return t.once(`error`,()=>{}),t.pid===void 0?{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:`spawn(${e.bin}): no pid (binary not found or unexecutable)`}:(t.unref(),{ok:!0,stdout:``,stderr:``,exitCode:null})}function gt(e,t,n){let r=_t(e);p.mkdirSync(s.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??p.statSync(r,{throwIfNoEntry:!1})?.mode;try{p.writeFileSync(i,t,a===void 0?{}:{mode:a}),p.renameSync(i,r)}catch(e){throw p.rmSync(i,{force:!0}),e}}function _t(e){let t=e;for(let e=0;e<O;e++){let e;try{e=p.lstatSync(t)}catch(e){if(e.code===`ENOENT`)return t;throw e}if(!e.isSymbolicLink())return t;t=s.resolve(p.realpathSync(s.dirname(t)),p.readlinkSync(t))}throw Error(`${e}: more than ${O} symbolic links`)}const O=40;function vt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function yt(e=process.env){let t=vt(e,`XDG_STATE_HOME`)??s.join(C.homedir(),`.local`,`state`);return s.join(t,`cc-candybar`)}function bt(){let e=vt(process.env,`XDG_CACHE_HOME`)??s.join(C.homedir(),`.cache`);return s.join(e,`cc-candybar`)}function xt(){return yt()}function St(){return process.env.CC_CANDYBAR_SOCKET||Ct()}function Ct(){let e=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function wt(e){p.mkdirSync(e,{recursive:!0,mode:448});let t=p.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=C.userInfo().uid;if(typeof n==`number`&&t.uid!==n)throw Error(`directory is not owned by uid ${n}: ${e} (owner uid=${t.uid})`);if(t.mode&63)throw Error(`directory has unsafe permissions: ${e} (mode=${(t.mode&511).toString(8)}, expected 0700)`)}function Tt(e){wt(s.dirname(e));for(let t of[e,Et(e)])try{if(p.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function Et(e){return`${e}.lease`}function Dt(){return Et(St())}function Ot(){return s.join(yt(),`session-state.json`)}function kt(){return s.join(yt(),`settings-history.json`)}function At(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=C.userInfo().uid;return s.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function jt(){return s.join(yt(),`spawn.lock`)}function Mt(){return s.join(yt(),`spawn.cooldown`)}function Nt(){return s.join(yt(),`spawn.backoff`)}function Pt(){return s.join(yt(),`diagnostics`)}function Ft(e=process.env){return s.join(yt(e),`daemon.log`)}const It=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function Lt(e){return Object.fromEntries(It.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const Rt=[`native`,`node`,`frames`];function zt(e,t){return{kind:e,bundle:t,source:null}}const Bt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Vt(e){let t=Yt(e.termCols),n=Yt(e.termRows),r=Xt(e.ssh),i=qt(e.tmux),a=Kt(e.configEnv),o=Kt(e.claudeConfigDir),s=k(e.terminalEnv),c=nn(e.client);return{...t!==void 0&&{termCols:t},...n!==void 0&&{termRows:n},...r!==void 0&&{ssh:r},...i!==void 0&&{tmux:i},...a!==void 0&&{configEnv:a},...o!==void 0&&{claudeConfigDir:o},...s!==void 0&&{terminalEnv:s},...c!==void 0&&{client:c}}}function Ht(e,t){return Bt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Ut(e){return e.length===0?null:`Client hints refused: ${e.map(({hint:e,sent:t})=>`${e}=${JSON.stringify(t)}`).join(`, `)} — is the statusline client older than the daemon? Reinstall it (\`cc-candybar install\`, or \`just install-rust\` in a checkout).`}const Wt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function Gt(e){let t=Object.keys(Wt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Wt[t](n.join(`, `))]});return t.length===0?null:t.join(`
|
|
3
3
|
`)}function k(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=It.filter(e=>t[e]!==void 0);return n.every(e=>typeof t[e]==`string`&&t[e]!==``)?Object.fromEntries(n.map(e=>[e,t[e]])):void 0}function Kt(e){return typeof e==`string`&&s.isAbsolute(e)?e:void 0}function qt(e){if(e===null)return null;if(typeof e!=`object`)return;let{socket:t,pane:n,truecolor:r}=e;if(!(typeof t!=`string`||t===``)&&!(typeof n!=`string`||n===``)&&!(r!==null&&(typeof r!=`string`||r===``)))return{socket:t,pane:n,truecolor:r}}const Jt=1e4;function Yt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Jt?Jt:t}function Xt(e){return typeof e==`boolean`?e:void 0}function Zt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var A=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function Qt(e){return $t(JSON.stringify(e))}function $t(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function en(e,t){let n=Buffer.alloc(0);return function(r){for(n=Buffer.concat([n,r]);n.length>=4;){let r=n.readUInt32BE(0);if(r>16777216){t(new A(`frame too large: ${r}`));return}if(n.length<4+r)return;let i=n.subarray(4,4+r);n=n.subarray(4+r);try{e(JSON.parse(i.toString(`utf8`)))}catch(e){let n=new A(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function tn(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.removeAllListeners();try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=en(e=>o(()=>r(e)),e=>o(()=>i(e)));e.on(`data`,c),e.on(`error`,e=>o(()=>i(e))),e.on(`close`,()=>o(()=>i(Error(`socket closed before response`)))),e.write(Qt(t))})}function nn(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Kt(n);return Rt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function rn(e,t,n){let r=null;try{r=await ln(St(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await tn(r,{v:3,...a},i);return sn(a.kind,o,n)}catch(e){return cn(e)}finally{r&&r.destroy()}}function an(e,t){return typeof e==`string`?e:t}function on(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function sn(e,t,n){let r=t;if(r.ok===!0){let r=n(t);return r===void 0?{kind:`permanent`,cause:`malformed_response`,message:`ok response without payload for "${e}" request`}:{kind:`ok`,value:r}}let i=an(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:on(r.daemonV)};case`TIMEOUT`:return{kind:`transient`,cause:`timeout`,message:i};case`BAD_REQUEST`:return{kind:`permanent`,cause:`bad_request`,message:i};case`RENDER_FAILED`:return{kind:`permanent`,cause:`render_failed`,message:i};case`SWITCHED_OFF`:return{kind:`permanent`,cause:`switched_off`,message:i};default:return{kind:`permanent`,cause:`malformed_response`,message:`unknown error code: ${String(r.code)}`}}}function cn(e){if(e instanceof A||e instanceof SyntaxError)return{kind:`permanent`,cause:`malformed_response`,message:e instanceof Error?e.message:String(e)};let t=e instanceof Error?e.message:String(e);return t===`CONNECT_TIMEOUT`||t===`TIMEOUT`?{kind:`transient`,cause:`timeout`,message:t}:t.includes(`ECONNREFUSED`)||t.includes(`ENOENT`)||t.includes(`ENOTSOCK`)?{kind:`transient`,cause:`unreachable`,message:t}:{kind:`transient`,cause:`io_error`,message:t}}function ln(e,t){return new Promise((n,r)=>{let i=ue.createConnection({path:e}),a=setTimeout(()=>{i.destroy(),r(Error(`CONNECT_TIMEOUT`))},t);i.once(`connect`,()=>{clearTimeout(a),n(i)}),i.once(`error`,e=>{clearTimeout(a),r(e)})})}function un(e){if(e.kind===`transient`)return`daemon unavailable (${e.cause}: ${e.message})\nHint: daemon may not be running. Run \`cc-candybar\` once to spawn it.`;switch(e.cause){case`version_mismatch`:{let t=e.daemonV===0?`unknown`:`v${e.daemonV}`;return`daemon protocol mismatch (client v${e.clientV} ≠ daemon ${t})`}case`bad_request`:case`render_failed`:case`switched_off`:case`malformed_response`:return`daemon error (${e.cause}): ${e.message}`}}const dn={connectMs:50,budgetMs:150},fn={connectMs:50,budgetMs:200};function pn(e){let t=e.output;return typeof t==`string`?t:void 0}function mn(e){return sn(`render`,e,pn)}function hn(e,t,n,r){return rn(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),dn,pn)}function gn(e,t){return rn(()=>({kind:`pane-session`,socket:e,pane:t}),fn,e=>`paneSession`in e?e.paneSession:void 0)}function _n(e,t){return rn(()=>({kind:`click`,verb:e,value:t,clientVersion:Ze}),fn,pn)}let vn=null;function yn(){if(vn!==null){try{p.closeSync(vn.fd)}catch{}vn=null}}async function bn(e){let t=await p.promises.stat(e).catch(()=>null);if(vn!==null&&vn.path===e&&t!==null&&vn.id===xn(t))return{held:vn,size:t.size};yn(),await p.promises.mkdir(s.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>p.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>p.fstat(n,(n,r)=>n===null?e(r):t(n)));return vn={path:e,fd:n,id:xn(r)},{held:vn,size:r.size}}function xn(e){return`${e.dev}:${e.ino}`}function Sn(e,t){return new Promise((n,r)=>p.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function Cn(e){for(let t=2;t>=1;t--)await p.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await p.promises.rename(e,`${e}.1`).catch(()=>{})}let wn=[],Tn=0,En=0,Dn=0,j=null,On=!1;const kn=[];let An=!1,jn=!1;function M(e,t){let n=`${new Date().toISOString()} [${e}] ${t}\n`;if(jn||(jn=!0,process.on(`exit`,()=>{An=!0,Rn(!0,In)})),wn.push(n),Tn+=Buffer.byteLength(n),Tn>4194304){let e=0;for(;Tn>4194304/2&&e<wn.length-1;){let t=Buffer.byteLength(wn[e]);Tn-=t,Dn+=t,e++}wn.splice(0,e),En+=e}An?Rn(!0,In):On||Nn()}function Mn(){Rn(!1,Ln)}async function Nn(){On=!0;try{for(;wn.length>0;){let e=Pn();j={bytes:Buffer.from(e),state:{kind:`taken`}};try{await Fn(Ft(),j)}catch(t){yn(),j.state.kind!==`landed`&&Bn(e,t)}finally{j=null}}}finally{On=!1;for(let e of kn.splice(0))e()}}function Pn(){let e=(En===0?``:`${new Date().toISOString()} [warn] log: ${En} earlier line(s) dropped (${Dn} bytes): more than 4194304 bytes were waiting for the disk\n`)+wn.join(``);return wn=[],Tn=0,En=0,Dn=0,e}async function Fn(e,t){let{held:n,size:r}=await bn(e);if(t.state.kind===`landed`)return;let{bytes:i}=t,a=r+i.length;t.state={kind:`issued`,fd:n.fd,endsAt:a};for(let e=0;e<i.length;){let t=await Sn(n.fd,i.subarray(e));if(t===0)throw Error(`the disk took 0 bytes of a write`);e+=t}if(t.state={kind:`landed`},a>=5242880){yn();let e=await p.promises.stat(n.path).catch(()=>null);e!==null&&xn(e)===n.id&&await Cn(n.path)}}const In=1e3,Ln=2e3;function Rn(e,t){let n=j,r=Buffer.alloc(0);n!==null&&n.state.kind===`taken`&&(r=n.bytes,n.state={kind:`landed`});let i=null;if(n!==null&&n.state.kind===`issued`){let{fd:a,endsAt:o}=n.state;try{let s=zn(a,o,t);s<o&&e?(r=n.bytes.subarray(Math.max(0,s-(o-n.bytes.length))),n.state={kind:`landed`}):s<o&&(i={fd:a,endsAt:o})}catch(t){e&&(r=n.bytes,n.state={kind:`landed`}),Bn(n.bytes.toString(),t)}}if(r.length===0&&wn.length===0)return;let a=Buffer.concat([r,Buffer.from(Pn())]);try{let e=Ft();p.mkdirSync(s.dirname(e),{recursive:!0}),p.appendFileSync(e,a),i!==null&&n!==null&&xn(p.fstatSync(i.fd))===xn(p.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){Bn(a.toString(),e)}}function zn(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=p.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function Bn(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const Vn=5e3;function Hn(e){let t=[];for(let n of e){let e=n.read();if(e.kind===`text`)return`# memory report from: ${n.name}\n${e.text}`;t.push(`# ${n.name}: unavailable — ${e.reason}`)}return[`# memory report: no probe answered`,...t.length>0?t:[`# no probe is known for this platform`]].join(`
|
|
4
4
|
`)}const Un=`/usr/bin/footprint`;function Wn(e,t){return e===`darwin`?[Jn(Un,[`-p`,String(t)]),Jn(`/usr/bin/vmmap`,[`--summary`,String(t)])]:e===`linux`?[Yn(`/proc/self/smaps_rollup`),Yn(`/proc/self/status`)]:[]}function Gn(e,t){return e===`darwin`?Kn(t,e=>pt({bin:Un,args:e,timeoutMs:Vn,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function Kn(e,t){return async n=>{let r=await t([`-p`,String(e),`--noCategories`,`-f`,`bytes`]);if(!r.ok)return{kind:`stand-in`,bytes:n,unread:`footprint ${r.reason}${r.error===void 0?``:`: ${r.error}`}${Xn(r.stderr)}`};let i=qn(r.stdout);return i===null?{kind:`stand-in`,bytes:n,unread:`footprint printed no phys_footprint line`}:{kind:`charged`,measure:`phys_footprint`,bytes:i}}}function qn(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Jn(e,t){return{name:`${e} ${t.join(` `)}`,read:()=>{let n=D({bin:e,args:[...t],timeoutMs:Vn,category:`limits.memory-report`});return n.ok?n.stdout.trim().length>0?{kind:`text`,text:n.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${n.reason}${n.error===void 0?``:`: ${n.error}`}${Xn(n.stderr)}`}}}}function Yn(e){return{name:e,read:()=>{try{let t=p.readFileSync(e,`utf8`);return t.trim().length>0?{kind:`text`,text:t}:{kind:`unavailable`,reason:`empty file`}}catch(e){return{kind:`unavailable`,reason:e.message}}}}}function Xn(e){let t=e.split(`
|
|
5
5
|
`).map(e=>e.trim()).find(e=>e.length>0);return t===void 0?``:` (${t})`}const Zn=`CC_CANDYBAR_RSS_LIMIT_MB`;function Qn(e){let t=e[Zn];if(t===void 0)return 1024;let n=/^\d+$/.test(t)?Number(t):NaN;if(!Number.isSafeInteger(n)||n<=0)throw Error(`${Zn} must be a positive integer (MB), got ${JSON.stringify(t)}`);return n}function $n(e){return Qn(e)*2}const er=1024*1024,tr=e=>Math.round(e/er);function nr(e){return Qn(e)*er}const rr={memoryReport:{prefix:`memory-`,suffix:`.txt`},heapSnapshot:{prefix:`heap-`,suffix:`.heapsnapshot`}};function ir(e,t){return e>t}function ar(e,t){if(e.kind===`charged`)return e;let n=t.kind===`unmeasured`?0:t.charge.kind===`charged`?t.rss-t.charge.bytes:t.charge.gap;return{...e,bytes:e.bytes-n,gap:n}}const or=.75;function sr(e,t){return e>t*or}function cr(e,t,n){let{prefix:r,suffix:i}=rr[t];return s.join(e,`${r}${n}${i}`)}function lr(e){for(let t of Object.keys(rr)){let{prefix:n,suffix:r}=rr[t];if(e.startsWith(n)&&e.endsWith(r))return t}return null}function ur(e){let t=e.limitBytes??1024*er,n=e.snapshotsKeep??3,r=!1,i={kind:`unmeasured`},a=null;function o(){return a??=s().finally(()=>{a=null}),a}async function s(){if(r)return!0;let{rss:a,heapTotal:o}=e.memoryBytes(),s=ar(await e.memoryCharge(a),i),c={kind:`measured`,charge:s,rss:a,heapTotal:o};if(i=c,e.log(`info`,`memory ${pr(c,t)}`),s.bytes<=t)return!1;r=!0,e.log(`warn`,`${dr(s)} > limit ${tr(t)} MB (rss ${tr(a)} MB, v8 heap ${tr(o)} MB); recording memory then shutting down`);let l=`${new Date(e.now()).toISOString().replace(/[:.]/g,`-`)}-${e.pid}`;return mr(e.log,`memory report`,()=>{let t=cr(e.snapshotDir,`memoryReport`,l);e.writeMemoryReport(t,e.captureMemoryReport()),e.log(`info`,`memory report written: ${t}`)}),mr(e.log,`heap snapshot`,()=>{e.writeLogNow();let t=cr(e.snapshotDir,`heapSnapshot`,l);e.log(`info`,`heap snapshot written: ${e.writeHeapSnapshot(t)}`)}),mr(e.log,`artifact rotation`,()=>{for(let{artifacts:t}of hr(e.listArtifacts()).slice(n))for(let n of Object.values(t))mr(e.log,`evicting ${n}`,()=>e.removeFile(n))}),e.shutdown(0),!0}function c(){return i.kind===`measured`&&sr(i.charge.bytes,t)?`${dr(i.charge)} approaching limit ${tr(t)} MB (v8 heap ${tr(i.heapTotal)} MB)`:null}function l(){let n;try{n={kind:`ok`,value:hr(e.listArtifacts())}}catch(e){n={kind:`failed`,reason:e.message}}return{pid:e.pid,memory:i,limit:t,postMortems:n}}function u(t=6e4){let n,r=!0,i=async()=>{try{if(await o())return}catch(t){e.log(`warn`,`memory check failed: ${t.message}`)}r&&(n=setTimeout(()=>void i(),t),n.unref())};return i(),{disarm:()=>{r=!1,clearTimeout(n)}}}return{check:o,describeNextRestart:c,serving:l,arm:u}}function dr(e){return e.kind===`charged`?`${e.measure} ${tr(e.bytes)} MB`:`rss ${tr(e.bytes+e.gap)} MB${e.gap===0?``:` less its last ${tr(e.gap)} MB gap`} (standing in: ${e.unread})`}function fr(e){return e.kind===`charged`?e.measure:`rss-stand-in`}function pr({charge:e,rss:t,heapTotal:n},r){let i=e.kind===`stand-in`?` unread=${JSON.stringify(e.unread)} gap=${tr(e.gap)}MB`:``;return`measure=${fr(e)} charge=${tr(e.bytes)}MB rss=${tr(t)}MB heap=${tr(n)}MB limit=${tr(r)}MB${i}`}function mr(e,t,n){try{n()}catch(n){e(`warn`,`${t} failed: ${n.message}`)}}function hr(e){let t=new Map;for(let n of e){let e=s.basename(n),r=lr(e);if(r===null)continue;let{prefix:i,suffix:a}=rr[r],o=e.slice(i.length,e.length-a.length);t.set(o,{...t.get(o),[r]:n})}let n=Object.keys(rr);return[...t].sort(([e],[t])=>ir(e,t)?-1:1).map(([e,t])=>({identity:e,artifacts:Object.fromEntries(n.flatMap(e=>t[e]===void 0?[]:[[e,t[e]]]))}))}function gr(e,t,n={}){let r=xt();return{now:()=>Date.now(),pid:process.pid,snapshotDir:r,log:M,memoryBytes:()=>{let e=process.memoryUsage();return{rss:e.rss,heapTotal:e.heapTotal}},memoryCharge:Gn(process.platform,process.pid),captureMemoryReport:()=>Hn(Wn(process.platform,process.pid)),writeMemoryReport:(e,t)=>p.writeFileSync(e,t,{mode:384}),writeHeapSnapshot:e=>de.writeHeapSnapshot(e),writeLogNow:Mn,listArtifacts:()=>{let e;try{e=p.readdirSync(r)}catch(e){if(e.code===`ENOENT`)return[];throw e}return e.filter(e=>lr(e)!==null).map(e=>s.join(r,e))},removeFile:e=>p.unlinkSync(e),shutdown:t,startedAtMs:e,...n}}function _r(e={}){if(Nr()!==null)return;let n=e.spawn??Fr,r=Ar();if(r.kind===`contended`){let e=yr();e!==null&&e>2e3&&(t.stderr.write(`cc-candybar: spawn-lock held ${e}ms (likely crashed holder) — spawning unlocked\n`),vr(n));return}if(r.kind===`error`){t.stderr.write(`cc-candybar: spawn-lock unavailable (${r.reason}) — spawning unlocked\n`),vr(n);return}try{vr(n)}finally{Mr()}}function vr(e){Er()&&br(e)}function yr(){try{let e=p.statSync(jt());return Date.now()-e.mtimeMs}catch{return null}}function br(e){try{e()||t.stderr.write(`cc-candybar: daemon spawn returned false (unable to resolve script path?)
|
|
@@ -189,16 +189,16 @@ Config tooling:
|
|
|
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)`?F:P(t)}else if(e.startsWith(`branch.head `)){let n=e.slice(12).trim();t=n===`(detached)`?`detached`:n}else if(e.startsWith(`branch.upstream `))r=P(e.slice(16).trim());else if(e.startsWith(`branch.ab `)){let t=e.slice(10).trim().match(/^\+(\d+)\s+-(\d+)$/);t&&(i=P({ahead:parseInt(t[1],10),behind:parseInt(t[2],10)}))}continue}let e=l[0];if(e===`1`||e===`2`){let e=l.slice(2,4);e[0]!==`.`&&a++,e[1]!==`.`&&o++}else e===`u`?c++:e===`?`&&s++}let l=`clean`;return c>0?l=`conflicts`:(a||o||s)&&(l=`dirty`),{branch:t,status:l,aheadBehind:i,oid:n,upstream:r,workingTree:{staged:a,unstaged:o,untracked:s,conflicts:c}}}function aG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`gh pr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!rG(t))return I(`gh pr view: JSON is not an object`);let{number:n,state:r,url:i,headRefOid:a}=t;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`gh pr view: missing number/state/url/headRefOid`);let o=MW(`gh pr view`,AW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function oG(e){let t;try{t=JSON.parse(e)}catch(e){return I(`glab mr view: unparseable JSON (${e instanceof Error?e.message:String(e)})`)}if(!rG(t))return I(`glab mr view: JSON is not an object`);let n=t.iid,r=t.state,i=t.web_url,a=t.sha;if(typeof n!=`number`||typeof r!=`string`||typeof i!=`string`||typeof a!=`string`)return I(`glab mr view: missing iid/state/web_url/sha`);let o=MW(`glab mr view`,jW,r);return o.kind===`ok`?P({number:n,state:o.value,url:i,head:a}):o}function sG(e){try{let t=p.statSync(e);return{key:`${t.dev}:${t.ino}`,stamp:`${t.mtimeMs}:${t.size}`}}catch{return null}}var cG=class{isGitRepo(e){return UV(e)}async execGitAsync(e,t){return pt({bin:`git`,args:[...e],cwd:t.cwd,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:t.timeout,category:`git`})}resolveEffectiveGitDir(e,t){return this.isWorktree(e)?P(e):t&&this.isGitRepo(t)?P(t):this.isGitRepo(e)?P(e):this.findGitRoot(e)}findGitRoot(e){let t=WV(e);return t===void 0?F:P(t)}async getGitInfo(e,t={},n){try{return await this.computeGitInfo(e,t,n)}catch(e){return I(`git: ${e instanceof Error?e.message:String(e)}`)}}async computeGitInfo(e,t={},n){let r,i=this.isWorktree(e);if(i)r=e;else if(n&&this.isGitRepo(n))r=n;else if(this.isGitRepo(e))r=e;else{let t=this.findGitRoot(e);if(t.kind!==`ok`)return t;r=t.value}let a=await this.getCoreAsync(r);if(a.kind!==`ok`)return a;let o={branch:a.value.branch,status:a.value.status,aheadBehind:a.value.aheadBehind,head:a.value.oid};t.showWorkingTree&&(o.workingTree=a.value.workingTree),t.showSha&&(o.sha=RW(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=RW(s,e=>this.repoNameFrom(e,r)),o.isWorktree=i),s!==void 0&&t.showRepoUrl&&(o.repoUrl=RW(s,tG)),t.showOperation&&(o.operation=this.getOngoingOperation(r)),P(o)}resolveGitDir(e){let t=s.join(e,`.git`);try{if(p.existsSync(t)&&p.statSync(t).isFile()){let n=p.readFileSync(t,`utf-8`).match(/^gitdir:\s*(.+)$/m);if(n?.[1])return s.resolve(e,n[1].trim())}}catch{}return t}getOngoingOperation(e){try{let t=this.resolveGitDir(e);return p.existsSync(s.join(t,`MERGE_HEAD`))?P(`MERGE`):p.existsSync(s.join(t,`CHERRY_PICK_HEAD`))?P(`CHERRY-PICK`):p.existsSync(s.join(t,`REVERT_HEAD`))?P(`REVERT`):p.existsSync(s.join(t,`BISECT_LOG`))?P(`BISECT`):p.existsSync(s.join(t,`rebase-merge`))||p.existsSync(s.join(t,`rebase-apply`))?P(`REBASE`):F}catch(e){return I(`git operation probe: ${e instanceof Error?e.message:String(e)}`)}}async getNearestTagAsync(e){return zW(FW(`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=zW(FW(`git log -1`,await this.execGitAsync([`log`,`-1`,`--format=%ct`,t,`--`],{cwd:e,timeout:2e3}),`absent`));if(n.kind!==`ok`)return n;let r=parseInt(n.value,10);return Number.isNaN(r)?I(`git log -1: unparseable timestamp "${n.value}"`):P(r)}resolveCommonGitDir(e){let t=this.resolveGitDir(e);try{let e=p.readFileSync(s.join(t,`commondir`),`utf-8`).trim();if(e)return s.resolve(t,e)}catch{}return t}getStashCount(e){let t=s.join(this.resolveCommonGitDir(e),`logs`,`refs`,`stash`),n;try{n=p.readFileSync(t,`utf-8`)}catch(e){return e.code===`ENOENT`?P(0):I(`git stash reflog ${t}: ${e instanceof Error?e.message:String(e)}`)}let r=n.trim();return P(r?r.split(`
|
|
190
190
|
`).length:0)}async getRemotesAsync(e){let t=sG(s.join(this.resolveCommonGitDir(e),`config`));if(t===null)return this.readRemotes(e);let{key:n,stamp:r}=t,i=this.remotesByConfig.get(n);if(i!==void 0&&i.stamp===r)return this.remotesByConfig.delete(n),this.remotesByConfig.set(n,i),i.remotes;let a=this.readRemotes(e);for(this.remotesByConfig.set(n,{stamp:r,remotes:a}),a.then(e=>{let t=this.remotesByConfig.get(n);e.kind!==`ok`&&t?.remotes===a&&this.remotesByConfig.delete(n)},()=>{this.remotesByConfig.get(n)?.remotes===a&&this.remotesByConfig.delete(n)});this.remotesByConfig.size>256;){let e=this.remotesByConfig.keys().next().value;if(e===void 0)break;this.remotesByConfig.delete(e)}return a}remotesByConfig=new Map;async readRemotes(e){return qW(await this.execGitAsync(KW,{cwd:e,timeout:2e3}))}repoNameFrom(e,t){let n=ZW(e);return(n===null?null:$W(n))??s.basename(t)}async getRepoRemoteUrl(e){let t=await this.getRemotesAsync(e);if(t.kind!==`ok`)return t;let n=QW(t.value);return n===null?F:P(n)}async execForgeAsync(e,t,n){return pt({bin:e,args:[...t],cwd:n.cwd,env:{...process.env},timeoutMs:n.timeout,category:`forge`})}async resolvePullRequest(e,t){let n=GW(t);return n===`github`?nG(`gh pr view`,await this.execForgeAsync(BW.github,[`pr`,`view`,`--json`,`number,state,url,headRefOid`],{cwd:e,timeout:5e3}),/no (open )?pull requests? found/i,aG):n===`gitlab`?nG(`glab mr view`,await this.execForgeAsync(BW.gitlab,[`mr`,`view`,`--output`,`json`],{cwd:e,timeout:5e3}),/no (open )?merge requests? (found|available)/i,oG):F}isWorktree(e){try{let t=s.join(e,`.git`);return!!(p.existsSync(t)&&p.statSync(t).isFile())}catch{return!1}}async getCoreAsync(e){E(`[GIT-EXEC] Running git status --porcelain=v2 in ${e}`);let t=FW(`git status --porcelain=v2 --branch`,await this.execGitAsync([`status`,`--porcelain=v2`,`--branch`],{cwd:e,timeout:2e3}),`failed`);return t.kind===`ok`?P(iG(t.value)):t}};const lG=(e,t)=>E(t);function uG(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 dG=e=>e===null?{kind:`unknown`}:{kind:`changed`,names:new Set([e])};var fG=class{slots=new Map;counters;logger;closed=!1;constructor(e={}){this.counters=e.counters,this.logger=e.logger??lG}acquire(e,t,n){if(this.closed)return{release:()=>{},refused:[...t.files,...t.dirs.map(e=>e.path)].map(e=>({path:e,reason:`the watcher registry is closed`}))};let r=this.slots.get(e);if(r)return r.refcount++,r.onInvalidate=n,this.makeHandle(r);let i={key:e,watchers:[],refcount:1,debounce:null,onInvalidate:n,targets:t,refused:[]};return this.openWatchers(i),this.slots.set(e,i),this.counters&&(i.refused.length===0?this.counters.watchersOpened++:this.counters.watchRefusals++),this.makeHandle(i)}makeHandle(e){let t=!1;return{refused:e.refused,release:()=>{t||(t=!0,this.slots.get(e.key)===e&&(e.refcount=Math.max(0,e.refcount-1),e.refcount===0&&(this.closeSlot(e),this.slots.delete(e.key))))}}}openWatchers(e){let t=t=>{if(e.debounce!==null){e.debounce.window=uG(e.debounce.window,t);return}let n={window:t,timer:setTimeout(()=>{e.debounce=null;try{e.onInvalidate(n.window)}catch(e){this.logger(`warn`,`watcher invalidate threw: ${e.message}`)}},50)};n.timer.unref(),e.debounce=n},n=e=>n=>{this.logger(`warn`,`watcher error ${e}: ${n.message}`),this.counters&&this.counters.watchErrors++,t({kind:`failed`,reason:`${e}: ${n.message}`})},r=[],i=(e,t)=>{let n=t.message;this.logger(`warn`,`watch failed ${e}: ${n}`),r.push({path:e,reason:n})};for(let r of e.targets.files)try{let i=p.watch(r,{persistent:!1},(e,n)=>t(dG(n)));i.on(`error`,n(r)),e.watchers.push(i)}catch(e){i(r,e)}for(let r of e.targets.dirs)try{let i=r.filenames?new Set(r.filenames):null,a=p.watch(r.path,{persistent:!1},(e,n)=>{i&&(!n||!i.has(n))||t(dG(n))});a.on(`error`,n(r.path)),e.watchers.push(a)}catch(e){i(r.path,e)}e.refused=r}closeSlot(e){e.debounce!==null&&(clearTimeout(e.debounce.timer),e.debounce=null);for(let t of e.watchers)try{t.close()}catch{}e.watchers=[],this.counters&&this.counters.watchersClosed++}size(){return this.slots.size}closeAll(){this.closed=!0;for(let e of this.slots.values())this.closeSlot(e);this.slots.clear()}};function pG(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var mG=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 hG(){return J.observable.box(gG(`unread`),{deep:!1})}function gG(e){let t;return{kind:`pending`,why:e,landed:new Promise(e=>{t=e}),land:t}}function _G(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 vG(e,t){let n=e.reading.get();n.kind===`read`?(0,J.runInAction)(()=>e.reading.set(gG(t))):n.why!==t&&t===`unread`&&(0,J.runInAction)(()=>e.reading.set({...n,why:t}))}function yG(e,t){e.reading.get().kind===`pending`&&_G(e,t)}function bG(e){return typeof e==`object`&&!!e&&e.kind===`pending`}function xG(e){let t=e.reading.get();return t.kind===`read`?t.outcome:t}async function SG(e){for(;;){let t=e();if(!bG(t))return t;await t.landed}}function CG(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),Math.max(0,t));return new Promise((t,i)=>{r.signal.addEventListener(`abort`,()=>t(`deadline`)),e(r.signal).then(()=>t(`answered`),e=>r.signal.aborted?n(e):i(e))}).finally(()=>{clearTimeout(i),r.abort()})}function wG(e){return{current:()=>e}}function TG(e){return SG(()=>e.current())}const EG=`pass`,DG={okMs:5*6e4,failedMs:45e3};function OG(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function kG(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function AG(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function jG(e){let t=[{path:e,filenames:[`HEAD`,`index`]}],n=s.join(e,`refs/heads`);try{p.statSync(n).isDirectory()&&t.push({path:n})}catch{}return{files:[],dirs:t}}function MG(e){return e.find(e=>e.kind===`ok`)?.value.branch}function NG(e){e.missed=!0,vG(e,`unread`)}function PG(e,t){return e.missed&&e.reading.get().kind===`pending`&&_G(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function FG(e,t){let n=xG(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:xG(t)})}function IG(e){return t=>I(`${e} threw: ${String(t)}`)}var LG=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 cG,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Me;let t=e.ledger??new Lk(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 fG({logger:this.logger}),this.ownsWatchers=!0)}getWatcherRegistry(){return this.watchers}getStats(){let e=0;for(let t of this.repos.values())t.holders>0&&e++;return{size:this.repos.size,held:e,hits:this.hits,misses:this.misses,changes:this.changes,watchers:this.watchers.size()}}resolution(e,t){let n=`${e}|${t??``}`,r=Date.now(),i=this.resolutions.get(n);if(i&&r-i.computedAt<3e4)return this.resolutions.delete(n),this.resolutions.set(n,i),i.known;let a;try{a=this.inner.resolveEffectiveGitDir(e,t)}catch(e){a=I(`resolver threw: ${String(e)}`)}for(this.resolutions.set(n,{known:a,computedAt:r}),a.kind===`failed`&&this.logger(`warn`,`git resolve failed (${e}): ${a.reason}`);this.resolutions.size>this.maxRepos;){let e=this.resolutions.keys().next().value;if(e===void 0)break;this.resolutions.delete(e)}return a}declare(e,t,n={},r){let i=this.asked(e,t,n,r);if(i.kind===`not-a-repo`)return wG(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>FG(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n=this.inner.resolveGitDir(e),r={root:e,refresh:new Fk,watcher:this.watchers.acquire(`git:${e}`,jG(n),()=>this.changed(e)),period:new mG(()=>{r.refresh.share(EG,()=>this.refreshPass(r))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,r),r}changedPass(e,t){e.asked.add(t),e.refresh.run(EG,()=>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&&NG(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(EG,()=>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:hG(),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=AG(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(kG(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?r.push(t):t.missed=!0;let i=e.pr,[a,o]=await Promise.all([Promise.all(r.map(t=>this.inner.getGitInfo(e.root,t.options).catch(IG(`git fetch`)))),i!==null&&i.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let s=new Set;r.forEach((e,t)=>{let n=a[t];if(e.missed=!1,_G(e,n),n.kind===`failed`&&s.add(n.reason),n.kind===`ok`)for(let e of PW(n.value))s.add(e)});let c=MG(a),l=i===null||r.length===0?`-`:c===void 0?PG(i,s):this.movePr(e,i,c,o??i.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${r.length} pr=${l}`,OG(n),s.size===0?P(null):I([...s].join(`; `)),Date.now()-t)}prSource(e){let t={period:new mG(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:hG(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(IG(`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?(NG(t),`owed`):(vG(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,_G(t,a.outcome),t.period.landed(pG(DG,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(IG(`PR lookup`)):Promise.resolve(i.kind===`failed`?i:F)).then(i=>{if(t.inFlight?.key===r&&(t.inFlight=null),this.repos.get(e.root)!==e)return;this.prRefreshes.recorded(`${e.root} key=${os(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||(_G(t,i),t.period.landed(pG(DG,i),o))});return t.inFlight={key:r,done:o},o}drop(e){let t=I(`git state dropped: ${e.root}`);for(let n of e.values.values())yG(n,t);e.pr!==null&&yG(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watcher.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},RG=class{static CACHE_DIR=bt();static USAGE_CACHE_DIR=s.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=s.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=s.join(this.LOCKS_DIR,e);if(!p.existsSync(t))return!1;try{let n=p.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return E(`Invalid PID in lock file ${e}, removing stale lock`),p.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(E(`Removing stale lock file ${e} for dead process ${r}`),p.unlinkSync(t),!1):(E(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return E(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=s.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await p.promises.writeFile(n,i,{flag:`wx`}),E(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await be(50);else throw e}return E(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=s.join(this.LOCKS_DIR,e);try{await p.promises.unlink(t),E(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&E(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([p.promises.mkdir(this.CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),p.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){E(`Failed to create cache directories:`,e)}}static createProjectHash(e){return te(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=s.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){E(`Cache for ${e} is locked, waiting...`),await be(75);continue}try{let r=await p.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(E(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(E(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return E(`No shared ${e} usage cache found`),null;E(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await be(75)}}return E(`Failed to read ${e} cache after 3 attempts.`),null}static deserializeDates(e){return Array.isArray(e)?e.map(e=>({...e,timestamp:new Date(e.timestamp)})):e}static async setUsageCache(e,t,n){let r=`${e}.usage.lock`;if(!await this.acquireLock(r)){E(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=s.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await p.promises.writeFile(r,i,`utf-8`),E(`[CACHE-SET] ${e} disk cache stored`)}catch(t){E(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const zG={"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 BG=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 RG.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await RG.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ye({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){E(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){E(`Response too large`),r.destroy(),e(null);return}n+=t}),t.on(`end`,()=>{try{let t=JSON.parse(n),r=t._meta,i={};for(let[e,n]of Object.entries(t))e!==`_meta`&&(i[e]=n);this.validatePricingData(i)?(E(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),E(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(E(`Invalid pricing data structure`),e(null))}catch(t){E(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{E(`Response error:`,t),e(null)})});r.on(`error`,t=>{E(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{E(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return E(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return E(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),E(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(E(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(zG).length} models`),this.executionCache=zG,E(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(zG).length} models`),zG)}static validatePricingData(e){if(!e||typeof e!=`object`)return!1;for(let[,t]of Object.entries(e)){if(!t||typeof t!=`object`)return!1;let e=t;if(typeof e.input!=`number`||typeof e.output!=`number`||typeof e.cache_read!=`number`)return!1}return!0}static async getModelPricing(e){if(this.modelPricingCache.has(e))return E(`[CACHE-HIT] Model pricing cache: ${e}`),this.modelPricingCache.get(e);let t=await this.getCurrentPricing(),n;return n=t[e]?t[e]:this.fuzzyMatchModel(e,t),this.modelPricingCache.set(e,n),E(`[CACHE-SET] Model pricing cache: ${e}`),n}static fuzzyMatchModel(e,t){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(e.toLowerCase()===n)return r;for(let{pattern:e,fallback:r}of[{pattern:[`opus-4-6`,`claude-opus-4-6`],fallback:`claude-opus-4-6-20260205`},{pattern:[`opus-4-5`,`claude-opus-4-5`],fallback:`claude-opus-4-5-20251101`},{pattern:[`opus-4-1`,`claude-opus-4-1`],fallback:`claude-opus-4-1-20250805`},{pattern:[`opus-4`,`claude-opus-4`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet-4-6`,`sonnet-4.6`,`claude-sonnet-4-6`],fallback:`claude-sonnet-4-6`},{pattern:[`sonnet-4.5`,`4-5-sonnet`,`sonnet-4-5`],fallback:`claude-sonnet-4-5-20250929`},{pattern:[`sonnet-4`,`claude-sonnet-4`],fallback:`claude-sonnet-4-20250514`},{pattern:[`haiku-4.5`,`4-5-haiku`,`haiku-4-5`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`haiku`],fallback:`claude-haiku-4-5-20251001`},{pattern:[`opus`],fallback:`claude-opus-4-20250514`},{pattern:[`sonnet`],fallback:`claude-sonnet-4-5-20250929`}])if(e.some(e=>n.includes(e))&&t[r])return t[r];return t[`claude-sonnet-4-5-20250929`]||{name:`${e} (Unknown Model)`,input:3,cache_write_5m:3.75,cache_write_1h:6,cache_read:.3,output:15}}static async calculateCostForEntry(e){let t=e.message?.usage;if(!t)return 0;let n=this.extractModelId(e),r=await this.getModelPricing(n),i=t.input_tokens||0,a=t.output_tokens||0,o=t.cache_creation_input_tokens||0,s=t.cache_read_input_tokens||0,c=i/1e6*r.input,l=a/1e6*r.output,u=s/1e6*r.cache_read,d=o/1e6*r.cache_write_5m;return c+l+d+u}static extractModelId(e){if(e.model&&typeof e.model==`string`)return e.model;let t=e.message;if(t?.model){let e=t.model;if(typeof e==`string`)return e;let n=e;return(typeof n?.id==`string`?n.id:null)||`claude-sonnet-4-5-20250929`}return e.model_id&&typeof e.model_id==`string`?e.model_id:`claude-sonnet-4-5-20250929`}};const VG=/<command-name>\s*([^<\s][^<]*?)\s*<\/command-name>/;function HG(e){if(typeof e==`string`)return VG.exec(e)?.[1]}function UG(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 WG(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 GG(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=UG(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`?HG(WG(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 KG(e){if(e!==void 0)return[e];let t=w();return[d(t,`.config`,`claude`),d(t,`.claude`)].filter(e=>g(e))}async function qG(e){let t=[];for(let n of e){let e=d(n,`projects`),r=await JG(Ia(e,{withFileTypes:!0}));for(let n of r??[])n.isDirectory()&&t.push(d(e,n.name))}return t}async function JG(e){try{return await e}catch(e){if(e.code===`ENOENT`)return;throw e}}async function YG(e,t,n){let r=[],i=[],a=d(t,e,`subagents`);try{let t=(await Ia(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 Ha(t,void 0,void 0);if(s.kind!==`ok`){E(`Failed to check agent file ${t}`);continue}i=rK(i,t,s.value);let c=eK(Ua(s.value,e=>e.subarray(0,Math.max(0,e.indexOf(10))).toString(`utf-8`)));c.kind===`object`&&c.value.sessionId===e&&r.push(t)}}catch(e){E(`Failed to read subagents directory ${a}:`,e)}return{paths:r,longLines:i}}function XG(e){let t=e.message;if((e.type||t?.role||t?.type)!==`user`)return;if(QG(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=WG(t?.content).trimStart();return r.startsWith(`[Request interrupted by user`)?`interrupt`:e.isMeta===!0||e.isCompactSummary===!0||ZG.test(r)?`claude-code`:`prompt`}const ZG=/^<(?:command-name|local-command-std(?:out|err)|bash-(?:input|stdout|stderr))>/;function QG(e){let t=e?.content;return Array.isArray(t)&&typeof t[0]==`object`&&t[0]?t[0].type:void 0}function $G(e){if(!e.timestamp)return null;let t=e.message,n=t?.usage,r=XG(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:GG(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 eK(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 tK(e){let t=eK(e);if(t.kind===`unparsed`)return E(`Failed to parse JSONL line: ${t.reason}`),null;if(t.kind===`blank`)return null;try{return $G(t.value)}catch(e){return E(`Failed to project JSONL line: ${e}`),null}}function nK(e){let t=[];for(let n of e.split(`
|
|
191
191
|
`)){let e=tK(n);e&&t.push(e)}return t}function rK(e,t,n){return n.longLine===0?e:[...e,{path:t,offset:n.start,bytes:n.longLine}]}function iK(e){return e.map(e=>`transcript long line path=${JSON.stringify(e.path)} offset=${e.offset} bytes=${e.bytes}`)}async function aK(e,t,n,r){let i=[],a=t?.cursor,o=t?.value??n,s;for(;;){let t=await Ha(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=rK(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,Ua(c,e=>nK(e.toString(`utf-8`)))),a={offset:l,stamp:s.stamp,ino:c.ino},c.atEnd)return P({folded:{cursor:a,value:o},longLines:i})}}var oK=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}},sK=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:()=>xG(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,vG(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:hG(),holders:0,flight:null,changed:!1,superseding:0,revisit:cK(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();uK(()=>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{_G(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(),yG(e,I(`${this.spec.name} entry dropped`))}};function cK(e,t){if(e===null)return new lK(t.holdReturned);let n=new mG(t.period);return{landed:t=>n.landed(pG(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var lK=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 uK(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function dK(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 fK={okMs:60*1e3,failedMs:10*1e3},pK={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},mK={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function hK(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function gK(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function _K(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const vK={entries:0,cost:0,breakdown:_K(),days:new Map};async function yK(e,t){let n=hK(new Date(gK())),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 BG.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=hK(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...pK};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 bK(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function xK(e){let t=0,n=0,r=_K(),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)??{...pK};bK(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:mK,days:i};let a=r.input+r.output+r.cacheCreation+r.cacheRead;return{sessionInfo:{cost:n,calculatedCost:n,officialCost:null,tokens:a,tokenBreakdown:r},days:i}}function SK(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function CK(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!SK(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...pK};bK(r,t),n.set(e,r)}return n}async function wK(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 TK(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function EK(e,t){(0,J.runInAction)(()=>e.set(t))}var DK=class{sessions=J.observable.map(void 0,{deep:!1});flight=new oK;scans;daySets=new Map;speedFlight=new oK;requestFlight=new oK;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Me,this.ledger=e.ledger??new Lk(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new sK({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${os(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??fK,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=Ma(t);return n={stamp:r,record:this.refreshed(e,t,r)},n};return{usage:async e=>{let t=await r().record;return t.kind===`failed`?t:P(TK(t.kind===`ok`?t.value.sessionInfo:mK,e))},speed:t=>this.observed(e,r,t),today:async e=>{await TG(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return ka;let r=n.failure.get();return r===null?P(TK(n.record?.sessionInfo??mK,t)):I(r)}refreshed(e,t,n){return this.requestFlight.run(`${e}:${n}`,async()=>{let r={hits:0,misses:0},i=Date.now(),a=await this.ingest(e,t,r,n);return this.renderTally.hits+=r.hits,this.renderTally.misses+=r.misses,r.misses>0&&this.usage.recorded(`sid=${os(e)}`,`request`,a,Date.now()-i),EK(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=KG(t),r=this.scans.declare(e,n),i=this.daySet(n);return{current:()=>{let e=r.current();return e.kind===`ok`?P({roots:i.roots,sums:i.sums.read()}):e}}}todayAt(e,t,n){let r=this.sessions.get(t?.session_id??``),i=r?.failure.get()??null;if(i!==null)return I(i);let a=hK(dk(n)),o={...pK},s=e.sums.get(a);s!==void 0&&bK(o,s);let c=SK(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&bK(o,c),s===void 0&&c===void 0?F:P({cost:o.cost,tokens:o.input+o.output+o.cacheCreation+o.cacheRead,tokenBreakdown:{input:o.input,output:o.output,cacheCreation:o.cacheCreation,cacheRead:o.cacheRead},date:a})}observeSpeed(e,t,n){return this.request(e,t).speed(n)}async observed(e,t,n){if(!e)return F;let{stamp:r,record:i}=t();return this.speedFlight.run(`${e}:${r}`,async()=>{let t=await i;if(t.kind===`failed`)return EK(this.hold(e).speed,t),t;let r=dK(t.kind===`ok`?t.value.sessionInfo.tokenBreakdown:null,n),{ring:a}=this.hold(e),o;for(let e of a)e.atMs<r.atMs&&(o===void 0||e.atMs>o.atMs)&&(o=e);a.push(r),a.sort((e,t)=>e.atMs-t.atMs),a.length>64&&a.shift();let s=P({...o!==void 0&&{prev:o},cur:r,samples:[...a]});return EK(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??ka:F}async ingest(e,t,n,r){if(!e)return F;let i=this.see(e)?.record;if(i&&r!==``&&i.transcriptStamp===r)return n.hits++,P(i);if(!t)return i?P(i):F;n.misses++;let a;try{a=await this.flight.run(`${e}:${r}`,async()=>{let n=this.sessions.get(e)?.record;return{prior:n,outcome:await this.refold(e,t,n)}})}catch(t){return I(`usage refold (${e}): ${t instanceof Error?t.message:String(t)}`)}let{prior:o,outcome:s}=a;if(s.kind!==`ok`)return s;let c={files:s.value.files,sessionInfo:s.value.sessionInfo,days:s.value.days,transcriptStamp:s.value.mainStamp,transcriptPath:t},l=this.sessions.get(e)?.record;return l===o?(this.stored(e,c),P(c)):l===void 0?P(c):this.ingest(e,t,n,r)}stored(e,t){let n=this.hold(e);(0,J.runInAction)(()=>this.sessions.set(e,{...n,record:t}))}see(e){let t=this.sessions.get(e);return t&&(t.lastSeenAt=Date.now()),t}hold(e){let t=this.see(e);if(t)return t;let n={lastSeenAt:Date.now(),record:void 0,ring:[],failure:J.observable.box(null),speed:J.observable.box(void 0,{deep:!1})};return(0,J.runInAction)(()=>this.sessions.set(e,n)),n}daySet(e){let t=e.join(`\0`),n=this.daySets.get(t);if(n!==void 0)return n;let r=e.map(e=>d(e,`projects`)+f),i={roots:r,sums:new lS(`today over ${e.join(`,`)}`,()=>CK(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await YG(e,l(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of iK(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 aK(e,r,vK,yK);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 iK(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...xK(i),mainStamp:a})}async scan(e){try{let t=gK(),n=await qG(e),r=[];for(let e of n){let n=await JG(Ia(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=d(e,i),a=await JG(La(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Na(a)})}}let i=[],a={hits:0,misses:0};return await wK(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=${os(e.join(`,`))} sessions=${r.length} read=${a.misses} failed=${i.length}`),i.length>0?I(`usage scan: ${i.length} of ${r.length} sessions could not be read — ${i[0]}`):P({sessions:r.length,read:a.misses})}catch(e){return I(`usage scan: ${e instanceof Error?e.message:String(e)}`)}}sweepStale(){let e=Date.now(),t=hK(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()}},OK=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)}})}},kK=class{sessions;constructor(e,t,n,r=Me,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new OK(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=Ma(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 aK(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${os(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 iK(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??ka}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function AK(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 jK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new kK(void 0,AK,(e.ledger??new Lk(t)).declare({name:`context`,scope:`session`,refresh:[`request`]}),t)}thresholds={LOW:50,MEDIUM:80};getContextUsageThresholds(){return this.thresholds}ratioPercentages(e,t){let n=Math.min(100,Math.max(0,Math.round(e/t*100)));return{percentage:n,contextLeftPercentage:Math.max(0,100-n)}}calculateContextFromHookData(e){let t=e.context_window;if(!t?.current_usage)return E(`No current_usage in hook data, falling back to transcript parsing`),null;let n=t.current_usage,r=t.context_window_size,i=(n.input_tokens||0)+(n.cache_creation_input_tokens||0)+(n.cache_read_input_tokens||0);E(`Native current_usage: input=${n.input_tokens}, cache_create=${n.cache_creation_input_tokens}, cache_read=${n.cache_read_input_tokens}, total=${i} (limit: ${r})`);let a=this.ratioPercentages(i,r);return{totalTokens:i,maxTokens:r,percentage:t.used_percentage==null?a.percentage:Math.round(t.used_percentage),contextLeftPercentage:t.remaining_percentage==null?a.contextLeftPercentage:Math.round(t.remaining_percentage)}}async calculateContextTokensFromTranscript(e,t,n){return this.contextFrom(await this.fold.read(e,t),n)}async getContextInfo(e){let t=this.calculateContextFromHookData(e);return t?P(t):this.calculateContextTokensFromTranscript(e.session_id,e.transcript_path,MK(e))}contextOf(e){let t=this.calculateContextFromHookData(e);if(t)return P(t);let n=this.fold.answer(e.session_id);return n.kind===`pending`?n:this.contextFrom(n,MK(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(E(`No main chain entries with usage data found`),F):(E(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function MK(e){return e.context_window?.context_window_size??2e5}const NK={messageCount:0,nonPrompts:0,recent:[]},PK=new Set([`turn`,`interrupt`,`claude-code`]);function FK(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!PK.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function IK(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 LK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new kK(NK,FK,(e.ledger??new Lk(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){E(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?RK(e,n,await this.fold.read(e,t.transcript_path)):F}metricsOf(e,t){let n=t.cost;if(!n)return F;let r=this.fold.answer(e);return r.kind===`pending`?r:RK(e,n,r)}};function RK(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:IK(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 zK={command:null,todos:[],pending:[],done:[]};function BK(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 VK(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 HK(e,t){if(t.isSidechain)return e;let n=VK(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=BK(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 UK(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>BK(e,t.name),[]),done:e.done}}var WK=class{fold;constructor(e={}){let t=e.logger??Me;this.fold=new kK(zK,HK,(e.ledger??new Lk(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return GK(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:GK(e,t)}};function GK(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(UK(t.value))}function KK(e,t,n,r){return{bin:`tmux`,args:[`-S`,e.socket,...n],timeoutMs:2e3,category:t,stdinInput:r}}function qK(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 JK(e,t,n,r){return qK(D(KK(e,t,n,r)),n)}async function YK(e,t,n,r){return qK(await pt(KK(e,t,n,r)),n)}const XK=3e4;var ZK=class{names;constructor(e={}){let t=e.logger??Me;this.names=new sK({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${os(e.pane)} socket=${os(e.socket)}`,read:QK,every:{okMs:XK,failedMs:XK},maxEntries:64,logger:t,ledger:e.ledger??new Lk(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function QK(e){let t=await YK(e,`tmux`,[`display-message`,`-p`,`-t`,e.pane,`#S`]);if(t.kind!==`ok`)return I(t.reason);let n=t.stdout.trim();return n?P(n):F}const $K=6e4,eq={okMs:$K,failedMs:$K};function tq(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function nq(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var rq=class{name;user;constructor(e={}){let t=e.logger??Me,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:eq,maxEntries:1,logger:t,ledger:e.ledger??new Lk(t)};this.name=new sK({...n,name:`host.name`,read:()=>nq(`name`,()=>tq(C.hostname()))}),this.user=new sK({...n,name:`host.user`,read:()=>nq(`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()}},iq=class{known=new OK(64);refreshes;constructor(e=Me,t=new Lk(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=aq(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=xP(e);return this.refreshes.recorded(`path=${os(e)} stamp=${os(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??ka}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function aq(e){try{let t=p.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Na(t)}catch(e){return`unread:${e.code??`error`}`}}const oq=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function sq(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 cq=class{known=new OK(256);refreshes;constructor(e=Me,t=new Lk(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=Ma(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??ka}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 lq(t);return this.refreshes.recorded(`sid=${os(e)} stamp=${os(n)}`,`request`,i,Date.now()-r),i}};async function lq(e){let t=await uq(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function uq(e){for(let t of[65536,1048576]){let n=await Ka(e,t);if(n.kind!==`ok`)return n;let r=dq(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function dq(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||!oq.test(t))continue;let r=sq(t);if(r!=null)return r}return null}var fq=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const pq=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}},mq=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,hq=e=>cV(e),gq=e=>s.join(e.storage.folder,hq(e.sessionId)),_q=e=>JSON.stringify([e.folder,e.generation]),vq=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var yq=class{sessions;folders=new Map;watched=new Map;faults=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??pq,this.sessions=new sK({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${os(gq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Lk(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`||!mq(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${os(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(_q(e))??this.opened(e);t.holders++;let n=!1;return()=>{n||(n=!0,t.holders--,t.holders===0&&this.closed(t))}}declare(e,t,n){return this.sessions.declare(e,{storage:t,sessionId:n})}supersede(e,t){return this.sessions.supersede({storage:e,sessionId:t})}stats(){return{...this.sessions.stats(),folders:this.watched.size,faults:{...this.faultCounts},lost:this.lost}}close(){this.sessions.close();for(let e of[...this.watched.values()])this.closed(e)}recorded(e){let t={generation:0,identity:null,lost:!1,unusable:null};return this.folders.set(e,t),t}opened(e){let t=this.folders.get(e.folder);if(t===void 0)throw Error(`plugin storage: no key was asked for ${e.folder}`);let n=e.generation===t.generation?t.unusable:null,r=n===null?this.identityOf(e.folder):`gone`;e.generation===t.generation&&(t.identity=r===`gone`?null:r);let i={key:e,folder:t,identity:r,holders:0,handle:this.watchers.acquire(`plugin-storage:${_q(e)}`,{files:[],dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5)};i.sweep.unref(),this.watched.set(_q(e),i);for(let e of i.handle.refused)this.faulted(i,`refused`,e.reason);return n!==null&&this.faulted(i,`unusable`,n),this.sweep(e),i}closed(e){let t=_q(e.key);this.watched.delete(t),this.faults.delete(t),clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>vq(e.storage,n);switch(t.kind){case`unknown`:this.sessions.changed(r);return;case`changed`:{let{names:i}=t;i.has(s.basename(n.folder))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(hq(e.sessionId)));return}case`failed`:this.judged(e,()=>this.faulted(e,`error`,t.reason));return}}judged(e,t){let{key:n,folder:r}=e,i;try{i=this.identityOf(n.folder)}catch(t){this.faulted(e,`error`,`stat failed: ${t.message}`);return}let a=e.identity;if(i!==`gone`&&a!==`gone`&&mq(i,a)){t();return}n.generation===r.generation&&(r.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${os(n.folder)} generation=${n.generation} now=${i===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>vq(e.storage,n)))}faulted(e,t,n){let{key:r,folder:i}=e;this.faults.set(_q(r),`cannot refresh: ${r.folder} ${n}; reload the config or restart the daemon`),this.faultCounts[t]++,r.generation===i.generation&&(i.lost=!0),this.logger(`warn`,`plugin storage fault folder=${os(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>vq(e.storage,r))}async read(e){let t=this.faults.get(_q(e.storage));if(t!==void 0)return I(t);let n=gq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Pk(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${os(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&&hq(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 bq(e){let{logger:t,ledger:n}=e;return{hostService:new rq({logger:t,ledger:n}),gitProvider:new LG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new DK({logger:t,ledger:n}),contextProvider:new jK({logger:t,ledger:n}),metricsProvider:new LK({logger:t,ledger:n}),activityProvider:new WK({logger:t,ledger:n}),tmuxService:new ZK({logger:t,ledger:n}),autoCompact:new iq(t,n),cacheExpiry:new cq(t,n),managedStorage:new yq({watchers:e.watchers,logger:t,ledger:n}),faults:new fq,log:e.logger}}function xq(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&>(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const Sq=`repo-configs.json`;function Cq(e=yt()){return s.join(e,Sq)}const wq=(e=yt())=>xq(e,Sq,{},ZV);function Tq(e,t,n){return{sessionId:e,action:ui,declaration:t,evaluated:n}}function Eq(e,t,n){return e.awaiting.map(e=>{let r=`${e} has a cc-candybar config — run it?`,i=qV.map(r=>xb(`[${r===`approved`?`approve`:`decline`}]`,N([{verb:ui,args:[t,e,r,n.sign(Tq(t,e,r))]}])));return{severity:yb,message:r,lines:[[xb(r,N([{verb:Wr,args:[r]}])),...i]]}})}function Dq(e){return Math.max(1,e-2)}function Oq(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[Ja,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function kq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function Aq(e){return{...Object.fromEntries(my.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:UH(e.preset)}}}const jq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function Mq(e,t){if(!t)return`-`;if(Aa(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return Aa(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const Nq=10*1e3;function Pq(e,t){if(!(t<60))return e*3600/t}function Fq(e,t,n,r){let i=r-t;if(i<50||i>Nq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Iq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Fq(t.input,t.atMs,n.input,n.atMs),i=Fq(t.output,t.atMs,n.output,n.atMs),a=Fq(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 Lq(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>Nq)continue;let o=Fq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function Rq(e,t){let n=ax(e,t),r=[...Wg.flatMap(e=>{let t=n[e];return Gg(t)?[t]:[]})];for(let n of D_(ix(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...zq(e,n.name));return Vq(e,r)}function zq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function Bq(e,t,n){return Vq(e,[...zq(e,t),...n])}function Vq(e,t){let n=uB(e),r=new Map(Gx(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=cB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Hq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=Rq(e,n);return t.set(n,i),i}}function Uq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Wq(e){let t=t=>e.has(t),n=t(`git.staged`)||t(`git.unstaged`)||t(`git.untracked`)||t(`git.conflicts`);return{...t(`git.sha`)&&{showSha:!0},...n&&{showWorkingTree:!0},...t(`git.stash`)&&{showStashCount:!0},...(t(`git.upstream`)||t(`git.tracking`))&&{showUpstream:!0},...t(`git.repoName`)&&{showRepoName:!0},...t(`git.repoUrl`)&&{showRepoUrl:!0},...t(`git.operation`)&&{showOperation:!0},...t(`git.committedAt`)&&{showCommittedAt:!0},...Object.keys(jq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Gq=new WeakMap;function Kq(e){let t=Gq.get(e);return t===void 0&&(t=qq(e),Gq.set(e,t)),t}function qq(e){let t=t=>Uq(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 Jq(e){return Dq(e.termCols??120)}function Yq(e){return Za(Xa(e.claudeConfigDir))}function Xq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Zq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=Kq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(dk(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Yq(a)))])}function Qq(e,t){return[...t.keys()].filter(t=>e.has(t))}function $q(e,t){let n=wG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function eJ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Wq(n),t.workspace?.project_dir]}function tJ(e,t,n,r,i){let a=Kq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return wG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),wG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...eJ(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(Qq(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function nJ(e){let{hookData:t,deps:n}=e,r=Kq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(Yq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function rJ(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 iJ(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=Kq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return ka;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`?ka:_J(n.git,()=>ka),m=n.tmuxSession.kind===`pending`?ka:d(n.tmuxSession),h=n.hostName.kind===`pending`?ka:d(n.hostName),g=n.hostUser.kind===`pending`?ka:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?ka:fJ(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`?ka:sJ(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,cJ),x=u(n.usage,e=>hJ({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>hJ({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,pJ),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=gJ(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:gJ(r.workspace.current_dir)??``,project_dir:gJ(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>gJ(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}},...Aq(a),history:t.history,navigation:{back:t.back},term:{cols:Jq(i)},...c,...s!==null&&{configPath:s},resumeCommand:Oq(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:oJ(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?ka:t})}}function aJ(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function oJ(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function sJ(e,t){let n=e!=null&&t!=null?Pq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function cJ(e){let t=Iq(e),n=Lq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function lJ(e,t){return iJ(e,t,nJ(e))}function uJ({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 ka;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?ka:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function dJ(e,t,n){await Zq(e,t,n),await SG(()=>{let t=rJ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function fJ(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return SP(e.value,t)}}function pJ(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=mJ(e.running),i=mJ(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 mJ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function hJ(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 gJ(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function _J(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(OW(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:kW(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 vJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const yJ={kind:`hidden`},bJ={kind:`shown`};function xJ(e,t){try{return vJ(e,t)?bJ:yJ}catch(e){let t=oS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function SJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function CJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function wJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function TJ({text:e,placement:t,lead:n,trail:r}){return{text:EJ(e),placement:t,...n!==void 0&&{lead:EJ(n)},...r!==void 0&&{trail:EJ(r)}}}function EJ(e){let t=e.blankCopy(e.plain);t.style=Uy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Uy(i).clearMetaAndLinks(),n,r);return t}function DJ(e){let t=wJ(e);if(t.length===1)return e.text;let n=SJ(t);return n.style=e.text.style,n}function OJ(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=SJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:SJ([d,...c],a)},...l.length>0&&{trail:SJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(CJ(u,n,p),[{text:u,...f}])}const kJ=RegExp(`\\x1b\\[[0-9;]*m|${Qd.source}`,`g`);function AJ(e){return Math.max(0,...e.split(`
|
|
193
|
-
`).map(e=>Ws(e.replace(
|
|
194
|
-
`);if(i.length>1)return n();let a=Math.max(0,t.width-AJ(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];CJ(c,c.cellLength+a,n)}),n()}function MJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=NJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Uy(a.style)};if(e.style.link){i();let r=NJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function NJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>PJ(e.frag,n?n.add(e.style):e.style)),i=W.fromFragments(r);return i.end=``,i.overflow=`ignore`,r.length===1?i.style=r[0].style:n!==void 0&&(i.style=n),i}function PJ(e,t){let n=e.copy();return n.style=t,n}function FJ(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 IJ(e,t){let{look:n}=FJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function LJ(e,t){let{layout:n}=FJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function RJ(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 zJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,BJ(e,t,o,n,r,i));return i}function BJ(e,t,n,r,i,a){if(`set`in n){let e=r.get(n.set)??n.set;if(`to`in n)return{kind:`set-literal`,key:n.set,value:n.to,stateVar:e};if(`from`in n){let t=dx(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=Oy.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=dx(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=dx(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:UJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:UJ(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:hx(n),argv:n.run.map(n=>UJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,UJ(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:UJ(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 VJ(e){return e.kind===`do`?VJ(e.head):e}function HJ(e){switch(VJ(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 UJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function WJ(e,t){return e.has(t)?nS(e.read(t)):``}function GJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function KJ(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 qJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Uy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Uy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function JJ(e,t){return Math.max(e.members.indexOf(WJ(t,e.stateVar)),0)}function YJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=WJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=WJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=WJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(JJ(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[GJ(e.text,Ek(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[GJ(e.target,Ek(r))]}],active:!1};case`persist-literal`:{let t=WJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=WJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(JJ(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,GJ(e.name,Ek(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=Ek(r),n=JSON.stringify({run:e.argv.map(e=>GJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,GJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,zI(e.op)]}],active:!1};case`do`:{let o=YJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>YJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,zI(r)]}],active:!1}}}}function XJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,JJ(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 ZJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=FJ(n,`action "${e}"`).store,{display:a,boundValue:o}=XJ(e,VJ(r),t,i),s=WJ(i,`session.id`),{effects:c,active:l}=YJ(r,a.plain,o,i,s,n.signer);return qJ(a,N(c),l)}function QJ(e){return{action:{fn:(t,...n)=>ZJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function $J(e,t){return KJ(`✕`,N([{verb:Rr,args:[WJ(e,`session.id`),t,yi]}]),!1)}function eY(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Zh(e,t,n))})}function tY({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function nY(e,t,n){return new V({color:z.fromRgba(Il(Vh(e,`warning`),t,Xh,n))})}function rY(e,t,n){return V.combine([eY(e,t,n),nY(e,t,n)])}function iY(e,t,n){return eY(e.palette,wg(e.palette,e.disclosure,t,n),n)}function aY(e){let t=z.fromRgba(Vh(e,`background`)),n=W.fromFragments(hh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Vh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const oY=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},sY=e=>new V({bold:e});function cY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>oY(a,V.combine([iY(e,{...n,distribution:t},i),sY(o)]));let o=eY(e.palette,a,i);return(e,t,i,a)=>lY(i,V.combine([o,sY(a)]),r(t,n))}const lY=(e,t,n)=>oY(W.fromFragments([oY(e,t),oY(` `,t),aY(n)]));function uY(e,t){return t===void 0?(e,t,n)=>oY(n):(n,r,i)=>lY(i,void 0,t(r,e))}function dY(e,t,n,r,i){let a=eY(e.palette,i,r);return(e,r,i,o)=>oY(W.fromFragments([oY(o?`[`:` `,a),aY(n(r,t)),oY(o?`]`:` `,a)]))}function fY(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=>pY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function pY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function mY(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function hY(e){return{current:null,drawnAt:e}}function gY(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 _Y(e,t,n){return yY(e,()=>n(gY(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function vY(e,t){return yY(e,()=>(e.current=null,t()))}function yY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function bY(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 xY(e){return new W(e).cellLength}function SY(e){let{width:t,chromeCols:n,padding:r}=FJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function CY(e){let{padding:t,seamCols:n}=FJ(e,`a row fit`);return Math.max(1,SY(e)-(xY(`✕`)+2*t+n))}function wY(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 TY(e,t,n){let r=xY(`←`)+1+xY(`→`)+1,i=wY(e,t,n);return(i.length>1?wY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function EY(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 DY(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 OY(e,t,n){let r=e.compiled.get(t),i=r&&VJ(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 kY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=FJ(a,`picker`).store,d=WJ(u,`session.id`),f=`stateVar`in t?WJ(u,t.stateVar):void 0,p=(e,n)=>{let r=t.options[e];return o({index:e,count:t.options.length},r,n,r===f)},m=i?r.kind===`led`?CY(a):SY(a):1/0,h=(r.kind===`led`?0:xY(`✕`)+1)+c.reduce((e,t)=>e+xY(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?TY(_.map(e=>e.cellLength),m,h):fY(g.entries,g.groups,i),y=parseInt(WJ(u,n.stateVar),10),b=e=>Math.max(0,v.findIndex(t=>t.some(t=>t.indices.includes(e)))),ee=b(f===void 0?-1:t.options.indexOf(f)),x=Number.isInteger(y)?y<0?ee:Math.min(y,v.length-1):0,S=v[x]??[],te=e=>N([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>N([...YJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>qJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[KJ(`✕`,N(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>KJ(e,N([...YJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(KJ(`←`,te(x-1),!1));let w=x<v.length-1?[KJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[EY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[EY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(EY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>xY(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:Py(a),s=` `.repeat(n-xY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(EY([ae(p(r,mY(c,m)),r)],i))}}return ce}function AY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{rk(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=DY(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=OY(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=bY(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]=kY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,cY(u,Ah(void 0),IJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),nY(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function jY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function MY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function NY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=FJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=WJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return EY([],!0);let d=WJ(o,t.stateVar),f=jY(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=N(YJ(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=qJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):qJ(uY(IJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),N(YJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=MY(e=>v(e).cellLength,u,xY(`◀`)+1+y.cellLength+1+xY(`▶`),CY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return EY([...ee(-1).reverse(),KJ(`◀`,h(-1),!1),y,KJ(`▶`,h(1),!1),...ee(1)],!0)}function PY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(rk(`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&&HJ(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=OY(e,n,`carousel`),l=bY(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return NY(n,c,e,cY(l,Ah(void 0),IJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function FY(e,t,n){let r=OY(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 IY(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 LY(e,t,n,r){let i=FY(e,t,n),a=r??WJ(FJ(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,IJ(e,`{{ ${n} }}`))}function RY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(rk(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return aY(LY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function zY(e,t,n){return{swatches:{fn:(r,i)=>{let a=FY(e,r,`swatches`),o=DY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=bY(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]=kY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,dY(s,IJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),nY(s.palette,s.bg,c),u===0?[]:(()=>{let t=jY(l,WJ(FJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[IY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const BY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function VY(e,t,n,r){let i=dg(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Zh(e,n,r)});return[[Th(t).map((n,i)=>{let a=Hh(e,n);return{text:BY[i%BY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Vh(e,`warning`)),a(`error`,Vh(e,`error`))]]]}function HY(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:tY({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 UY(e,t,n,r,i){let a=VY(e,t,n,r).map(e=>HY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
195
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}function
|
|
196
|
-
`),...e]));return o.overflow=`ignore`,o.end=``,o}const
|
|
192
|
+
`),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!oq.test(t))continue;let r=sq(t);if(r!=null)return r}return null}var fq=class{bySession=J.observable.map(void 0,{deep:!1});of(e,t){let n=this.bySession.get(e)?.get(t);return n===void 0?void 0:I(n)}refreshed(e,t,n){let r=this.bySession.get(e);if(n===null&&r?.has(t)!==!0)return;let i=new Map(r);n===null?i.delete(t):i.set(t,n),(0,J.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const pq=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}},mq=(e,t)=>e.dev===t.dev&&e.ino===t.ino&&e.birthtimeNs===t.birthtimeNs,hq=e=>cV(e),gq=e=>s.join(e.storage.folder,hq(e.sessionId)),_q=e=>JSON.stringify([e.folder,e.generation]),vq=(e,t)=>e.folder===t.folder&&e.generation===t.generation,yq=(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 bq=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??pq,this.sessions=new sK({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${os(gq(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new Lk(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`||!mq(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${os(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(_q(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:${_q(e)}`,{files:[],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(_q(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=_q(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=>vq(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(hq(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`&&mq(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${os(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>vq(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=${os(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>vq(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=${os(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=${os(e.key.folder)} generation=${e.key.generation} since=${new Date(n).toISOString()}`),this.sessions.changed(t=>vq(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=${os(e.key.folder)} generation=${e.key.generation} stalled=${Date.now()-t.since}ms`),this.sessions.changed(t=>vq(t.storage,e.key)))}standing(e){let t=this.watched.get(_q(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`?yq(e,t.delivery.since):null;case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return I(t);let n=gq(e),r;try{r=await p.promises.readFile(n,`utf8`)}catch(e){let t=e;return t.code===`ENOENT`?F:I(`${n}: ${t.message}`)}if(r.trim()===``)return F;let i=Pk(r);return i.kind===`failed`?I(`${n}: ${i.reason}`):i}async sweep(e){let t=Date.now(),n=t-2592e6,r=0,i=0,a=()=>`plugin storage sweep folder=${os(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&&hq(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 xq(e){let{logger:t,ledger:n}=e;return{hostService:new rq({logger:t,ledger:n}),gitProvider:new LG({watchers:e.watchers,logger:t,ledger:n}),usageStore:new DK({logger:t,ledger:n}),contextProvider:new jK({logger:t,ledger:n}),metricsProvider:new LK({logger:t,ledger:n}),activityProvider:new WK({logger:t,ledger:n}),tmuxService:new ZK({logger:t,ledger:n}),autoCompact:new iq(t,n),cacheExpiry:new cq(t,n),managedStorage:new bq({watchers:e.watchers,logger:t,ledger:n}),faults:new fq,log:e.logger}}function Sq(e,t,n,r){let i=s.join(e,t),a=()=>{let e;try{e=p.readFileSync(i,`utf8`)}catch(e){return e.code===`ENOENT`?{kind:`ok`,value:n}:{kind:`failed`,reason:`${i}: ${e.message}`}}let t;try{t=JSON.parse(e)}catch(e){return{kind:`failed`,reason:`${i} is not JSON: ${e.message}`}}let a=r(t);return a.kind===`ok`?a:{kind:`failed`,reason:`${i} ${a.reason}`}};return{read:a,update:e=>{let t=a();if(t.kind===`failed`)return t;let n=e(t.value);return n!==t.value&>(i,`${JSON.stringify(n,null,2)}\n`),{kind:`ok`,value:n}}}}const Cq=`repo-configs.json`;function wq(e=yt()){return s.join(e,Cq)}const Tq=(e=yt())=>Sq(e,Cq,{},ZV);function Eq(e,t,n){return{sessionId:e,action:ui,declaration:t,evaluated:n}}function Dq(e,t,n){return e.awaiting.map(e=>{let r=`${e} has a cc-candybar config — run it?`,i=qV.map(r=>xb(`[${r===`approved`?`approve`:`decline`}]`,N([{verb:ui,args:[t,e,r,n.sign(Eq(t,e,r))]}])));return{severity:yb,message:r,lines:[[xb(r,N([{verb:Wr,args:[r]}])),...i]]}})}function Oq(e){return Math.max(1,e-2)}function kq(e,t,n){return Ie({dir:e.project_dir,env:n===void 0?[]:[[Ja,n]],program:`claude`,args:[`--resume`,t,...e.added_dirs.flatMap(e=>[`--add-dir`,e])]})}function Aq(e,t){return{endcaps:e.endcaps,separator:e.separator,colorCompatibility:e.colorCompatibility,wrap:e.autoWrap,padding:e.padding,width:t}}function jq(e){return{...Object.fromEntries(my.map(t=>[t,{effective:e[t]}])),preset:{effective:e.preset,customized:e.presetCustomized,bundled:UH(e.preset)}}}const Mq={prNumber:!0,prState:!0,prUrl:!0,prError:!0,prEarlier:!0};function Nq(e,t){if(!t)return`-`;if(Aa(e))return`pending`;let{prState:n,prError:r,prEarlier:i}=e??{};return Aa(n)?`pending`:n===void 0?r===void 0?i===void 0?`-`:`earlier-${String(i)}`:`failed`:n}const Pq=10*1e3;function Fq(e,t){if(!(t<60))return e*3600/t}function Iq(e,t,n,r){let i=r-t;if(i<50||i>Pq)return;let a=n-e;if(!(a<=0))return a*1e3/i}function Lq(e){let{prev:t,cur:n}=e;if(t===void 0)return;let r=Iq(t.input,t.atMs,n.input,n.atMs),i=Iq(t.output,t.atMs,n.output,n.atMs),a=Iq(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 Rq(e){let{samples:t}=e,n=[];for(let e=1;e<t.length;e++){let r=t[e-1],i=t[e],a=i.atMs-r.atMs;if(a<50||a>Pq)continue;let o=Iq(r.total,r.atMs,i.total,i.atMs);n.push(o??0)}if(n.length!==0)return n.join(`,`)}function zq(e,t){let n=ax(e,t),r=[...Wg.flatMap(e=>{let t=n[e];return Gg(t)?[t]:[]})];for(let n of D_(ix(e,t).node))n.when&&r.push(n.when),n.kind===`segment`&&r.push(...Bq(e,n.name));return Hq(e,r)}function Bq(e,t){let n=e.segments[t];return n?[n.template,n.when,n.bg,n.fg].flatMap(e=>e?[e]:[]):[]}function Vq(e,t,n){return Hq(e,[...Bq(e,t),...n])}function Hq(e,t){let n=uB(e),r=new Map(Gx(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=cB(e,t);s!==void 0&&o.add(s);for(let{reaches:e}of n.ofVariable(t))i.push(...e)}return o}function Uq(e){let t=new Map;return n=>{let r=t.get(n);if(r!==void 0)return r;let i=zq(e,n);return t.set(n,i),i}}function Wq(e,t){for(let n of e)if(n===t||n.startsWith(t+`.`))return!0;return!1}function Gq(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(Mq).some(e=>t(`git.${e}`))&&{showPullRequest:!0}}}const Kq=new WeakMap;function qq(e){let t=Kq.get(e);return t===void 0&&(t=Jq(e),Kq.set(e,t)),t}function Jq(e){let t=t=>Wq(e,t);return{git:t(`git`),session:t(`session.cost`)||t(`session.tokens`)||t(`burn`),today:t(`today`),context:t(`context`)||t(`autocompact`),metrics:t(`metrics`)||t(`burn`),burn:t(`burn`),activity:t(`activity`),tmux:t(`tmux.session`),hostName:t(`host.name`),hostUser:t(`host.user`),cache:t(`cache`),speed:t(`speed`),autocompact:t(`autocompact`),block:t(`block`)}}function Yq(e){return Oq(e.termCols??120)}function Xq(e){return Za(Xa(e.claudeConfigDir))}function Zq(e){return[...e].map(([e,t])=>`${e}:${t===null?`…`:`${t}ms`}`).join(`,`)||`-`}async function Qq(e,t,n){let{hookData:r,deps:i,hints:a}=e,o=qq(e.neededInputPaths),s=r.session_id,c=i.usageStore.request(s,r.transcript_path),l=async(e,t,r)=>{if(!t)return;let a=performance.now();n.set(e,null);let o=null;try{await r()}catch(t){i.log(`error`,`${e} lane threw: ${T(t)}`),o=`${e}: ${String(t)}`}n.set(e,Math.round(performance.now()-a)),i.faults.refreshed(s,e,o)};await Promise.all([l(`session`,o.session,()=>c.usage(r)),l(`today`,o.today,()=>c.today(i.lanes().today)),l(`context`,o.context,()=>i.contextProvider.getContextInfo(r)),l(`metrics`,o.metrics,()=>i.metricsProvider.getMetricsInfo(s,r)),l(`activity`,o.activity,()=>i.activityProvider.getActivityInfo(s,r)),l(`cache`,o.cache,()=>i.cacheExpiry.refresh(s,r.transcript_path)),l(`speed`,o.speed,()=>c.speed(dk(t).getTime())),l(`autocompact`,o.autocompact,async()=>i.autoCompact.window(Xq(a)))])}function $q(e,t){return[...t.keys()].filter(t=>e.has(t))}function eJ(e,t){let n=wG(e);return{git:n,tmux:n,hostName:n,hostUser:n,today:n,sources:new Map(t.map(e=>[e,n]))}}function tJ({cwd:e,hookData:t},n){return[e??t.workspace?.current_dir,Gq(n),t.workspace?.project_dir]}function nJ(e,t,n,r,i){let a=qq(r),o=n.hints.tmux??null,s=[],c=(e,t,n)=>{if(!t)return wG(F);try{return n()}catch(t){return s.push(`${e}: ${T(t)}`),wG(I(`${e}: ${String(t)}`))}};return{lanes:{git:c(`git`,a.git,()=>e.gitProvider.declare(t,...tJ(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($q(r,i).map(r=>[r,c(r,!0,()=>e.managedStorage.declare(t,i.get(r),n.sessionId))]))},faults:s}}function rJ(e){let{hookData:t,deps:n}=e,r=qq(e.neededInputPaths),i=t.session_id,a=n.lanes(),o=(e,t,r)=>{if(!t)return F;let a=n.faults.of(i,e);if(a!==void 0)return a;try{return r()}catch(t){return n.log(`error`,`${e} read threw: ${T(t)}`),I(`${e}: ${String(t)}`)}};return{git:a.git.current(),usage:o(`session`,r.session,()=>n.usageStore.usageOf(i,t)),context:o(`context`,r.context,()=>n.contextProvider.contextOf(t)),metrics:o(`metrics`,r.metrics,()=>n.metricsProvider.metricsOf(i,t)),activity:o(`activity`,r.activity,()=>n.activityProvider.activityOf(i)),tmuxSession:a.tmux.current(),hostName:a.hostName.current(),hostUser:a.hostUser.current(),cache:o(`cache`,r.cache,()=>n.cacheExpiry.expiryOf(i)),speed:o(`speed`,r.speed,()=>n.usageStore.speedOf(i)),autoCompact:o(`autocompact`,r.autocompact,()=>n.autoCompact.stored(Xq(e.hints))),sources:new Map([...a.sources].map(([e,t])=>[e,t.current()]))}}function iJ(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 aJ(e,t,n){let{hookData:r,hints:i}=e,{effective:a,configFacts:o}=t,{configPath:s,...c}=o,l=qq(e.neededInputPaths),u=(e,t)=>{switch(e.kind){case`pending`:return ka;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`?ka:vJ(n.git,()=>ka),m=n.tmuxSession.kind===`pending`?ka:d(n.tmuxSession),h=n.hostName.kind===`pending`?ka:d(n.hostName),g=n.hostUser.kind===`pending`?ka:d(n.hostUser),_=n.autoCompact.kind===`pending`||l.autocompact&&n.context.kind===`pending`?ka:pJ(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`?ka:cJ(d(n.usage)?.session.cost,d(n.metrics)?.sessionDuration):void 0,ee=u(n.speed,lJ),x=u(n.usage,e=>gJ({cost:e.session.cost,tokens:e.session.tokens})),S=u(n.metrics,e=>gJ({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,mJ),ne=u(n.context,e=>({totalTokens:e.totalTokens,contextLeft:e.contextLeftPercentage})),re=u(n.cache,e=>({expiresAt:e})),ie=_J(process.env.HOME??process.env.USERPROFILE),ae=r.workspace?{...r.workspace,current_dir:_J(r.workspace.current_dir)??``,project_dir:_J(r.workspace.project_dir)??``,added_dirs:(r.workspace.added_dirs??[]).map(e=>_J(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}},...jq(a),history:t.history,navigation:{back:t.back},term:{cols:Yq(i)},...c,...s!==null&&{configPath:s},resumeCommand:kq(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:sJ(n.sources.keys(),e=>{let t=n.sources.get(e);return t.kind===`pending`?ka:t})}}function oJ(e){return{sources:String(e.size),sourcesPending:[...e].flatMap(([e,t])=>{let n=t.current();return n.kind===`pending`?[`${e}:${n.why}`]:[]}).join(`,`)||`-`}}function sJ(e,t){let n={};for(let r of e){let[,e,i]=r.split(`.`);(n[e]??={})[i]=t(r)}return n}function cJ(e,t){let n=e!=null&&t!=null?Fq(e,t):void 0;return n===void 0?void 0:{costPerHour:n}}function lJ(e){let t=Lq(e),n=Rq(e);return t!==void 0||n!==void 0?{...t,...n!==void 0&&{history:n}}:void 0}function uJ(e,t){return aJ(e,t,rJ(e))}function dJ({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 ka;if(o.kind!==`ok`)return;let s=(()=>{try{return e.todayAt(o.value,i,a)}catch(e){return n(`error`,`today read threw: ${T(e)}`),F}})();return s.kind===`pending`?ka:s.kind===`ok`?{cost:s.value.cost,tokens:s.value.tokens}:void 0}async function fJ(e,t,n){await Qq(e,t,n),await SG(()=>{let t=iJ(e.deps.lanes());return t.length>0?{kind:`pending`,why:`unread`,landed:Promise.all(t).then(()=>{})}:!0})}function pJ(e,t){switch(e.kind){case`absent`:return;case`failed`:return{error:e.reason};case`ok`:return SP(e.value,t)}}function mJ(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=hJ(e.running),i=hJ(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 hJ(e){return e.length===0?void 0:e.map(e=>`${e.name}:${e.count}`).join(`,`)}function gJ(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 _J(e){return e===void 0||e.length===0||s.sep!==`\\`?e:e.replace(/\\/g,`/`)}function vJ(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(OW(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:kW(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 yJ(e,t){return e===void 0?!0:e.evaluate(t).map(e=>e.plain).join(``)!==`false`}const bJ={kind:`hidden`},xJ={kind:`shown`};function SJ(e,t){try{return yJ(e,t)?xJ:bJ}catch(e){let t=oS(e);return t===void 0?{kind:`failed`,message:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}}function CJ(e,t){let n=W.fromFragments(e);return n.end=``,n.overflow=`ignore`,t!==void 0&&!t.isNull&&(n.style=t),n}function wJ(e,t,n){e.cellLength>t?e.truncate(t,{mode:n.truncate,marker:`…`}):e.cellLength<t&&e.align(n.justify,t)}function TJ({lead:e,text:t,trail:n}){return[...e===void 0?[]:[e],t,...n===void 0?[]:[n]]}function EJ({text:e,placement:t,lead:n,trail:r}){return{text:DJ(e),placement:t,...n!==void 0&&{lead:DJ(n)},...r!==void 0&&{trail:DJ(r)}}}function DJ(e){let t=e.blankCopy(e.plain);t.style=Uy(e.style).clearMetaAndLinks();for(let{start:n,end:r,style:i}of e.spans)t.stylize(Uy(i).clearMetaAndLinks(),n,r);return t}function OJ(e){let t=TJ(e);if(t.length===1)return e.text;let n=CJ(t);return n.style=e.text.style,n}function kJ(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=CJ(e,a).pad(o),d=new W(` `.repeat(o)),f={placement:s,...c.length>0&&{lead:CJ([d,...c],a)},...l.length>0&&{trail:CJ([...l,d],a)}};if(n===`auto`)return[{text:u,...f}];let p={justify:r,truncate:i};return n===`fill`?[{text:u,fill:p,...f}]:(wJ(u,n,p),[{text:u,...f}])}const AJ=RegExp(`\\x1b\\[[0-9;]*m|${Qd.source}`,`g`);function jJ(e){return Math.max(0,...e.split(`
|
|
193
|
+
`).map(e=>Ws(e.replace(AJ,``))))}function MJ(e,t){let n=()=>e.map(e=>({owner:OJ(e),placement:e.placement})),r=[];if(e.forEach(({fill:e},t)=>{e!==void 0&&r.push({at:t,how:e})}),r.length===0||!Number.isFinite(t.width))return n();let i=mb(e.map(OJ),t).split(`
|
|
194
|
+
`);if(i.length>1)return n();let a=Math.max(0,t.width-jJ(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];wJ(c,c.cellLength+a,n)}),n()}function NJ(e,t){let n=[],r=[],i=()=>{if(!r.length)return;let e=PJ(r,t);e.plain.length>0&&n.push(e),r=[]};for(let a of e){let e={frag:a,style:Uy(a.style)};if(e.style.link){i();let r=PJ([e],t);r.plain.length>0&&n.push(r)}else r.push(e)}return i(),n}function PJ(e,t){let n=t!==void 0&&!t.isNull?t:void 0,r=e.map(e=>FJ(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 FJ(e,t){let n=e.copy();return n.style=t,n}function IJ(e,t){if(e.bound===void 0)throw Error(`${t} ran outside a render: no render bound its store and clocks`);return e.bound}function LJ(e,t){let{look:n}=IJ(e,t);if(n===void 0)throw Error(`${t} read the render's look before it was resolved`);return n}function RJ(e,t){let{layout:n}=IJ(e,t);if(n===void 0)throw Error(`${t} read the render's rows before they were laid`);return n()}function zJ(e,t){if(e.bound!==void 0)throw Error(`a render bound a compile another render holds`);return e.bound=t,{[Symbol.dispose]:()=>{e.bound=void 0}}}function BJ(e,t,n,r){let i=new Map,a=Object.entries(t);for(let[t,o]of[...a.filter(([,e])=>!(`do`in e)),...a.filter(([,e])=>`do`in e)])i.set(t,VJ(e,t,o,n,r,i));return i}function VJ(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=dx(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=Oy.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=dx(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=dx(n.insertSegmentFrom,i);return{kind:`layout-op-option`,key:n.persist,anchor:n.anchor,relation:n.relation,options:[...e.members],paletteOf:e.paletteOf,library:e.library}}return{kind:`persist-bounded`,key:n.persist,by:n.by}}if(`copy`in n)return{kind:`copy`,text:WJ(e,n.copy,t)};if(`open`in n)return{kind:`open`,target:WJ(e,n.open,t)};if(`reset`in n)return{kind:`reset`,key:n.reset};if(`doctor`in n)switch(n.doctor){case`run`:return{kind:`doctor-run`};case`fix`:return{kind:`doctor-fix`,check:n.check};case`mark`:return{kind:`doctor-mark`,check:n.check,mark:n.mark}}if(`slash`in n)return{kind:`slash`,line:n.slash};if(`run`in n)return{kind:`run`,name:t,declaration:hx(n),argv:n.run.map(n=>WJ(e,n,t)),env:Object.entries(n.env).map(([n,r])=>[n,WJ(e,r,t)])};if(`undo`in n)return{kind:`undo`};if(`redo`in n)return{kind:`redo`};if(`back`in n)return{kind:`back`};if(`rewind`in n)return{kind:`rewind`};if(`save`in n)return{kind:`save`};if(`preset`in n)return n.preset===`save`?{kind:`preset-save`}:{kind:`preset-delete`,name:WJ(e,n.name,t)};if(`themeDefault`in n)return{kind:`theme-default-save`};let[o,...s]=n.do.map(e=>{let n=a.get(e);if(n===void 0)throw Error(`action "${t}" fires "${e}", which is not declared in this config`);return n});return{kind:`do`,head:o,rest:s}}function HJ(e){return e.kind===`do`?HJ(e.head):e}function UJ(e){switch(HJ(e).kind){case`set-option`:case`set-int`:case`persist-option`:case`layout-op-option`:return!0;case`set-literal`:case`set-bounded`:case`set-cycle`:case`copy`:case`open`:case`persist-literal`:case`persist-bounded`:case`persist-cycle`:case`reset`:case`layout-op`:case`undo`:case`redo`:case`back`:case`rewind`:case`save`:case`preset-save`:case`preset-delete`:case`theme-default-save`:case`doctor-run`:case`doctor-fix`:case`doctor-mark`:case`slash`:case`run`:case`do`:return!1}}function WJ(e,t,n){try{return e(t)}catch(e){throw Error(`Template parse error in actions.${n}: ${e.message}`,{cause:e})}}function GJ(e,t){return e.has(t)?nS(e.read(t)):``}function KJ(e,t){return e.evaluate(t).map(e=>e.plain).join(``)}function qJ(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 JJ(e,t,n=!1){let r=new V({link:t,bold:n?!0:void 0}),i=new W(e.plain,{style:V.combine([Uy(e.style),r])});for(let t of e.spans)i.stylize(V.combine([Uy(t.style),r]),t.start,t.end);return i.overflow=`ignore`,i.end=``,i}function YJ(e,t){return Math.max(e.members.indexOf(GJ(t,e.stateVar)),0)}function XJ(e,t,n,r,i,a){switch(e.kind){case`set-literal`:{let t=GJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,e.value]}],active:t===e.value}}case`set-option`:{let a=n??t,o=GJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-int`:{let a=n??t,o=GJ(r,e.stateVar);return{effects:[{verb:Rr,args:[i,e.key,a]}],active:o===a}}case`set-cycle`:{let t=e.members[(YJ(e,r)+1)%e.members.length];return{effects:[{verb:Rr,args:[i,e.key,t]}],active:!1}}case`set-bounded`:return{effects:[{verb:zr,args:[i,e.key,String(e.by)]}],active:!1};case`copy`:return{effects:[{verb:Br,args:[KJ(e.text,Ek(r))]}],active:!1};case`open`:return{effects:[{verb:Vr,args:[KJ(e.target,Ek(r))]}],active:!1};case`persist-literal`:{let t=GJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,e.value]}],active:t===e.value}}case`persist-option`:{let a=n??t,o=GJ(r,e.stateVar);return{effects:[{verb:Kr,args:[i,e.key,a]}],active:o===a}}case`persist-cycle`:{let t=e.members[(YJ(e,r)+1)%e.members.length];return{effects:[{verb:Kr,args:[i,e.key,t]}],active:!1}}case`persist-bounded`:return{effects:[{verb:qr,args:[i,e.key,String(e.by)]}],active:!1};case`reset`:return{effects:[{verb:Qr,args:[i,e.key]}],active:!1};case`undo`:return{effects:[{verb:ei,args:[i]}],active:!1};case`redo`:return{effects:[{verb:ti,args:[i]}],active:!1};case`back`:return{effects:[{verb:ni,args:[i]}],active:!1};case`rewind`:return{effects:[{verb:ri,args:[i]}],active:!1};case`save`:return{effects:[{verb:Jr,args:[i]}],active:!1};case`preset-save`:return{effects:[{verb:Yr,args:[i]}],active:!1};case`theme-default-save`:return{effects:[{verb:Xr,args:[i]}],active:!1};case`preset-delete`:return{effects:[{verb:Zr,args:[i,KJ(e.name,Ek(r))]}],active:!1};case`doctor-run`:return{effects:[{verb:ai,args:[i]}],active:!1};case`doctor-fix`:return{effects:[{verb:oi,args:[i,e.check]}],active:!1};case`doctor-mark`:return{effects:[{verb:si,args:[i,e.check,e.mark]}],active:!1};case`slash`:return{effects:[{verb:li,args:[i,e.line]}],active:!1};case`run`:{let t=Ek(r),n=JSON.stringify({run:e.argv.map(e=>KJ(e,t)),env:Object.fromEntries(e.env.map(([e,n])=>[e,KJ(n,t)]))}),o=a.sign({sessionId:i,action:e.name,declaration:e.declaration,evaluated:n});return{effects:[{verb:`run`,args:[i,e.name,n,o]}],active:!1}}case`layout-op`:return{effects:[{verb:$r,args:[i,e.key,zI(e.op)]}],active:!1};case`do`:{let o=XJ(e.head,t,n,r,i,a);return{effects:[...o.effects,...e.rest.flatMap(e=>XJ(e,t,void 0,r,i,a).effects)],active:o.active}}case`layout-op-option`:{let r={op:`insert`,segment:n??t,anchor:e.anchor,relation:e.relation};return{effects:[{verb:$r,args:[i,e.key,zI(r)]}],active:!1}}}}function ZJ(e,t,n,r){if(n.length===0)throw Error(`action "${e}" needs a display (the clickable text)`);if(t.kind===`set-cycle`||t.kind===`persist-cycle`)return{display:Si(`action "${e}"`,n,t.members.length,YJ(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 QJ(e,t,n){let r=n.compiled.get(e);if(!r)throw Error(`action "${e}" is not declared in this config`);let i=IJ(n,`action "${e}"`).store,{display:a,boundValue:o}=ZJ(e,HJ(r),t,i),s=GJ(i,`session.id`),{effects:c,active:l}=XJ(r,a.plain,o,i,s,n.signer);return JJ(a,N(c),l)}function $J(e){return{action:{fn:(t,...n)=>QJ(t,n,e),argTypes:[`string`,`liftable`],arity:{kind:`variadic`},returnType:`T`}}}function eY(e,t){return qJ(`✕`,N([{verb:Rr,args:[GJ(e,`session.id`),t,yi]}]),!1)}function tY(e,t,n){return new V({bgcolor:z.fromRgba(t),color:z.fromRgba(Zh(e,t,n))})}function nY({tint:e,text:t}){return new V({bgcolor:z.fromRgba(e),color:z.fromRgba(t)})}function rY(e,t,n){return new V({color:z.fromRgba(Il(Vh(e,`warning`),t,Xh,n))})}function iY(e,t,n){return V.combine([tY(e,t,n),rY(e,t,n)])}function aY(e,t,n){return tY(e.palette,wg(e.palette,e.disclosure,t,n),n)}function oY(e){let t=z.fromRgba(Vh(e,`background`)),n=W.fromFragments(hh.map(n=>new W(`▀`,{style:new V({color:z.fromRgba(Vh(e,n)),bgcolor:t})})));return n.overflow=`ignore`,n.end=``,n}const sY=(e,t)=>{let n=typeof e==`string`?new W(e,{style:t}):e;return n.overflow=`ignore`,n.end=``,n},cY=e=>new V({bold:e});function lY(e,t,n,r,i,a){if(r===void 0)return(n,r,a,o)=>sY(a,V.combine([aY(e,{...n,distribution:t},i),cY(o)]));let o=tY(e.palette,a,i);return(e,t,i,a)=>uY(i,V.combine([o,cY(a)]),r(t,n))}const uY=(e,t,n)=>sY(W.fromFragments([sY(e,t),sY(` `,t),oY(n)]));function dY(e,t){return t===void 0?(e,t,n)=>sY(n):(n,r,i)=>uY(i,void 0,t(r,e))}function fY(e,t,n,r,i){let a=tY(e.palette,i,r);return(e,r,i,o)=>sY(W.fromFragments([sY(o?`[`:` `,a),oY(n(r,t)),sY(o?`]`:` `,a)]))}function pY(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=>mY(e.indices,8).map(t=>[{label:e.label,indices:t}])):[r]}function mY(e,t){return Array.from({length:Math.ceil(e.length/t)},(n,r)=>e.slice(r*t,(r+1)*t))}function hY(e,t){return new W(e).truncate(t,{marker:`…`}).plain}function gY(e){return{current:null,drawnAt:e}}function _Y(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 vY(e,t,n){return bY(e,()=>n(_Y(e,t.segName,t.placementId,t.palette,t.disclosure,t.tint,t.text)))}function yY(e,t){return bY(e,()=>(e.current=null,t()))}function bY(e,t){let n=e.current;try{return t()}finally{e.current=n}}function xY(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 SY(e){return new W(e).cellLength}function CY(e){let{width:t,chromeCols:n,padding:r}=IJ(e,`a row fit`);return Math.max(1,t-n-2*r)}function wY(e){let{padding:t,seamCols:n}=IJ(e,`a row fit`);return Math.max(1,CY(e)-(SY(`✕`)+2*t+n))}function TY(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 EY(e,t,n){let r=SY(`←`)+1+SY(`→`)+1,i=TY(e,t,n);return(i.length>1?TY(e,t,n+r):i).map(e=>[{label:``,indices:e}])}function DY(e,t){let n=[];for(let t of e)n.length>0&&n.push(new W(` `)),n.push(t);let r=W.fromFragments(n);return r.overflow=t?`ignore`:void 0,r.end=``,r}function OY(e,t,n,r,i){let a=e.compiled.get(t);if(!a||a.kind!==n)throw Error(`${i} references action "${t}" which must be ${r}, got ${a?`a ${a.kind} action`:`no such action`}`);return a}function kY(e,t,n){let r=e.compiled.get(t),i=r&&HJ(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 AY(e,t,n,r,i,a,o,s,c=[]){let l=a.compiled.get(e),u=IJ(a,`picker`).store,d=GJ(u,`session.id`),f=`stateVar`in t?GJ(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`?wY(a):CY(a):1/0,h=(r.kind===`led`?0:SY(`✕`)+1)+c.reduce((e,t)=>e+SY(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?EY(_.map(e=>e.cellLength),m,h):pY(g.entries,g.groups,i),y=parseInt(GJ(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=>N([{verb:Rr,args:[d,n.key,String(e)]}]),ne=r.kind===`led`?[]:[{verb:Rr,args:[d,...r.writes.flatMap(([e,t])=>[e,t])]}],re=r.kind===`own`&&r.onPick?ne:[],ie=e=>N([...XJ(l,e,e,u,d,a.signer).effects,...re]),ae=(e,n)=>JJ(e,ie(t.options[n])),C=r.kind===`led`?[]:[qJ(`✕`,N(ne),!1,s)];C.push(...c.map(({glyph:e,option:r})=>qJ(e,N([...XJ(l,r,r,u,d,a.signer).effects,{verb:Rr,args:[d,n.key,String(b(t.options.indexOf(r)))]}]),!1))),x>0&&C.push(qJ(`←`,te(x-1),!1));let w=x<v.length-1?[qJ(`→`,te(x+1),!1)]:[];if(g===void 0){let e=S.flatMap(e=>e.indices);return[DY([...C,...e.map(e=>ae(_[e],e)),...w],i)]}let oe=new V({bold:!0}),se=v.length>1?` ${x+1}/${v.length}`:``,T=S.length===1?[new W(`${S[0].label}${se}`,{style:oe})]:[],ce=[DY([...C,...T,...w],i)];for(let e of S){S.length>1&&ce.push(DY([new W(e.label,{style:oe})],i));let n=Math.max(...e.indices.map(e=>SY(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:Py(a),s=` `.repeat(n-SY(e)+2),c=o===void 0?e:`${e}${s}${o}`;ce.push(DY([ae(p(r,hY(c,m)),r)],i))}}return ce}function jY(e,t){return{picker:{fn:(n,r,i,a,o,...s)=>{rk(`picker "${n}"`,[`closeOnPick`,`paged`,`inBody`],s);let c=OY(e,r,`set-int`,`an int action ({ set, int: true })`,`picker`);if(o===!0&&i===!0)throw Error(`{{ picker "${n}" … }} sets both closeOnPick and inBody; a picker in a body is closed by the body's ✕, so it has no close to fold into a pick`);let l=kY(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=xY(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]=AY(n,l,{key:c.key,stateVar:c.stateVar},o===!0?{kind:`led`}:{kind:`own`,writes:[[c.key,`-1`]],onPick:i===!0},a===!0,e,lY(u,Ah(void 0),LJ(e,`{{ picker }}`),l.paletteOf,t.drawnAt(),u.bg),rY(u.palette,u.bg,t.drawnAt()));return d},argTypes:[`string`,`string`,`bool`],arity:{kind:`variadic`},returnType:`T`}}}function MY(e,t){let n=e.length,r=Math.max(e.indexOf(t),0);return e=>((r+e)%n+n)%n}function NY(e,t,n,r,i){let a=Math.min(Math.floor((t-1)/2),i),o=n,s=0;for(;s<a;){let t=o+e(-(s+1))+1+e(s+1)+1;if(t>r)break;o=t,s+=1}return s}function PY(e,t,n,r,i,a){if(!(`stateVar`in t))throw Error(`carousel references action "${e}", which inserts a segment and holds no current value to centre on — a carousel needs a { set, from } or { persist, from } action`);let o=IJ(n,`carousel`).store;if(!o.has(t.stateVar))throw Error(`carousel references action "${e}", whose key "${t.stateVar}" no variable reads back, so there is no current value to centre on — declare { kind: "state", key: "${t.stateVar}" } among the variables`);let s=n.compiled.get(e),c=GJ(o,`session.id`),{options:l}=t,u=l.length;if(u===0)return DY([],!0);let d=GJ(o,t.stateVar),f=MY(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=N(XJ(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=JJ(g(e),h(e));return _.set(e,n),n},y=a===void 0?v(0):JJ(dY(LJ(n,`{{ carousel }}`),t.paletteOf)({index:f(0),count:u},p(0),p(0),!1),N(XJ(n.compiled.get(a),p(0),void 0,o,c,n.signer).effects)),b=NY(e=>v(e).cellLength,u,SY(`◀`)+1+y.cellLength+1+SY(`▶`),wY(n),i),ee=e=>Array.from({length:b},(t,n)=>v(e*(n+1)));return DY([...ee(-1).reverse(),qJ(`◀`,h(-1),!1),y,qJ(`▶`,h(1),!1),...ee(1)],!0)}function FY(e,t){return{carousel:{fn:(n,...r)=>{let[i,a,...o]=r;if(rk(`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&&UJ(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=kY(e,n,`carousel`),l=xY(t,`{{ carousel }}`);if(l.bg===void 0)throw Error(`{{ carousel }} is not available while segments.${l.segName}'s own "bg:" is being evaluated — a carousel is drawn on that background`);return PY(n,c,e,lY(l,Ah(void 0),LJ(e,`{{ carousel }}`),c.paletteOf,t.drawnAt(),l.bg),s,a)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function IY(e,t,n){let r=kY(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 LY(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 RY(e,t,n,r){let i=IY(e,t,n),a=r??GJ(IJ(e,n).store,i.stateVar);if(!i.options.includes(a))throw Error(`${n} "${t}": "${a}" is not one of its options, so it has no palette to draw`);return i.paletteOf(a,LJ(e,`{{ ${n} }}`))}function zY(e){return{swatch:{fn:(t,...n)=>{let[r,...i]=n;if(rk(`swatch "${t}"`,[`option`],i),r!==void 0&&typeof r!=`string`)throw Error(`swatch "${t}": option must be text, got ${JSON.stringify(r)}`);return oY(RY(e,t,`swatch`,r))},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function BY(e,t,n){return{swatches:{fn:(r,i)=>{let a=IY(e,r,`swatches`),o=OY(e,i,`set-int`,`an int action ({ set, int: true })`,`swatches`),s=xY(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]=AY(r,a,{key:o.key,stateVar:o.stateVar},{kind:`led`},!0,e,fY(s,LJ(e,`{{ swatches }}`),a.paletteOf,c,s.bg),rY(s.palette,s.bg,c),u===0?[]:(()=>{let t=MY(l,GJ(IJ(e,`swatches`).store,a.stateVar));return[{glyph:`◀`,option:l[t(-1)]},{glyph:`?`,option:l[LY(n().getTime(),u,t(0))]},{glyph:`▶`,option:l[t(1)]}]})());return d},argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`T`}}}const VY=[`~/code`,`main`,`opus`,`42%`,`5m`,`$1.20`];function HY(e,t,n,r){let i=dg(e,n,r),a=(t,n)=>({text:t,colour:n,ink:Zh(e,n,r)});return[[Th(t).map((n,i)=>{let a=Hh(e,n);return{text:VY[i%VY.length],colour:a,ink:t.shade.text(e,n.hue,a,r)}})],[[a(`▾ open`,i.state),a(`menu`,i.plane)],[a(`warn`,Vh(e,`warning`)),a(`error`,Vh(e,`error`))]]]}function UY(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:nY({tint:n,text:r})})}))),r=[],i=0;for(let{gap:e,cell:a}of n){if(i+=e.length+a.cellLength,i>t)break;e!==``&&r.push(new W(e)),r.push(a)}return r}function WY(e,t,n,r,i){let a=HY(e,t,n,r).map(e=>UY(e,i)),o=W.fromFragments(a.flatMap((e,t)=>t===0?e:[new W(`
|
|
195
|
+
`),...e]));return o.overflow=`ignore`,o.end=``,o}function GY(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(rk(`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}=LJ(e,`{{ themePreview }}`);return WY(r===void 0?a:RY(e,r,`themePreview`),o,{...xY(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),wY(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const KY=e=>e.slice(e.lastIndexOf(`.`)+1),qY=(e,t)=>{let n=new W(KY(e));return n.truncate(t,{marker:`…`}),n.plain};function JY(e,t){let n=e.map(e=>e.map(({name:e})=>SY(KY(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 YY(e,t,n,r){let i=JY(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new W(` ${qY(s,i)} `,{style:nY(Pg(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 XY=`layoutPreview`;function ZY(e,t){return{[XY]:{fn:()=>YY(RJ(e,`{{ layoutPreview }}`),LJ(e,`{{ layoutPreview }}`).decor,t.drawnAt(),wY(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function QY(e,t,n,r){let i=xY(r.activeSegment,`{{ menu }}`),a=r.action,o=OA(i.placementId,e,n.key),s=jA(o),c=DA(e),l=IJ(a,`menu`).store,u=GJ(l,o)===c,d=GJ(l,`session.id`),f=u?yi:c,p=qJ(Si(`{{ menu "${e}" }}`,t,2,+!!u),N([{verb:Rr,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=dg(i.palette,i.disclosure,t).plane,l=kY(a,e,`menu`);return AY(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,yi],[s,`0`]],onPick:n.closeOnPick},n.paged,a,lY(i,n.distribution,LJ(a,`{{ menu }}`),l.paletteOf,t,c),rY(i.palette,c,t))})():[]),p}const $Y=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function eX(e,t){let n=t[t.length-1],r=$Y(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:FA(r??{})}}function tX(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=eX(t,n);return QY(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function nX(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=rX(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 rX(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 iX(e){let t={fn:(()=>{let t=xY(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:(()=>xY(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=xY(e,`{{ keptOn }}`),i=Dl(r,t),a=Dl(r,n),o=vc(Rl(i,R.TRUECOLOR),Rl(a,R.TRUECOLOR)),s=Math.min(Xh,Math.max(o,3));return(Ll(i,e.drawnAt(),(e,t)=>vc(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i=VO(()=>xY(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),a={fn:((e,t,n,r,a,o,...s)=>{let c=o===void 0?void 0:[o,...aX(s)];return nX({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 aX(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 oX(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>wk.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const sX={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},cX=new WeakMap;function lX(e){let t=cX.get(e);return t===void 0&&(t=uX(e),cX.set(e,t)),t}function uX(e){let t=new Map(Gx(e)),n=uB(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:sX[t.kind]])),i=new Map([...t].map(([e,t])=>[e,oX(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 dX(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 dX(e){let t=new Map;return e.map(e=>{let n=`${e.place}.${e.band}`,r=t.get(n)??0;return t.set(n,r+1),{line:e,row:`${n}#${r}`}})}const fX=e=>e.kind===`failed`?yJ:e;function pX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function mX(e,t){let n=[],r=[],i;for(let a of t)(a.band===`own`?n:r).push(a),i??=a.cells.find(t=>t.placement.id===e)?.placement.ground;return{drawing:i===void 0?null:{own:n,opened:r.length>0,ground:i},deeper:r}}function hX(e){return{...e,cells:e.cells.map(TJ)}}function gX(e,t){let n=t.flatMap(e=>e.filter(e=>e.place===`above`)),r=t.map(e=>e.filter(e=>e.place===`flow`));return[...n,..._X(e,r)]}function _X(e,t){switch(e){case`vertical`:return t.flatMap(e=>e);case`horizontal`:return t.reduce((e,t)=>Math.max(e,t.length),0)===0?[]:[{cells:t.flatMap(e=>e[0]?.cells??[]),band:`own`,place:`flow`},...t.flatMap(e=>e.slice(1))]}}function vX(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:gX(e.direction,e.children.map((t,i)=>n(t,[...r,yX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function yX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:S_[e.direction]}}const bX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ah(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,O_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),gX(e.direction,e.children.map((n,r)=>t.renderChild(n,fX(t.gate),yX(e,r))))}},xX={drop:e=>e.place,above:()=>`above`},SX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},CX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:C_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,k_(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,wX(e,t))};function wX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=Ok(t.scope,e.settings);if(t.gate.kind===`failed`)return AX(e,r,t,t.gate.message);try{let i=t.placement(e),a=pX(t.gate,i.gate());if(a.kind===`failed`)return AX(e,r,t,a.message);if(a.kind===`hidden`)return[];let o=i.bodyGate(),s=o.kind===`failed`&&a.kind===`pending`?a:o;if(s.kind===`failed`)return AX(e,r,t,s.message);let c=Pb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:qj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?TX(f.variable):EX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?DX(p.segment,u):OX(e,r,t,p.variable,c,d,u);if(m===null)return[];let{styles:h,inline:g,drops:_}=m,v=e.opens,y=v===void 0?[]:t.renderBody(v.body,d?a:yJ,h.disclosure).map(e=>({...e,place:xX[v.placement](e)})),b=(e,t,n)=>OJ(MJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?SX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(kX(wJ(e)))),h.trigger,0)),ne=(e,t)=>e.band===`own`?t===ee?x:te:[],re=y.map((e,t)=>({cells:[...ne(e,t),...e.cells],band:`deeper`,place:e.place})),ie=[...S,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ie.flatMap(e=>e.cells),...y.flatMap(ne)].flatMap(wJ)),[...ie,...re]}catch(n){return AX(e,r,t,n.message??String(n))}}const TX=e=>({kind:`waiting`,variable:e});function EX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=oS(e);if(t===void 0)throw e;return TX(t.variable)}}function DX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:uX(MJ(r,c)).map((e,t)=>({cells:OJ(e,{...l,lead:t===0?MJ(i,c):[],trail:t===0?MJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:OJ(MJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function OX(e,t,n,r,i,a,o){n.waited(r);let s=n.lastDrawn(e.id);if(s?.kind===`hidden`)return null;let c=n.decorations(e,i),l=a?c.trigger:c.closed,u=MJ(jX(e.lead,e,t,n),l),d=MJ(jX(e.trail,e,t,n),l);return{styles:c,inline:(s===void 0||s.drawing.own.length===0?[[`auto`]]:s.drawing.own.map(e=>e.cells.map(e=>e.text.cellLength))).map((e,t)=>({cells:e.flatMap((e,n)=>{let r=t===0&&n===0;return OJ(MJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function kX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function AX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:OJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:qj(n.palette)},lead:jX(e.lead,e,t,n),trail:jX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function jX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=oS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const MX={container:bX,segment:CX};function NX(e){return MX[e]}var PX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?FX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const FX={kind:`hidden`},IX={palette:`theme`,style:`style`,effect:`effect`},LX=Oy.get(`colorCompatibility`),RX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function zX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function BX(e){if(e.ok)return e.value;throw e.error}const VX=e=>({read:()=>e}),HX=ph({basePalette:fh,palette:fh,decor:Dg});var UX=class{evaluated=0;memory=new PX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&HX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=Ek(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(LX);return typeof e==`string`&&d_(e)?e:`truecolor`});let i=(0,J.observable)(RX,void 0,{deep:!1});this.facts=i;let a=this.look,o=this.phase,s=()=>this.layout.read();this.binding={store:e,registry:t,get width(){return i.width},get chromeCols(){return i.chromeCols},get padding(){return i.padding},get seamCols(){return i.seamCols},get look(){return o.ruling?void 0:a.get()},get layout(){return o.ruling?void 0:s}},this.layout=this.derive(`layout`,n.layoutReadsInstant,()=>{let e=n.roots.get(i.preset),t=a.get().palette;return vX(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jI(e);return i===void 0?[]:[{name:i,address:n,palette:Pb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>f_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=mA(e);return t===void 0?fA(e)===void 0?tA(this.view.get().payload(),e):tA(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[IX[e]];if(t.kind===`decided`)return KX(t.name,null,null);let r=JX(this.source,e,t.source);if(this.source.instant.has(r.template))return{kind:`per-draw`,rule:r};let i=this.rule(r.template);switch(i.kind){case`named`:{let t=null;return n=YX(this.source,e,i.name,r.where,e=>{t=e}),KX(n,t,null)}case`pending`:return KX(n??Qg[e],null,i.variable);case`failed`:return n=Qg[e],KX(n,$g(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!qX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??Qg[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return xJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>vY(this.source.activeSegment,()=>xJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new XX(this,e),this.placements.set(e,t)),t}rule(e){let t=this.rules.get(e);return t===void 0&&(t=this.derive(`rule`,this.readsInstant(e),()=>{this.phase.ruling=!0;let t=this.source.runtime.bound===this.binding?null:RJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=oS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:zX(e)}),BX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function WX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new UX(t,n,e,r);return e.views.set(t,a),a}function GX(e,t){let n=e.views.get(t);if(n===void 0)throw Error(`a store was drawn before its view was bound (bindView): its inputs have no source`);return n}const KX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),qX=(e,t)=>e.kind===`settled`?t.kind===`settled`&&e.name===t.name&&e.warning===t.warning&&e.waited===t.waited:t.kind===`per-draw`&&e.rule===t.rule;function JX(e,t,n){let r=e.globalExpressions.get(t)?.get(n);if(r===void 0)throw Error(`the ${t} rule ${JSON.stringify(n)} reached the view but no compiled template exists — the compile and the resolution disagree about isExpression`);return r}function YX(e,t,n,r,i){switch(t){case`palette`:return zb(n,r,i).name;case`style`:return Yg(n,e.styles).name;case`effect`:return a_(n).name}}var XX=class{where=ZX(ph({palette:fh,region:Tg}));ground=ZX(ph({colours:$X,bodyOpen:fh}));opened=ZX(ph({colours:$X,open:fh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ok(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?VX(bJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>vY(r,()=>xJ(a,i))),this.open=d===void 0?VX(yJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>vY(r,()=>xJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return nZ(r,t,n,a,e.registry.drawnAt(),o,s,i)}),this.body=e.derive(`${t.id} body`,e.readsInstant(c),()=>{let{colours:e,bodyOpen:n}=this.ground.get();return rZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?VX(aZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return iZ(r,t,e,n,l,u,i)})}gate(){return this.ownGate.read()}bodyGate(){return this.open.read()}evaluate(e,t){this.where.set({palette:e,region:t});let n=this.colours.read();this.ground.set({colours:n,bodyOpen:this.open.read().kind===`shown`});let r=this.body.read();return this.opened.set({colours:n,open:r.open}),sZ(n,r,this.affixes.read())}};function ZX(e){let t=J.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,J.runInAction)(()=>t.set(e)),get:()=>t.get()}}const QX=(e,t)=>e.hex===t.hex,$X=ph({palette:fh,drawnAt:fh,tint:QX,text:QX,bg:QX,disclosure:Og});function eZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const tZ=e=>dg(e.palette,e.disclosure,e.drawnAt);function nZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Pg(n,r,i)};return _Y(e,eZ(t,c),e=>{let t=Yj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function rZ(e,t,n,r,i,a){return _Y(e,eZ(t,n),e=>(e.bg=i?tZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function iZ(e,t,n,r,i,a,o){return _Y(e,eZ(t,n),e=>(e.bg=r?tZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const aZ={lead:[],trail:[],drops:[]};function oZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return eY(t,tZ(e).state,n)},get band(){return eY(t,tZ(e).plane,n)},get close(){return rY(t,tZ(e).state,n)},disclosure:r}}function sZ(e,t,n){return{styles:oZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?tZ(e).shortfalls:[]}}function cZ(e,t,n,r,i,a,o){let s=nZ(e,t,n,r,i,void 0,void 0,o);return sZ(s,rZ(e,t,s,a,!1,o),aZ)}function lZ(e,t,n,r,i){return oZ(nZ(e,t,n,r,i,void 0,void 0,{}))}function uZ(e,t){return{payload:()=>e,selections:()=>t}}function dZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Vk(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function fZ(e,t){switch(M_(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function pZ(e,t,n,r,i){switch(n.kind){case`literal`:e.declareLiteral(t,n.value);break;case`dropped`:e.declareFailedDocument(t,n.reason);break;case`source`:e.declareSourceDocument(t);break;case`input`:e.declareInput(t,n.path,n.type??`string`,n.default,i);break;case`env`:e.declareEnv(t,n.name,n.default);break;case`file`:e.declareFile(t,n.path,{readMode:n.readMode,cache:dZ(n.cache),parse:fZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:dZ(n.cache),parse:fZ(n.parse,n.default)});break;case`template`:e.declareTemplate(t,n.template,{type:n.type??`string`,varDefault:n.default,derivation:i});break;case`time`:e.declareTime(t,{format:n.layout,varDefault:n.default});break;case`state`:e.declareState(t,{key:n.key,...n.default!==void 0&&{varDefault:n.default}});break}}function mZ(e,t){let n=JS.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function hZ(e,t,n){let{compiled:r,loadWarnings:i}=_Z(e,t,n.cwd,gZ(n.signer),xZ);return{...r,loadWarnings:i}}const gZ=e=>(t,n)=>SZ(n,e);function _Z(e,t,n,r,i=xZ){let a=vZ(e),o=yZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:bZ(e,t,n,i)}}function vZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of ky)n in t&&r.set(e,n);for(let[t,n]of R_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...mB(e)].sort(([e],[t])=>e<t?-1:1)}}function yZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function bZ(e,t,n,r){let i=cX(e),a=mB(e),o=[];for(let[s,c]of Gx(e))if(r.has(i.get(s)))try{pZ(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const xZ=new Set([`directory`,`view`]);function SZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>FJ(i,`drawnAt`).registry.drawnAt(),o=hY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=tx(e.presets),u=bI(e),d=[e=>zY(i,o,e.now)],f=Tk({extraFuncs:{...QJ(i),...RY(i),...AY(i,o),...PY(i,o),...WY(i,o),...XY(i,o),...eX(s),...rX(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=mZ(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=zJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=H_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>J_(t,e,a,t=>String(FJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return NX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=ix(e,t);S.set(t,x(n,r))}let te=new Map(Wg.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of gB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:TZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:sB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:Sk(d)},re=yB(ne),ie=[...S.values()].flatMap(wZ(y)).some(e=>re(m.get(e))),ae=ie?yB({...ne,clock:new Set([...ne.clock,YY])}):re;return{segments:y,roots:S,activeSegment:o,menuRuntime:s,globalExpressions:te,instant:new Set([...m].flatMap(([e,t])=>ae(t)?[e]:[])),layoutReadsInstant:ie,styles:e.styles,runtime:i,views:new WeakMap}}function CZ(e){return Object.entries(e.segments).flatMap(([t,n])=>[n.when,n.bg,n.fg,n.template].some(t=>t!==void 0&&e.instant.has(t))?[t]:[])}const wZ=e=>t=>{let n=[];return vX(t,e=>(n.push(e),!0)),n.flatMap(t=>[...t.when===void 0?[]:[t.when],...t.kind===`segment`&&e[t.name].when!==void 0?[e[t.name].when]:[]])};function TZ(e,t,n){try{return e(n)}catch(e){throw Error(`${t} is not a valid template: ${e instanceof Error?e.message:String(e)}`)}}const EZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function DZ(e,t,n,r,i){let a=OZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function OZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Qg[e];case`failed`:return r({kind:`rule`,slot:e,message:$g(t.where,e,`the rule failed — ${n.error}`)}),Qg[e]}}function kZ(e){return AZ(e).filter(e=>!e.name.startsWith(SA)).map(e=>e.id)}function AZ(e){return e.kind===`container`?e.children.flatMap(AZ):[e,...e.opens===void 0?[]:AZ(e.opens.body)]}function jZ(e,t,n,r,i,a,o,s,c=XH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return WX(t,n,r,uZ(l,c)),NZ(e,t,n,r,l,a,o,s,c)}function MZ(...e){return jZ(...e).text}function NZ(e,t,n,r,i,a,o,s,c){try{var l=ja();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new eb(``),g=h.clockAt(a,t_[c.animationSpeed]);l.u(pk(a,g.anim));let _=GX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:cb(v),padding:v.padding,seamCols:lb(v),preset:c.preset},i);let y=_.evaluated;l.u(RJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:wh[c.variation],shade:Sh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,mX),ne=_.memory.from(S),re=new Set,ie={held:e=>ne?.rules.get(e),waited:e=>re.add(e),settled:te.rule},ae=new Map,C=e=>{let n=_.slot(e);if(ae.set(e,n.kind===`settled`?`kept`:`per-draw`),n.kind===`settled`)return n.warning!==null&&p({kind:`rule`,slot:e,message:n.warning}),n.waited!==null&&re.add(n.waited),n.name;let r=YX(t,e,DZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:oe,effect:se}=_.selections(),T=w.kind===`decided`?w:zb(C(`palette`),``,EZ),ce=oe.kind===`decided`?oe:Yg(C(`style`),e.styles),le=se.kind===`decided`?se:a_(C(`effect`)),ue=T.value,de=Ib(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Yv(c.idleSince,c.menuTimeout,a),pe=Vh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Zh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:mX,hold:hX},me);u?.clear();let ge=t=>e.segments[t],_e=e=>{for(let t of e.shortfalls)m.add(t);return e},ve=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>_e(t.evaluate(e,n))}},ye=(e,i,a)=>{let o=i.kind===`hidden`?i:pX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${kZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:de,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:ve,evaluateOnce:(e,n,i,o)=>_e(cZ(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,Mg(a,n)),renderBody:(e,t,n)=>ye(e,t,Ng(n)),closeDisclosure:e=>$J(n,e),placed:(e,t)=>te.placed(e,he.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>lZ(t.activeSegment,e,n,a,r.drawnAt())};return NX(e.kind).render(e,c)},be=t.roots.get(b);if(be===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${$b}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=dX(ye(be,bJ,jg(x))).map(({line:e,row:t})=>{let n=jJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...pb(n.map(e=>e.owner),v,he.row(t,r,n))}});he.drawn(),te.commit();let Se=xe.filter(e=>e.kind===`menu`).length,Ce=xe.some(e=>e.moves)?`moves`:Se>0||_.selections().effect.kind===`expression`||ee||AZ(be).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:xe.map(e=>e.text).join(`
|
|
199
|
-
`),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*
|
|
200
|
-
`)||null}function qZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vH(t.layers,VH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??VH,l=a.find(e=>e.path===t.home)?.raw??{},u=new yS,d=new aA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=_Z(o,d,e,r.compile??gZ(r.signer),ZZ),n.push(...f.loadWarnings);let t=d.view();n.push(...bZ(o,t,e,QZ)),t.dispose(),MU(o),eL(o),p=JZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Hq(o),authoredRoots:WZ(c,l),fileHeldSettings:vU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>IZ(e.raw,c)).map(e=>[`${e.kind}:${e.name}`,e])).values()],plugins:{checkout:s.checkout,roots:s.roots,loaded:[...s.rendering.values()],dropped:[...s.dropped,...a.flatMap(e=>e.plugins.dropped)],unreached:s.unreached,reached:s.reached,rendering:s.rendering},sources:p}}function JZ(e,t,n){let r=new Map,i=new Map;for(let[a,o]of Object.entries(e.variables)){if(o.kind!==`source`)continue;let e=r.get(o.storage);e===void 0&&(e=t.keyFor(o.storage),r.set(o.storage,e),n.own(t.watch(e))),i.set(a,e)}return i}function YZ(e,t,n,r){let i=performance.now(),a=rH(wq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[uH(e,t),cH(a),QV(o)],l,u=null;try{l=qZ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof Q_&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:KZ(c),state:null,error:e instanceof Q_||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:KZ(c),state:l,error:null}}function XZ(e,t,n){return qZ(e,{layers:[],home:``,repo:t},[],n)}const ZZ=new Set([`directory`]),QZ=new Set([`view`]);function $Z(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new LZ;bZ(e.config,l,t,QZ);let d=()=>YH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),$q(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});WX(e.compiled,l.variableStore,l,_);let v=(0,J.reaction)(()=>{let{sources:t,...n}=m.get().lanes;return[_.payload(),_.selections(),l.published(),e.registry.published(),...[...Object.values(n),...t.values()].map(e=>e.current())]},()=>o(c),{equals:J.compareShallow,fireImmediately:!0,onError:e=>s(`error`,`session view change threw sid=${JSON.stringify(c)}: ${String(e)}`)});return{sessionId:c,state:e,store:l.variableStore,registry:l,holds:u,source:_,requested:e=>h(e,d()),facts:()=>m.get().facts,lanes:()=>m.get().lanes,lastRenderCellsBySegment:new Map,retire:v,dispose:()=>(g(),v(),u.close(),l.dispose())}}var eQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{};let{dir:n,name:r}=Xx(Cq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{files:[],dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??SZ(t,this.deps.signer)}accountedBytes(){let e=new Set([...this.entries.values()].map(e=>e.state.compileKey));return this.entries.size*3145728+e.size*10485760+this.views.size*2621440}getOrCreate(e,t,n){let r=UZ(e,t,n),i=this.entries.get(r);if(i)return this.entries.delete(r),this.entries.set(r,i),i;let a=this.load(e,t,n);a.state!==null&&this.log(`info`,BZ(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,failedFile:null,lastError:a.error,lastWarning:a.warning,state:a.state??XZ(t,a.repos.plugins,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=ja();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(UZ(t,n,r));if(a!==void 0&&s?.state===a.state)return;let c=i.u(this.hold(t,n,r));this.viewOf(c.entry,c.state,o,`click`)}catch(e){i.e=e}finally{i.d()}}pin(e){this.pins.set(e,(this.pins.get(e)??0)+1);let t=!1;return()=>{if(t)throw Error(`render-cache pin released twice`);t=!0;let n=(this.pins.get(e)??0)-1;n>0?this.pins.set(e,n):this.pins.delete(e)}}viewOf(e,t,n,r){let{sessionId:i}=n,a=this.views.get(i);if(a?.state===t)return this.views.delete(i),this.views.set(i,a),a.requested(n),a;this.views.delete(i);let o=a!==void 0&&this.leaseOf(a).read,s;try{s=this.opened(e,t,n,o,r)}finally{a!==void 0&&this.retireView(a,`moved`)}return this.fit(e),s}opened(e,t,n,r,i){let{sessionId:a}=n,o;try{o=$Z(t,e.cwd,n,{sessionState:this.deps.sessionState,declare:this.deps.declare,source:this.deps.source,changed:e=>this.observers.onViewChanged?.(e),log:this.log})}catch(e){throw this.openFailures.set(a,{error:e,facts:n}),e}return this.openFailures.delete(a),this.views.set(a,o),this.viewHolds.set(o,{entry:e,holders:0,retired:null,read:r}),this.log(`info`,`session view opened sid=${JSON.stringify(a)} by=${i} cwd=${e.cwd} views=${this.views.size}`),o}leaseOf(e){let t=this.viewHolds.get(e);if(t===void 0)throw Error(`render-cache view never served`);return t}retireView(e,t){this.views.get(e.sessionId)===e&&this.views.delete(e.sessionId),e.retire();let n=this.leaseOf(e);n.retired={reason:t,held:n.holders},this.reclaimView(e,n)}reclaimView(e,t){t.retired===null||t.holders>0||(this.viewHolds.delete(e),this.log(`info`,`session view closed sid=${JSON.stringify(e.sessionId)} reason=${t.retired.reason} released=${e.dispose()} held=${t.retired.held} views=${this.views.size}`))}armSweep(){this.sweep===null&&(this.sweep=setInterval(()=>this.releaseIdle(),15e4),this.sweep.unref?.())}releaseIdle(){for(let[e,t]of this.viewHolds)t.retired!==null||this.pins.has(e.sessionId)||(t.read?t.read=!1:this.retireView(e,`idle`));for(let e of this.openFailures.keys())this.pins.has(e)||this.openFailures.delete(e);this.entries.size===0&&this.sweep!==null&&(clearInterval(this.sweep),this.sweep=null)}close(){if(this.closed)return;this.closed=!0,this.sweep!==null&&clearInterval(this.sweep),this.sweep=null,this.answersWatch.release();let e=this.entries.size;for(let[e,t]of this.entries)this.drop(e,t,`close`);this.log(`info`,`render-cache closed entries=${e} deferred=${this.stats.retired}`)}load(e,t,n){if(this.closed)throw Error(`render cache used after close`);return YZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,HZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,BZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let n=GZ(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const tQ=16384;var nQ=class e{startedAt=new Date;requestsTotal=0;requestsErrored=0;requestsTimedOut=0;inFlight=0;unknownHookFields=new Set;firstSightOfUnknownHookField(e){let t=!this.unknownHookFields.has(e);return this.unknownHookFields.add(e),t}watchersOpened=0;watchersClosed=0;watchRefusals=0;watchErrors=0;subprocessTotal=0;subprocessInFlight=0;subprocessCount=new Map;subprocessHistogram=new Map;subprocessHistogramRotator=new Map;rollingTimestamps=[];rollingHead=0;launchStats={onStart:e=>{this.subprocessTotal++,this.subprocessInFlight++,this.subprocessCount.set(e,(this.subprocessCount.get(e)??0)+1),this.recordRollingNow()},onEnd:(e,t)=>{this.subprocessInFlight=Math.max(0,this.subprocessInFlight-1),this.recordDuration(e,t)}};recordRollingNow(){let e=Date.now();if(this.rollingTimestamps.length<tQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%tQ}recordDuration(e,t){let n=this.subprocessHistogram.get(e);if(n||(n=[],this.subprocessHistogram.set(e,n)),n.length<16){n.push(t);return}let r=(this.subprocessHistogramRotator.get(e)??0)%16;n[r]=t,this.subprocessHistogramRotator.set(e,r+1)}snapshotSubprocesses(){let e=Date.now()-6e4,t=0;for(let n of this.rollingTimestamps)n>=e&&t++;let n={};for(let[e,t]of this.subprocessCount)t>0&&(n[e]=t);let r={},i={};for(let[e,t]of this.subprocessHistogram){if(t.length===0)continue;let n=[...t].sort((e,t)=>e-t),a=Math.floor(n.length*.5),o=Math.min(n.length-1,Math.floor(n.length*.99)),s=n[a],c=n[o];s!==void 0&&(r[e]=s),c!==void 0&&(i[e]=c)}return{total:this.subprocessTotal,inFlight:this.subprocessInFlight,lastMinute:t,byCategory:n,p50DurationMs:r,p99DurationMs:i}}static referenceSnapshot(){return new e().snapshot({gitCache:{size:0,held:0,hits:0,misses:0,changes:0,watchers:0},usageCache:{size:0,hits:0,misses:0,sweeps:0},sources:{records:[],homes:{daemon:0,configDir:0,repo:0,directory:0,session:0,view:0,pane:0},held:{git:0,tmux:0,host:0,today:0,pluginStorage:0},pluginStorage:{folders:0,faults:{unusable:0,refused:0,error:0},lost:0}},transcriptReads:{reads:0,bytes:0,longLines:0,largestLine:0},renderCache:{size:0,held:0,retired:0,compiles:0,views:0,pinned:0,retiredViews:0,accountedBytes:0,budgetBytes:0},effectCache:{sessions:0,effects:0},menuIdle:{sessions:0,armed:0},runs:{started:0,failed:0,timedOut:0,refused:0,running:0},sessionState:{sessions:0,observers:0,revision:0},frameFeeds:{feeds:0,subscribers:0,drawn:0,pushed:0,refused:0,lookups:0,found:0},tmuxStatus:{sessions:0,layouts:0,writes:0,failedWrites:0},watchersActive:0,handlerProbes:[],clients:[],bundle:`/`,daemon:{pid:0,memory:{kind:`unmeasured`},limit:0,postMortems:{kind:`ok`,value:[]}},doctorStores:{marks:{kind:`ok`,value:{}},clicked:{kind:`ok`,value:[]},postMortemsRead:{kind:`ok`,value:{through:null}}}})}snapshot(e){let t=process.memoryUsage();return{pid:process.pid,version:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function rQ(e,t,n){let r=(r,i,a)=>{let o=i.filter(t).map(t=>({key:t,before:e.get(r,t)}));a();for(let{key:t,before:i}of o)n(r,t,i,e.get(r,t))};return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(t,n,i)=>r(t,[n],()=>e.set(t,n,i)),setBatch:(t,n)=>r(t,n.map(e=>e.key),()=>e.setBatch(t,n)),clear:(t,n)=>r(t,[n],()=>e.clear(t,n))}}const iQ={load:()=>({}),save:()=>{},flush:()=>{}};var aQ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=iQ,t=256){this.maxSessions=t,this.storage=e,this.sessions=new Map,this.hydrateFromStorage()}useStorage(e){this.storage=e,this.hydrateFromStorage()}hydrateFromStorage(){this.sessions=new Map(Object.entries(this.storage.load()).map(([e,t])=>[e,{values:new Map(Object.entries(t)),revision:++this.head}])),this.evictOldest(),this.persist()}get(e,t){this.atom.reportObserved();let n=this.sessions.get(e);return n?(this.touch(e,n),n.values.get(t)??null):null}revision(e){return this.atom.reportObserved(),this.sessions.get(e)?.revision??0}observers(){return this.atom.observers_?.size??0}latestRevision(){return this.head}size(){return this.sessions.size}set(e,t,n){this.setBatch(e,[{key:t,value:n}])}setBatch(e,t){t.length!==0&&(0,J.runInAction)(()=>{let n=this.sessions.get(e)??{values:new Map,revision:0};t.some(({key:e,value:t})=>n.values.get(e)!==t)&&(n.revision=++this.head);for(let{key:e,value:r}of t)n.values.set(e,r);this.touch(e,n),this.evictOldest(),this.persist(),this.atom.reportChanged()})}clear(e,t){(0,J.runInAction)(()=>{let n=this.sessions.get(e);n&&(n.values.delete(t)&&(n.revision=++this.head),n.values.size===0?this.sessions.delete(e):this.touch(e,n)),this.persist(),this.atom.reportChanged()})}prune(e){(0,J.runInAction)(()=>{for(let t of this.sessions.keys())e.has(t)||this.sessions.delete(t);this.persist(),this.atom.reportChanged()})}touch(e,t){this.sessions.delete(e),this.sessions.set(e,t)}evictOldest(){let e=this.sessions.size-this.maxSessions;if(!(e<=0)){for(let t of this.sessions.keys())if(this.sessions.delete(t),--e===0)break}}flush(){this.storage.flush()}persist(){this.storage.save(this.serialize())}serialize(){let e=Object.create(null);for(let[t,{values:n}]of this.sessions)e[t]=Object.fromEntries(n);return e}};function oQ(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;for(let t of Object.values(e)){if(typeof t!=`object`||!t||Array.isArray(t))return!1;for(let e of Object.values(t))if(typeof e!=`string`)return!1}return!0}var sQ=class{timer=null;pending=null;writing=!1;generation=0;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return oQ(t)?t:(this.logger(`warn`,`session-state load: unexpected shape, starting empty`),{})}catch{return this.logger(`warn`,`session-state load: corrupt JSON, starting empty`),{}}}save(e){this.pending=e,this.schedule()}schedule(){this.timer!==null||this.writing||(this.timer=setTimeout(()=>{this.timer=null,this.write()},this.debounceMs),this.timer.unref())}async write(){let e=this.pending;if(e===null)return;let t=this.generation,n=performance.now(),r=JSON.stringify(e),i=`${this.filePath}.writing`;this.writing=!0;let a=performance.now()-n;try{await p.promises.mkdir(s.dirname(this.filePath),{recursive:!0});let o=await p.promises.open(i,`w`,384);try{await o.writeFile(r),await o.chmod(384),await o.datasync()}finally{await o.close()}if(t!==this.generation){await p.promises.rm(i,{force:!0});return}let c=performance.now();p.renameSync(i,this.filePath),this.saved(r,e,n,a+performance.now()-c),this.pending===e&&(this.pending=null)}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}finally{this.writing=!1,this.pending!==null&&this.pending!==e&&this.schedule()}}flush(){if(this.timer&&=(clearTimeout(this.timer),null),this.generation++,this.pending===null)return;let e=this.pending,t=performance.now();try{p.mkdirSync(s.dirname(this.filePath),{recursive:!0});let n=`${this.filePath}.tmp`,r=JSON.stringify(e);p.writeFileSync(n,r,{mode:384}),p.chmodSync(n,384),p.renameSync(n,this.filePath),this.saved(r,e,t,performance.now()-t),this.pending=null}catch(e){this.logger(`warn`,`session-state save failed: ${e.message}`)}}saved(e,t,n,r){this.logger(`info`,`session-state saved bytes=${Buffer.byteLength(e)} sessions=${Object.keys(t).length} took=${Math.round(performance.now()-n)}ms held=${Math.round(r)}ms`)}};const cQ=new Set([`1`,`true`]),lQ=new Set([`0`,`false`,``]);function uQ(e,t){let n=FQ(e),r=n.scope===`segment-palette`?`string`:by(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(cQ.has(t))return`true`;if(lQ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function dQ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function fQ(e,t,n){try{if(t===null){p.rmSync(_t(e),{force:!0});return}gt(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function pQ(e){return/^\s*$/.test(e)?null:Wi(e)}function mQ(e,t){return e!==null&&Ki(e,t)!==void 0}function hQ(e){if(e.kind===`segment`)return e.when===void 0?e.name:{seg:e.name,when:e.when};if(e.kind===`container`){let{kind:t,direction:n,children:r,...i}=e;return{[n===`horizontal`?`h`:`v`]:r.map(hQ),...i}}return e}function gQ(e){if(!Gb(e))return hQ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,hQ(t)])),...n}}const _Q=zH,vQ=_Q.segments,yQ=_Q.presets,bQ=_Q.root;function xQ(e,t,n,r){if(!mQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function SQ(e,t){let n=Cj(t);return t.scope===`segment-palette`&&xQ(e,[`segments`,t.segment],vQ[t.segment],n.join(`.`)),n}function CQ(e){return Wi(ea(e))}function wQ(){return Object.entries(bQ.rows).map(([e,t])=>{let n=hQ(t);return{path:[`root`],fragment:CQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function TQ(e,t){let n=e===null?void 0:Ki(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function EQ(e,t){if(t===void 0)return null;let n=gQ(t);return{path:e,fragment:CQ(n),unit:{path:e,value:n}}}function DQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=yQ[t];xQ(e,n,i,r.join(`.`));let a=TQ(e,r)??EQ(r,i?.root);return a!==null&&xa(a.fragment)?a:null}function OQ(e,t){let n=ba(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function kQ(e,t){return[...wQ(),TQ(e,[`root`]),DQ(e,t)].filter(e=>e!==null).reduce(OQ,new Map)}function AQ(e,t,n){for(let{node:r,...i}of kQ(e,t).values())if(Ca(r,n))return i;throw new q(`${jQ(e,t).join(`.`)} holds no placement "${n}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`)}function jQ(e,t){return DQ(e,t)?.path??[`root`]}function MQ(e,t){return t.scope===`preset-root`?jQ(e,t.preset):Cj(t)}function NQ(e,{unit:t}){return t===null?e:ma(e,t.path,ea(t.value),Qi)}function PQ(e){let t=Sj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function FQ(e){let t=PQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function IQ(e,t,n,r,i){i(t,n,qQ(t,r)),fQ(t.path,r,e.logger),e.record(t.path,n,r)}function LQ(e,t,n){let r=BQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const RQ=()=>{};function zQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function BQ(e,t,n){let r=VQ(e,t);if(r===null)return[];let i=new Set(GQ(WQ(r),WQ(n)));return GQ(UQ(e,r),UQ(e,n)).filter(e=>!i.has(e))}function VQ(e,t){try{return HQ(e,t)}catch(e){if(e instanceof Q_)return null;throw e}}function HQ(e,t){return vH(t===null?e.above:[e.path,...e.above],VH,{entered:()=>{},warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function UQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function WQ(e){return e.layers.at(-1)?.config??e.base}function GQ(e,t,n=``){return!KQ(e)||!KQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>GQ(e[r],t[r],n===``?r:`${n}.${r}`))}function KQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qQ(e,t){try{return HQ(e,t)}catch(e){throw e instanceof Q_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function JQ(e,t){let n=FQ(t),r=pQ(dQ(e)??``),i=r===null?void 0:Ki(r,Cj(n));return i!==void 0&&`value`in i?i.value:void 0}function YQ(e,t,n){XQ(e,t,n,[])}function XQ(e,t,n,r){let i=dQ(t.path),a=n.reduce((e,[t,n])=>ma(e,SQ(pQ(e),FQ(t)),uQ(t,n),Qi),i??``);IQ(e,t,i,zQ(t,()=>ZQ(a,t.path,r,e=>e)),LQ)}function ZQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=AQ(pQ(s),n,i),l=Da(NQ(s,c),c.path,i,a,ea(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function QQ(e,t,n){let r=pQ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of kQ(r,t)){if(!Ca(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ji(e,c):ea(s.value);if(a!==`#`)return ma(e,[...i,`rows`,a],l,Qi);if(DQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ma(e,i,l,Qi)}return e}function $Q(e,t){return ga(e,t,t[0]===`presets`&&t.length>2&&!UH(t[1])?2:0)}function e$(e,t,n){let r=n.map(PQ),i=dQ(t.path);if(i===null)return;let a=r.reduce((e,t)=>$Q(e,MQ(pQ(e),t)),i);a!==i&&IQ(e,t,i,a,RQ)}function t$(e){let t=e===null?void 0:Ki(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function n$(e,t){let n=new Set([...HH,...t$(e),...t.above.flatMap(e=>Object.keys(Li.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(vA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(vA(e)))}function r$(e,t,n,r,i,a){let o=dQ(t.path),s=pQ(o??``),c=n$(s,t),l=[`presets`,c],u=zQ(t,()=>DQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ji(o??``,u.fragment):ea(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],ea(r)]]],f=i.map(([e,t])=>{let n=xj(c,e);return[SQ(s,FQ(n)),uQ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ma(e,t,n,Qi),ma(o??``,l,`{}`,Qi));return IQ(e,t,o,zQ(t,()=>ZQ(p,t.path,a.map(e=>({...e,preset:c})),QQ)),LQ),c}function i$(e,t,n,r){let i=dQ(t.path);IQ(e,t,i,ma(i??``,[`themeDefaults`,n],ea(r),Qi),LQ)}function a$(e,t,n){if(UH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=dQ(t.path),a=pQ(i??``);if(i===null||a===null||Ki(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ki(a,[`globals`,`preset`]);IQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>$Q(e,t),i),RQ)}function o$(e,t,n,r){let i=PQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=dQ(t.path),o=r.op===`remove`?r.target:r.anchor,s=zQ(t,()=>AQ(pQ(a??``),i.preset,o)),c=NQ(a??``,s),{after:l,placed:u}=s$(c,s.path,r,()=>{let e=qQ(t,c).config;return tx(e.presets).map(t=>ix(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return IQ(e,t,a,l,LQ),u}function s$(e,t,n,r){switch(n.op){case`remove`:return{after:Ta(e,t,n.target),placed:null};case`insert`:{let i=VI(n.segment,n.anchor,r());return{after:Ea(e,t,i,n.anchor,n.relation),placed:i}}}}const c$={load:()=>({}),save:()=>{}},l$=new Set(Ty.map(e=>e.sessionKey)),u$=e=>l$.has(e)||e.startsWith(Fj),d$=8*1024*1024,f$={past:[],future:[]},p$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var m$=class{held=J.observable.map(void 0,{deep:!1});get state(){return this.held}set state(e){(0,J.runInAction)(()=>this.held.replace(e))}constructor(e,t,n=c$){this.sessionState=e,this.logger=t,this.storage=n,this.state=new Map(Object.entries(n.load()))}useStorage(e){this.storage=e,this.state=new Map(Object.entries(e.load()))}depth(e){let{past:t,future:n,savepoint:r}=this.state.get(e)??f$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??f$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(p$(n));r.set(p$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:rQ(this.sessionState,e=>u$(e)||e===`edit.mode`,(e,r,i,a)=>{if(r===`edit.mode`){let t=n.get(e);n.set(e,{before:t===void 0?i:t.before,after:a});return}t(e,{kind:`session`,key:r,before:i,after:a})}),file:(e,n,r,i)=>t(e,{kind:`file`,file:n,before:r,after:i}),commit:()=>{let t=new Map(e),r=new Map(n);e.clear(),n.clear();for(let e of new Set([...t.keys(),...r.keys()])){let n=[...t.get(e)?.values()??[]].filter(e=>e.before!==e.after),i=this.history(e),a=n.length===0?i:S$(i,n),o=r.get(e),s=o===void 0?a:E$(a,o);s!==i&&this.put(e,s)}}}}undo(e){let t=this.history(e),n=t.past.at(-1);if(n===void 0)throw new q(`undo: nothing to undo`);return this.apply(e,n,`before`,`undo`,w$(t,n)),n}rewind(e){let t=this.history(e),{savepoint:n}=t;if(n===void 0)throw new q(`rewind: edit mode has no savepoint — nothing to cancel`);let r=n.net.filter(t=>this.read(e,t)!==t.after),i=new Set(r.map(p$)),a=n.net.filter(e=>!i.has(p$(e))),o=_$(D$(T$(t,n),i));if(this.apply(e,a,`before`,`rewind`,{past:o,future:[],savepoint:{at:o.length,net:[],below:[]}}),r.length>0)throw new q(`rewind: ${r.map(k$).join(`, `)} changed since edit mode opened — kept as it is; everything else edit mode changed was put back`);return a}redo(e){let t=this.history(e),{past:n,future:r}=t,i=r.at(-1);if(i===void 0)throw new q(`redo: nothing to redo`);let a=[...n,i],o=_$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...y$(t.savepoint,a.length-o.length,i)}),i}apply(e,t,n,r,i){let a=n===`before`?`after`:`before`,o=t.filter(t=>this.read(e,t)!==t[a]);if(o.length>0){let t=new Set(o.map(p$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:D$(n,t),future:D$(i,t),...a!==void 0&&{savepoint:{at:D$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(p$(e))),below:D$(a.below,t)}}}),new q(`${r}: ${o.map(k$).join(`, `)} changed since that edit — refusing to overwrite it; this session's undo history no longer steps it`)}let s=[];try{for(let r of t)this.write(e,r,r[n]),s.push(r);this.put(e,i)}catch(t){try{for(let t of s.reverse())this.write(e,t,t[a])}catch(e){throw Error(`${t.message}; and putting the step back failed, so it is half-applied: ${e.message}`)}throw t}}read(e,t){return t.kind===`session`?this.sessionState.get(e,t.key):dQ(t.file)}write(e,t,n){t.kind===`file`?fQ(t.file,n,this.logger):n===null?this.sessionState.clear(e,t.key):this.sessionState.set(e,t.key,n)}put(e,t){let n=new Map(this.state);for(n.delete(e),(t.past.length>0||t.future.length>0||t.savepoint!==void 0)&&n.set(e,t);n.size>32||h$(n)>d$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,g$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${d$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function h$(e){let t=0;for(let{past:n,future:r,savepoint:i}of e.values())for(let e of[...n,...r,...i===void 0?[]:[i.net,...i.below]])for(let n of e)t+=(n.before?.length??0)+(n.after?.length??0);return t}function g$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...y$(n,1,[])}:{past:e,future:t.slice(1),...y$(n,0,[])}}function _$(e){return e.slice(-50)}const v$=e=>e===Lj.member;function y$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:b$(e.net,n),below:e.below}}}function b$(e,t){let n=new Map(e.map(e=>[p$(e),e]));for(let e of t){let t=n.get(p$(e));n.set(p$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const x$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function S$(e,t){let n=[...e.past,t],r=_$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...y$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...C$(e.future,a),...i.below]},n.length-r.length,t)}}function C$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function w$(e,t){return{past:e.past.slice(0,-1),future:_$([...e.future,t]),...y$(e.savepoint,0,x$(t))}}function T$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...C$(r,t.at-i.length),...t.below]}function E$(e,t){if(v$(t.after)&&!v$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!v$(t.after)&&v$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function D$(e,t){return e.map(e=>e.filter(e=>!t.has(p$(e)))).filter(e=>e.length>0)}function O$(e){return e.map(k$).join(`, `)}function k$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function A$(e){if(typeof e!=`object`||!e)return!1;let t=e,n=e=>e===null||typeof e==`string`;return(t.kind===`session`&&typeof t.key==`string`||t.kind===`file`&&typeof t.file==`string`)&&n(t.before)&&n(t.after)}function j$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(A$))}function M$(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(A$)&&j$(t.below)}function N$(e){if(typeof e!=`object`||!e)return!1;let t=e;return j$(t.past)&&j$(t.future)&&(t.savepoint===void 0||M$(t.savepoint))}function P$(e,t){let n=e=>e.kind===`file`||u$(e.key)?!0:(t.add(e.key),!1),r=e=>e.map(e=>e.filter(n)).filter(e=>e.length>0),{savepoint:i}=e,a=r(e.past),o=r(e.future);return i===void 0?{past:a,future:o}:{past:a,future:o,savepoint:{at:r(e.past.slice(0,i.at)).length,net:i.net.filter(n),below:r(i.below)}}}function F$(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(N$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,P$(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),gt(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const I$=e=>!u$(e)&&!uP(e)&&e!==`update.dismissed`;var L$=class{past=J.observable.map(void 0,{deep:!1});depth(e,t,n){return this.restorable(e,t,n).length}restorable(e,t,n){let r=new Map,i=n=>r.has(n)?r.get(n):t.get(e,n),a=[];for(let t of[...this.past.get(e)??[]].reverse())if(t.every(e=>i(e.key)===e.after&&(e.before===null||n.validate(e.key,e.before).ok))){a.unshift(t);for(let e of t)r.set(e.key,e.before)}return a}begin(e){let t=new Map;return{sessionState:rQ(e,I$,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new q(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,J.runInAction)(()=>{let n=a.flatMap(({key:e,before:t})=>t===null?[]:[{key:e,value:t}]);n.length>0&&t.setBatch(e,n);for(let{key:n,before:r}of a)r===null&&t.clear(e,n)}),this.put(e,i.slice(0,-1)),{step:a,discarded:o}}push(e,t){let n=this.past.get(e)??[];this.put(e,[...n,t].slice(-20))}put(e,t){(0,J.runInAction)(()=>{for(this.past.delete(e),t.length>0&&this.past.set(e,t);this.past.size>32;)this.past.delete(this.past.keys().next().value)})}};const R$={inside:()=>[],defaultOf:()=>yi,menus:[]},z$=e=>`${e.key}\0${e.member}`;function B$(e){let t=new Map,n=n=>{let r=`${n.name}\0${C_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:nz(a,C_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(z$(e))??new Map;n.set(z$(t),t),o.set(z$(e),n)},d=(e,t)=>{if(e.kind===`container`){for(let n of e.children)d(n,t);return}for(let n of r(e)){l(n),c.set(z$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of tx(e.presets))d(ix(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Mi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(z$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(z$(e))??[])n.has(t)||(n.set(t,i),r(i))};r(e);let i=new Map;for(let{key:e,member:t}of n.values())i.set(e,(i.get(e)??new Set).add(t));let a=[...i].map(([e,t])=>({key:e,outside:new Set([...s.get(e)].filter(e=>!t.has(e)))}));return f.set(z$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const V$=new WeakMap;function H$(e){let t=V$.get(e);if(t!==void 0)return t;let n=B$(e);return V$.set(e,n),n}function U$(e,t,n){let r=new Set(n.map(e=>e.key)),i=n=>t(n)??e.defaultOf(n),a=new Set;for(let{key:t,value:o}of n){let n=i(t);if(n!==o)for(let o of e.inside({key:t,member:n})){let t=i(o.key);t!==e.defaultOf(o.key)&&!o.outside.has(t)&&!r.has(o.key)&&a.add(o.key)}}return[...a]}function W$(e,t){let n=({key:n,member:r})=>(t(n)??e.defaultOf(n))===r,r=(t,n)=>e.inside(n).some(({key:e,outside:n})=>e===t.key&&!n.has(t.member));return e.menus.filter(n).filter(t=>{let i=e.menus.filter(e=>e!==t&&r(t,e)),a=i.length>0&&e.defaultOf(t.key)===t.member;return!i.some(n)&&!a})}function G$(e,t,n){let r=(r,i,a)=>{let o=U$(t(r),t=>e.get(r,t),i);(0,J.runInAction)(()=>{a();for(let t of o)e.clear(r,t)}),o.length>0&&n(`close-nested: folded=${o.join(`,`)} (session=${r})`)},i=(t,n)=>r(t,n,()=>e.setBatch(t,n));return{get:(t,n)=>e.get(t,n),revision:t=>e.revision(t),set:(e,t,n)=>i(e,[{key:t,value:n}]),setBatch:i,clear:(n,i)=>r(n,[{key:i,value:t(n).defaultOf(i)}],()=>e.clear(n,i))}}const K$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function q$(e,t){let n={...e};for(let e of K$)delete n[e];return{...n,CLAUDE_CODE_SESSION_ID:t.sessionId,CLAUDE_PROJECT_DIR:t.projectDir,...t.claudeConfigDir!==void 0&&{CLAUDE_CONFIG_DIR:t.claudeConfigDir}}}const J$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Y$(e){let t=e=>({kind:`failed`,reason:e});if(!J$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!J$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!ZM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${ZM.join(` or `)}`)}return{kind:`ok`,value:e}}function X$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Z$=e=>xq(e,`doctor-marks.json`,{},Y$),Q$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},$$=(e,t)=>e.includes(t)?e:[...e,t],e1=e=>xq(e,`doctor-clicked-terminals.json`,[],Q$);var t1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const n1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},r1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),i1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=r1(e,t);return r===void 0?n:r.projectDir},a1=(e,t)=>r1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function o1(e){let t=new Map;for(let n of e.split(`
|
|
201
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(n);if(e===null)continue;let r=Number(e[1]);t.set(r,{pid:r,ppid:Number(e[2]),command:e[3].trim()})}return t}function*
|
|
198
|
+
`);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function fX(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 pX=e=>e.kind===`failed`?bJ:e;function mX(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function hX(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 gX(e){return{...e,cells:e.cells.map(EJ)}}function _X(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,...vX(e,r)]}function vX(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 yX(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:_X(e.direction,e.children.map((t,i)=>n(t,[...r,bX(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function bX(e,t){return{index:t,count:e.children.length,distribution:e.distribution,axis:S_[e.direction]}}const xX={compile(e,t){return{kind:`container`,direction:e.direction,when:t.when,distribution:Ah(e.distribution),children:e.children.map((e,n)=>t.compileChild(e,O_(t.path,n)))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),_X(e.direction,e.children.map((n,r)=>t.renderChild(n,pX(t.gate),bX(e,r))))}},SX={drop:e=>e.place,above:()=>`above`},CX={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},wX={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:C_(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(Ti(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,k_(t.path)),key:e.opens.ref.key,placement:e.opens.placement}},...e.lead!==void 0&&{lead:t.parse(e.lead,`lead`)},...e.trail!==void 0&&{trail:t.parse(e.trail,`trail`)}}},render:(e,t)=>t.placed(e.id,TX(e,t))};function TX(e,t){let n=t.lookupSegment(e.name);if(n===void 0)throw Error(`Layout segment "${e.name}" has no matching segment`);if(t.gate.kind===`hidden`)return[];let r=Ok(t.scope,e.settings);if(t.gate.kind===`failed`)return jX(e,r,t,t.gate.message);try{let i=t.placement(e),a=mX(t.gate,i.gate());if(a.kind===`failed`)return jX(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 jX(e,r,t,s.message);let c=Pb(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:qj(c)},u=e=>({width:n.width??`auto`,justify:n.justify??`left`,truncate:n.truncate??`right`,baseStyle:e,padding:t.padding,placement:l}),d=s.kind===`shown`,f=a.kind===`pending`?a:s,p=f.kind===`pending`?EX(f.variable):DX(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?OX(p.segment,u):kX(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:bJ,h.disclosure).map(e=>({...e,place:SX[v.placement](e)})),b=(e,t,n)=>kJ(NJ([e],t),{...u(t),width:`auto`,padding:n}),ee=y.findIndex(e=>e.band===`own`),{lead:x,stays:S}=v!==void 0&&ee!==-1?CX[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},te=x.flatMap(e=>b(new W(` `.repeat(AX(TJ(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(TJ)),[...ie,...re]}catch(n){return jX(e,r,t,n.message??String(n))}}const EX=e=>({kind:`waiting`,variable:e});function DX(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=oS(e);if(t===void 0)throw e;return EX(t.variable)}}function OX(e,t){let{styles:n,fragments:r,lead:i,trail:a,drops:o,open:s}=e,c=s?n.trigger:n.closed,l=t(c);return{styles:n,inline:dX(NJ(r,c)).map((e,t)=>({cells:kJ(e,{...l,lead:t===0?NJ(i,c):[],trail:t===0?NJ(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:kJ(NJ([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function kX(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=NJ(MX(e.lead,e,t,n),l),d=NJ(MX(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 kJ(NJ([new W(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function AX(e){return e.reduce((e,t)=>e+t.cellLength,0)}function jX(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:kJ([new W(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:qj(n.palette)},lead:MX(e.lead,e,t,n),trail:MX(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function MX(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=oS(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const NX={container:xX,segment:wX};function PX(e){return NX[e]}var FX=class{last=null;from(e){let{last:t}=this;return t!==null&&t.source.config===e.config&&t.source.preset===e.preset&&t.source.revision===e.revision&&t.source.width===e.width?t:null}begin(e,t){let n=new Map,r=new Map;return{placed:(e,r)=>{let{drawing:i}=t(e,r);return n.set(e,i===null?IX:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const IX={kind:`hidden`},LX={palette:`theme`,style:`style`,effect:`effect`},RX=Oy.get(`colorCompatibility`),zX={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function BX(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function VX(e){if(e.ok)return e.value;throw e.error}const HX=e=>({read:()=>e}),UX=ph({basePalette:fh,palette:fh,decor:Dg});var WX=class{evaluated=0;memory=new FX;scope;binding;facts;look=J.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&UX(e,t)});layout;phase={ruling:!1};gates=new Map;placements=new Map;rules=new Map;slots=new Map;view;projected=void 0;drawnSlots=new Map;constructor(e,t,n,r){this.store=e,this.registry=t,this.source=n,this.view=J.observable.box(r,{deep:!1}),this.scope=Ek(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(RX);return typeof e==`string`&&d_(e)?e:`truecolor`});let i=(0,J.observable)(zX,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 yX(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=jI(e);return i===void 0?[]:[{name:i,address:n,palette:Pb(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>f_(this.colorCompatibility())})}bind(e){(0,J.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,J.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=mA(e);return t===void 0?fA(e)===void 0?tA(this.view.get().payload(),e):tA(this.projected,e):this.slotName(t)}depth;colorCompatibility(){return this.depth.read()}slot(e){let t=this.slots.get(e);if(t===void 0){let n,r=()=>{let t=this.selections()[LX[e]];if(t.kind===`decided`)return qX(t.name,null,null);let r=YX(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=XX(this.source,e,i.name,r.where,e=>{t=e}),qX(n,t,null)}case`pending`:return qX(n??Qg[e],null,i.variable);case`failed`:return n=Qg[e],qX(n,$g(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!JX(i,e))&&(i=e),i}),this.slots.set(e,t)}return t.read()}slotName(e){let t=this.slot(e);return t.kind===`settled`?t.name:this.drawnSlots.get(e)??Qg[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,J.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return SJ(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>yY(this.source.activeSegment,()=>SJ(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new ZX(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:zJ(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=oS(e);return t===void 0?{kind:`failed`,error:e instanceof Error?e.message:String(e)}:{kind:`pending`,variable:t.variable}}finally{t?.[Symbol.dispose](),this.phase.ruling=!1}}),this.rules.set(e,t)),t.read()}readsInstant(...e){return e.some(e=>e!==void 0&&this.source.instant.has(e))}derive(e,t,n){let r=()=>(this.evaluated++,n());return this.store.derive(`part ${e}`,t?`projection`:`computed`,t?this.oncePerDraw(r):r)}oncePerDraw(e){let t=null;return()=>(t?.draw!==this.draws&&(t={draw:this.draws,answer:BX(e)}),VX(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:jI(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function GX(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new WX(t,n,e,r);return e.views.set(t,a),a}function KX(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 qX=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),JX=(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 YX(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 XX(e,t,n,r,i){switch(t){case`palette`:return zb(n,r,i).name;case`style`:return Yg(n,e.styles).name;case`effect`:return a_(n).name}}var ZX=class{where=QX(ph({palette:fh,region:Tg}));ground=QX(ph({colours:eZ,bodyOpen:fh}));opened=QX(ph({colours:eZ,open:fh}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=Ok(e.scope,t.settings),{when:a,bg:o,fg:s,template:c}=n,{lead:l,trail:u}=t,d=t.opens?.open;this.ownGate=a===void 0?HX(xJ):e.derive(`${t.id} when`,e.readsInstant(a),()=>yY(r,()=>SJ(a,i))),this.open=d===void 0?HX(bJ):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>yY(r,()=>SJ(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return rZ(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 iZ(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?HX(oZ):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return aZ(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}),cZ(n,r,this.affixes.read())}};function QX(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 $X=(e,t)=>e.hex===t.hex,eZ=ph({palette:fh,drawnAt:fh,tint:$X,text:$X,bg:$X,disclosure:Og});function tZ(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const nZ=e=>dg(e.palette,e.disclosure,e.drawnAt);function rZ(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Pg(n,r,i)};return vY(e,tZ(t,c),e=>{let t=Yj(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function iZ(e,t,n,r,i,a){return vY(e,tZ(t,n),e=>(e.bg=i?nZ(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function aZ(e,t,n,r,i,a,o){return vY(e,tZ(t,n),e=>(e.bg=r?nZ(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const oZ={lead:[],trail:[],drops:[]};function sZ(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return tY(t,nZ(e).state,n)},get band(){return tY(t,nZ(e).plane,n)},get close(){return iY(t,nZ(e).state,n)},disclosure:r}}function cZ(e,t,n){return{styles:sZ(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open,shortfalls:t.open?nZ(e).shortfalls:[]}}function lZ(e,t,n,r,i,a,o){let s=rZ(e,t,n,r,i,void 0,void 0,o);return cZ(s,iZ(e,t,s,a,!1,o),oZ)}function uZ(e,t,n,r,i){return sZ(rZ(e,t,n,r,i,void 0,void 0,{}))}function dZ(e,t){return{payload:()=>e,selections:()=>t}}function fZ(e){if(`ttl`in e)return{kind:`ttl`,durationMs:Vk(e.ttl)};if(`watch_file`in e)return{kind:`watch_file`,path:e.watch_file};if(`depends_on`in e)return{kind:`depends_on`,varNames:e.depends_on};if(`key`in e)return{kind:`key`,template:e.key};if(`never`in e)return{kind:`never`};throw Error(`Unknown CacheDecl discriminator — loader invariant violated: ${JSON.stringify(e)}`)}function pZ(e,t){switch(M_(e)){case`json`:return{kind:`json`,default:t};case`regex`:return{kind:`regex`,regex:new RegExp(e.regex),default:t};case`text`:return{kind:`text`,default:t}}}function mZ(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:fZ(n.cache),parse:pZ(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:fZ(n.cache),parse:pZ(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 hZ(e,t){let n=JS.EMPTY;for(let[r,i]of Object.entries(t))try{n=e.parse(`{{ define "${r}" }}${i}{{ end }}`,n).defines()}catch(e){throw Error(`Template parse error in helpers.${r}: ${e.message}`,{cause:e})}return n}function gZ(e,t,n){let{compiled:r,loadWarnings:i}=vZ(e,t,n.cwd,_Z(n.signer),SZ);return{...r,loadWarnings:i}}const _Z=e=>(t,n)=>CZ(n,e);function vZ(e,t,n,r,i=SZ){let a=yZ(e),o=bZ(a);return{compiled:r(o,a),compileKey:o,loadWarnings:xZ(e,t,n,i)}}function yZ(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of ky)n in t&&r.set(e,n);for(let[t,n]of R_(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...mB(e)].sort(([e],[t])=>e<t?-1:1)}}function bZ(e){return te(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function xZ(e,t,n,r){let i=lX(e),a=mB(e),o=[];for(let[s,c]of Gx(e))if(r.has(i.get(s)))try{mZ(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const SZ=new Set([`directory`,`view`]);function CZ({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>IJ(i,`drawnAt`).registry.drawnAt(),o=gY(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=tx(e.presets),u=bI(e),d=[e=>BY(i,o,e.now)],f=Tk({extraFuncs:{...$J(i),...zY(i),...jY(i,o),...FY(i,o),...GY(i,o),...ZY(i,o),...tX(s),...iX(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=hZ(f,e.helpers),m=new Map,h=e=>{let t=f.parse(e,p);return m.set(t,e),t},g=new Map,_=e=>{let t=g.get(e);if(t!==void 0)return t;let n=h(e);return g.set(e,n),n},v=new Map(t);i.compiled=BJ(h,e.actions,v,u);let y=Object.create(null);for(let[t,n]of Object.entries(e.segments)){let e=(e,n,r=h)=>{try{return r(e)}catch(e){throw Error(`Template parse error in segments.${t}.${n}: ${e.message}`,{cause:e})}};y[t]={when:n.when===void 0?void 0:e(n.when,`when`,_),template:e(n.template,`template`),bg:n.bg===void 0?void 0:e(n.bg,`bg`),fg:n.fg===void 0?void 0:e(n.fg,`fg`)}}let b=(e,t,n)=>{try{return _(e)}catch(e){throw Error(`Template parse error in ${t}.${n}: ${e.message}`,{cause:e})}},ee=t=>{let n=H_(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>J_(t,e,a,t=>String(IJ(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},x=(e,t)=>{let n={path:t,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:x,placementSettings:ee};return PX(e.kind).compile(e,n)},S=new Map;for(let t of l){let{node:n,path:r}=ix(e,t);S.set(t,x(n,r))}let te=new Map(Wg.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of gB(e)){let e=t.join(`.`),i=te.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:EZ(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let ne={reads:sB({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:Sk(d)},re=yB(ne),ie=[...S.values()].flatMap(TZ(y)).some(e=>re(m.get(e))),ae=ie?yB({...ne,clock:new Set([...ne.clock,XY])}):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 wZ(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 TZ=e=>t=>{let n=[];return yX(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 EZ(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 DZ=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function OZ(e,t,n,r,i){let a=kZ(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function kZ(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??Qg[e];case`failed`:return r({kind:`rule`,slot:e,message:$g(t.where,e,`the rule failed — ${n.error}`)}),Qg[e]}}function AZ(e){return jZ(e).filter(e=>!e.name.startsWith(SA)).map(e=>e.id)}function jZ(e){return e.kind===`container`?e.children.flatMap(jZ):[e,...e.opens===void 0?[]:jZ(e.opens.body)]}function MZ(e,t,n,r,i,a,o,s,c=XH(e,()=>null,()=>!1)){let l={...i,term:{cols:o.width},colorCompatibility:{effective:o.colorCompatibility}};return GX(t,n,r,dZ(l,c)),PZ(e,t,n,r,l,a,o,s,c)}function NZ(...e){return MZ(...e).text}function PZ(e,t,n,r,i,a,o,s,c){try{var l=ja();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=new Set,h=c.effects??new eb(``),g=h.clockAt(a,t_[c.animationSpeed]);l.u(pk(a,g.anim));let _=KX(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:cb(v),padding:v.padding,seamCols:lb(v),preset:c.preset},i);let y=_.evaluated;l.u(zJ(t.menuRuntime.action,_.binding));let{preset:b,transitions:ee}=c,x={variation:wh[c.variation],shade:Sh[c.shade]},S={config:e,preset:b,revision:r.stateRevision(),width:v.width},te=_.memory.begin(S,hX),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=XX(t,e,OZ(e,n.rule,_,p,ie),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:w,style:oe,effect:se}=_.selections(),T=w.kind===`decided`?w:zb(C(`palette`),``,DZ),ce=oe.kind===`decided`?oe:Yg(C(`style`),e.styles),le=se.kind===`decided`?se:a_(C(`effect`)),ue=T.value,de=Ib(ue,ce.value);_.publishLook({basePalette:ue,palette:de,decor:x});let fe=c.idleSince===void 0?null:Yv(c.idleSince,c.menuTimeout,a),pe=Vh(de,`warning`),me=fe===null?null:{t:fe,fill:pe,text:Zh(de,pe,r.drawnAt())},he=h.motion(le.value,g,{transitions:ee,source:S,last:ne,returned:hX,hold:gX},me);u?.clear();let ge=t=>e.segments[t],_e=e=>{for(let t of e.shortfalls)m.add(t);return e},ve=e=>{let t=_.placement(e);return{gate:()=>t.gate(),bodyGate:()=>t.bodyGate(),evaluate:(e,n)=>_e(t.evaluate(e,n))}},ye=(e,i,a)=>{let o=i.kind===`hidden`?i:mX(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${AZ(e).join(`, `)||`no placement`}`;p({kind:`when`,where:t,error:o.message,message:`${t}: ${o.message} — what it gates is hidden`})}}:o,c={scope:_.scope,palette:de,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:ve,evaluateOnce:(e,n,i,o)=>_e(lZ(t.activeSegment,e,i,a,r.drawnAt(),o,n)),lookupSegment:ge,renderChild:(e,t,n)=>ye(e,t,Mg(a,n)),renderBody:(e,t,n)=>ye(e,t,Ng(n)),closeDisclosure:e=>eY(n,e),placed:(e,t)=>te.placed(e,he.placed(e,t)),lastDrawn:e=>ne?.placements.get(e),waited:e=>re.add(e),decorations:(e,n)=>uZ(t.activeSegment,e,n,a,r.drawnAt())};return PX(e.kind).render(e,c)},be=t.roots.get(b);if(be===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${$b}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let xe=fX(ye(be,xJ,jg(x))).map(({line:e,row:t})=>{let n=MJ(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,...pb(n.map(e=>e.owner),v,he.row(t,r,n))}});he.drawn(),te.commit();let Se=xe.filter(e=>e.kind===`menu`).length,Ce=xe.some(e=>e.moves)?`moves`:Se>0||_.selections().effect.kind===`expression`||ee||jZ(be).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`)?`can-move`:`still`;for(let e of m)p({kind:`band-floor`,message:e});for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{text:xe.map(e=>e.text).join(`
|
|
199
|
+
`),motion:Ce,menuRows:Se,evaluated:_.evaluated-y,pending:[...re].sort(),rules:ae}}catch(e){l.e=e}finally{l.d()}}function*FZ(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*IZ(e){for(let t of Object.values(e.segments))for(let e of[t.template,t.bg,t.fg,t.when])e!==void 0&&(yield e);for(let t of tx(e.presets)){for(let n of D_(ix(e,t).node))n.when!==void 0&&(yield n.when);let n=ax(e,t);for(let e of Wg){let t=n[e];Gg(t)&&(yield t)}}for(let[,t]of FZ(e))for(let[,e]of F_(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of gx(t))yield e}function LZ(e,t){let n=uB(t),r=new Set,i=new Set,a=new Set;for(let e of IZ(t)){for(let{reaches:t}of n.ofTemplate(e))for(let e of t)r.add(e);for(let{name:n}of Lx(e,t.helpers))i.add(n);for(let n of Hx(e,t.helpers))a.add(n)}for(let[,e]of FZ(t))for(let{reaches:t}of n.ofVariable(e))for(let e of t)r.add(e);let o=new Set(i);for(let e of i){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)o.add(e)}let s=new Set,c=new Set;for(let e of o){let n=t.actions[e];if(n!==void 0&&(`set`in n&&s.add(n.set),`insertSegment`in n&&c.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)c.add(e)}for(let e of tx(t.presets))for(let n of D_(ix(t,e).node))n.kind===`segment`&&c.add(n.name);let l=(e,t)=>r.has(e)||t.kind===`state`&&s.has(t.key),u=e=>[...e].filter(e=>!wA(e)),d=(e,t,n)=>u(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),f=new Map(FZ(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 RZ=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 zZ(e){return Math.floor(Math.max(e/4,e*or-67108864))}const BZ={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function VZ(e,{plugins:t,config:n,compiled:r},i){let{checkout:a,loaded:o,dropped:s,unreached:c}=t,l=a===null?`-`:`${a.git?`git`:`dir`}:${a.root}`,u=e=>{let t=aV(e),r=t===void 0?void 0:n.variables[sV(t)];return r?.kind===`file`?r.path:`none`},d=o.flatMap(e=>{let t=aV(e);return t===void 0?[]:[t]}).flatMap(e=>Object.entries(n.variables).filter(([t])=>pV(e)(t)&&t!==sV(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${e.join(` < `)||`<default>`}: projections=${[...mB(n).keys()].join(`,`)||`-`} instantSegments=${wZ(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 HZ(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 UZ(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function WZ(e,t,n){return e+`\0`+t+`\0`+(n??``)}function GZ(e,t){return new Set(tx(e.presets).filter(n=>ix(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function KZ(e,t){let n=new Map,{loaded:r,dropped:i,unreached:a}=e.state.plugins,o=[...new Set([...e.state.plugins.roots,s.join(e.projectDir,RV)])];for(let t of[...tH(e.projectDir,e.cwd,e.configFile),...o,...r,...[...i,...a].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))]){let{dir:e,name:r}=Xx(t),i=n.has(e)?n.get(e):new Set;i?.add(r),n.set(e,i)}for(let e of o){let{dir:t,name:r,leaf:i}=Xx(s.join(e,`_`));i&&r===`_`&&n.set(t,null)}return{files:t,dirs:[...n.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>t===null?{path:e}:{path:e,filenames:[...t].sort()})}}function qZ(e){return e.filter(Boolean).join(`
|
|
200
|
+
`)||null}function JZ(e,t,n,r,i=()=>{}){let{layers:a,config:o,installed:s}=vH(t.layers,VH,{entered:i,warned:e=>n.push(...e)},{repo:t.repo,cwd:e});i(a.length===1?a[0].path:null);let c=a.at(-1)?.config??VH,l=a.find(e=>e.path===t.home)?.raw??{},u=new yS,d=new aA(u,o.globals.default_empty_value??``,r.sessionState,null,r.ledger),f,p;try{f=vZ(o,d,e,r.compile??_Z(r.signer),QZ),n.push(...f.loadWarnings);let t=d.view();n.push(...xZ(o,t,e,$Z)),t.dispose(),MU(o),eL(o),p=YZ(o,r.storage,d)}catch(e){throw d.dispose(),e}return{config:o,compileKey:f.compileKey,store:u,registry:d,compiled:f.compiled,neededInputPaths:Uq(o),authoredRoots:GZ(c,l),fileHeldSettings:vU(l),configPath:t.layers.includes(t.home)?t.home:null,unused:[...new Map(a.flatMap(e=>LZ(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 YZ(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 XZ(e,t,n,r){let i=performance.now(),a=rH(Tq().read(),e,t,n),{repos:o}=a,s={layers:a.kind===`chain`?a.layers:[],home:a.home,repo:o.plugins},c=[uH(e,t),cH(a),QV(o)],l,u=null;try{l=JZ(t,s,c,r,e=>{u=e})}catch(e){return e instanceof Q_&&c.push(...e.warnings),{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,failedFile:u,warning:qZ(c),state:null,error:e instanceof Q_||e instanceof Error?e.message:String(e)}}return{layers:s.layers,home:s.home,ms:Math.round(performance.now()-i),repos:o,warning:qZ(c),state:l,error:null}}function ZZ(e,t,n){return JZ(e,{layers:[],home:``,repo:t},[],n)}const QZ=new Set([`directory`]),$Z=new Set([`view`]);function eQ(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new RZ;xZ(e.config,l,t,$Z);let d=()=>YH(e.config,e=>r.get(c,e)),f=(t,n)=>{try{let r=e.neededInputPaths(n),{result:{lanes:a,faults:o},acquired:l,released:d}=u.declare(()=>i(u,t,r,e.sources));for(let e of o)s(`error`,`session view declaration threw sid=${JSON.stringify(c)} ${e}`);return l+d>0&&s(`info`,`session view declared sid=${JSON.stringify(c)} acquired=${l} released=${d} held=${u.size}`),a}catch(t){return s(`error`,`session view declaration threw sid=${JSON.stringify(c)}: ${String(t)}`),eJ(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=J.observable.box(p(n,d()),{deep:!1}),h=(e,t)=>{let n=m.get();if(e===n.facts&&t===n.preset)return;let r=p(e,t);(0,J.runInAction)(()=>m.set(r))},g=(0,J.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});GX(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 tQ=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;viewHolds=new Map;pins=new Map;openFailures=new Map;compiles=new Map;deps;log;budgetBytes;maxEntries;observers;constructor(e,t){this.deps={...e,compile:(e,t)=>this.compileOf(e,t)},this.log=e.log??Me,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{};let{dir:n,name:r}=Xx(wq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{files:[],dirs:[{path:n,filenames:[r]}]},()=>this.reloadEvery())}compileOf(e,t){return this.compiles.get(e)??CZ(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=WZ(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`,VZ(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??ZZ(t,a.repos.plugins,this.deps),watcher:null,watcherKey:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[]),o}hold(e,t,n){let r=this.getOrCreate(e,t,n);return this.holdState(r,r.state)}holdState(e,t){let n=this.holdOf(t);n.holders++,this.armSweep();let r=!1;return{entry:e,state:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache hold released twice`);r=!0,n.holders--,this.reclaim(t,n)}}}holdSession(e,t,n,r){let i=this.hold(e,t,n),a,o;try{a=this.viewOf(i.entry,i.state,r,`request`),o=this.leaseOf(a)}catch(e){throw i[Symbol.dispose](),e}return o.read=!0,this.holdViewOf(i,a,o)}holdView(e){let t=this.views.get(e);if(t===void 0)return null;let n=this.leaseOf(t);return this.holdViewOf(this.holdState(n.entry,t.state),t,n)}holdViewOf(e,t,n){n.holders++;let r=!1;return{entry:e.entry,state:e.state,view:t,[Symbol.dispose]:()=>{if(r)throw Error(`render-cache view hold released twice`);r=!0,n.holders--,this.reclaimView(t,n),e[Symbol.dispose]()}}}openFailure(e){return this.openFailures.get(e)??null}follow(e,t,n,r){try{var i=ja();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(WZ(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=eQ(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 XZ(e,t,n,this.deps)}drop(e,t,n){t.watcher?.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${tr(this.accountedBytes())}/${tr(this.budgetBytes())}MB`)}serve(e){let t=this.compiles.get(e.compileKey);if(t!==void 0&&t!==e.compiled)throw Error(`render cache: a second compile for key ${e.compileKey.slice(0,12)}`);this.holds.set(e,{holders:0,retired:null}),this.compiles.set(e.compileKey,e.compiled),t===void 0&&this.log(`info`,`render-cache compile built key=${e.compileKey.slice(0,12)} compiles=${this.compiles.size}`)}holdOf(e){let t=this.holds.get(e);if(t===void 0)throw Error(`render-cache state never served`);return t}retire(e,t,n){for(let r of[...this.views.values()])if(r.state===e){if(n!==null)try{this.opened(n.entry,n.state,r.facts(),this.leaseOf(r).read,`reload`)}catch(e){this.log(`error`,`session view reopen failed sid=${JSON.stringify(r.sessionId)}: ${String(e)}`)}this.retireView(r,t)}let r=this.holdOf(e);r.retired={reason:t,held:r.holders},this.reclaim(e,r)}reclaim(e,t){t.retired===null||t.holders>0||(this.holds.delete(e),this.log(`info`,UZ(t.retired,e.registry.dispose())),[...this.holds.keys()].some(t=>t.compileKey===e.compileKey)||this.compiles.delete(e.compileKey))}sessionsOn(e){return[...this.views.values()].filter(t=>t.state===e.state).map(e=>e.sessionId)}reload(e,t,n){this.reloadInto(this.getOrCreate(e,t,n))}reloadInto(e){let t=this.sessionsOn(e),n=this.load(e.projectDir,e.cwd,e.configFile);if(e.lastWarning=n.warning,e.lastError=n.error,n.state!==null){this.log(`info`,VZ(n.layers,n.state,n.ms));let t=e.state;e.state=n.state,this.serve(n.state),this.retire(t,`reload`,{entry:e,state:n.state})}this.fit(e),this.refreshWatcher(e,n),this.observers.onReload?.(e,t)}reloadEvery(){this.log(`info`,`repo-config answers changed, reloading entries=${this.entries.size}`);for(let e of this.entries.values())this.reloadInto(e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos,e.failedFile=t.error===null?null:t.failedFile;let n=KZ(e,t.layers),r=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${JSON.stringify(n)}`;e.watcher!==null&&e.watcherKey===r||(e.watcher?.release(),e.watcherKey=r,e.watcher=this.deps.watchers.acquire(r,n,()=>this.onConfigChanged(e)))}onConfigChanged(e){this.log(`info`,`config change detected for entry projectDir=${e.projectDir} cwd=${e.cwd}`),this.reloadInto(e)}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}};const nQ=16384;var rQ=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<nQ){this.rollingTimestamps.push(e);return}this.rollingTimestamps[this.rollingHead]=e,this.rollingHead=(this.rollingHead+1)%nQ}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:Ze,sourceDigest:et(),protocolVersion:3,startedAt:this.startedAt.toISOString(),uptimeSec:Math.floor((Date.now()-this.startedAt.getTime())/1e3),rssBytes:t.rss,heapUsedBytes:t.heapUsed,heapTotalBytes:t.heapTotal,externalBytes:t.external,arrayBuffersBytes:t.arrayBuffers,requests:{total:this.requestsTotal,errored:this.requestsErrored,timedOut:this.requestsTimedOut,inFlight:this.inFlight},unknownHookFields:[...this.unknownHookFields],gitCache:e.gitCache,usageCache:e.usageCache,sources:e.sources,transcriptReads:e.transcriptReads,renderCache:e.renderCache,effectCache:e.effectCache,menuIdle:e.menuIdle,runs:e.runs,sessionState:e.sessionState,frameFeeds:e.frameFeeds,tmuxStatus:e.tmuxStatus,watchers:{active:e.watchersActive,opened:this.watchersOpened,closed:this.watchersClosed,refused:this.watchRefusals,errors:this.watchErrors},subprocesses:this.snapshotSubprocesses(),nextRestartReason:e.nextRestartReason??null,handlerProbes:e.handlerProbes,clients:e.clients,bundle:e.bundle,daemon:e.daemon,doctorStores:e.doctorStores}}};function iQ(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 aQ={load:()=>({}),save:()=>{},flush:()=>{}};var oQ=class{sessions;storage;head=0;atom=(0,J.createAtom)(`SessionState`);constructor(e=aQ,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 sQ(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 cQ=class{timer=null;pending=null;writing=!1;generation=0;writingPath;constructor(e,t=500,n=Me){this.filePath=e,this.debounceMs=t,this.logger=n,this.writingPath=`${e}.writing`}load(){let e;try{e=p.readFileSync(this.filePath,`utf8`)}catch(e){let t=e.code;return t!==`ENOENT`&&this.logger(`warn`,`session-state read failed (${t}); starting empty`),{}}try{let t=JSON.parse(e);return sQ(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 lQ=new Set([`1`,`true`]),uQ=new Set([`0`,`false`,``]);function dQ(e,t){let n=IQ(e),r=n.scope===`segment-palette`?`string`:by(n.field);if(r===`string`)return JSON.stringify(t);if(r===`number`){let n=Number(t);if(!Number.isFinite(n))throw Error(`persistValueText: "${e}" expects a number, got "${t}"`);return String(n)}if(lQ.has(t))return`true`;if(uQ.has(t))return`false`;throw Error(`persistValueText: "${e}" expects boolean-ish (1, 0, true, false), got "${t}"`)}function fQ(e){try{return p.readFileSync(e,`utf8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}function pQ(e,t,n){try{if(t===null){p.rmSync(_t(e),{force:!0});return}gt(e,t)}catch(t){let r=`config write failed (${e}): ${t.message}`;throw n(`error`,r),Error(r)}}function mQ(e){return/^\s*$/.test(e)?null:Wi(e)}function hQ(e,t){return e!==null&&Ki(e,t)!==void 0}function gQ(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(gQ),...i}}return e}function _Q(e){if(!Gb(e))return gQ(e);let{rows:t,...n}=e;return{rows:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,gQ(t)])),...n}}const vQ=zH,yQ=vQ.segments,bQ=vQ.presets,xQ=vQ.root;function SQ(e,t,n,r){if(!hQ(e,t)&&n===void 0)throw new q(`cannot edit ${r}: neither the config file nor the bundled default declares ${t.join(`.`)}`)}function CQ(e,t){let n=Cj(t);return t.scope===`segment-palette`&&SQ(e,[`segments`,t.segment],yQ[t.segment],n.join(`.`)),n}function wQ(e){return Wi(ea(e))}function TQ(){return Object.entries(xQ.rows).map(([e,t])=>{let n=gQ(t);return{path:[`root`],fragment:wQ({rows:{[e]:n}}),unit:{path:[`root`,`rows`,e],value:n}}})}function EQ(e,t){let n=e===null?void 0:Ki(e,t);return n===void 0?null:{path:t,fragment:n,unit:null}}function DQ(e,t){if(t===void 0)return null;let n=_Q(t);return{path:e,fragment:wQ(n),unit:{path:e,value:n}}}function OQ(e,t){let n=[`presets`,t],r=[...n,`root`],i=bQ[t];SQ(e,n,i,r.join(`.`));let a=EQ(e,r)??DQ(r,i?.root);return a!==null&&xa(a.fragment)?a:null}function kQ(e,t){let n=ba(t.fragment);return n===null?new Map([[`#`,{path:t.path,unit:t.unit,node:t.fragment}]]):new Map([...e,...n.map(e=>[e.key,{path:[...t.path,`rows`,e.key],unit:t.unit,node:e.value}])])}function AQ(e,t){return[...TQ(),EQ(e,[`root`]),OQ(e,t)].filter(e=>e!==null).reduce(kQ,new Map)}function jQ(e,t,n){for(let{node:r,...i}of AQ(e,t).values())if(Ca(r,n))return i;throw new q(`${MQ(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 MQ(e,t){return OQ(e,t)?.path??[`root`]}function NQ(e,t){return t.scope===`preset-root`?MQ(e,t.preset):Cj(t)}function PQ(e,{unit:t}){return t===null?e:ma(e,t.path,ea(t.value),Qi)}function FQ(e){let t=Sj(e);if(t===null)throw Error(`"${e}" is not a valid persist target`);return t}function IQ(e){let t=FQ(e);if(t.scope===`preset-root`)throw Error(`"${e}" names a layout, not a value`);return t}function LQ(e,t,n,r,i){i(t,n,JQ(t,r)),pQ(t.path,r,e.logger),e.record(t.path,n,r)}function RQ(e,t,n){let r=VQ(e,t,n);if(r.length>0)throw new q(`refused: ${e.above.join(`, `)} sets ${r.join(`, `)} over ${e.path}, so this click would change nothing on the bar — edit it there`)}const zQ=()=>{};function BQ(e,t){try{return t()}catch(t){throw!(t instanceof q)||e.above.length===0?t:new q(`${t.message} — or it is declared by ${e.above.join(`, `)}, which the bar does not edit`)}}function VQ(e,t,n){let r=HQ(e,t);if(r===null)return[];let i=new Set(KQ(GQ(r),GQ(n)));return KQ(WQ(e,r),WQ(e,n)).filter(e=>!i.has(e))}function HQ(e,t){try{return UQ(e,t)}catch(e){if(e instanceof Q_)return null;throw e}}function UQ(e,t){return vH(t===null?e.above:[e.path,...e.above],VH,{entered:()=>{},warned:()=>{}},{repo:e.repo,cwd:e.cwd},n=>n===e.path&&t!==null?t:p.readFileSync(n,`utf8`))}function WQ(e,t){let[n]=t.layers;return n?.path===e.path?n.config:t.base}function GQ(e){return e.layers.at(-1)?.config??e.base}function KQ(e,t,n=``){return!qQ(e)||!qQ(t)?JSON.stringify(e)===JSON.stringify(t)?[]:[n]:[...new Set([...Object.keys(e),...Object.keys(t)])].flatMap(r=>KQ(e[r],t[r],n===``?r:`${n}.${r}`))}function qQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JQ(e,t){try{return UQ(e,t)}catch(e){throw e instanceof Q_?new q(`refused: the config file would not load after this click — ${e.message}`):e}}function YQ(e,t){let n=IQ(t),r=mQ(fQ(e)??``),i=r===null?void 0:Ki(r,Cj(n));return i!==void 0&&`value`in i?i.value:void 0}function XQ(e,t,n){ZQ(e,t,n,[])}function ZQ(e,t,n,r){let i=fQ(t.path),a=n.reduce((e,[t,n])=>ma(e,CQ(mQ(e),IQ(t)),dQ(t,n),Qi),i??``);LQ(e,t,i,BQ(t,()=>QQ(a,t.path,r,e=>e)),RQ)}function QQ(e,t,n,r){return n.reduce((e,{preset:n,id:i,setting:a,value:o})=>{let s=r(e,n,i),c=jQ(mQ(s),n,i),l=Da(PQ(s,c),c.path,i,a,ea(o));if(l===null)throw new q(`${c.path.join(`.`)} in ${t} has no placement "${i}" — the bar you clicked is stale (it reloads on the next render)`);return l},e)}function $Q(e,t,n){let r=mQ(e),i=[`presets`,t,`root`];for(let[a,{path:o,unit:s,node:c}]of AQ(r,t)){if(!Ca(c,n))continue;if(i.every((e,t)=>o[t]===e))return e;let l=s===null?Ji(e,c):ea(s.value);if(a!==`#`)return ma(e,[...i,`rows`,a],l,Qi);if(OQ(r,t)!==null)throw new q(`cannot give preset "${t}" its own copy of ${o.join(`.`)}: it already stages rows of its own over that tree`);return ma(e,i,l,Qi)}return e}function e$(e,t){return ga(e,t,t[0]===`presets`&&t.length>2&&!UH(t[1])?2:0)}function t$(e,t,n){let r=n.map(FQ),i=fQ(t.path);if(i===null)return;let a=r.reduce((e,t)=>e$(e,NQ(mQ(e),t)),i);a!==i&&LQ(e,t,i,a,zQ)}function n$(e){let t=e===null?void 0:Ki(e,[`presets`]);return t?.kind===`object`?t.entries.map(e=>e.key):[]}function r$(e,t){let n=new Set([...HH,...n$(e),...t.above.flatMap(e=>Object.keys(Li.default.parse(p.readFileSync(e,`utf8`)).presets??{}))].map(vA));return Array.from({length:n.size+1},(e,t)=>`custom-${t+1}`).find(e=>!n.has(vA(e)))}function i$(e,t,n,r,i,a){let o=fQ(t.path),s=mQ(o??``),c=r$(s,t),l=[`presets`,c],u=BQ(t,()=>OQ(s,n)),d=[...u===null?[]:[[[...l,`root`],u.unit===null?Ji(o??``,u.fragment):ea(u.unit.value)]],...Object.keys(r).length===0?[]:[[[...l,`globals`],ea(r)]]],f=i.map(([e,t])=>{let n=xj(c,e);return[CQ(s,IQ(n)),dQ(n,t)]}),p=[...d,...f].reduce((e,[t,n])=>ma(e,t,n,Qi),ma(o??``,l,`{}`,Qi));return LQ(e,t,o,BQ(t,()=>QQ(p,t.path,a.map(e=>({...e,preset:c})),$Q)),RQ),c}function a$(e,t,n,r){let i=fQ(t.path);LQ(e,t,i,ma(i??``,[`themeDefaults`,n],ea(r),Qi),RQ)}function o$(e,t,n){if(UH(n))throw new q(`cannot delete preset "${n}": it is bundled — reset its settings instead`);let r=[`presets`,n],i=fQ(t.path),a=mQ(i??``);if(i===null||a===null||Ki(a,r)===void 0)throw new q(`cannot delete preset "${n}": ${t.path} declares no ${r.join(`.`)} — the bar you clicked is stale; it reloads on the next render`);let o=Ki(a,[`globals`,`preset`]);LQ(e,t,i,[r,...o?.kind===`string`&&o.value===n?[[`globals`,`preset`]]:[]].reduce((e,t)=>e$(e,t),i),zQ)}function s$(e,t,n,r){let i=FQ(n);if(i.scope!==`preset-root`)throw Error(`"${n}" is not a "presets.<name>.root" target`);let a=fQ(t.path),o=r.op===`remove`?r.target:r.anchor,s=BQ(t,()=>jQ(mQ(a??``),i.preset,o)),c=PQ(a??``,s),{after:l,placed:u}=c$(c,s.path,r,()=>{let e=JQ(t,c).config;return tx(e.presets).map(t=>ix(e,t).node)});if(l===null)throw new q(`${s.path.join(`.`)} in ${t.path} has no placement "${o}" — the bar you clicked is stale (it reloads on the next render), or the action names a placement the layout never held`);return LQ(e,t,a,l,RQ),u}function c$(e,t,n,r){switch(n.op){case`remove`:return{after:Ta(e,t,n.target),placed:null};case`insert`:{let i=VI(n.segment,n.anchor,r());return{after:Ea(e,t,i,n.anchor,n.relation),placed:i}}}}const l$={load:()=>({}),save:()=>{}},u$=new Set(Ty.map(e=>e.sessionKey)),d$=e=>u$.has(e)||e.startsWith(Fj),f$=8*1024*1024,p$={past:[],future:[]},m$=e=>e.kind===`session`?`session:${e.key}`:`file:${e.file}`;var h$=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=l$){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)??p$;return{undo:t.length,redo:n.length,sinceEdit:r?.net.length??0}}history(e){return this.state.get(e)??p$}begin(){let e=new Map,t=(t,n)=>{let r=e.get(t)??new Map,i=r.get(m$(n));r.set(m$(n),i===void 0?n:{...n,before:i.before}),e.set(t,r)},n=new Map;return{sessionState:iQ(this.sessionState,e=>d$(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:C$(i,n),o=r.get(e),s=o===void 0?a:D$(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`,T$(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(m$)),a=n.net.filter(e=>!i.has(m$(e))),o=v$(O$(E$(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(A$).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=v$(a);return this.apply(e,i,`after`,`redo`,{past:o,future:r.slice(0,-1),...b$(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(m$)),{past:n,future:i,savepoint:a}=this.history(e);throw this.put(e,{past:O$(n,t),future:O$(i,t),...a!==void 0&&{savepoint:{at:O$([...n,...[...i].reverse()].slice(0,a.at),t).length,net:a.net.filter(e=>!t.has(m$(e))),below:O$(a.below,t)}}}),new q(`${r}: ${o.map(A$).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):fQ(t.file)}write(e,t,n){t.kind===`file`?pQ(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||g$(n)>f$;){let[e,t]=n.entries().next().value;n.size>1?n.delete(e):t.past.length+t.future.length>0?n.set(e,_$(t)):(this.logger(`warn`,`settings-history: edit mode's changes for session ${e} exceed ${f$} bytes; cancel is no longer available`),n.delete(e))}this.storage.save(Object.fromEntries(n)),this.state=n}};function g$(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 _$({past:e,future:t,savepoint:n}){return e.length>0?{past:e.slice(1),future:t,...b$(n,1,[])}:{past:e,future:t.slice(1),...b$(n,0,[])}}function v$(e){return e.slice(-50)}const y$=e=>e===Lj.member;function b$(e,t,n){return e===void 0?{}:{savepoint:{at:Math.max(0,e.at-t),net:x$(e.net,n),below:e.below}}}function x$(e,t){let n=new Map(e.map(e=>[m$(e),e]));for(let e of t){let t=n.get(m$(e));n.set(m$(e),t===void 0?e:{...t,after:e.after})}return[...n.values()].filter(e=>e.before!==e.after)}const S$=e=>e.map(e=>({...e,before:e.after,after:e.before}));function C$(e,t){let n=[...e.past,t],r=v$(n),{savepoint:i}=e,a=i===void 0?0:Math.max(0,i.at-e.past.length);return{past:r,future:[],...b$(i&&{at:Math.min(i.at,e.past.length),net:i.net,below:[...w$(e.future,a),...i.below]},n.length-r.length,t)}}function w$(e,t){let n=Math.min(t,e.length);return e.slice(e.length-n).reverse()}function T$(e,t){return{past:e.past.slice(0,-1),future:v$([...e.future,t]),...b$(e.savepoint,0,S$(t))}}function E$(e,t){let{past:n,future:r}=e,i=n.slice(0,t.at);return[...i,...w$(r,t.at-i.length),...t.below]}function D$(e,t){if(y$(t.after)&&!y$(t.before))return{...e,savepoint:{at:e.past.length,net:[],below:[]}};if(!y$(t.after)&&y$(t.before)){let{past:t,future:n}=e;return{past:t,future:n}}return e}function O$(e,t){return e.map(e=>e.filter(e=>!t.has(m$(e)))).filter(e=>e.length>0)}function k$(e){return e.map(A$).join(`, `)}function A$(e){return e.kind===`session`?`session setting "${e.key}"`:e.file}function j$(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 M$(e){return Array.isArray(e)&&e.every(e=>Array.isArray(e)&&e.every(j$))}function N$(e){if(typeof e!=`object`||!e)return!1;let t=e;return Number.isInteger(t.at)&&t.at>=0&&Array.isArray(t.net)&&t.net.every(j$)&&M$(t.below)}function P$(e){if(typeof e!=`object`||!e)return!1;let t=e;return M$(t.past)&&M$(t.future)&&(t.savepoint===void 0||N$(t.savepoint))}function F$(e,t){let n=e=>e.kind===`file`||d$(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 I$(e,t){return{load:()=>{let n;try{n=p.readFileSync(e,`utf8`)}catch(e){let n=e.code;return n!==`ENOENT`&&t(`warn`,`settings-history read failed (${n}); starting empty`),{}}try{let e=JSON.parse(n);if(typeof e==`object`&&e&&!Array.isArray(e)&&Object.values(e).every(P$)){let n=new Set,r=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,F$(t,n)]));return n.size>0&&t(`warn`,`settings-history load: dropped the changes to ${[...n].map(e=>`"${e}"`).join(`, `)}, no longer a setting`),r}}catch{}return t(`warn`,`settings-history load: unexpected shape, starting empty`),{}},save:n=>{try{p.mkdirSync(s.dirname(e),{recursive:!0}),gt(e,JSON.stringify(n),384)}catch(e){let n=`settings-history write failed — the change landed but is not undoable: ${e.message}`;throw t(`error`,n),Error(n)}}}}const L$=e=>!d$(e)&&!uP(e)&&e!==`update.dismissed`;var R$=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:iQ(e,L$,(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 z$={inside:()=>[],defaultOf:()=>yi,menus:[]},B$=e=>`${e.key}\0${e.member}`;function V$(e){let t=new Map,n=n=>{let r=`${n.name}\0${C_(n)}`,i=t.get(r);if(i!==void 0)return i;let a=e.segments[n.name]?.template,o=a===void 0?[]:nz(a,C_(n));return t.set(r,o),o},r=e=>[...e.opens===void 0?[]:[e.opens.ref],...n(e)],i=new Map,a=new Map;for(let t of Object.values(e.variables))t.kind===`state`&&(t.default!==void 0&&i.set(t.key,t.default),t.within!==void 0&&a.set(t.key,t.within));let o=new Map,s=new Map,c=new Map,l=e=>{s.set(e.key,(s.get(e.key)??new Set).add(e.member))},u=(e,t)=>{let n=o.get(B$(e))??new Map;n.set(B$(t),t),o.set(B$(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(B$(n),n);for(let e of t)u(e,n)}e.opens!==void 0&&d(e.opens.body,[...t,e.opens.ref])};for(let t of tx(e.presets))d(ix(e,t).node,[]);for(let t of Object.values(e.actions)){let e=Mi(t);e!==void 0&&l(e)}for(let[e,t]of a)for(let n of s.get(e)??[])for(let r of t)u(r,{key:e,member:n});let f=new Map;return{inside:e=>{let t=f.get(B$(e));if(t!==void 0)return t;let n=new Map,r=e=>{for(let[t,i]of o.get(B$(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(B$(e),a),a},menus:[...c.values()],defaultOf:e=>i.get(e)??`closed`}}const H$=new WeakMap;function U$(e){let t=H$.get(e);if(t!==void 0)return t;let n=V$(e);return H$.set(e,n),n}function W$(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 G$(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 K$(e,t,n){let r=(r,i,a)=>{let o=W$(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 q$=[`CLAUDE_CODE_SESSION_ID`,`CLAUDE_PROJECT_DIR`,`CLAUDE_CONFIG_DIR`,`TMUX`,`TMUX_PANE`];function J$(e,t){let n={...e};for(let e of q$)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 Y$=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function X$(e){let t=e=>({kind:`failed`,reason:e});if(!Y$(e))return t(`is not an object`);for(let[n,r]of Object.entries(e)){if(!Y$(r))return t(`holds ${JSON.stringify(n)} as something other than its sightings`);for(let[e,n]of Object.entries(r))if(!ZM.includes(n))return t(`marks ${JSON.stringify(e)} ${JSON.stringify(n)}, not ${ZM.join(` or `)}`)}return{kind:`ok`,value:e}}function Z$(e,t,n,r){return{...e,[t]:{...e[t],[n]:r}}}const Q$=e=>Sq(e,`doctor-marks.json`,{},X$),$$=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of terminals`},e1=(e,t)=>e.includes(t)?e:[...e,t],t1=e=>Sq(e,`doctor-clicked-terminals.json`,[],$$);var n1=class extends Error{constructor(e){super(`the doctor looked at ${e} less than a second ago — click again`),this.name=`DoctorBusy`}};const r1=e=>e===void 0||e===``?{kind:`recent`}:{kind:`shell`,sessionId:e},i1=(e,t)=>t.filter(t=>e.kind===`recent`?t.ago<=300:t.sessionId===e.sessionId),a1=(e,t,n)=>{if(e.kind===`recent`)return n;let[r]=i1(e,t);return r===void 0?n:r.projectDir},o1=(e,t)=>i1(e,t).map(({role:e,frame:t,projectDir:n,claudeConfigDir:r})=>({role:e,frame:t,projectDir:n,claudeConfigDir:r}));function s1(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*c1(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 l1={pullRequests:e=>Gq(e).showPullRequest===!0,rateLimits:e=>Wq(e,`block`)||Wq(e,`weekly`)};function u1(e,t){let n=new Map;for(let r of D_(ix(e,t).node)){if(r.kind!==`segment`)continue;let e=n.get(r.name)??[];r.when&&e.push(r.when),n.set(r.name,e)}let r=[...n.keys()].filter(t=>L_(e.segments[t])===`fail`),i=new Map(r.map(t=>[t,Vq(e,t,n.get(t))])),a=e=>r.filter(t=>l1[e](i.get(t)));return{pullRequests:a(`pullRequests`),rateLimits:a(`rateLimits`)}}
|
|
202
202
|
/*!
|
|
203
203
|
* Copyright (c) Squirrel Chat et al., All rights reserved.
|
|
204
204
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
@@ -226,9 +226,9 @@ Config tooling:
|
|
|
226
226
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
227
227
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
228
228
|
*/
|
|
229
|
-
function
|
|
229
|
+
function d1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().length+1]}function f1(e,t,n){let r=e.split(/\r?\n/),i=``,a=(Math.log10(t+1)|0)+1;for(let e=t-1;e<=t+1;e++){let o=r[e-1];o&&(i+=e.toString().padEnd(a,` `),i+=`: `,i+=o,i+=`
|
|
230
230
|
`,e===t&&(i+=` `.repeat(a+n+2),i+=`^
|
|
231
|
-
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=
|
|
231
|
+
`))}return i}var Q=class e extends Error{line;column;codeblock;constructor(e,t){let[n,r]=d1(t.toml,t.ptr),i=f1(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 u1(e,t){let n=e.slice(0,t).split(/\r?\n/);return[n.length,n.pop().lengt
|
|
|
256
256
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
257
257
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
258
258
|
*/
|
|
259
|
-
function
|
|
259
|
+
function p1(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 f1(e){let t=e.p,n=e.s.charCodeAt(e.p++),r=n,i=n===39,a=n===e.s.charCode
|
|
|
285
285
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
286
286
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
287
287
|
*/
|
|
288
|
-
let
|
|
288
|
+
let m1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[-+]\d{2}:\d{2})?$/i;var h1=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(m1);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 p1=/^(\d{4}-\d{2}-\d{2})?[Tt ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|z|[
|
|
|
313
313
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
314
314
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
315
315
|
*/
|
|
316
|
-
function
|
|
316
|
+
function g1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48+t}function _1(e,t){return e===32||e===9||e===10||e===13||t&&(e===t||e===44)||e===35}function v1(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?k1(e):O1(e);return e.d++,t}return r===34||r===39?p1(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?y1(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?S1(e,r,t):e.s.charCodeAt(e.p+2)===58?C1(e,r,t):y1(e,e.p,r,0,t)}function y1(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||_1(a=e.s.charCodeAt(e.p),i))return e.bi===!0?0n:0;if(!r){if(a===120)return b1(e,t,16,i);if(a===98)return b1(e,t,2,i);if(a===111)return b1(e,t,8,i)}a===46?o=2:a===101||a===69?o=4:Q.x(`illegal leading zero`,e,t)}else g1(a)||Q.x(`invalid value`,e,t);for(;++e.p<e.s.length&&(a=e.s.charCodeAt(e.p),!_1(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:g1(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):x1(e,c,10,t)}function b1(e,t,n,r){let i,a=1;for(;++e.p<e.s.length&&(i=e.s.charCodeAt(e.p),!_1(i,r));)i===95?(a&1&&Q.x(`illegal underscore`,e),a=3):g1(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(`_`,``)),x1(e,o,n,t)}function x1(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 S1(e,t,n){let r=e.p++,i;if(!g1(t)||!g1(e.s.charCodeAt(e.p++))||!g1(e.s.charCodeAt(e.p++))||!g1(e.s.charCodeAt(e.p++)))return y1(e,e.p=r,t,0,n);if(e.p+=5,g1(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,!g1(e.s.charCodeAt(e.p+1))))&&t!==84&&t!==116)return w1(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(;g1(e.s.charCodeAt(++e.p)););if(t=e.s.charCodeAt(e.p)){if(t===90||t===122)return w1(e,e.s.slice(r,++e.p),1,i,r,`[+00:00]`);if(t===43||t===45)return w1(e,e.s.slice(r,e.p+=6),1,i,r,!e.ld&&`[`+e.s.slice(e.p-6,e.p)+`]`)}return w1(e,e.s.slice(r,e.p),2,i,r)}function C1(e,t,n){let r=e.p;if(!g1(t)||!g1(e.s.charCodeAt(++e.p)))return y1(e,--e.p,t,0,n);if(e.s.charCodeAt(e.p+=4)===58&&(e.p+=3),e.s.charCodeAt(e.p)===46)for(;g1(e.s.charCodeAt(++e.p)););return w1(e,e.s.slice(r,e.p),4,!1,r)}function w1(e,t,n,r,i,a){if(e.ld){let a=new h1(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 h1(e,t=10){return t===16?e>47&&e<58||e>64&&e<71||e>96&&e<103:e>47&&e<48
|
|
|
341
341
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
342
342
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
343
343
|
*/
|
|
344
|
-
function
|
|
344
|
+
function T1(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 E1(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;T1(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 w1(e){for(;e.p<e.s.length;e.p++){let t=e.s.charCodeAt(e.p);if(t===10)br
|
|
|
369
369
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
370
370
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
371
371
|
*/
|
|
372
|
-
function
|
|
372
|
+
function D1(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(p1(e)),r=2,e.p--):o===32||o===9?r===1&&(i.push(e.s.slice(a,e.p)),r=2):r===2||o<48&&o!==45||o>57&&o<65||o>90&&o<97&&o!==95||o>122?Q.x(`illegal character in key`,e):r||(r=1,a=e.p);while(o=e.s.charCodeAt(++e.p));Q.x(`incomplete key-value: cannot find end of key`,e,n)}function O1(e){let t=e.p++,n=Object.create(null),r=new Set,i;for(;e.p<e.s.length;){if(E1(e),(i=e.s.charCodeAt(e.p))===125)return e.p++,n;let t,a=n,o=!1,s=e.p,c=D1(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),E1(e,!0,!0);let l=v1(e,125);if(a&&typeof(a[t]=l)==`object`&&r.add(l),E1(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 k1(e){let t=e.p++,n=[],r;for(;e.p<e.s.length;){if(E1(e),(r=e.s.charCodeAt(e.p))===93)return e.p++,n;if(n.push(v1(e,93)),E1(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 E1(e,t=61){let n,r=0,i=[],a,o=e.s.charCodeAt(n=e.p);do if(o===t)return
|
|
|
397
397
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
398
398
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
399
399
|
*/
|
|
400
|
-
function
|
|
400
|
+
function A1(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 j1(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 M1(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++,E1(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=D1(n,93);t&&(e.charCodeAt(n.p)!==93&&Q.x(`expected end of table array declaration`,n),n.p++);let u=A1(n,l,r,i,t?2:1);u?(c=u[2],s=u[1]):(j1(n,u,a),o=!0)}else{a=n.p;let e=A1(n,D1(n),s,c,0);!e&&!o&&j1(n,e,a),E1(n,!0,!0);let t=v1(n,void 0);e&&!o&&(e[1][e[0]]=t)}E1(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),E1(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 k1(e,t,n,r,i){let a=n,o=r,s,c=!1,l;for(let n=0;n<t.length;n++){if(n){if
|
|
|
425
425
|
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
426
426
|
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
427
427
|
*/
|
|
428
|
-
const
|
|
428
|
+
const N1=e=>e.codePointAt(0).toString(16).toUpperCase(),P1=String.raw`
|
|
429
429
|
ObjC.import("AppKit");
|
|
430
430
|
ObjC.import("CoreText");
|
|
431
431
|
function lacksOf(font, points) {
|
|
@@ -472,49 +472,49 @@ function run(argv) {
|
|
|
472
472
|
: iterm(argv[1], points),
|
|
473
473
|
);
|
|
474
474
|
}
|
|
475
|
-
`;function
|
|
476
|
-
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const
|
|
477
|
-
`,`:family=${
|
|
478
|
-
`)){let e=/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\w{3} \w{3}\s+\d+ [\d:]{8} \d{4})\s+.* (\/.*) daemon$/.exec(r);e===null||!t(e[5])||n.push({pid:Number(e[1]),ppid:Number(e[2]),rss:Number(e[3])*1024,started:`${e[4].replace(/\s+/g,` `)} UTC`})}return n.filter(e=>!n.some(t=>t.ppid===e.pid))}function
|
|
475
|
+
`;function F1(e){let t=D({bin:`osascript`,args:[`-l`,`JavaScript`,`-e`,P1,...e],timeoutMs:3e3,category:`doctor.font`});if(!t.ok){if(t.reason===`rate-limited`)throw new n1(`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 I1=e=>e.map(e=>String.fromCodePoint(parseInt(e,16))),L1=e=>[...e].map(N1).join(`,`);function R1(e,t){let n=F1([`font`,e.kind,e.name,L1(t)]);if(n.kind===`failed`)return n;let{lacks:r}=n.value;return{kind:`ok`,value:{font:e.name,lacks:r===null?null:I1(r)}}}function z1(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=>!PM(t,e));return{kind:`ok`,value:{font:e.font,from:n,lacks:r}}}const B1=e=>e.kind===`ok`&&e.value.lacks!==null&&e.value.lacks.length===0;function V1(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=>z1(e,n));if(t!==null)return r[0];let i=r.find(e=>!B1(e));return i===void 0?{kind:`ok`,value:{font:[...new Set(r.flatMap(e=>e.kind===`ok`?[e.value.font]:[]))].join(`, `),from:`every iTerm2 profile, since the session does not say which draws the bar`,lacks:[]}}:i.kind===`failed`?i:{kind:`ok`,value:{...i.value,from:`${i.value.from}, one of its profiles, and the session does not say which draws the bar`}}}function H1(e,t,n){if(process.platform!==`darwin`)return{kind:`failed`,reason:`iTerm2 runs only on macOS`};let r=t.ITERM_PROFILE??null,i=F1([`iterm`,r??``,L1(n)]);return i.kind===`failed`?i:V1(i.value.profiles.map(e=>({...e,lacks:e.lacks===null?null:I1(e.lacks)})),r,e)}function U1(e,t){let n=e.split(`
|
|
476
|
+
`).filter(e=>e!==``).map(e=>{let t=e.indexOf(` `);return t<=0?null:{family:e.slice(0,t),ranges:e.slice(t+1).split(/\s+/).filter(e=>e!==``).map(e=>{let[t,n=t]=e.split(`-`).map(e=>parseInt(e,16));return[t,n]})}});if(n.length===0||n.some(e=>e===null))return{kind:`failed`,reason:`fc-match answered ${JSON.stringify(e.slice(0,200))}, not families and their charsets`};let r=n.flatMap(e=>e.ranges),i=[...t].filter(e=>{let t=e.codePointAt(0);return!r.some(([e,n])=>e<=t&&t<=n)});return{kind:`ok`,value:{font:n[0].family,lacks:i}}}const W1=e=>e.replace(/[\\:,=-]/g,`\\$&`);function G1(e,t){let n=D({bin:`fc-match`,args:[`--sort`,`--format`,`%{family[0]} %{charset}
|
|
477
|
+
`,`:family=${W1(e)}`],timeoutMs:3e3,category:`doctor.font`});if(!n.ok){if(n.reason===`rate-limited`)throw new n1(`the font`);return{kind:`failed`,reason:`fc-match failed (${n.error??`${n.reason}: ${n.stderr.trim()}`})`}}return U1(n.stdout,t)}function K1(e,t){return process.platform===`darwin`?R1(e,t):G1(e.name,t)}function q1(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 J1(e){return e===`darwin`?`Menlo`:`monospace`}const Y1=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function X1(e){let t=Y1(e.font)?e.font:{},n=Y1(t.normal)?t.normal:{},r=(Y1(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 Z1(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=M1(r)}catch(t){return{kind:`failed`,reason:`cannot parse ${e}: ${t.message}`}}let a=X1(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=Z1(i,t,n+1);if(a.kind===`failed`)return a;o=a.value??o}return{kind:`ok`,value:o}}function Q1(e,t){let n=C.homedir(),r=q1(n,e.XDG_CONFIG_HOME).find(e=>p.existsSync(e)),i=r===void 0?{kind:`ok`,value:null}:Z1(r,n,0);if(i.kind===`failed`)return i;let a=i.value?.family??J1(process.platform),o=i.value?.from??(r===void 0?`Alacritty's default, no config file`:`Alacritty's default, ${r} sets none`),s=K1({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 $1={iterm2:H1,alacritty:(e,t,n)=>Q1(t,n)};function e0(e,t,n){return $1[e.name](e.version,t,n)}function t0(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 n0=e=>Sq(e,`doctor-post-mortems-read.json`,{through:null},t0);function r0(e){try{return{kind:`ok`,value:e()}}catch(e){return{kind:`failed`,reason:e instanceof Error?e.message:String(e)}}}const i0={realpath:e=>r0(()=>p.realpathSync(e)),checkoutOf:Qe,digest:e=>r0(()=>Ye(e)),nativeShipped:yo(process.platform,process.arch)};function a0(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 o0=e=>({marks:Q$(e),clicked:t1(e),postMortemsRead:n0(e)}),s0=e=>({marks:e.marks.read(),clicked:e.clicked.read(),postMortemsRead:e.postMortemsRead.read()});function c0(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 l0=/^(sshd|mosh-server)\b/;function u0(e,t){let n=s1(e);if(!n.has(t))return{kind:`failed`,reason:`process ${t} is not running`};for(let e of c1(n,t))if(l0.test(e.command.slice(e.command.lastIndexOf(`/`)+1)))return{kind:`ok`,value:!0};return{kind:`ok`,value:!1}}function d0(e){let t=D({bin:`ps`,args:[`-A`,`-o`,`pid=,ppid=,comm=`],timeoutMs:2e3,category:`doctor.process`});if(!t.ok){if(t.reason===`rate-limited`)throw new n1(`the processes`);return{kind:`failed`,reason:`ps failed (${t.error??`${t.reason}: ${t.stderr.trim()}`})`}}return u0(t.stdout,e)}const f0=/^(.*)\/(?:dist\/index\.mjs|src\/index\.ts|bin\/cc-candybar)$/;function p0(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 m0(e){let t;try{t=p.realpathSync(e)}catch{return!1}let n=f0.exec(t)?.[1];return n!==void 0&&p.existsSync(s.join(n,`bin`,`cc-candybar`))}function h0(){let e=D({bin:`ps`,args:[`-U`,String(C.userInfo().uid),`-ww`,`-o`,`pid=,ppid=,rss=,lstart=,args=`],timeoutMs:2e3,category:`doctor.daemons`,env:{...process.env,LC_ALL:`C`,TZ:`UTC`}});return e.ok?{kind:`ok`,value:p0(e.stdout,m0)}:{kind:`failed`,reason:`ps failed (${e.error??`${e.reason}: ${e.stderr.trim()}`})`}}function g0(e){let t=JK(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 n1(`tmux`);return t.kind===`failed`?{kind:`failed`,reason:t.reason}:c0(t.stdout)}function _0(e){return{probeTmux:g0,remoteLogin:d0,fontInUse:e0,loadConfig:e,managedSettingsDir:process.env.CC_CANDYBAR_CLAUDE_MANAGED_DIR??ro(process.platform),install:i0,daemons:h0,forge:S0,transcript:y0}}function v0(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=eK(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function
|
|
482
|
-
`)};return e.error===null?{...t,kind:`loaded`,unused:e.unused}:{...t,kind:`failed`,error:e.error}}const
|
|
483
|
-
`);let i=
|
|
481
|
+
`)){let t=eK(e);t.kind!==`blank`&&(a++,t.kind===`unparsed`&&o++)}return{lines:a,unparsed:o,whole:t}}function y0(e){let t=qa(e,QM+1);return t.kind===`ok`?P(v0(t.value.buf,t.value.fromStart)):t}function b0(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 x0={github:{loginHost:()=>`github.com`,args:e=>[`auth`,`token`,`--hostname`,e],nonZero:`logged-out`},gitlab:{loginHost:e=>e,args:()=>[`--version`],nonZero:`failed`}};function S0(e){if(WV(e)===void 0)return{kind:`ok`,value:null};let t=qW(D({bin:`git`,args:[...KW],cwd:e,env:{...process.env,GIT_OPTIONAL_LOCKS:`0`},timeoutMs:2e3,category:`doctor.forge`}));if(t.kind===`failed`)return t;let n=QW(t.value);if(n===null)return{kind:`ok`,value:null};let r=GW(n);if(r===null)return{kind:`ok`,value:null};let i=BW[r],a=x0[r],o=a.loginHost(WW(n)),s=D({bin:i,args:[...a.args(o)],cwd:e,timeoutMs:2e3,category:`doctor.forge`});return C0(i,o,a.nonZero,s)}function C0(e,t,n,r){let i=n=>({kind:`ok`,value:{cli:e,host:t,status:n}});return r.ok?i(`ready`):VW(r)?i(`missing`):r.reason===`non-zero`&&n===`logged-out`?i({loggedOut:LW(r.stderr)}):{kind:`failed`,reason:IW(e,r)}}function w0(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 T0=e=>r0(()=>ao(e));function E0(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:Za(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:T0(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 D0(e,t){return t===void 0?{kind:`unreported`}:t===null?{kind:`outside`}:{kind:`inside`,hint:t,client:e.probeTmux(t)}}function O0(e,t){switch(e.kind){case`unreported`:return{kind:`unreported`};case`outside`:return t===void 0?{kind:`unreported`}:{kind:`seen`,identified:VM(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:BM(t),tmuxClient:t}}}}function k0(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(AM(s))return{kind:`bundling`,name:s,version:c};if(!jM(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 A0(e){switch(e.via){case`link`:return{kind:`arrived`,handler:e.handler,bar:Ze};case`tmux-status`:return{kind:`unprobed`,reason:"this run was asked from the tmux status line, whose clicks tmux runs rather than the URL handler — run `cc-candybar doctor` to probe the handler"}}}function j0(e,t){let[n,...r]=e;return n===void 0?{kind:`unneeded`}:{kind:`needed`,segments:[n,...r],fact:t()}}function M0(e,t,n,r){return{pullRequests:j0(t.pullRequests,()=>e.forge(n.cwd)),rateLimits:j0(t.rateLimits,()=>r)}}function N0(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 P0(e,t,n,r,i,a,o,s,c,l,u){let d=e.loadConfig(n),f=XH(d.config,r,()=>!1),p=D0(e,t.tmux),m=O0(p,t.terminalEnv),h=[...new Set([...fb(f),...db(JSON.stringify(d.config))])].join(``);return{tmux:p,width:l,terminal:m,nerdFont:h===``?{kind:`none`}:{kind:`glyphs`,glyphs:h,terminal:k0(e,m,t,h)},marks:u.marks,clicked:u.clicked,daemon:{serving:i,processes:e.daemons(),read:u.postMortemsRead},config:w0(d),sighted:s,frames:c.kind===`failed`?c:{kind:`read`},data:M0(e,u1(d.config,f.preset),n,a),transcripts:b0(e,o),claudeSettings:E0({managedDir:e.managedSettingsDir,projectDir:n.projectDir,userFile:Za(Xa(t.claudeConfigDir))},c.kind===`ok`?c.value:[])}}function F0(e,t,n){switch(t.kind){case`claude-settings`:{let e=t.file.path;gt(e,ma(eo(e),t.path,JSON.stringify(t.value),$i));let r=e=>({...e,sources:T0(e.at)}),{origin:i,elsewhere:a}=n.claudeSettings;return{kind:`ok`,value:{...n,claudeSettings:{origin:r(i),elsewhere:a.map(r)}}}}case`post-mortems-read`:{let r=e.postMortemsRead.update(e=>e.through===null||ir(t.through,e.through)?{through:t.through}:e);return r.kind===`failed`?r:{kind:`ok`,value:{...n,daemon:{...n.daemon,read:r}}}}default:return t}}const I0={connectMs:200,budgetMs:500};async function L0(e){let n=e.includes(`--json`),r=await R0();r.kind!==`ok`&&(t.stderr.write(`daemon-stats: ${un(r)}\n`),t.exit(1)),n&&t.stdout.write(JSON.stringify(r.value,null,2)+`
|
|
483
|
+
`);let i=z0(r.value);if(i!==null){t.stderr.write(`daemon-stats: ${i}\n`),t.exitCode=1;return}n||t.stdout.write(q0(r.value))}function R0(){return rn(()=>({kind:`stats`}),I0,e=>`stats`in e?e.stats:void 0)}function z0(e,t=B0){let n=rQ.referenceSnapshot(),r=V0(Object.fromEntries(t.map(e=>[e,n[e]])),e);if(r.length===0)return null;let i=U0(e.version,e.sourceDigest??null),a=U0(Ze,et());return`the daemon (${i}) reports no ${r.join(`, `)}; it is another build than this client (${a}), and restarts only when its own bundle changes`}const B0=Object.keys(rQ.referenceSnapshot());function V0(e,t,n=``){if(Array.isArray(e))return Array.isArray(t)?[]:[n||`<snapshot>`];if(!H0(e))return[];if(!H0(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(...V0(e[i],t[i],a)):r.push(a)}return r}function H0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U0(e,t){return`${e} [${t===null?`no digest`:Xe(t)}]`}function W0(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/1024/1024).toFixed(1)}MB`}function G0(e,t){let n=e+t;return n===0?`n/a`:`${(e/n*100).toFixed(1)}%`}function K0(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 q0(e){let t=[];t.push(`cc-candybar daemon stats`),t.push(``),t.push(`process`),t.push(` pid ${e.pid}`),t.push(` build ${U0(e.version,e.sourceDigest)}`),t.push(` protocol ${e.protocolVersion}`),t.push(` startedAt ${e.startedAt}`),t.push(` uptime ${K0(e.uptimeSec)}`),t.push(` rss ${W0(e.rssBytes)}`),t.push(` heapUsed ${W0(e.heapUsedBytes)}`),t.push(` heapTotal ${W0(e.heapTotalBytes)}`),t.push(` external ${W0(e.externalBytes)}`),t.push(` arrayBuffers ${W0(e.arrayBuffersBytes)}`),t.push(``),t.push(`requests`),t.push(` total ${e.requests.total}`),t.push(` errored ${e.requests.errored}`),t.push(` timedOut ${e.requests.timedOut}`),t.push(` inFlight ${e.requests.inFlight}`),t.push(` unknownFields ${e.unknownHookFields.map(e=>JSON.stringify(e)).join(`, `)||`-`}`),t.push(``),t.push(`gitCache`),t.push(` size ${e.gitCache.size}`),t.push(` held ${e.gitCache.held}`),t.push(` hit rate ${G0(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 ${G0(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 ${W0(e.transcriptReads.bytes)}`),t.push(` long lines ${e.transcriptReads.longLines}`),t.push(` largest line ${W0(e.transcriptReads.largestLine)}`),t.push(``),t.push(`renderCache`),t.push(` size ${e.renderCache.size}`),t.push(` held ${e.renderCache.held}`),t.push(` retired ${e.renderCache.retired}`),t.push(` compiles ${e.renderCache.compiles}`),t.push(` views ${e.renderCache.views}`),t.push(` pinned ${e.renderCache.pinned}`),t.push(` retired views ${e.renderCache.retiredViews}`),t.push(` accounted ${W0(e.renderCache.accountedBytes)} / ${W0(e.renderCache.budgetBytes)}`),t.push(``),t.push(`effectCache`),t.push(` sessions ${e.effectCache.sessions}`),t.push(` effects ${e.effectCache.effects}`),t.push(``),t.push(`menuIdle`),t.push(` sessions ${e.menuIdle.sessions}`),t.push(` armed ${e.menuIdle.armed}`),t.push(``),t.push(`sessionState`),t.push(` sessions ${e.sessionState.sessions}`),t.push(` observers ${e.sessionState.observers}`),t.push(` revision ${e.sessionState.revision}`),t.push(``),t.push(`watchers`),t.push(` active ${e.watchers.active}`),t.push(` opened ${e.watchers.opened}`),t.push(` closed ${e.watchers.closed}`),t.push(` refused ${e.watchers.refused}`),t.push(` errors ${e.watchers.errors}`),t.push(``),t.push(`subprocesses`),t.push(` total ${e.subprocesses.total}`),t.push(` inFlight ${e.subprocesses.inFlight}`),t.push(` lastMinute ${e.subprocesses.lastMinute}`);let o=Object.entries(e.subprocesses.byCategory),s=o.reduce((e,[t])=>Math.max(e,t.length),13);for(let[n,r]of o){let i=e.subprocesses.p50DurationMs[n],a=e.subprocesses.p99DurationMs[n],o=i!==void 0&&a!==void 0?` (p50 ${i}ms · p99 ${a}ms)`:``;t.push(` ${n.padEnd(s)} ${r}${o}`)}return e.nextRestartReason&&(t.push(``),t.push(`nextRestart ${e.nextRestartReason}`)),t.join(`
|
|
484
484
|
`)+`
|
|
485
|
-
`}const
|
|
486
|
-
`).join(` — `));let t=
|
|
487
|
-
`);return{inMode:n!==`0`,screen:r}}function v2(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 y2(e,t){let n=g2(e,`claude-input.type`,v2(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 b2(){return{read:_2,type:y2}}function x2(e){let t=DW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function S2(e){return jb(()=>decodeURIComponent(e))}function C2(e,t,n){let r=D(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function w2(e,t){C2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const T2=(e,t)=>w2(S2(e),t),E2=(e,t)=>C2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,S2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),D2=(e,t)=>w2(S2(e),t),O2=(e,t)=>w2(S2(e),t),k2=(e,t)=>{let n=x2(S2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},A2=(e,t)=>{let[n=``,...r]=jb(()=>fi(e)),i=x2(n),a=MU(G2(t,i));if(r.length===0)throw new q(`set-state: <key>/<value> is required (have keys: ${a.listKeys().join(`, `)})`);if(r.length%2!=0)throw new q(`set-state: expected even-count <key>/<value> pairs, got ${r.length} segment(s) after session id (have keys: ${a.listKeys().join(`, `)})`);let o=[];for(let e=0;e<r.length;e+=2){let t=r[e],n=r[e+1];if(!t)throw new q(`set-state: empty key at pair ${e/2+1} (expected <sessionId>/<key>/<value>[/<key>/<value>...] segments)`);let i=a.validate(t,n);if(!i.ok)throw new q(`set-state: pair ${e/2+1}: ${i.reason}`);o.push({key:t,value:i.value})}P2(t,i,`set-state`,o),t.navigating.setBatch(i,o);let s=o.map(e=>`${e.key}=${e.value}`).join(` `);t.dlog(`info`,`set-state: ${s} (session=${i})`)},j2=/^-?\d+$/;function M2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const N2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=x2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!j2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=G2(t,a),c=MU(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&&j2.test(u)?F2(l,parseInt(u,10)):I2(`step-state`,r,l,FU(s,e=>t.sessionState.get(a,e),r)),f=M2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);P2(t,a,`step-state`,[{key:r,value:p.value}]),t.navigating.set(a,r,p.value),t.dlog(`info`,`step-state: ${r} ${d}→${p.value} (by ${o}, session=${a})`)};function P2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Fj));if(i.length===0)return;let a=dU(G2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function F2(e,t){return Math.max(e.min,Math.min(e.max,t))}function I2(e,t,n,r){if(r===null)return n.min;if(!j2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return F2(n,parseInt(r,10))}const L2=`render-origin`;function R2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function z2(e){return JSON.stringify(e)}function B2(e){let t;try{t=JSON.parse(e)}catch{throw new q(`render origin is not JSON: ${e}`)}if(typeof t!=`object`||!t)throw new q(`render origin is not an object: ${e}`);let{projectDir:n,cwd:r,configFile:i}=t;if(typeof n!=`string`||typeof r!=`string`||i!==null&&typeof i!=`string`)throw new q(`render origin has the wrong shape: ${e}`);return{projectDir:n,cwd:r,configFile:i}}function V2(e,t){let n=U2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function H2(e,t){let n=e.sessionState.get(t,L2);return n===null?null:B2(n)}function U2(e,t){let n=H2(e,t);return n===null?null:R2(n,e.sessionState,t)}function W2(e,t,n){let r=U2(e,t);if(r===null)return;let{path:i}=J2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function G2(e,t){return e.configFor(V2(e,t))}function K2(e,t){let n=H2(e,t);if(n===null)return null;let r=()=>e.lanes.of(R2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function q2(e,t){let n=U2(e,t);return n===null?R$:H$(e.configFor(n))}function J2(e){return sH(wq().read(),e.projectDir,e.cwd,e.configFile??void 0)}function Y2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const X2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=x2(n),o=V2(t,a),s=t.configFor(o),c=eL(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=J2(o),d=lU(s,e=>t.sessionState.get(a,e),r);YQ(Y2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},Z2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=x2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!j2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=V2(t,a),c=t.configFor(s),l=eL(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=J2(s),f=lU(c,e=>t.sessionState.get(a,e),r),p=JQ(d.path,f.key),m=typeof p==`number`?F2(u,p):I2(`step-config`,r,u,nL(f.globals,r)),h=M2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);YQ(Y2(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})`)},Q2=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=x2(n),i=V2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=sU(a,o),c=uU(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=MU(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]});e4(`save`,l,c);let d=J2(i);XQ(Y2(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($2)].join(` `)} → ${d.path} (session=${r})`)},$2=e=>`${e.preset}/${e.id}.settings.${e.setting}=${K_(e.value)}`;function e4(e,t,n){for(let r of n){let n=t.validate(r.key,K_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const t4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=x2(n),i=V2(t,r),a=t.configFor(i),o=mU(a,e=>t.sessionState.get(r,e)),s=MU(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]});e4(`save-preset`,s,o.placements);let l=J2(i),u=r$(Y2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Ty.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Cy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map($2)].join(` `)} → ${l.path} (session=${r})`)},n4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=x2(n),i=V2(t,r),a=gU(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=J2(i);i$(Y2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(sU(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=gy.map(e=>Cy[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} ${gy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},r4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=x2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=V2(t,i),o=J2(a);a$(Y2(t,i),o,r),t.reloadConfig(a);let s=Cy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},i4=(e,t)=>{let[n=``,...r]=jb(()=>fi(e)),i=x2(n),a=V2(t,i),o=eL(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=J2(a),l=r.map(_U),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);e$(Y2(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 a4(e,t){let n=(e,t)=>[...D_(ix(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(tx(t.presets).flatMap(e=>n(t,e).map(t=>Ij(vA(e),C_(t)))));return tx(e.presets).flatMap(t=>n(e,t).map(e=>({member:Ij(vA(t),C_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function o4(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Mj]:[]])}const s4=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=x2(n),o=V2(t,a),s=t.configFor(o),c=eL(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=BI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=J2(o),f=o$(Y2(t,a),d,r,u);t.reloadConfig(o);let p=o4(a4(s,t.configFor(o)),t.sessionState.get(a,Mj)).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})`)},c4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=x2(n);t.journal.commit();let i=t.history.undo(r);W2(t,r,i),t.dlog(`info`,`undo: restored ${O$(i)} (session=${r})`)},l4=(e,t)=>{let n=x2(S2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,MU(G2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},u4=(e,t)=>{let n=x2(S2(e));t.journal.commit();let r=t.history.rewind(n);W2(t,n,r),t.dlog(`info`,`rewind: put back ${O$(r)||`nothing`} as edit mode found it (session=${n})`)},d4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=x2(n);t.journal.commit();let i=t.history.redo(r);W2(t,r,i),t.dlog(`info`,`redo: re-applied ${O$(i)} (session=${r})`)},f4=(e,t)=>{x2(S2(e)),t.applyUpdate()},p4=`client-hints`;function m4(e,t){let n=e.sessionState.get(t,p4);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function h4(e,t,n){let r=HN(n);e.sessionState.setBatch(t,iP(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${nP(n.nerdFont,n.marks)} ${KN(n.terminal,n.clicked)} ${qN(n.terminal,n.width)} ${JN(n.install)} ${XN(n.daemon)} ${ZN(n.data)} ${tP(n.transcripts)} ${QN(n.frames,n.claudeSettings)} ${eP(n.claudeSettings.origin.sources)} (session=${t})`)}function g4(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,uk(new Date)),i;try{i=N0(e.doctor,m4(e,t),V2(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:a1(n,r)},M0(t,r),o0(e.doctorStores))}catch(e){throw e instanceof t1?new q(e.message):e}return{...i,urlHandler:k0(e.arrival),install:i0(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:_4(e,i)}}function _4(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?HM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>$$(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 v4=(e,t)=>{let n=x2(S2(e));h4(t,n,g4(t,n))},y4=(e,t)=>{let n=Z0(S2(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`}`)},b4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=x2(n),a=UN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=g4(t,i),s=a.probe(o);if(s.ok||s.fix===void 0)throw new q(`doctor-fix: ${a.label} — ${s.ok?`nothing to fix`:s.reason}`);let c=P0(t.doctorStores,s.fix,o);if(c.kind===`failed`)throw new q(`doctor-fix: ${a.label} — ${c.reason}`);t.dlog(`info`,`doctor-fix: ${a.name} → ${eN(s.fix)} (session=${i})`),h4(t,i,c.value)},x4=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=x2(n),o=UN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!ZM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${ZM.join(` or `)}`);let s=g4(t,a),c=o.probe(s);if(c.ok||c.sighting===void 0)throw new q(`doctor-mark: ${o.label} — ${c.ok?`nothing to mark`:`shows nothing to look at`}`);let l=[o.name,c.sighting.id,i],u=t.doctorStores.marks.update(e=>X$(e,...l));if(u.kind===`failed`)throw new q(`doctor-mark: ${u.reason}`);t.dlog(`info`,`doctor-mark: ${o.name} ${i} on ${c.sighting.id} (session=${a})`),h4(t,a,{...s,marks:u})},S4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=x2(n),a=Object.values(t.configFor(V2(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=h2(t.claudeInput,m4(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 C4([e=``,t=``,n=``,r=``],i){let a=x2(e),o=V2(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=hx(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:{...q$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:m4(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const w4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=jb(()=>fi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=C4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},T4=(e,t)=>{let[n=``,r=``,i=``,a=``]=jb(()=>fi(e)),o=x2(n),s=i;if(!t.links.verify(Tq(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=wq().update(e=>XV(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(V2(t,o))},E4=`config-override`,D4=new Map([[Br,T2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=x2(jb(()=>decodeURIComponent(e.slice(0,n)))),i=jb(()=>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,E4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,E4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,E2],[Rr,A2],[zr,N2],[Kr,X2],[qr,Z2],[Qr,i4],[Jr,Q2],[Yr,t4],[Xr,n4],[Zr,r4],[$r,s4],[ei,c4],[ti,d4],[ni,l4],[ri,u4],[Ur,D2],[Wr,O2],[Hr,k2],[ii,f4],[ai,v4],[oi,b4],[si,x4],[ci,y4],[li,S4],[`run`,w4],[ui,T4]]),O4=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,ui,Gr]);function k4(e,t){return A4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function A4(e){let t=e.find(e=>O4.has(e.verb)),n=t===void 0?``:jb(()=>pi(t.value));return n===``?null:DW(n)}const j4=(e,t)=>{let n=[],r=!1,i=mi(e),a=A4(i);for(let{verb:e,value:a}of gi(i)){let i=D4.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&&es(t.sessionState,a.id,n.join(`
|
|
488
|
-
`),uk(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function M4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:K2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>G$(e,e=>q2(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=U2(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 N4=new Map([...D4,[Lr,j4]].map(([e,t])=>[e,M4(t,t=>{let n=k4(e,t);return n?.ok?n.id:null})]));Object.freeze([...N4.keys()]);function P4(e,t,n){M4((n,r)=>{let i=W$(q2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const F4=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`]),I4=[[`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`]],L4=[[`workspace.added_dirs`,`string-list`]];function R4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of I4){let i=V4(n,e);if(i==null)t.missingRequired.push(e);else{let n=z4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of L4){let i=V4(n,e),a=i===void 0?r:B4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))F4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function z4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function B4(e){return Array.isArray(e)&&e.every(e=>z4(e)===`string`)?`string-list`:z4(e)}function V4(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 H4(e,t){switch(e){case`vars`:return{what:e,vars:U4(t)};case`segments`:return{what:e,segments:J4(t)};case`config`:return{what:e,config:Q4(t)}}}function U4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=K4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=W4(r),s=n.getLastError(e);o.push({name:e,source:i.get(e)??null,...a,lastError:s===void 0?null:{timestampMs:s.timestamp,message:s.message},ageMs:G4(r.lastUpdatedMs())})}return o}function W4(e){if(e.kind===`projection`)return{type:e.type,value:`(read at each frame's instant)`};if(e.kind!==`document`)try{return{type:e.type,value:e.read()}}catch(t){return{type:e.type,value:t instanceof Error?t.message:String(t)}}let t=e.read();switch(t.kind){case`ok`:return{type:`document`,value:JSON.stringify(t.value)};case`pending`:return{type:`document`,value:`(not yet scanned)`};case`absent`:return{type:`document`,value:`(nothing to read, and no default)`};case`failed`:return{type:`document`,value:t.reason}}}function G4(e){return e===null?null:Math.max(0,Date.now()-e)}function K4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,q4(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}`,q4(i));return t}function q4(e){return e.kind}function J4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=X4(n),o=Y4(n),s=[];for(let e of a){let t=n.segments[e];t&&s.push({name:e,description:t.description??null,template:t.template,referencedVars:Z4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function Y4(e){let t=new Map;for(let n of tx(e.presets))for(let r of D_(ix(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=C_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function X4(e){let t=[],n=new Set;for(let r of D_(Jb(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 Z4(e,t,n){let r=new Set([...Nx(e,t).keys()].flatMap(e=>Kx(e,n)));return Array.from(r).sort()}function Q4(e){return e===null?null:e.config}const $4=[`vars`,`segments`,`config`];function e3(e){return typeof e==`string`&&$4.includes(e)}function t3(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>XH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return lJ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...yU(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 n3={moving:1e3/30,still:1e3},r3=[`data`,`state`,`reload`,`visibility`];function i3(e){return Iv.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 a3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const o3=e=>({resp:e,bytes:JSON.stringify(e)}),s3=(e,t)=>Fv[t].elsewhere===null?e.statusline:e.bar,c3=e=>Math.round(1e3/e);var l3=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 Hv;let r=t-1,i=this.shown(n);return Vv(e=>{let a=n.rates.get(e);if(a===void 0)return zv;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:c3(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=c3(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:o3(t.resp),statusline:o3(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||s3(i,n).bytes!==s3(r,n).bytes)&&a3(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}=s3(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:uM(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=Ik.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=${r3.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 u3(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 d3=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,f3=`#{session_id} #{client_control_mode} #{pane_id}`;function p3(e){let t=new Set;for(let n of e.split(`
|
|
489
|
-
`)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function
|
|
490
|
-
`)){let[e,i,a,o,s,c]=r.trim().split(` `);e===void 0||e===``||i===void 0||Number(a)>0&&(o===`1`||t.has(i))&&(s!==`1`||c===`1`)&&n.add(e)}return n}function
|
|
485
|
+
`}const J0=e=>({kind:`ok`,value:e}),Y0=e=>({kind:`failed`,reason:e});var X0=class{arrivals=[];arrive(e){this.arrivals=[...this.arrivals,e].slice(-16)}list(){return this.arrivals}};const Z0=/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;function Q0(e){return Z0.test(e)?e:null}function $0(e){let t=e.opener();if(t.kind===`failed`)return t;if(t.value===null)return J0(null);let n=t.value,r=e.script(n);if(r.kind===`failed`)return J0({app:n,missing:Y0(`its script could not be read (${r.reason})`)});let i=Ao(r.value);return J0({app:n,missing:i===null?Y0("its script is not one `cc-candybar install` wrote"):J0([i.node,i.script].filter(t=>!e.exists(t)))})}async function e2(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 t2(e){if(e.platform!==`darwin`)return{kind:`unsupported`};if(e.sockets.own!==e.sockets.handler)return{kind:`unprobed`,reason:`this shell's daemon is at ${e.sockets.own} (CC_CANDYBAR_SOCKET); the URL handler delivers links to ${e.sockets.handler}`};let t=await e.daemon();if(t.kind===`failed`)return{kind:`unprobed`,reason:`the daemon could not be asked whether a link arrives: ${t.reason}`};let n=e.nonce(),r=e.open(`${Ir}://${ci}/${n}`);return(r===null?await e2(e,n):null)??{kind:`lost`,unopened:r,opener:$0(e)}}function n2(e,t,n){let r=D({bin:t,args:[...n],category:e,timeoutMs:5e3});return r.ok?J0(r.stdout):Y0(r.stderr.trim()||r.error||r.reason)}const r2=`ObjC.import("AppKit");var u = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString("${Ir}://probe"));u.isNil() ? "" : u.path.js`;async function i2(){let e=await R0();if(e.kind!==`ok`)return Y0(un(e).split(`
|
|
486
|
+
`).join(` — `));let t=z0(e.value,[`handlerProbes`]);if(t!==null)return Y0(t);let{version:n,handlerProbes:r}=e.value;return J0({version:n,arrivals:r})}function a2(){return{platform:process.platform,sockets:{own:St(),handler:Ct()},now:Date.now,nonce:ie,daemon:i2,open:e=>{let t=n2(`doctor.open`,`/usr/bin/open`,[`-g`,e]);return t.kind===`ok`?null:t.reason},pause:()=>new Promise(e=>setTimeout(e,100)),opener:()=>{let e=n2(`doctor.launch-services`,`/usr/bin/osascript`,[`-l`,`JavaScript`,`-e`,r2]);if(e.kind===`failed`)return e;let t=e.value.trim();return J0(t===``?null:t)},script:e=>n2(`doctor.osadecompile`,`/usr/bin/osadecompile`,[jo(e)]),exists:p.existsSync}}const o2=/^─{20,}/,s2=/^❯(\s|$)/,c2=/›\s*stashed$/;function l2(e){let t=e.screen.map(e=>e.trimEnd()),n=t.flatMap((e,t)=>o2.test(e)?[t]:[]).at(-2);return n===void 0||!s2.test(t[n+1]??``)?null:{hint:t[n-1]??``,prompt:t[n+1]}}function u2(e){if(e.inMode)return{kind:`in-mode`};let t=l2(e);return t===null?{kind:`no-prompt`}:c2.test(t.hint)?{kind:`stashed`}:{kind:`ready`}}function d2(e){return/^❯\s*\S/u.test(l2(e)?.prompt??``)}const f2=/^\S+\s+\S[^…]*…\s+\((\d+[hms]\s*)+/u;function p2(e){return e.screen.some(e=>f2.test(e))}const m2={"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 h2(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 g2(e,t,n){let r=h2(t);if(r.kind===`refused`)return r;let i=r.hint,a=u2(e.read(i));if(a.kind!==`ready`)return{kind:`refused`,reason:m2[a.kind]};let o=e.type(i,n);return o.kind===`typed`?{kind:`typed`,pane:i.pane}:o}function _2(e,t,n,r){let i=JK(e,t,n,r);if(i.kind===`failed`)throw Error(i.reason);return i}function v2(e){let t=_2(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 y2(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 b2(e,t){let n=_2(e,`claude-input.type`,y2(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 x2(){return{read:v2,type:b2}}function S2(e){let t=DW(e);if(!t.ok)throw new q(`session id ${t.problem}`);return t.id}function C2(e){return jb(()=>decodeURIComponent(e))}function w2(e,t,n){let r=D(e);if(r.ok)return;if(r.reason===`rate-limited`){n(`warn`,`${e.category} rate-limited: ${r.error??``}`);return}let i=r.error??r.stderr.trim();throw Error(`${t} failed (${r.reason}, exit ${r.exitCode??`null`})${i===``?``:`: ${i}`}`)}function T2(e,t){w2({bin:`/usr/bin/pbcopy`,stdinInput:e,category:`click.pbcopy`},`pbcopy`,t.dlog)}const E2=(e,t)=>T2(C2(e),t),D2=(e,t)=>w2({bin:`/usr/bin/open`,args:[`-a`,`Visual Studio Code`,C2(e)],category:`click.open`},`open -a "Visual Studio Code"`,t.dlog),O2=(e,t)=>T2(C2(e),t),k2=(e,t)=>T2(C2(e),t),A2=(e,t)=>{let n=S2(C2(e));t.navigating.get(n,`toolbar-expanded`)?t.navigating.clear(n,`toolbar-expanded`):t.navigating.set(n,`toolbar-expanded`,`1`)},j2=(e,t)=>{let[n=``,...r]=jb(()=>fi(e)),i=S2(n),a=MU(K2(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})}F2(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})`)},M2=/^-?\d+$/;function N2(e,t,n,r){let i=e+t;return i>r?e===r?n:r:i<n?e===n?r:n:i}const P2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=S2(n);if(!r)throw new q(`step-state: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!M2.test(i))throw new q(`step-state: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=K2(t,a),c=MU(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&&M2.test(u)?I2(l,parseInt(u,10)):L2(`step-state`,r,l,FU(s,e=>t.sessionState.get(a,e),r)),f=N2(d,o,l.min,l.max),p=c.validate(r,String(f));if(!p.ok)throw new q(`step-state: ${p.reason}`);F2(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 F2(e,t,n,r){let i=r.filter(e=>e.key.startsWith(Fj));if(i.length===0)return;let a=dU(K2(e,t),n=>e.sessionState.get(t,n),i);if(a.length>0)throw new q(`${n}: refused — ${a.join(`; `)}`)}function I2(e,t){return Math.max(e.min,Math.min(e.max,t))}function L2(e,t,n,r){if(r===null)return n.min;if(!M2.test(r))throw new q(`${e}: "${t}" shows ${JSON.stringify(r)} before any click, not an integer to step`);return I2(n,parseInt(r,10))}const R2=`render-origin`;function z2(e,t,n){return{...e,configFile:t.get(n,`config-override`)??e.configFile}}function B2(e){return JSON.stringify(e)}function V2(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 H2(e,t){let n=W2(e,t);if(n===null)throw new q(`session ${t} has not rendered yet — no config to act on`);return n}function U2(e,t){let n=e.sessionState.get(t,R2);return n===null?null:V2(n)}function W2(e,t){let n=U2(e,t);return n===null?null:z2(n,e.sessionState,t)}function G2(e,t,n){let r=W2(e,t);if(r===null)return;let{path:i}=Y2(r);n.some(e=>e.kind===`file`&&e.file===i)&&e.reloadConfig(r)}function K2(e,t){return e.configFor(H2(e,t))}function q2(e,t){let n=U2(e,t);if(n===null)return null;let r=()=>e.lanes.of(z2(n,e.sessionState,t),t);return{sessionId:t,before:r(),read:r}}function J2(e,t){let n=W2(e,t);return n===null?z$:U$(e.configFor(n))}function Y2(e){return sH(Tq().read(),e.projectDir,e.cwd,e.configFile??void 0)}function X2(e,t){return{record:(n,r,i)=>e.journal.file(t,n,r,i),logger:e.dlog}}const Z2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=S2(n),o=H2(t,a),s=t.configFor(o),c=eL(s);if(!r)throw new q(`set-config: <key>/<value> is required (have keys: ${c.listKeys().join(`, `)})`);let l=c.validate(r,i);if(!l.ok)throw new q(`set-config: ${l.reason}`);let u=Y2(o),d=lU(s,e=>t.sessionState.get(a,e),r);XQ(X2(t,a),u,[[d.key,l.value]]),t.reloadConfig(o),t.dlog(`info`,`set-config: ${d.key}=${l.value} → ${u.path} (session=${a})`)},Q2=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=S2(n);if(!r)throw new q(`step-config: <key> is required (shape: <sessionId>/<key>/<by>)`);if(!M2.test(i))throw new q(`step-config: delta must be an integer, got "${i}"`);let o=parseInt(i,10),s=H2(t,a),c=t.configFor(s),l=eL(c),u=l.rangeParamsFor(r);if(!u)throw new q(`step-config: key "${r}" is not a bounded (range) config key (have keys: ${l.listKeys().join(`, `)})`);let d=Y2(s),f=lU(c,e=>t.sessionState.get(a,e),r),p=YQ(d.path,f.key),m=typeof p==`number`?I2(u,p):L2(`step-config`,r,u,nL(f.globals,r)),h=N2(m,o,u.min,u.max),g=l.validate(r,String(h));if(!g.ok)throw new q(`step-config: ${g.reason}`);XQ(X2(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})`)},$2=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=S2(n),i=H2(t,r),a=t.configFor(i),o=e=>t.sessionState.get(r,e),s=sU(a,o),c=uU(a,o);if(s.length+c.length===0){t.dlog(`info`,`save: nothing unsaved (session=${r})`);return}let l=MU(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]});t4(`save`,l,c);let d=Y2(i);ZQ(X2(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(e4)].join(` `)} → ${d.path} (session=${r})`)},e4=e=>`${e.preset}/${e.id}.settings.${e.setting}=${K_(e.value)}`;function t4(e,t,n){for(let r of n){let n=t.validate(r.key,K_(r.value));if(!n.ok)throw new q(`${e}: ${n.reason}`)}}const n4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=S2(n),i=H2(t,r),a=t.configFor(i),o=mU(a,e=>t.sessionState.get(r,e)),s=MU(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]});t4(`save-preset`,s,o.placements);let l=Y2(i),u=i$(X2(t,r),l,o.from,o.globals,c,o.placements);t.reloadConfig(i);for(let e of[...Ty.map(e=>e.sessionKey),...o.placements.map(e=>e.key)])t.sessionState.clear(r,e);t.sessionState.set(r,Cy.preset.sessionKey,u),t.dlog(`info`,`save-preset: ${[`${u} from=${o.from}`,...c.map(([e,t])=>`${e}=${t}`),...o.placements.map(e4)].join(` `)} → ${l.path} (session=${r})`)},r4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=S2(n),i=H2(t,r),a=gU(t.configFor(i),e=>t.sessionState.get(r,e));if(a.kind===`rule`)throw new q(`save-theme-default: the theme is chosen by a rule (globals.palette), so there is no name to save as a theme's default — pick one in the menu first`);let o=Y2(i);a$(X2(t,r),o,a.theme,a.look),t.reloadConfig(i);let s=new Set(sU(t.configFor(i),e=>t.sessionState.get(r,e)).map(e=>e.sessionKey)),c=gy.map(e=>Cy[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} ${gy.map(e=>`${e}=${a.look[e]}`).join(` `)} → ${o.path} (session=${r})`)},i4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=S2(n);if(!r)throw new q(`delete-preset: <name> is required (shape: <sessionId>/<name>)`);let a=H2(t,i),o=Y2(a);o$(X2(t,i),o,r),t.reloadConfig(a);let s=Cy.preset.sessionKey;t.sessionState.get(i,s)===r&&t.sessionState.clear(i,s),t.dlog(`info`,`delete-preset: ${r} ← ${o.path} (session=${i})`)},a4=(e,t)=>{let[n=``,...r]=jb(()=>fi(e)),i=S2(n),a=H2(t,i),o=eL(t.configFor(a)).listKeys(),s=r.length===0?[``]:r.filter(e=>!o.includes(e));if(s.length>0)throw new q(`reset-config: unknown config key "${s.join(`", "`)}" (have: ${o.join(`, `)})`);let c=Y2(a),l=r.map(_U),u=l.flatMap(e=>e.fileKeys),d=l.flatMap(e=>e.sessionKeys);t$(X2(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 o4(e,t){let n=(e,t)=>[...D_(ix(e,t).node)].filter(e=>e.kind===`segment`),r=new Set(tx(t.presets).flatMap(e=>n(t,e).map(t=>Ij(vA(e),C_(t)))));return tx(e.presets).flatMap(t=>n(e,t).map(e=>({member:Ij(vA(t),C_(e)),node:e})).filter(({member:e})=>!r.has(e)))}function s4(e,t){return e.flatMap(({member:e,node:n})=>[...Object.values(n.drafts??{}).map(e=>e.key),...e===t?[Mj]:[]])}const c4=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=S2(n),o=H2(t,a),s=t.configFor(o),c=eL(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=BI(l.value);if(u===null)throw new q(`apply-layout-op: "${l.value}" is not a layout op token`);let d=Y2(o),f=s$(X2(t,a),d,r,u);t.reloadConfig(o);let p=s4(o4(s,t.configFor(o)),t.sessionState.get(a,Mj)).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})`)},l4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=S2(n);t.journal.commit();let i=t.history.undo(r);G2(t,r,i),t.dlog(`info`,`undo: restored ${k$(i)} (session=${r})`)},u4=(e,t)=>{let n=S2(C2(e)),{step:r,discarded:i}=t.navigation.back(n,t.sessionState,MU(K2(t,n))),a=r.map(e=>`${e.key}=${e.before??`∅`}`).join(` `);t.dlog(`info`,`back: ${a} discarded=${i} (session=${n})`)},d4=(e,t)=>{let n=S2(C2(e));t.journal.commit();let r=t.history.rewind(n);G2(t,n,r),t.dlog(`info`,`rewind: put back ${k$(r)||`nothing`} as edit mode found it (session=${n})`)},f4=(e,t)=>{let[n=``]=jb(()=>fi(e)),r=S2(n);t.journal.commit();let i=t.history.redo(r);G2(t,r,i),t.dlog(`info`,`redo: re-applied ${k$(i)} (session=${r})`)},p4=(e,t)=>{S2(C2(e)),t.applyUpdate()},m4=`client-hints`;function h4(e,t){let n=e.sessionState.get(t,m4);if(n===null)throw new q(`session ${t} has not rendered yet — no client facts are recorded for it`);let r;try{r=JSON.parse(n)}catch{throw new q(`client hints record is not JSON: ${n}`)}if(typeof r!=`object`||!r)throw new q(`client hints record is not an object: ${n}`);return Vt(r)}function g4(e,t,n){let r=HN(n);e.sessionState.setBatch(t,iP(r)),e.dlog(`info`,`doctor: ${r.map(e=>`${e.check.name}=${e.verdict.ok?`ok`:`failed(${1+(e.verdict.more?.length??0)})`}`).join(` `)} ${nP(n.nerdFont,n.marks)} ${KN(n.terminal,n.clicked)} ${qN(n.terminal,n.width)} ${JN(n.install)} ${XN(n.daemon)} ${ZN(n.data)} ${tP(n.transcripts)} ${QN(n.frames,n.claudeSettings)} ${eP(n.claudeSettings.origin.sources)} (session=${t})`)}function _4(e,t){let n={kind:`clicked`,sessionId:t,via:e.arrival.via},r=e.clients.ofSession(t,uk(new Date)),i;try{i=P0(e.doctor,h4(e,t),H2(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:o1(n,r)},N0(t,r),s0(e.doctorStores))}catch(e){throw e instanceof n1?new q(e.message):e}return{...i,urlHandler:A0(e.arrival),install:a0(e.doctor.install,e.bundle,r.map(e=>e.client)),clicked:v4(e,i)}}function v4(e,{terminal:t,clicked:n}){let r=t.kind===`seen`?HM(t.identified):null;if(r===null||e.arrival.via!==`link`)return n;try{return e.doctorStores.clicked.update(e=>e1(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 y4=(e,t)=>{let n=S2(C2(e));g4(t,n,_4(t,n))},b4=(e,t)=>{let n=Q0(C2(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`}`)},x4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=S2(n),a=UN(r);if(a===void 0)throw new q(`doctor-fix: unknown check "${r}"`);let o=_4(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=F0(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} → ${eN(s.fix)} (session=${i})`),g4(t,i,c.value)},S4=(e,t)=>{let[n=``,r=``,i=``]=jb(()=>fi(e)),a=S2(n),o=UN(r);if(o===void 0)throw new q(`doctor-mark: unknown check "${r}"`);if(!ZM.includes(i))throw new q(`doctor-mark: the mark is ${JSON.stringify(i)}, not ${ZM.join(` or `)}`);let s=_4(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=>Z$(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})`),g4(t,a,{...s,marks:u})},C4=(e,t)=>{let[n=``,r=``]=jb(()=>fi(e)),i=S2(n),a=Object.values(t.configFor(H2(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=g2(t.claudeInput,h4(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 w4([e=``,t=``,n=``,r=``],i){let a=S2(e),o=H2(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=hx(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:{...J$(process.env,{sessionId:a,projectDir:o.projectDir,claudeConfigDir:h4(i,a).claudeConfigDir}),...u.env},cwd:c.cwd,refreshes:c.refreshes.map(e=>({name:e,storage:p.get(e)}))}}const T4=(e,t)=>{let n={sessionId:`-`,action:`-`},r;try{let i=jb(()=>fi(e));n={sessionId:i[0]||`-`,action:i[1]||`-`},r=w4(i,t)}catch(e){throw e instanceof q&&t.runs.refused(n.sessionId,n.action,e.message),e}t.runs.start(r)},E4=(e,t)=>{let[n=``,r=``,i=``,a=``]=jb(()=>fi(e)),o=S2(n),s=i;if(!t.links.verify(Eq(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=Tq().update(e=>XV(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(H2(t,o))},D4=`config-override`,O4=new Map([[Br,E2],[Gr,(e,t)=>{let n=e.indexOf(`/`);if(n===-1)throw new q(`load-config: expected <sessionId>/<path> (missing separator)`);let r=S2(jb(()=>decodeURIComponent(e.slice(0,n)))),i=jb(()=>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,D4),t.dlog(`info`,`load-config: override cleared (session=${r})`)):(t.sessionState.set(r,D4,i),t.dlog(`info`,`load-config: ${i} (session=${r})`))}],[Vr,D2],[Rr,j2],[zr,P2],[Kr,Z2],[qr,Q2],[Qr,a4],[Jr,$2],[Yr,n4],[Xr,r4],[Zr,i4],[$r,c4],[ei,l4],[ti,f4],[ni,u4],[ri,d4],[Ur,O2],[Wr,k2],[Hr,A2],[ii,p4],[ai,y4],[oi,x4],[si,S4],[ci,b4],[li,C4],[`run`,T4],[ui,E4]]),k4=new Set([Rr,zr,Kr,qr,Qr,Jr,Yr,Xr,Zr,$r,ei,ti,ni,ri,Hr,ii,ai,oi,si,li,`run`,ui,Gr]);function A4(e,t){return j4(e===`dispatch`?mi(t):[{verb:e,value:t}])}function j4(e){let t=e.find(e=>k4.has(e.verb)),n=t===void 0?``:jb(()=>pi(t.value));return n===``?null:DW(n)}const M4=(e,t)=>{let n=[],r=!1,i=mi(e),a=j4(i);for(let{verb:e,value:a}of gi(i)){let i=O4.get(e);if(!i){n.push(`unknown effect verb "${e}"`);continue}try{i(a,t)}catch(t){t instanceof q||(r=!0),n.push(`${e}: ${t instanceof Error?t.message:String(t)}`)}}if(n.length>0){a?.ok&&es(t.sessionState,a.id,n.join(`
|
|
488
|
+
`),uk(new Date));let e=`dispatch: ${n.join(`; `)}`;throw r?Error(e):new q(e)}};function N4(e,t){return(n,r)=>{let i=t(n),a=i===null?null:q2(r,i),o=r.history.begin(),s=r.navigation.begin(o.sessionState),c=[],l=e=>K$(e,e=>J2(r,e),e=>r.dlog(`info`,e));try{e(n,{...r,sessionState:l(o.sessionState),journal:o,navigating:l(s.sessionState)})}catch(e){c.push(e)}s.commit();try{o.commit()}catch(e){c.push(e)}if(a!==null)try{r.lanes.clicked(a.sessionId,a.before,a.read())}catch(e){c.push(e)}if(i!==null)try{let e=W2(r,i);e!==null&&r.views.follow(i,e)}catch(e){c.push(e)}if(c.length===1)throw c[0];if(c.length>1)throw Error(c.map(e=>String(e.message??e)).join(`; `))}}const P4=new Map([...O4,[Lr,M4]].map(([e,t])=>[e,N4(t,t=>{let n=A4(e,t);return n?.ok?n.id:null})]));Object.freeze([...P4.keys()]);function F4(e,t,n){N4((n,r)=>{let i=G$(J2(r,e),t=>r.navigating.get(e,t));r.navigating.setBatch(e,i.map(({key:e})=>({key:e,value:yi}))),r.dlog(`info`,`menu-idle: closed=${i.map(({key:e})=>e).join(`,`)||`-`} idle=${t.idleS.toFixed(1)}s timeout=${t.timeoutS}s (session=${e})`)},()=>e)(``,n)}const I4=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`]),L4=[[`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`]],R4=[[`workspace.added_dirs`,`string-list`]];function z4(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of L4){let i=H4(n,e);if(i==null)t.missingRequired.push(e);else{let n=B4(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of R4){let i=H4(n,e),a=i===void 0?r:V4(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))I4.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function B4(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function V4(e){return Array.isArray(e)&&e.every(e=>B4(e)===`string`)?`string-list`:B4(e)}function H4(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 U4(e,t){switch(e){case`vars`:return{what:e,vars:W4(t)};case`segments`:return{what:e,segments:Y4(t)};case`config`:return{what:e,config:$4(t)}}}function W4(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=q4(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=G4(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:K4(r.lastUpdatedMs())})}return o}function G4(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 K4(e){return e===null?null:Math.max(0,Date.now()-e)}function q4(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,J4(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}`,J4(i));return t}function J4(e){return e.kind}function Y4(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=Z4(n),o=X4(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:Q4(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function X4(e){let t=new Map;for(let n of tx(e.presets))for(let r of D_(ix(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=C_(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function Z4(e){let t=[],n=new Set;for(let r of D_(Jb(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 Q4(e,t,n){let r=new Set([...Nx(e,t).keys()].flatMap(e=>Kx(e,n)));return Array.from(r).sort()}function $4(e){return e===null?null:e.config}const e3=[`vars`,`segments`,`config`];function t3(e){return typeof e==`string`&&e3.includes(e)}function n3(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>XH(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return uJ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...yU(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 r3={moving:1e3/30,still:1e3},i3=[`data`,`state`,`reload`,`visibility`];function a3(e){return Iv.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 o3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const s3=e=>({resp:e,bytes:JSON.stringify(e)}),c3=(e,t)=>Fv[t].elsewhere===null?e.statusline:e.bar,l3=e=>Math.round(1e3/e);var u3=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 Hv;let r=t-1,i=this.shown(n);return Vv(e=>{let a=n.rates.get(e);if(a===void 0)return zv;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:l3(this.deps.periods.still),drawMs:0,evaluated:0,woke:{data:0,state:0,reload:0,visibility:0},coalesced:0,summarizedAt:t,refreshesAtOpen:this.deps.refreshes()};return this.feeds.set(e,n),this.stopWatching??=this.deps.watching(),n}unsubscribe(e,t){if(e.followers.delete(t)){if([...e.followers.keys()].some(e=>e.lane===t.lane)||e.rates.delete(t.lane),e.followers.size>0){this.hasten(e);return}e.phase.kind===`due`&&clearTimeout(e.phase.timer),e.unwatch(),e.unpin(),this.feeds.delete(e.sessionId),this.feeds.size===0&&(this.stopWatching?.(),this.stopWatching=null),this.summarize(e,`closed`)}}draw(e){e.phase={kind:`drawing`};let t=this.deps.now();try{this.step(e,t)}catch(n){if(e.lastStart=t,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${T(n)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,t)}}step(e,t){let n=this.deps.render(e.sessionId,e.pace);if(n===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=t;let r=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=r-t,e.evaluated+=n.evaluated,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,n),this.push(e,n),this.feeds.get(e.sessionId)===e&&(r-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,n,t)))}schedule(e,t,n){let r=t?.moves===!0,i=r&&this.shown(e);i&&e.moving++,r&&!i&&e.unseen++;let a=i?this.deps.periods.moving:this.deps.periods.still;e.pace=l3(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:s3(t.resp),statusline:s3(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||c3(i,n).bytes!==c3(r,n).bytes)&&o3(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}=c3(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:uM(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=Ik.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=${i3.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 d3(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 f3=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,p3=`#{session_id} #{client_control_mode} #{pane_id}`;function m3(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 h3(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 g3(e,t){let n=new Map;for(let t of e.split(`
|
|
491
491
|
`)){let[e,r]=t.trim().split(` `);e!==void 0&&e!==``&&r!==void 0&&n.set(e,r)}let r=new Map;for(let e of t.split(`
|
|
492
|
-
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var
|
|
493
|
-
`).map(e=>e.split(` `)[0]??``),a={};for(let e of
|
|
494
|
-
`)){let[n,i,a=``]=r.split(` `);if(n===void 0||i===void 0||i===``)continue;let o=H3(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,[L3(`@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)} ${b3} 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,V3(n));if(r===null||this.closed)return null;let i=U3(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,C3(r),e])}),i!==n.status){let e=E3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,y3,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,M3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,W3(n));if(i===null)return;let a=G3(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,q3);if(r===null||this.closed)return;let i=J3(r[0]??``);if(n.kind===`none`&&Z3(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`&&Z3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...x3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${j3(`${this.deps.handler} ${X3(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,q3);if(r===null)return;let i=Q3(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=Q3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,P3(t));return n.kind===`ok`?F3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,P3(t)));return n.kind===`ok`?F3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,A3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,A3(t),n)))}};function e6(e){try{return fi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const t6=`CC_CANDYBAR_CONFIG`;function n6(e,t){return eV(t,e[t6])}const $=e=>({arity:e,keep:!0}),r6=e=>({arity:e,keep:!1}),i6={"--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":r6(`none`),"--background":r6(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":r6(`optional`),"-c":r6(`none`),"--continue":r6(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":r6(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":r6(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":r6(`none`),"--forward-subagent-text":$(`none`),"--from-pr":r6(`optional`),"-h":r6(`none`),"--help":r6(`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":r6(`none`),"--print":r6(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":r6(`optional`),"--resume":r6(`optional`),"--safe-mode":$(`none`),"--session-id":r6(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":r6(`optional`),"--tmux":r6(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":r6(`none`),"--version":r6(`none`),"-w":r6(`optional`),"--worktree":r6(`optional`)},a6={resume:`--resume`,fresh:`--session-id`};function o6(e){return[a6[e.kind],e.sessionId]}const s6=e=>e.startsWith(`-`)&&e!==`-`;function c6(e,t){let n=d6(t);return n===null?{dir:e??t,args:[]}:e!==null&&l6(e,n.top)?{dir:e,args:[]}:{dir:e===null||d6(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const l6=(e,t)=>e===t||e.startsWith(t+s.sep);function u6(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!s6(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=i6[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=>!s6(e)):o.arity===`variadic`?f6(n.slice(r),e=>!s6(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 d6(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 f6(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const p6=`candybar-band@cc-candybar`,m6=s.join(`bin`,`cc-candybar-native`),h6=`@cc-candybar-bar-pane`,g6=mP(`/reload-plugins`),_6=e=>({kind:`done`,said:e});function v6(e){let t=m2(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const y6={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Fv.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,m6);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 ${p6} from ${r}`,finished:b6(e,r,n)}},off:()=>_6(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=v6(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Fv.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:C6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>_6(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=v6(e),i=n.barPanes(r);return i.length>0?_6(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):_6(`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=m2(e.hints.tmux);if(r.kind===`refused`)return _6(`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 _6(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>_6(`the daemon draws ${v6(e).pane}'s bar in its status line`),off:()=>_6(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function b6(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`,p6],r);let i=h2(n.claudeInput,e.hints.tmux,g6);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 ${p6} from ${t} and typed /reload-plugins into ${i.pane}`}const x6=new Set([Ja,t6]);function S6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function C6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Fv.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=O6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Fv.statusline.label} off and on again`);let s=w6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=u6(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=S6(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])=>x6.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...o6(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=T6(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(c6(null,i.cwd),_))}let y=m(c6(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}\`, ${E6[g.kind](e.sessionId)}, and its statusline follows lane B`}function w6(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 T6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const E6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},D6={"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 O6(e){let t=l2(e);return t.kind===`ready`?f2(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:u2(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:D6[t.kind]}var k6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Iv.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}`),es(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=y6[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 A6(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 j6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function M6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function N6(e,t,n){let r=A6(`node`,e,t);return r===null?{kind:`refused`,why:"no `node` on PATH to run the attach launcher"}:s.basename(n(r))===`bun`?{kind:`refused`,why:`the \`node\` on PATH (${r}) is Bun; the attach launcher runs under Node`}:{kind:`node`,file:r}}const P6=2e3;function F6(e,t,n){let r=JK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function I6(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 L6(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 R6=`#{pane_id} #{${h6}}`;function z6(e,t){return e.split(`
|
|
495
|
-
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const
|
|
496
|
-
`);async function U6(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=I6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,H6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function W6(e,t){return I6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function G6(e){let t=await YK(e,`lane.tmux`,[`display`,`-p`,`-t`,e.pane,`#{pane_pid} #{pane_current_path}`]);if(t.kind!==`ok`)throw Error(t.reason);let[n=``,r=``]=t.stdout.trimEnd().split(` `),i=(await W6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function K6(e){let{panePid:t,cwd:n,foreground:r}=await G6(e),i=await W6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await U6(r),o=o1(i).get(r)?.ppid;if(o===void 0)throw Error(`pane ${e.pane}'s foreground job ${r} is gone`);return{pid:r,executable:await p.promises.realpath(a.executable),argv:a.argv,env:a.env,cwd:n,parent:o,fromShell:r!==t,attached:V6(i,r,t)}}function q6(e){return{claudeInput:b2(),barPanes:e=>z6(F6(e,[`list-panes`,`-a`,`-F`,R6]),e.pane),openBarPane:(e,t,n)=>{let r=F6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return F6(e,[`set-option`,`-p`,`-t`,r,h6,e.pane]),r},closePane:(e,t)=>void F6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void I6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:q$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:KV,paneClaude:K6,paneDir:async(e,t)=>{let n=Date.now()+P6;for(;;){let r=await G6(e);if(r.foreground===t){if(r.cwd===``)throw Error(`tmux read no directory for pane ${e.pane}`);return r.cwd}if(Date.now()>n)throw Error(`the shell in pane ${e.pane} (pid ${t}) did not take its terminal back within ${P6/1e3} s`);await be(100)}},launcherNode:e=>N6(e,e=>j6(e,p.constants.X_OK),M6),onPath:(e,t)=>{let n=A6(e,t,e=>j6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?L6(r.stdout):null;return i===null?(I6(`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(;Ts(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void F6(e,v2(e.pane,`cc-candybar-lane`,[]),t)}}function J6(e,t){return Iv.filter(n=>e[n]&&Fv[n].elsewhere!==null&&t.has(n))}function Y6(e,t){let n=`the bar is drawn in ${t.map(e=>Fv[e].elsewhere).join(` and `)}`,r=N([{verb:Qr,args:[e,...t.map(e=>Fv[e].setting)]}]);return{channels:[{severity:bb,message:n,lines:[[xb(n,N([{verb:Br,args:[n]}])),xb(`[⟲ draw it here]`,r)]]}]}}const X6={order:-1/0,text:null,failure:null};var Z6=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)??X6;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)??X6;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}`}}},Q6=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?Jv(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 $6(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 e8(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 t8(e,t){for(let n of Object.entries(t))e.push(n)}const n8={ok:`info`,"bad-request":`warn`,threw:`error`};function r8(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function i8(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...r8(n)];return{level:n8[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${os(t)}`).join(``)}`}}const a8=new nQ,o8=new Y0,s8=new DM,c8=i(import.meta.url),l8=a0(yt());dt(a8.launchStats);const u8=new fG({counters:a8,logger:M}),d8=new Lk(M),f8=bq({watchers:u8,logger:M,ledger:d8}),{gitProvider:p8,usageStore:m8,tmuxService:h8,hostService:g8,managedStorage:_8}=f8,v8=new aQ,y8=new m$(v8,M),b8=new L$,x8=new tb,S8=new Q6({now:()=>uk(new Date),close:(e,t)=>P4(e,t,l5),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),C8=Xo(),w8=new us({supersede:(e,t)=>_8.supersede(e,t),launch:pt,state:v8,log:M,now:()=>uk(new Date)}),T8=[t.execPath,...t.execArgv],E8=new k6({edge:q6(e=>O8.following(e)),host:{bundle:c8,node:T8,socket:St(),preload:Oo(c8)},state:v8,log:M,now:()=>uk(new Date),defer:e=>void _e(e)}),D8=new $3({edge:{run:(e,t,n)=>YK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>JK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>O8.subscribe(e,t),sessionInPane:(e,t)=>O8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...T8,c8].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),O8=new l3({render:(e,t)=>v5(e,t),watch:(e,t)=>(0,J.reaction)(()=>v8.revision(e),t),lanes:e=>b5(e),pin:e=>M8.pin(e),shown:e=>k8.shown(e.hints.tmux),watching:()=>k8.follow(),refreshes:()=>d8.totals(),periods:n3,now:()=>performance.now(),log:M}),k8=new g3({listPanes:e=>YK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,d3]),listClients:e=>YK({socket:e},`frames.visibility`,[`list-clients`,`-F`,f3]),sockets:()=>new Set(O8.watched().flatMap(({req:e})=>A8(e))),onAnswer:(e,t)=>D8.answered(e,t),onChange:e=>O8.wakeWhere(`visibility`,t=>A8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function A8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const j8=new Z6(Pt(),e=>O8.wake(e,`data`)),M8=new eQ({sessionState:v8,watchers:u8,log:M,storage:_8,signer:C8,ledger:d8,declare:(e,t,n,r)=>tJ(f8,e,t,n,r),source:t3({providers:f8,sessionState:v8,history:e=>y8.depth(e),navigation:(e,t)=>b8.depth(e,v8,MU(t))})},{budgetBytes:()=>(K8(),RZ(R8)),observers:{onReload:(e,t)=>{M(`info`,VZ(e));for(let e of t)O8.wake(e,`reload`)},onViewChanged:e=>O8.wake(e,`data`)}}),N8=60*1e3,P8=rW({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:N8,stat:p.statSync,exit:()=>Z8(0),log:M}),F8=eW({entryUrl:import.meta.url,intervalMs:N8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>P8.checkNow(),log:M});let I8=null,L8=null,R8=0;function z8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),Z8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),Z8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),Z8(0)});try{q8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),Z8(1);return}I8=xs(t.pid);let e=js(Ns(I8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Z8(1);return}L8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),v8.useStorage(new sQ(Ot(),500,M)),y8.useStorage(F$(kt(),M)),ws({anchor:Cs(t.env),isAlive:Ts,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),Z8(0)}}),V8(ue.createServer({allowHalfOpen:!1},e=>{Q8(e)}),St(),!1)}function B8(){let e=p8.getStats(),t=h8.getStats(),n=m8.scanStats(),r=_8.stats(),i=M8.stats;return{records:d8.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:m8.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:g8.held(),today:n.held,pluginStorage:r.held},pluginStorage:{folders:r.folders,faults:r.faults,lost:r.lost}}}function V8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),Z8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}H8(e,n)}),e.listen(n,()=>U8(n))}function H8(e,n){let r=ds(fs(Et(n)),(e,t)=>bs(e,t,{readStartTime:ys,pidAlive:Ts}));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}`),Z8(1);return}}V8(e,n,!0)}function U8(e){let n=hs(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Z8(0);return}J8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(R8)}MB`),Tr();let r=j8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),P8.arm(),F8.arm(),K8().arm(),W8(e,n.identity)}function W8(e,n){vs({bound:n,myPid:t.pid,readIdentity:()=>hs(e),readLease:()=>fs(Et(e)),shutdown:e=>Z8(e),log:M}).arm()}let G8=null;function K8(){if(G8===null)throw Error(`daemon: limits not yet established`);return G8}function q8(e){R8=nr(e),G8=ur(gr(a8.startedAt.getTime(),e=>Z8(e),{limitBytes:R8}))}function J8(e){let n=ps(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:I8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let Y8=0,X8=!1;function Z8(e){if(X8)return;X8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>D8.restoreAll()],[`gitService close`,()=>p8.close()],[`usageStore close`,()=>m8.close()],[`tmuxService close`,()=>h8.close()],[`hostService close`,()=>g8.close()],[`runs close`,()=>w8.close()],[`managedStorage close`,()=>_8.close()],[`watcherRegistry close`,()=>u8.closeAll()],[`sessionState flush`,()=>v8.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ms(Dt(),t.pid),L8!==null&&Ms(L8,t.pid,ks,e=>p.unlinkSync(e)),t.exit(e)}function Q8(e){let t=performance.now();Y8++,a8.inFlight=Y8;let n=!1,r=!0,i=()=>{r&&(r=!1,Y8=Math.max(0,Y8-1),a8.inFlight=Y8)},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:()=>Z8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,a8.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,$8)},200),c=en(e=>{o5(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(r5(e),null,$8)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,$8)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=u3(e),o=O8.subscribe(t,{lane:r,frame:(e,t)=>a($t(EW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const $8=()=>{},e5=e=>({resp:e,exitAfterFlush:null,delivered:$8}),t5=e=>({kind:`reply`,...e}),n5={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},r5=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),i5=(e,t)=>t5(e5({ok:!1,error:t,code:e,daemonV:3}));function a5(e){let t=DW(e.sessionId);if(!t.ok)return i5(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return i5(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Iv.join(`, `)}): it predates the lane toggles — update it`);let n=Uv(e.lane);return n===null?i5(`BAD_REQUEST`,`subscribe needs a lane, one of ${Iv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function o5(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?i5(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?a5(e):typeof e.kind!=`string`||!Object.hasOwn(n5,e.kind)?i5(`BAD_REQUEST`,`unknown kind`):t5(await s5(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:$8})}async function s5(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:$8};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return e5(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:O8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return e5({ok:!0,stats:a8.snapshot({gitCache:p8.getStats(),usageCache:m8.getStats(),sources:B8(),runs:w8.stats(),transcriptReads:za(),renderCache:M8.stats,effectCache:x8.getStats(),menuIdle:S8.getStats(),sessionState:{sessions:v8.size(),observers:v8.observers(),revision:v8.latestRevision()},frameFeeds:O8.getStats(),tmuxStatus:D8.stats(),watchersActive:u8.size(),nextRestartReason:K8().describeNextRestart(),handlerProbes:o8.list(),clients:s8.list(uk(new Date)),bundle:c8,daemon:K8().serving(),doctorStores:o0(l8)})});if(e.kind===`render`){let r=new Date,i=uk(r),a=performance.now(),o=Math.round(a-n),s=[],c=++a8.requestsTotal,l=S5(e),u=(e,t)=>s8.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:CM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),O8.note(l.req.sessionId,l.req,c));let d=l.ok?await M5(l.req,c,i,(e=>{let t=e8(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?$8:()=>ts(v8,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:r5(e),delivered:$8})):C5(l.problems);d.outcome.kind!==`ok`&&a8.requestsErrored++,t8(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=i8(`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=p5(e,i);t8(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=i8(`click`,i,a,Math.round(performance.now()-r));return M(o,s),e5(g5(a))}if(e.kind===`debug`){if(!e3(e.what))return e5({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${$4.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=M8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?f5(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??yy(`colorCompatibility`)):d5};return e5({ok:!0,debug:H4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function c5(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:eV(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const l5={sessionState:v8,dlog:M,applyUpdate:()=>F8.act(),doctor:g0(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];M8.reload(...t);let n=M8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:l8,probes:o8,clients:s8,bundle:c8,serving:()=>K8().serving(),claudeInput:b2(),history:y8,navigation:b8,configFor:e=>M8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>M8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>M8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:C8,runs:w8,lanes:{of:x5,clicked:F5},views:{follow:(e,t)=>M8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};l5.reloadConfig;const u5={endcaps:yy(`endcaps`),colorCompatibility:yy(`colorCompatibility`),wrap:yy(`autoWrap`),padding:yy(`padding`),width:1/0},d5=new Map;function f5(e,t){let n=new Map;for(let[r,i]of e)n.set(r,mb(i,{...u5,colorCompatibility:t}));return n}function p5(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 h5(n,r,{via:`link`,handler:Zt(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const m5={link:`verb`,"tmux-status":`linkVerb`};function h5(e,t,n,r){if(e===`tmux-status-click`)return t8(r,{verb:e}),_5(t,r);let i=N4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};t8(r,{[m5[n.via]]:e});let a=k4(e,t);return a===null?t8(r,{sid:`-`}):a.ok&&(t8(r,{sid:a.id}),S8.clicked(a.id,uk(new Date))),i(t,{...l5,arrival:n}),{kind:`ok`}}function g5(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 r5(e.error)}}function _5(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=D8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(t8(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=jb(()=>Bo(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):h5(e.verb,e.value,{via:`tmux-status`},n)}return C2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function v5(e,t){let n=new Date,r=uk(n),i=[];try{try{var a=ja();let n=a.u(E5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=O5(n,{by:`feed`,fps:t}),u=j8.linkFor(e,A5(o)),d=k5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:L5(e,o,u,d,J6(l,O8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=i8(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=r5(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function y5(e,t){return XH(t.config,t=>v8.get(e,t),e=>t.authoredRoots.has(e))}function b5(e){try{var t=ja();let n=t.u(M8.holdView(e));return n===null?null:qH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function x5(e,t){try{var n=ja();return qH(y5(t,n.u(M8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function S5(e){let{report:t}=R4(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=DW(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=$6(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)a8.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Vt(e),{configFile:o,refusedArgs:s}=c5(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:SM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const C5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:$8});function w5(e,t,n){t8(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return t8(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 T5(e,t,n){let r=e.sessionId,i=w5(e,t,n),a=R2(e.requested,v8,r);return D5(M8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function E5(e,t,n){let r=M8.holdView(e);if(r===null){let t=M8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=w5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return D5(r,i,a,t,n)}function D5(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:{...f8,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 O5(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=qH(u);t8(i,{lanes:Iv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=Jq(f),m=hb(f.termRows);t8(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:O8.feedsOf(a,r),today:uJ(f8,c.lanes().today,c.facts().hookData,r)},_=Aa(h.metrics)?void 0:h.metrics;t8(i,aJ(c.lanes().sources)),t8(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:Mq(h.git,Wq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:i3(g.feeds)});let v=[],y=kq(u,p),b=x8.of(a),ee=S8.since(a,r),x=NZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});S8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=S8.since(a,r);t8(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=rs(v8,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
|
|
497
|
-
`),ae=
|
|
498
|
-
`)),T=
|
|
499
|
-
`}function
|
|
500
|
-
`);return}t.stdout.write(
|
|
501
|
-
`;let t=[`variables (${e.length})`,``],n=e.reduce((e,t)=>Math.max(e,t.name.length),4),r=e.reduce((e,t)=>Math.max(e,(t.source??`—`).length),6),i=e.reduce((e,t)=>Math.max(e,t.type.length),4);for(let a of e){let e=a.ageMs===null?``:` ${
|
|
492
|
+
`)){let[t,n,i]=e.trim().split(` `);t!==void 0&&n===`0`&&i!==void 0&&r.set(t,i)}return{sessionOf:n,shownBy:r}}var _3=class{servers=new Map;loop={kind:`idle`};constructor(e){this.deps=e}follow(){switch(this.loop.kind){case`idle`:this.deps.log(`info`,`visibility following`),this.ask();break;case`asking`:this.loop.following=!0;break;case`due`:break}return()=>this.stop()}stop(){switch(this.loop.kind){case`due`:clearTimeout(this.loop.timer),this.end();return;case`asking`:this.loop.following=!1;return;case`idle`:return}}ask(){let e={kind:`asking`,following:!0};this.loop=e,Promise.resolve().then(()=>this.refresh(this.deps.sockets())).catch(e=>this.deps.log(`error`,`visibility refresh threw: ${T(e)}`)).then(()=>{if(e.following){this.loop={kind:`due`,timer:setTimeout(()=>this.ask(),this.deps.intervalMs).unref()};return}this.end()})}end(){this.deps.log(`info`,`visibility stopped forgot=${this.servers.size}`),this.loop={kind:`idle`},this.servers.clear()}shown(e){if(e==null)return!0;let t=this.servers.get(e.socket);return t?.kind!==`asked`||t.shown.has(e.pane)}async refresh(e){for(let t of this.servers.keys())e.has(t)||this.servers.delete(t);let t=await Promise.all([...e].map(async e=>{let[t,n]=await Promise.all([this.deps.listPanes(e),this.deps.listClients(e)]);return[e,t.kind===`ok`?n.kind===`ok`?{kind:`asked`,shown:h3(t.stdout,m3(n.stdout)),status:g3(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),!v3(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 v3(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 y3=`@cc-candybar-status-prior`,b3=`@cc-candybar-status-wrote`,x3=`@cc-candybar-binding-prior`,S3=[`-T`,`root`,`MouseDown1Status`],C3=Array.from({length:5},(e,t)=>t),w3=e=>`@cc-candybar-row-${e}`,T3=e=>`#[fill=terminal]#{${w3(e)}}`,E3=e=>`status-format[${e}]`;function D3(e){return e===0?`off`:e===1?`on`:String(e)}function O3(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 k3(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 A3(e){return e.endsWith(`;`)?`${e.slice(0,-1)}\\;`:e}function j3(e){return e.flatMap((e,t)=>[...t===0?[]:[`;`],...e])}function M3(e){return`"${e.replace(/[\\"$]/g,e=>`\\${e}`)}"`}function N3(e){return e.map(e=>e.map(M3).join(` `)).join(` ; `)}const P3=`ccb:separator`;function F3(e){return j3(e.flatMap((e,t)=>t===0?[e]:[[`display-message`,`-p`,P3],e]))}function I3(e,t){let n=e.split(`${P3}\n`);return n.length===t?n.map(e=>e.replace(/\n$/,``)):null}const L3=(e,t)=>[`show-options`,`-q`,`-v`,`-t`,e,t],R3=e=>[`show-options`,`-g`,`-q`,`-v`,e],z3=e=>[[`show-options`,`-t`,e],L3(e,`status`),...C3.map(t=>L3(e,E3(t)))];function B3(e){let[t=``,n=``,...r]=e,i=t.split(`
|
|
493
|
+
`).map(e=>e.split(` `)[0]??``),a={};for(let e of C3)i.includes(E3(e))&&(a[e]=r[e]??``);let o=i.includes(`status-format`)||Object.keys(a).length>0;return{status:i.includes(`status`)?n:null,formats:o?a:null}}function V3(e,t){return[[`set-option`,`-u`,`-t`,e,`status-format`],...Object.entries(t??{}).map(([t,n])=>[`set-option`,`-t`,e,E3(Number(t)),A3(n)])]}const H3=e=>[[`display-message`,`-p`,`-t`,e,`#{status}`],...z3(e),...C3.map(e=>R3(E3(e))),L3(e,y3),L3(e,b3)];function U3(e,t,n){let r,i;try{r=JSON.parse(e),i=t===``?r.base:O3(t)}catch(e){return{kind:`theirs`,why:`${y3} 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 W3(e,t,n){let[r=``,...i]=t,a=B3(i.slice(0,7)),o=i.slice(7,12),[s=``,c=``]=i.slice(12);if(s!==``)return U3(s,c,n);let l=O3(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,T3(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,y3,JSON.stringify(f)],...V3(e,d)]}}const G3=e=>[...z3(e),L3(e,b3)];function K3(e,t,n){let r=B3(n.slice(0,7)),i=n[7]??``,a=[],o=[];if(k3(r.formats,t.wrote))a.push(...V3(e,t.formats));else{o.push(`status-format`);for(let[n,i]of Object.entries(r.formats??{}))Number(n)>=t.base&&i===t.wrote[Number(n)]&&a.push([`set-option`,`-u`,`-t`,e,E3(+n)])}return i!==``&&(r.status===i?a.push(t.status===null?[`set-option`,`-u`,`-t`,e,`status`]:[`set-option`,`-t`,e,`status`,A3(t.status)]):o.push(`status`)),a.push(...C3.map(t=>[`set-option`,`-q`,`-u`,`-t`,e,w3(t)]),[`set-option`,`-q`,`-u`,`-t`,e,y3],[`set-option`,`-q`,`-u`,`-t`,e,b3]),{commands:a,kept:o}}const q3=/^bind-key\s+(?:-r\s+)?(?:-N\s+(?:"(?:[^"\\]|\\.)*"|\S+)\s+)?-T\s+root\s+MouseDown1Status\s+(.+)$/m,J3=[[`list-keys`,`-T`,`root`]];function Y3(e){let t=q3.exec(e);return t===null?null:{line:t[0],command:t[1]}}const X3=`cc-candybar://tmux-status-click/`,Z3=e=>`${X3}${di([e])}/#{s/%//:pane_id}/#{q:mouse_status_range}`,Q3=e=>e?.command.includes(X3)??!1;function $3(e,t){let n={command:[`set-option`,`-g`,`-q`,`-u`,x3]};return Q3(Y3(t))?{steps:[e===null?{command:[`unbind-key`,...S3]}:{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 e6=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=TW(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,G3(n));if(i===null)continue;let a=K3(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,J3);if(t===null)continue;this.writeBindingRestoreSync(e,n.prior,t[0]??``)}}}linkAt(e){let t=t6(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#{${y3}}\t#{${b3}}`]);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=U3(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,[R3(`@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)} ${x3} 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,H3(n));if(r===null||this.closed)return null;let i=W3(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,w3(r),e])}),i!==n.status){let e=D3(i);a.push([`set-option`,`-t`,t,`status`,e],[`set-option`,`-t`,t,b3,e])}(a.length===0||await this.write(e,[[`if-shell`,`-F`,`-t`,t,`#{@cc-candybar-status-prior}`,N3(a)]]))&&(n.rows=r,n.status=i)}async restore(e,t,n){let r=t.layouts.get(n);if(r===void 0)return;t.layouts.delete(n);let i=await this.ask(e,G3(n));if(i===null)return;let a=K3(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,J3);if(r===null||this.closed)return;let i=Y3(r[0]??``);if(n.kind===`none`&&Q3(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`&&Q3(i)?n.prior:i,o={owner:this.deps.owner,prior:a};if(t.binding={kind:`ours`,prior:a},!await this.write(e,[[`bind-key`,...S3,`if-shell`,`-F`,`#{m:ccb*,#{mouse_status_range}}`,`run-shell -b ${M3(`${this.deps.handler} ${Z3(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,J3);if(r===null)return;let i=$3(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=$3(t,n);for(let t of r.steps)this.writeSync(e,[t.command],t.stdin);this.deps.log(`info`,`tmux-status: socket=${JSON.stringify(e)} ${r.said}`)}counted(e,t){let n=this.serverOf(e);return t.kind===`ok`?(n.lastFailure=null,t):(this.failedWrites++,n.lastFailure!==t.reason&&this.deps.log(`warn`,`tmux-status: socket=${JSON.stringify(e)} ${t.reason}`),n.lastFailure=t.reason,t)}async run(e,t,n){return this.counted(e,await this.deps.edge.run(e,t,n))}async ask(e,t){let n=await this.run(e,F3(t));return n.kind===`ok`?I3(n.stdout,t.length):null}askSync(e,t){let n=this.counted(e,this.deps.edge.runSync(e,F3(t)));return n.kind===`ok`?I3(n.stdout,t.length):null}async write(e,t,n){return t.length===0?!0:(this.writes++,(await this.run(e,j3(t),n)).kind===`ok`)}writeSync(e,t,n){t.length!==0&&(this.writes++,this.counted(e,this.deps.edge.runSync(e,j3(t),n)))}};function t6(e){try{return fi(e)}catch(e){if(e instanceof URIError)return null;throw e}}const n6=`CC_CANDYBAR_CONFIG`;function r6(e,t){return eV(t,e[n6])}const $=e=>({arity:e,keep:!0}),i6=e=>({arity:e,keep:!1}),a6={"--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":i6(`none`),"--background":i6(`none`),"--bare":$(`none`),"--betas":$(`variadic`),"--brief":$(`none`),"--chrome":$(`none`),"--cloud":i6(`optional`),"-c":i6(`none`),"--continue":i6(`none`),"--dangerously-skip-permissions":$(`none`),"-d":$(`optional`),"--debug":$(`optional`),"--debug-file":$(`one`),"--desktop":i6(`none`),"--disable-slash-commands":$(`none`),"--disallowedTools":$(`variadic`),"--disallowed-tools":$(`variadic`),"--effort":$(`one`),"--environment":i6(`one`),"--exclude-dynamic-system-prompt-sections":$(`none`),"--fallback-model":$(`one`),"--file":$(`variadic`),"--fork-session":i6(`none`),"--forward-subagent-text":$(`none`),"--from-pr":i6(`optional`),"-h":i6(`none`),"--help":i6(`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":i6(`none`),"--print":i6(`none`),"--prompt-suggestions":$(`optional`),"--remote-control":$(`optional`),"--remote-control-session-name-prefix":$(`one`),"--replay-user-messages":$(`none`),"--restricted":$(`none`),"-r":i6(`optional`),"--resume":i6(`optional`),"--safe-mode":$(`none`),"--session-id":i6(`one`),"--setting-sources":$(`one`),"--settings":$(`one`),"--strict-mcp-config":$(`none`),"--system-prompt":$(`one`),"--system-prompt-snapshot":$(`one`),"--teleport":i6(`optional`),"--tmux":i6(`none`),"--tools":$(`variadic`),"--verbose":$(`none`),"-v":i6(`none`),"--version":i6(`none`),"-w":i6(`optional`),"--worktree":i6(`optional`)},o6={resume:`--resume`,fresh:`--session-id`};function s6(e){return[o6[e.kind],e.sessionId]}const c6=e=>e.startsWith(`-`)&&e!==`-`;function l6(e,t){let n=f6(t);return n===null?{dir:e??t,args:[]}:e!==null&&u6(e,n.top)?{dir:e,args:[]}:{dir:e===null||f6(e)!==null?n.repo:e,args:[`--worktree`,n.name]}}const u6=(e,t)=>e===t||e.startsWith(t+s.sep);function d6(e){let t=[],n=e.slice(1),r=0;for(;r<n.length;){let e=n[r];if(r+=1,e===`--`)break;if(!c6(e))continue;let i=e.indexOf(`=`),a=i===-1?e:e.slice(0,i),o=a6[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=>!c6(e)):o.arity===`variadic`?p6(n.slice(r),e=>!c6(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 f6(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 p6(e,t){let n=e.findIndex(e=>!t(e));return n===-1?[...e]:e.slice(0,n)}const m6=`candybar-band@cc-candybar`,h6=s.join(`bin`,`cc-candybar-native`),g6=`@cc-candybar-bar-pane`,_6=mP(`/reload-plugins`),v6=e=>({kind:`done`,said:e});function y6(e){let t=h2(e.hints.tmux);if(t.kind===`refused`)throw new q(t.reason);return t.hint}const b6={band:{on:(e,t,n)=>{let r=Qe(t.bundle);if(r===null)throw new q(`${Fv.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,h6);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 ${m6} from ${r}`,finished:x6(e,r,n)}},off:()=>v6(`nothing to stop: the band mod draws nothing while the lane is off`)},statusline:{on:(e,t,n)=>{let r=y6(e),i=Re(t.preload),a=[t.preload,i].find(e=>!n.fileExists(e));if(a!==void 0)throw new q(`${Fv.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:w6(e,r,{node:t.node[0],launcher:i,preload:t.preload},n)}},off:()=>v6(`nothing to stop: the attached statusline draws its command's output while the lane is off`)},pane:{on:(e,t,n)=>{let r=y6(e),i=n.barPanes(r);return i.length>0?v6(`bar pane ${i.join(`, `)} already draws ${r.pane}'s bar`):v6(`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=h2(e.hints.tmux);if(r.kind===`refused`)return v6(`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 v6(a.length===0?`no bar pane draws ${i.pane}'s bar`:`closed bar pane ${a.join(`, `)}`)}},tmuxStatus:{on:e=>v6(`the daemon draws ${y6(e).pane}'s bar in its status line`),off:()=>v6(`nothing to stop: the daemon puts the status line back once the lane is off`)}};async function x6(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`,m6],r);let i=g2(n.claudeInput,e.hints.tmux,_6);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 ${m6} from ${t} and typed /reload-plugins into ${i.pane}`}const S6=new Set([Ja,n6]);function C6(e){return new Map(e.flatMap(e=>{let t=e.indexOf(`=`);return t>0?[[e.slice(0,t),e.slice(t+1)]]:[]}))}async function w6(e,t,n,r){let i=await r.paneClaude(t);if(i.attached)return`left Claude Code in ${t.pane} running: it already runs under the attach launcher`;if(!i.fromShell)throw Error(`Claude Code is the first process of pane ${t.pane}, so nothing would be left in the pane to start it again under the attach launcher — start Claude Code from a shell in the pane`);let a=await r.moduleGraph(n.node,ze(n.launcher),i.executable);if(!a.ok)throw Error(`Claude Code in ${t.pane} runs ${i.executable}, which the attach launcher cannot start (${a.reason}) — ${Fv.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=k6(r.claudeInput.read(t));if(o!==null)throw Error(`Claude Code in ${t.pane} was left running: ${o} — then turn ${Fv.statusline.label} off and on again`);let s=T6(e,r.presence(e.transcript));if(s!==null)throw Error(`Claude Code in ${t.pane} was left running: ${s}`);let c=d6(i.argv);if(c.kind===`refused`)throw Error(`${c.reason} — restart it with that flag removed`);let l=C6(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])=>S6.has(e)),m=(e,t)=>He(n.preload,{dir:e.dir,env:p,program:f,args:[...e.args,...c.args,...s6(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=E6(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(l6(null,i.cwd),_))}let y=m(l6(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}\`, ${D6[g.kind](e.sessionId)}, and its statusline follows lane B`}function T6(e,t){return typeof t==`object`?`whether session ${e.sessionId} has a conversation could not be seen (${t.error})`:t===`present`||e.answered===`no`?null:e.answered===`yes`?`session ${e.sessionId} has a conversation but no transcript to resume it from (is session persistence off?), so a restart would lose it`:`this Claude Code does not say whether session ${e.sessionId} has a conversation, and it has no transcript to resume one from`}function E6(e,t){return typeof t==`object`?{kind:`unchecked`,error:t.error}:{kind:t===`present`?`resume`:`fresh`,sessionId:e.sessionId}}const D6={resume:e=>`resuming ${e}`,fresh:e=>`starting ${e} afresh, since it had no conversation yet`},O6={"in-mode":`its pane is in tmux copy mode — leave it (q)`,stashed:`it holds a stashed prompt (ctrl+s), which ending it would lose — restore or send it`,"no-prompt":`it is not at its prompt (a dialog or picker is open) — close it`};function k6(e){let t=u2(e);return t.kind===`ready`?p2(e)?`it is in the middle of a turn, which ending it would end — wait until it is idle`:d2(e)?`its prompt holds a draft, which ending it would lose — send or clear it`:null:O6[t.kind]}var A6=class{owed=new Map;queued=new Map;constructor(e){this.deps=e}clicked(e,t,n,r){let i=Iv.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}`),es(this.deps.state,e.sessionId,a,this.deps.now())},o;try{o=b6[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 j6(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 M6(e,t){try{return p.accessSync(e,t),p.statSync(e).isFile()}catch{return!1}}function N6(e){try{return p.realpathSync(e)}catch{return s.resolve(e)}}function P6(e,t,n){let r=j6(`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 F6=2e3;function I6(e,t,n){let r=JK(e,`lane.tmux`,t,n);if(r.kind!==`ok`)throw Error(r.reason);return r.stdout}function L6(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 R6(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 z6=`#{pane_id} #{${g6}}`;function B6(e,t){return e.split(`
|
|
495
|
+
`).map(e=>e.trim().split(` `)).filter(([,e])=>e===t).map(([e])=>e)}const V6=/(^|\/)(cc-attach|bun-attach\.js)(\s|$)/;function H6(e,t,n){for(let r of c1(s1(e),t)){if(r.command.split(` `).some(e=>V6.test(e)))return!0;if(r.pid===n)return!1}return!1}const U6=[`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 W6(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=L6(`reading process ${e}'s arguments`,await pt({bin:`python3`,args:[`-c`,U6,String(e)],timeoutMs:5e3,category:`lane.process`}));return JSON.parse(t)}async function G6(e,t){return L6(e,await pt({bin:`ps`,args:t,timeoutMs:2e3,category:`lane.process`}))}async function K6(e){let t=await YK(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 G6(`asking pane ${e.pane}'s foreground job`,[`-o`,`tpgid=`,`-p`,n])).trim();return{panePid:Number(n),cwd:r,foreground:Number(i)}}async function q6(e){let{panePid:t,cwd:n,foreground:r}=await K6(e),i=await G6(`listing processes`,[`-A`,`-o`,`pid=,ppid=,args=`]),a=await W6(r),o=s1(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:H6(i,r,t)}}function J6(e){return{claudeInput:x2(),barPanes:e=>B6(I6(e,[`list-panes`,`-a`,`-F`,z6]),e.pane),openBarPane:(e,t,n)=>{let r=I6(e,[`split-window`,`-d`,`-v`,`-l`,`1`,`-t`,e.pane,`-P`,`-F`,`#{pane_id}`,...Object.entries(n).flatMap(([e,t])=>[`-e`,`${e}=${t}`]),...t]).trim();return I6(e,[`set-option`,`-p`,`-t`,r,g6,e.pane]),r},closePane:(e,t)=>void I6(e,[`kill-pane`,`-t`,t]),claude:async(e,t)=>void L6(`claude ${e.join(` `)}`,await pt({bin:`claude`,args:[...e],env:J$(process.env,t),timeoutMs:3e4,category:`lane.claude`})),fileExists:e=>p.existsSync(e),presence:KV,paneClaude:q6,paneDir:async(e,t)=>{let n=Date.now()+F6;for(;;){let r=await K6(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 ${F6/1e3} s`);await be(100)}},launcherNode:e=>P6(e,e=>M6(e,p.constants.X_OK),N6),onPath:(e,t)=>{let n=j6(e,t,e=>M6(e,p.constants.X_OK));return n===null?null:p.realpathSync(n)},followed:async(t,n,r)=>{let i=Date.now()+r;for(;!e(t).has(n);){if(Date.now()>i)return!1;await be(200)}return!0},moduleGraph:async(e,t,n)=>{let r=await pt({bin:e,args:[t,n],timeoutMs:2e4,category:`lane.process`}),i=!r.ok&&r.reason===`non-zero`?R6(r.stdout):null;return i===null?(L6(`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(;Ts(e);){if(Date.now()>n)return!1;await be(100)}return!0},typeShellLine:(e,t)=>void I6(e,y2(e.pane,`cc-candybar-lane`,[]),t)}}function Y6(e,t){return Iv.filter(n=>e[n]&&Fv[n].elsewhere!==null&&t.has(n))}function X6(e,t){let n=`the bar is drawn in ${t.map(e=>Fv[e].elsewhere).join(` and `)}`,r=N([{verb:Qr,args:[e,...t.map(e=>Fv[e].setting)]}]);return{channels:[{severity:bb,message:n,lines:[[xb(n,N([{verb:Br,args:[n]}])),xb(`[⟲ draw it here]`,r)]]}]}}const Z6={order:-1/0,text:null,failure:null};var Q6=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)??Z6;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)??Z6;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}`}}},$6=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?Jv(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 e8(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 t8(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 n8(e,t){for(let n of Object.entries(t))e.push(n)}const r8={ok:`info`,"bad-request":`warn`,threw:`error`};function i8(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,T(e.error)]]}}function a8(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...i8(n)];return{level:r8[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${os(t)}`).join(``)}`}}const o8=new rQ,s8=new X0,c8=new DM,l8=i(import.meta.url),u8=o0(yt());dt(o8.launchStats);const d8=new fG({counters:o8,logger:M}),f8=new Lk(M),p8=xq({watchers:d8,logger:M,ledger:f8}),{gitProvider:m8,usageStore:h8,tmuxService:g8,hostService:_8,managedStorage:v8}=p8,y8=new oQ,b8=new h$(y8,M),x8=new R$,S8=new tb,C8=new $6({now:()=>uk(new Date),close:(e,t)=>F4(e,t,u5),failed:(e,t)=>M(`error`,`menu-idle: close failed (session=${e}): ${T(t)}`)}),w8=Xo(),T8=new us({supersede:(e,t)=>v8.supersede(e,t),launch:pt,state:y8,log:M,now:()=>uk(new Date)}),E8=[t.execPath,...t.execArgv],D8=new A6({edge:J6(e=>k8.following(e)),host:{bundle:l8,node:E8,socket:St(),preload:Oo(l8)},state:y8,log:M,now:()=>uk(new Date),defer:e=>void _e(e)}),O8=new e6({edge:{run:(e,t,n)=>YK({socket:e},`tmux-status`,t,n),runSync:(e,t,n)=>JK({socket:e},`tmux-status`,t,n)},subscribe:(e,t)=>k8.subscribe(e,t),sessionInPane:(e,t)=>k8.newestWhere(({hints:{tmux:n}})=>n!=null&&n.socket===e&&n.pane===t),handler:[`CC_CANDYBAR_SOCKET=${Fe(St())}`,...[...E8,l8].map(Fe),`url-handle`].join(` `),owner:St(),log:M}),k8=new u3({render:(e,t)=>y5(e,t),watch:(e,t)=>(0,J.reaction)(()=>y8.revision(e),t),lanes:e=>x5(e),pin:e=>N8.pin(e),shown:e=>A8.shown(e.hints.tmux),watching:()=>A8.follow(),refreshes:()=>f8.totals(),periods:r3,now:()=>performance.now(),log:M}),A8=new _3({listPanes:e=>YK({socket:e},`frames.visibility`,[`list-panes`,`-a`,`-F`,f3]),listClients:e=>YK({socket:e},`frames.visibility`,[`list-clients`,`-F`,p3]),sockets:()=>new Set(k8.watched().flatMap(({req:e})=>j8(e))),onAnswer:(e,t)=>O8.answered(e,t),onChange:e=>k8.wakeWhere(`visibility`,t=>j8(t).some(t=>e.has(t))),intervalMs:1e3,log:M});function j8({hints:{tmux:e}}){return e==null?[]:[e.socket]}const M8=new Q6(Pt(),e=>k8.wake(e,`data`)),N8=new tQ({sessionState:y8,watchers:d8,log:M,storage:v8,signer:w8,ledger:f8,declare:(e,t,n,r)=>nJ(p8,e,t,n,r),source:n3({providers:p8,sessionState:y8,history:e=>b8.depth(e),navigation:(e,t)=>x8.depth(e,y8,MU(t))})},{budgetBytes:()=>(q8(),zZ(z8)),observers:{onReload:(e,t)=>{M(`info`,HZ(e));for(let e of t)k8.wake(e,`reload`)},onViewChanged:e=>k8.wake(e,`data`)}}),P8=60*1e3,F8=rW({targets:[...new Set([...import.meta.url.startsWith(`file://`)?[i(import.meta.url)]:[],...t.argv[1]?[t.argv[1]]:[]])],intervalMs:P8,stat:p.statSync,exit:()=>Q8(0),log:M}),I8=eW({entryUrl:import.meta.url,intervalMs:P8,releaseIntervalMs:216e5,registryUrl:t.env.CC_CANDYBAR_REGISTRY_URL??`https://registry.npmjs.org`,fetchImpl:fetch,onApplied:()=>F8.checkNow(),log:M});let L8=null,R8=null,z8=0;function B8(){t.on(`uncaughtException`,e=>{M(`error`,`uncaughtException: ${e.stack||e.message}`),Q8(1)}),t.on(`unhandledRejection`,e=>{M(`error`,`unhandledRejection: ${String(e)}`),Q8(1)});for(let e of[`SIGINT`,`SIGTERM`,`SIGHUP`])t.on(e,()=>{M(`info`,`received ${e}, shutting down`),Q8(0)});try{J8(t.env)}catch(e){M(`error`,`refusing to boot: ${e.message}`),Q8(1);return}L8=xs(t.pid);let e=js(Ns(L8));if(!e.decision.allow){M(`warn`,`fork-bomb breaker: ${e.decision.reason}; refusing to boot`),Q8(1);return}R8=e.registryPath,p.mkdirSync(xt(),{recursive:!0}),Tt(St()),y8.useStorage(new cQ(Ot(),500,M)),b8.useStorage(I$(kt(),M)),ws({anchor:Cs(t.env),isAlive:Ts,onOrphaned:e=>{M(`info`,`parent watchdog: ${e}; shutting down`),Q8(0)}}),H8(ue.createServer({allowHalfOpen:!1},e=>{$8(e)}),St(),!1)}function V8(){let e=m8.getStats(),t=g8.getStats(),n=h8.scanStats(),r=v8.stats(),i=N8.stats;return{records:f8.snapshot(),homes:{daemon:1,configDir:n.entries,repo:e.size,directory:i.size,session:h8.getStats().size,view:i.views,pane:t.entries},held:{git:e.held,tmux:t.held,host:_8.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 H8(e,n,r){e.removeAllListeners(`error`),e.removeAllListeners(`listening`),e.once(`error`,i=>{if(i.code!==`EADDRINUSE`){M(`error`,`server error: ${i.message}`),Q8(1);return}if(r){M(`info`,`lost rebind race; another daemon is alive — exiting`),t.exit(0);return}U8(e,n)}),e.listen(n,()=>W8(n))}function U8(e,n){let r=ds(fs(Et(n)),(e,t)=>bs(e,t,{readStartTime:ys,pidAlive:Ts}));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}`),Q8(1);return}}H8(e,n,!0)}function W8(e){let n=hs(e);if(n.kind!==`present`){M(`warn`,`no ownable socket at bind callback (${n.kind}); exiting`),Q8(0);return}Y8(e);try{p.chmodSync(e,384)}catch(e){M(`warn`,`chmod socket failed: ${e.message}`)}M(`info`,`daemon up: pid=${t.pid} v=3 sock=${e} heapCap=${tr(de.getHeapStatistics().heap_size_limit)}MB memoryLimit=${tr(z8)}MB`),Tr();let r=M8.reset();r!==null&&M(`warn`,`diagnostic dump wipe failed: ${r}`),F8.arm(),I8.arm(),q8().arm(),G8(e,n.identity)}function G8(e,n){vs({bound:n,myPid:t.pid,readIdentity:()=>hs(e),readLease:()=>fs(Et(e)),shutdown:e=>Q8(e),log:M}).arm()}let K8=null;function q8(){if(K8===null)throw Error(`daemon: limits not yet established`);return K8}function J8(e){z8=nr(e),K8=ur(gr(o8.startedAt.getTime(),e=>Q8(e),{limitBytes:z8}))}function Y8(e){let n=ps(Et(e),{pid:t.pid,version:3,binPath:t.argv[1],startTime:L8});n!==null&&M(`warn`,`lease write failed: ${n}`)}let X8=0,Z8=!1;function Q8(e){if(Z8)return;Z8=!0,setTimeout(()=>t.kill(t.pid,`SIGKILL`),500);let n=[[`tmuxStatusLines restore`,()=>O8.restoreAll()],[`gitService close`,()=>m8.close()],[`usageStore close`,()=>h8.close()],[`tmuxService close`,()=>g8.close()],[`hostService close`,()=>_8.close()],[`runs close`,()=>T8.close()],[`managedStorage close`,()=>v8.close()],[`watcherRegistry close`,()=>d8.closeAll()],[`sessionState flush`,()=>y8.flush()]];for(let[e,t]of n)try{t()}catch(t){M(`warn`,`${e} failed: ${t.message}`)}ms(Dt(),t.pid),R8!==null&&Ms(R8,t.pid,ks,e=>p.unlinkSync(e)),t.exit(e)}function $8(e){let t=performance.now();X8++,o8.inFlight=X8;let n=!1,r=!0,i=()=>{r&&(r=!1,X8=Math.max(0,X8-1),o8.inFlight=X8)},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:()=>Q8(r);try{e.end(Qt(t),e=>{e??i(),a?.()})}catch(e){M(`warn`,`response write failed: ${e.message}`),a?.()}},o=!1,s=setTimeout(()=>{o=!0,o8.requestsTimedOut++,a({ok:!1,error:`request exceeded 200ms`,code:`TIMEOUT`,daemonV:3},null,e5)},200),c=en(e=>{s5(e,()=>o,t).then(e=>e.kind===`reply`?a(e.resp,e.exitAfterFlush,e.delivered):l(e.sessionId,e.lane)).catch(e=>{M(`error`,`handler threw: ${T(e)}`),a(i5(e),null,e5)})},e=>{M(`warn`,`frame parse failed: ${e.message}`),a({ok:!1,error:e.message,code:`BAD_REQUEST`,daemonV:3},null,e5)}),l=(t,r)=>{if(n||e.destroyed)return;clearTimeout(s),i(),e.off(`data`,c);let a=d3(e),o=k8.subscribe(t,{lane:r,frame:(e,t)=>a($t(EW[r](e,t))),refused:t=>e.end(Qt(t)),drawing:()=>!0});n=!0,e.on(`close`,o)};e.on(`data`,c),e.on(`error`,e=>{M(`warn`,`socket error: ${e.message}`)}),e.on(`close`,()=>{clearTimeout(s),i()})}const e5=()=>{},t5=e=>({resp:e,exitAfterFlush:null,delivered:e5}),n5=e=>({kind:`reply`,...e}),r5={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},i5=e=>({ok:!1,error:e instanceof Error?e.message:T(e),code:`RENDER_FAILED`,daemonV:3}),a5=(e,t)=>n5(t5({ok:!1,error:t,code:e,daemonV:3}));function o5(e){let t=DW(e.sessionId);if(!t.ok)return a5(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return a5(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Iv.join(`, `)}): it predates the lane toggles — update it`);let n=Uv(e.lane);return n===null?a5(`BAD_REQUEST`,`subscribe needs a lane, one of ${Iv.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function s5(e,t,n){return!e||typeof e!=`object`||typeof e.v!=`number`?a5(`BAD_REQUEST`,`malformed request`):e.v===3?e.kind===`subscribe`?o5(e):typeof e.kind!=`string`||!Object.hasOwn(r5,e.kind)?a5(`BAD_REQUEST`,`unknown kind`):n5(await c5(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:e5})}async function c5(e,t,n){if(e.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:e5};if(e.kind===`pane-session`){let{socket:t,pane:n}=e;return t5(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:k8.newestWhere(({hints:{tmux:e}})=>e!=null&&e.socket===t&&e.pane===n)})}if(e.kind===`stats`)return t5({ok:!0,stats:o8.snapshot({gitCache:m8.getStats(),usageCache:h8.getStats(),sources:V8(),runs:T8.stats(),transcriptReads:za(),renderCache:N8.stats,effectCache:S8.getStats(),menuIdle:C8.getStats(),sessionState:{sessions:y8.size(),observers:y8.observers(),revision:y8.latestRevision()},frameFeeds:k8.getStats(),tmuxStatus:O8.stats(),watchersActive:d8.size(),nextRestartReason:q8().describeNextRestart(),handlerProbes:s8.list(),clients:c8.list(uk(new Date)),bundle:l8,daemon:q8().serving(),doctorStores:s0(u8)})});if(e.kind===`render`){let r=new Date,i=uk(r),a=performance.now(),o=Math.round(a-n),s=[],c=++o8.requestsTotal,l=C5(e),u=(e,t)=>c8.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Xa(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:CM(e.hookData),frame:t},i,c);l.ok&&(u(l.req,`drawing`),k8.note(l.req.sessionId,l.req,c));let d=l.ok?await N5(l.req,c,i,(e=>{let t=t8(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?e5:()=>ts(y8,l.req.sessionId,n)}),e=>(u(l.req,`failed`),{outcome:{kind:`threw`,error:e},resp:i5(e),delivered:e5})):w5(l.problems);d.outcome.kind!==`ok`&&o8.requestsErrored++,n8(s,{timedOut:t()?`Y`:`N`,queued:`${o}ms`});let{level:f,line:p}=a8(`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=m5(e,i);n8(i,{timedOut:t()?`Y`:`N`});let{level:o,line:s}=a8(`click`,i,a,Math.round(performance.now()-r));return M(o,s),t5(_5(a))}if(e.kind===`debug`){if(!t3(e.what))return t5({ok:!1,error:`unknown debug 'what': ${String(e.what)} (have: ${e3.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let t=N8.latestView(),n=t===null?null:{store:t.store,registry:t.registry,config:t.state.config,compiled:t.state.compiled,lastRenderBySegment:e.what===`segments`?p5(t.lastRenderCellsBySegment,t.state.config.globals.colorCompatibility??yy(`colorCompatibility`)):f5};return t5({ok:!0,debug:U4(e.what,n)})}throw Error(`no reply for request ${T(e)}`)}function l5(e,t){let{tokens:n}=ce({args:e.slice(1),options:{config:{type:`string`}},strict:!1,tokens:!0,allowPositionals:!0}),r=(n??[]).filter(e=>e.kind===`option`&&e.name===`config`).at(-1),i=(n??[]).flatMap(e=>{switch(e.kind){case`option`:return e.name===`config`?e===r&&e.value===void 0?[{arg:e.rawName,why:`no-value`}]:[]:[{arg:e.rawName,why:`unknown`}];case`positional`:return[{arg:e.value,why:`positional`}];case`option-terminator`:return[]}});return{configFile:eV(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}const u5={sessionState:y8,dlog:M,applyUpdate:()=>I8.act(),doctor:_0(e=>{let t=[e.projectDir,e.cwd,e.configFile??void 0];N8.reload(...t);let n=N8.getOrCreate(...t);return{layers:n.configLayers,error:n.lastError,warning:n.lastWarning,unused:n.state.unused,config:n.state.config}}),doctorStores:u8,probes:s8,clients:c8,bundle:l8,serving:()=>q8().serving(),claudeInput:x2(),history:b8,navigation:x8,configFor:e=>N8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.config,reloadConfig:e=>N8.reload(e.projectDir,e.cwd,e.configFile??void 0),sourcesFor:e=>N8.getOrCreate(e.projectDir,e.cwd,e.configFile??void 0).state.sources,links:w8,runs:T8,lanes:{of:S5,clicked:I5},views:{follow:(e,t)=>N8.follow(e,t.projectDir,t.cwd,t.configFile??void 0)}};u5.reloadConfig;const d5={endcaps:yy(`endcaps`),colorCompatibility:yy(`colorCompatibility`),wrap:yy(`autoWrap`),padding:yy(`padding`),width:1/0},f5=new Map;function p5(e,t){let n=new Map;for(let[r,i]of e)n.set(r,mb(i,{...d5,colorCompatibility:t}));return n}function m5(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 g5(n,r,{via:`link`,handler:Zt(e.clientVersion)},t)}catch(e){return e instanceof q?{kind:`bad-request`,problems:[e.message]}:{kind:`threw`,error:e}}}const h5={link:`verb`,"tmux-status":`linkVerb`};function g5(e,t,n,r){if(e===`tmux-status-click`)return n8(r,{verb:e}),v5(t,r);let i=P4.get(e);if(!i)return{kind:`bad-request`,problems:[`unknown click verb: ${e}`]};n8(r,{[h5[n.via]]:e});let a=A4(e,t);return a===null?n8(r,{sid:`-`}):a.ok&&(n8(r,{sid:a.id}),C8.clicked(a.id,uk(new Date))),i(t,{...u5,arrival:n}),{kind:`ok`}}function _5(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 i5(e.error)}}function v5(e,n){let r=e=>({kind:`bad-request`,problems:[e]}),i=O8.linkAt(e);if(i.kind===`refused`)return r(i.reason);if(n8(n,{link:i.url}),i.url.startsWith(`cc-candybar://`)){let e=jb(()=>Bo(i.url));return e.verb===`tmux-status-click`?r(`a status-line link names another status-line click`):g5(e.verb,e.value,{via:`tmux-status`},n)}return w2({bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[i.url],category:`click.open`},`opening ${i.url}`,M),{kind:`ok`}}function y5(e,t){let n=new Date,r=uk(n),i=[];try{try{var a=ja();let n=a.u(D5(e,r,i));if(n===null)return null;let{drawn:o,motion:s,evaluated:c,lanes:l}=k5(n,{by:`feed`,fps:t}),u=M8.linkFor(e,j5(o)),d=A5(o,u);return{at:r,resp:{ok:!0,output:d},statusline:{ok:!0,output:R5(e,o,u,d,Y6(l,k8.following(e)))},moves:s===`moves`,evaluated:c,failure:null}}catch(e){a.e=e}finally{a.d()}}catch(e){let{level:t,line:a}=a8(`render`,i,{kind:`threw`,error:e},Date.now()-n.getTime()),o=i5(e);return{at:r,resp:o,statusline:o,moves:!1,evaluated:0,failure:{level:t,line:`frame ${a}`}}}}function b5(e,t){return XH(t.config,t=>y8.get(e,t),e=>t.authoredRoots.has(e))}function x5(e){try{var t=ja();let n=t.u(N8.holdView(e));return n===null?null:qH(n.view.source.effective())}catch(e){t.e=e}finally{t.d()}}function S5(e,t){try{var n=ja();return qH(b5(t,n.u(N8.hold(e.projectDir,e.cwd,e.configFile??void 0)).state))}catch(e){n.e=e}finally{n.d()}}function C5(e){let{report:t}=z4(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=DW(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=e8(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)o8.firstSightOfUnknownHookField(e)&&M(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let a=Vt(e),{configFile:o,refusedArgs:s}=l5(e.args,e.cwd);return{ok:!0,req:{...e,deadline:i,sessionId:r.id,hints:a,rateLimits:SM(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,configFile:o??a.configEnv??null},refusedArgs:s}}}const w5=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:e5});function T5(e,t,n){n8(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=Ht(e,r),a=Ut(i);return n8(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 E5(e,t,n){let r=e.sessionId,i=T5(e,t,n),a=z2(e.requested,y8,r);return O5(N8.holdSession(a.projectDir,a.cwd,a.configFile??void 0,e),e,i,t,n)}function D5(e,t,n){let r=N8.holdView(e);if(r===null){let t=N8.openFailure(e);if(t!==null)throw t.error;return null}let i=r.view.facts(),a;try{a=T5(i,t,n)}catch(e){throw r[Symbol.dispose](),e}return O5(r,i,a,t,n)}function O5(e,t,n,r,i){try{let{entry:a,state:o,view:s}=e,{sessionId:c,hints:l}=t,u=s.source.effective();return{req:t,at:r,facts:i,sessionId:c,entry:a,state:o,view:s,hintsError:n,payloadInputs:{hookData:t.hookData,deps:{...p8,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 k5(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=qH(u);n8(i,{lanes:Iv.filter(e=>d[e]).join(`,`)||`-`});let{hints:f}=c.facts(),p=Yq(f),m=hb(f.termRows);n8(i,{width:String(p)});let h=c.source.payload(),g={drawing:t,feeds:k8.feedsOf(a,r),today:dJ(p8,c.lanes().today,c.facts().hookData,r)},_=Aa(h.metrics)?void 0:h.metrics;n8(i,oJ(c.lanes().sources)),n8(i,{prompts:String(_?.messageCount??`-`),nonPrompts:String(_?.nonPrompts??`-`),pr:Nq(h.git,Gq(e.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:a3(g.feeds)});let v=[],y=Aq(u,p),b=S8.of(a),ee=C8.since(a,r),x=PZ(s.config,s.compiled,c.store,c.registry,g,r,y,{perSegmentSink:c.lastRenderCellsBySegment,onRenderWarning:e=>v.push(e)},{...u,effects:b,idleSince:ee});C8.observe(a,r,x.menuRows>0,u.menuTimeout);let S=C8.since(a,r);n8(i,{menuIdle:S===void 0?`-`:`${(r-S).toFixed(1)}s/${u.menuTimeout}s`});let te=rs(y8,a,r,t.by),ne=te.kind===`held`||te.kind===`owed`?te.error:null,re=ne?.text??null,ie=[Gt(n.refusedArgs),l,o.lastError,re].filter(Boolean).join(`
|
|
497
|
+
`),ae=I8.notice({sessionId:a,dismissed:y8.get(a,RU),enabled:u.updateNotice}),C=o.lastError===null?null:o.failedFile,w=[...o.lastWarning===null?[]:[{kind:`load`,message:o.lastWarning}],...v],oe=Dq(o.repos,a,w8),se=Sb(ie,[...ae,...oe],w.map(e=>e.message).join(`
|
|
498
|
+
`)),T=m8.getStats(),ce=h8.getStats(),le=b.lastFrame(),ue=le.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,de=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,fe=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 n8(i,{git:`${T.size}/${T.hits}h/${T.misses}m`,usage:`${ce.size}/${ce.hits}h/${ce.misses}m`,effect:le.effect,effectT:le.t.toFixed(3),speed:`${le.speed}x`,effectRows:`${le.made}made/${le.reused}reused`,effectOwn:ue,fadeBasis:le.basis,stateRev:String(le.revision),fades:de(le.fades),leaves:de(le.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(oe.length),warn:fe}),{drawn:{body:x.text,diagnostics:se,failedConfigFile:C,geometry:{width:p,rowCap:m,colorCompatibility:u.colorCompatibility}},motion:x.motion,evaluated:x.evaluated,clickShown:ne,lanes:d}}function A5(e,t){return Tb(e.body,e.diagnostics,{fullText:t,failedConfigFile:e.failedConfigFile},e.geometry)+`
|
|
499
|
+
`}function j5(e){return e.diagnostics===null?null:wb(e.diagnostics)}function M5(e){let t=e.sessionId,{client:n,...r}=e.hints,i=JSON.stringify(r);y8.get(t,`client-hints`)!==i&&y8.set(t,m4,i);let a=B2(e.requested);y8.get(t,`render-origin`)!==a&&y8.set(t,R2,a)}async function N5(e,t,n,r,i){return M5(e),L5(e,t,n,r,i)}function P5(e,t){D8.noted(F5(e),t),O8.observe(e.hookData.session_id,e.hints.tmux,t.tmuxStatus)}function F5(e){let t=e.hookData.session_id;return{sessionId:t,hints:e.hints,origin:z2(e.requested,y8,t),transcript:e.hookData.transcript_path,answered:bM(e.hookData)}}function I5(e,t,n){let r=k8.latest(e);D8.clicked(e,r===null?null:F5(r),t,n),r!==null&&t.tmuxStatus!==n.tmuxStatus&&O8.observe(e,r.hints.tmux,n.tmuxStatus)}async function L5(e,t,n,r,i){try{var a=ja();let o=a.u(E5(e,n,i));P5(e,qH(o.view.source.effective())),n8(i,{deadline:`${r.stated}:${r.ms}ms`});let s=performance.now(),c=new Map,l=await CG(e=>Promise.all([fJ(o.payloadInputs,n,c),o.view.registry.inFlight(e)]),r.endsAt-s,e=>M(`error`,`render wait failed after its deadline sid=${JSON.stringify(o.sessionId)}: ${T(e)}`)),u=performance.now();n8(i,{waited:`${Math.round(u-s)}ms`,ended:l,refreshed:Zq(c)});let{drawn:d,motion:f,clickShown:p,lanes:m}=k5(o,Lv),{link:h,failure:g}=M8.sync(e.sessionId,t,j5(d));n8(i,{dumpFailed:g===null?`-`:JSON.stringify(g)});let _=A5(d,h),v=e.sessionId,y=Y6(m,k8.following(v)),b=R5(v,d,h,_,y),ee=EM(e.hints.client??null)===`statusline`;return n8(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 R5(e,t,n,r,i){let[a,...o]=i;return a===void 0?r:A5({...t,body:Eb(X6(e,[a,...o]),t.geometry)},n)}const z5={connectMs:200,budgetMs:500};async function B5(e,n){let r=n.includes(`--json`),i=await V5(e);if(i.kind!==`ok`&&(t.stderr.write(`${e}: ${un(i)}\n`),t.exit(1)),r){t.stdout.write(JSON.stringify(i.value,null,2)+`
|
|
500
|
+
`);return}t.stdout.write(H5(i.value))}function V5(e){return rn(()=>({kind:`debug`,what:e}),z5,e=>`debug`in e?e.debug:void 0)}function H5(e){switch(e.what){case`vars`:return U5(e.vars);case`segments`:return W5(e.segments);case`config`:return G5(e.config);default:return e}}function U5(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?``:` ${q5(a.ageMs)}`,o=a.lastError?` ✗ ${a.lastError.message}`:``;t.push(` ${a.name.padEnd(n)} ${(a.source??`—`).padEnd(r)} ${a.type.padEnd(i)} ${K5(a.value)}${e}${o}`)}return t.join(`
|
|
502
502
|
`)+`
|
|
503
|
-
`}function
|
|
503
|
+
`}function W5(e){if(e.length===0)return`no segments (DSL not active)
|
|
504
504
|
`;let t=[`segments (${e.length})`,``];for(let n of e){t.push(` ${n.name}`),n.description!==null&&t.push(` shows ${n.description}`),t.push(` template ${n.template}`),n.referencedVars.length>0&&t.push(` vars ${n.referencedVars.join(`, `)}`);for(let{id:e,lastRender:r}of n.placements)r!==null&&t.push(` last ${e}: ${r}`)}return t.join(`
|
|
505
505
|
`)+`
|
|
506
|
-
`}function
|
|
506
|
+
`}function G5(e){return e===null?`config: DSL not active
|
|
507
507
|
`:JSON.stringify(e,null,2)+`
|
|
508
|
-
`}function
|
|
508
|
+
`}function K5(e){let t=typeof e==`string`?e:JSON.stringify(e);return t.length>60?t.slice(0,57)+`…`:t}function q5(e){return e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m`}function J5(){let e=X5();return e===null?null:p.readFileSync(e,`utf-8`)}function Y5(){let e;try{e=J5()}catch(e){t.stderr.write(`schema: cannot read bundled schema: ${e instanceof Error?e.message:String(e)}\n`),t.exit(2)}e===null&&(t.stderr.write("schema: bundled schema not found (expected schema/cc-candybar.schema.json). Run `pnpm gen:schema` from a source checkout.\n"),t.exit(2)),t.stdout.write(e),t.exit(0)}function X5(){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 Z5=5e3;function Q5(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:SP(4e5,1e6),...jq(t),history:{undo:1,redo:1,sinceEdit:1},navigation:{back:1},unsaved:1,resettable:Ay(()=>!0),themeDefault:t.theme.kind===`decided`?{differs:!0,theme:t.theme.name}:{differs:!1},resumeCommand:kq(s,o,void 0),configPath:n??`${i}/.config/cc-candybar/config.json5`,plugins:sJ(Object.entries(e.variables).flatMap(([e,t])=>t.kind===`source`?[e]:[]),()=>F)}}const $5={cost:12.5,tokens:34e5};function e7(e,t){let n=cH(e);return n!==null&&t.push(n),e.kind===`chain`?e.layers:[]}async function t7(e,n=t.cwd(),r=Z5){let i=[],a=eV(n,e)??null,o=rH(Tq().read(),n,n,a??void 0);i.push(...$V(o.repos));let s=a===null?e7(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=uH(n,n);c!==null&&i.push(c);try{return{kind:`clean`,layers:s,warnings:i,rendered:await i7(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 Q_&&i.push(...e.warnings),{kind:`fatal`,layers:s,message:e instanceof Q_||e instanceof Error?e.message:String(e),warnings:i})}}async function n7(e,t,n,r,i,a=Z5){let o=vH(e,VH,{entered:()=>{},warned:e=>r.push(...e)},{repo:t,cwd:n}),{config:s}=o,c=new yS,l=new aA(c,s.globals.default_empty_value??``,new oQ);try{let t=gZ(s,l,{cwd:n,signer:Xo()});r.push(...t.loadWarnings);let u=XH(s,()=>null,()=>!1);GX(t,c,l,dZ({...Q5(s,u,e.at(-1)??null,i),today:$5},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 r7({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:NZ(t,n,r,i,{...Q5(t,a,e.at(-1)??null,s),today:$5},s,Aq(a,o),{onSegmentError:(e,t)=>c.set(`segment "${e}"`,t),onRenderWarning:u},a),failures:c,advisories:l}}async function i7(e,t,n,r,i){let a=uk(new Date),o=await n7(e,t,n,r,a,i),{config:s}=o;try{let e=$U();try{MU(s),eL(s)}finally{e()}let t=nx(null,s.globals.preset,s.presets),n=(e,t)=>{let n=XH(s,t=>t===`preset`?e:null,()=>t),r;try{r=r7(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),...tx(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
|
|
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`,`/${RV}/`)}function
|
|
512
|
-
`));let c=a.map(e=>{let n=s.basename(e),r=s.join(t,n);return{folder:e,name:n,target:r,placed:
|
|
513
|
-
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:
|
|
510
|
+
`));return d}finally{o.registry.dispose()}}function a7(e){return e.map(e=>`warning: ${e}\n`).join(``)}function o7(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:a7(e.warnings),code:0};case`fatal`:return{stdout:``,stderr:a7(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 s7=`--render`,c7=`Usage: cc-candybar check [${s7}] [config-file]\n`;function l7(e){let t=e.filter(e=>e.startsWith(`--`)),n=e.filter(e=>!e.startsWith(`--`)),r=t.filter(e=>e!==s7);return r.length>0?{kind:`usage`,message:`check: unknown option ${r.join(` `)}\n${c7}`}:n.length>1||n[0]===``?{kind:`usage`,message:`check: expected at most one non-empty path\n${c7}`}:{kind:`run`,target:n[0],render:t.includes(s7)}}async function u7(e){let n=l7(e),r=n.kind===`usage`?{stdout:``,stderr:n.message,code:2}:o7(await t7(n.target??r6(t.env,t.cwd())),n.render);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}const d7=/^[a-z][a-z0-9+.-]*:\/\//i,f7=/^[^@\s/]+@[^:\s/]+:/,p7=/^([A-Za-z0-9-]+\/[A-Za-z0-9._-]+?)(?:\.git)?$/;function m7(e){if(!URL.canParse(e))return e;let t=new URL(e);return t.password===``?e:(t.password=`***`,t.href)}function h7(e,t,n){let r=$B(t,e);if(n(r))return{kind:`path`,dir:r};if(d7.test(e)||f7.test(e))return{kind:`git`,url:e,shown:m7(e)};let i=p7.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 g7(e,t){let n=s.join(e,RV),r=VV(n);if(`error`in r)throw Error(`${t}: could not list ${RV}: ${r.error}`);if(r.folders.length===0)throw Error(`${t} has no plugins: none at ${RV}/<name>/${rV}`);return r.folders.map(e=>s.join(n,e,rV))}function _7(e,t,n){let r=(n,...r)=>{let i=D({bin:`git`,args:r,env:n,category:`plugin.git`});if(!i.ok)throw Error(`git ${r.map(n=>n===e?t:n).join(` `)} failed (${i.reason}): ${i.stderr.trim()||i.error||``}`);return i.stdout},i={...process.env,GIT_TERMINAL_PROMPT:`0`};for(let e of r(i,`rev-parse`,`--local-env-vars`).split(`
|
|
511
|
+
`))delete i[e];r(i,`clone`,`--quiet`,`--depth`,`1`,`--filter=blob:none`,`--sparse`,`--`,e,n),r(i,`-C`,n,`sparse-checkout`,`set`,`--no-cone`,`/${RV}/`)}function v7(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 _7(e.url,e.shown,s.join(n,`repo`)),t(s.join(n,`repo`))}finally{p.rmSync(n,{recursive:!0,force:!0})}}}}function y7(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 b7(e,t,n,r){switch(r){case`updated`:p.renameSync(s.join(e,rV),s.join(t,rV));return;case`replaced`:p.renameSync(t,n),p.renameSync(e,t);return;case`installed`:p.renameSync(e,t);return}}function x7(e,t,n){let r=g7(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,rV))}catch(e){if(e.code!==`ENOENT`)throw e}return t}),o=gH(a.map(e=>s.join(e,rV)),VH,{root:e,git:!1});if(o.length>0)throw Error(o.map(e=>`${n}: ${s.join(RV,s.relative(i,e.path))} would not load: ${e.reason.split(i).join(s.join(n,RV))}`).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:y7(r)}}),l=[];try{for(let{folder:e,name:t,target:n,placed:r}of c)b7(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,rV),placed:t}))}finally{p.rmSync(i,{recursive:!0,force:!0})}}function S7(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=h7(n,process.cwd(),Yk);if(`error`in i)return console.error(`plugin install: ${i.error}`),2;try{let e=i.kind===`path`?i.dir:i.shown,t=v7(i,t=>x7(t,LV(),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 C7(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 w7=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function T7(e,t,n){return{termCols:C7(e.COLUMNS,n.columns),termRows:C7(e.LINES,n.rows),ssh:w7.some(t=>(e[t]??``)!==``),tmux:vM(e),configEnv:r6(e,t),claudeConfigDir:Ya(e,t),terminalEnv:Lt(e)}}function E7(e){return e.clients.map(e=>typeof e==`object`&&e?e:{})}function D7(e){let t=z0(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=E7(e);return n.every(e=>typeof e.ago==`number`&&typeof e.sessionId==`string`)?{kind:`ok`,value:{bundle:e.bundle,clients:n.map(e=>({client:nn(e.client)??null,sessionId:e.sessionId,ago:e.ago}))}}:{kind:`failed`,reason:`the running daemon (${e.version}) reported clients without their age or session: ${JSON.stringify(e.clients)}`}}const O7=e=>{let{identity:t,artifacts:n}=e??{};return typeof t==`string`&&typeof n==`object`&&!!n&&Object.values(n).every(e=>typeof e==`string`)},k7=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 A7(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 j7(e){let t=z0(e,[`daemon`]);if(t!==null)return{kind:`failed`,reason:t};let n=e.daemon,r=A7(n?.postMortems,e=>Array.isArray(e)&&e.every(O7)?{kind:`ok`,value:e}:{kind:`failed`,reason:`is not a list of post-mortems`});return typeof n?.pid==`number`&&k7(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 M7(e,t,n){let r=z0(e,[`clients`]);if(r!==null)return{kind:`failed`,reason:r};let i=E7(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 N7=e=>TM.includes(e.role),P7=e=>M7(e,e=>typeof e.ago==`number`&&typeof e.sessionId==`string`&&typeof e.claudeConfigDir==`string`&&xM.includes(e.rateLimits),`the rate-limit windows they carried`),F7=e=>M7(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`),I7=e=>M7(e,e=>typeof e.ago==`number`&&typeof e.claudeConfigDir==`string`&&typeof e.projectDir==`string`&&typeof e.sessionId==`string`&&N7(e)&&wM.includes(e.frame),`what they drew and from which project`),L7=e=>M7(e,e=>typeof e.sessionId==`string`&&typeof e.ago==`number`&&N7(e)&&(e.termCols===null||typeof e.termCols==`number`),`whose they were or the width they measured`);function R7(e,t,n){let r=e.doctorStores?.[t],i=A7(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 z7(e){let t=z0(e,[`doctorStores`]);if(t!==null){let e={kind:`failed`,reason:t};return{marks:e,clicked:e,postMortemsRead:e}}return{marks:R7(e,`marks`,X$),clicked:R7(e,`clicked`,$$),postMortemsRead:R7(e,`postMortemsRead`,t0)}}async function B7(){let e=await R0();if(e.kind!==`ok`){let t={kind:`failed`,reason:un(e).split(`
|
|
513
|
+
`).join(` — `)};return{clients:t,rateLimits:t,transcripts:t,frames:t,widths:t,serving:t,stores:{marks:t,clicked:t,postMortemsRead:t}}}return{clients:D7(e.value),rateLimits:P7(e.value),transcripts:F7(e.value),frames:I7(e.value),widths:L7(e.value),serving:j7(e.value),stores:z7(e.value)}}const V7=` (fix: click the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor, then [fix] on the bar)`,H7=`mark them ✓ shapes or ✗ boxes in the bar's doctor, and this command reads your mark: the settings menu (${bi} by default) › 🧰 tools › 🩺 doctor`;function U7({check:e,verdict:t}){return t.ok?`✓ ${e.label}${t.note===void 0?``:` — ${t.note}`}\n`:`✗ ${e.label} — ${t.reason}${t.fix===void 0?``:V7}\n`+(t.more??[]).map(e=>` ${e}\n`).join(``)+(t.sighting===void 0?``:` look: ${t.sighting.glyphs} — ${H7}\n`)}function W7(e){let t={sessionState:new oQ,storage:BZ,signer:Xo()},n=XZ(e.projectDir,e.cwd,e.configFile??void 0,t),r=n.state??ZZ(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 G7(e,t,n){return n.kind===`failed`?n:a0(e,n.value.bundle,i1(t,n.value.clients).map(({client:e})=>e))}function K7(e,t,n){return t.kind===`failed`?t:{kind:`ok`,value:i1(e,t.value).filter(e=>e.claudeConfigDir===n).map(e=>e.rateLimits)}}function q7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:i1(e,t.value).map(e=>e.transcript)}}function J7(e,t){return t.kind===`failed`?t:{kind:`ok`,value:o1(e,t.value)}}function Y7(e,t,n){return e.kind===`recent`?{kind:`ok`,value:{columns:n,of:{kind:`command`}}}:t.kind===`failed`?t:N0(e.sessionId,i1(e,t.value))}async function X7(e,t,n,r,i,a,o=void 0){let s;try{let c=await n(),l=T7(r,i,a()),u=r1(r.CLAUDE_CODE_SESSION_ID);s={...P0(e,l,{projectDir:a1(u,c.frames.kind===`ok`?c.frames.value:[],i),cwd:i,configFile:eV(i,o)??r6(r,i)??null},()=>null,c.serving,K7(u,c.rateLimits,Xa(l.claudeConfigDir)),q7(u,c.transcripts),u,J7(u,c.frames),Y7(u,c.widths,l.termCols??null),c.stores),urlHandler:await t2(t),install:G7(e.install,u,c.clients)}}catch(e){return{stdout:``,stderr:`doctor: ${e instanceof Error?e.message:String(e)}\n`,code:2}}let c=HN(s);return{stdout:c.map(U7).join(``),stderr:``,code:+!c.every(e=>e.verdict.ok)}}function Z7(){if(t.stderr.isTTY)return t.stderr;let e;try{e=v(`/dev/tty`,`r+`)}catch{return{}}let n=new xe(e),{columns:r}=n;return n.destroy(),{columns:r}}async function Q7(e){(e.length>1||e[0]===``||e[0]?.startsWith(`--`))&&(t.stderr.write(`doctor: expected at most one config file
|
|
514
514
|
Usage: cc-candybar doctor [config-file]
|
|
515
|
-
`),t.exit(2));let n=t.cwd(),r=await
|
|
516
|
-
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const
|
|
517
|
-
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?
|
|
515
|
+
`),t.exit(2));let n=t.cwd(),r=await X7(_0(W7),a2(),B7,t.env,n,Z7,e[0]);t.stdout.write(r.stdout),t.stderr.write(r.stderr),t.exit(r.code)}function $7(e){return!e.ok&&e.code!==`RENDER_FAILED`}function e9(e,t,n,r,i){let a=null,o=e=>{a===null&&(a=e,s.destroy(),i(e))},s=ue.createConnection({path:e}),c={v:3,kind:`subscribe`,sessionId:t,lane:n};return s.once(`connect`,()=>s.write(Qt(c))),s.on(`data`,en(e=>{let t=e;$7(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 t9(e,t){switch(t){case`frame-ok`:return 250;case`frame-failed`:return e;case`fault`:return Math.min(2e3,e*2)}}function n9(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 r9(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=e9(e,t,n,e=>{s=t9(s,e.ok?`frame-ok`:`frame-failed`),r.frame(e)},e=>{if(e.kind===`closed-here`||o)return;let t=n9(e);switch(t.kind){case`exit`:r.exit(t.reason);return;case`off`:r.off(t.resp),c(5e3,!1);return;case`reconnect`:{r.fault(t.reason,s),t.kick&&_r();let e=s;s=t9(s,`fault`),c(e,!0);return}}})};return l(),{close:()=>{o=!0,a!==null&&clearTimeout(a),i?.close()}}}function i9(e,t){return t.kind===`frame`||t.kind!==e.kind?!0:t.kind===`fault`&&e.kind===`fault`&&t.reason!==e.reason}async function a9(e,n){let{values:r,tokens:i}=ce({args:e.slice(3),options:{config:{type:`string`},lane:{type:`string`}},strict:!0,tokens:!0}),a=[e[1],...i.flatMap(e=>e.kind===`option`&&e.name===`config`?[e.rawName,e.value]:[])],o=t.cwd(),s=e=>{t.stderr.write(`cc-candybar frames: ${e}\n`)},c=Uv(r.lane);c===null&&(s(`--lane needs one of ${Iv.join(`, `)}`),t.exit(2)),t.stdout.on(`error`,()=>t.exit(0));let l=d3(t.stdout),u=null,d=null,f=null,p={kind:`none`},m=(e,t)=>{i9(p,e)&&t(),p=e},h=async e=>{let r=await hn(e,a,o,{...T7(t.env,o,t.stderr),client:zt(`frames`,n)});r.kind!==`ok`&&(s(un(r)),r.kind===`transient`&&_r())},g=e=>{f?.close(),f=r9(St(),e,c,{frame:e=>m({kind:`frame`},()=>l(`${JSON.stringify(e)}\n`)),off:e=>m({kind:`off`},()=>l(`${JSON.stringify(e)}\n`)),fault:(e,t)=>m({kind:`fault`,reason:e},()=>s(`${e}; reconnecting in ${t}ms`)),exit:e=>{s(e),t.exit(1)},beforeReconnect:()=>d===null?Promise.resolve():h(d)})};for await(let e of Se({input:t.stdin})){if(e.trim()===``)continue;let t;try{t=JSON.parse(e)}catch(e){s(`stdin line is not JSON: ${e.message}`);continue}if(typeof t.session_id!=`string`||t.session_id===``){s(`stdin line carries no session_id`);continue}d=t,await h(t),t.session_id!==u&&(u=t.session_id,g(u))}t.exit(0)}function o9(e){let t=e.replace(/\n+$/,``).split(`
|
|
516
|
+
`);return{bytes:t.map((e,t)=>`\x1b[${t+1}H[2K${e}`).join(``)+`\x1B[J`,rows:t.length}}const s9=5e3,c9=`usage: cc-candybar bar-pane <claude-code-pane-id, e.g. %3>`;function l9(e,t,n,r){let i=e.split(`
|
|
517
|
+
`).map(e=>e.trim().split(` `));return i.some(([e])=>e===n)?h3(e,m3(t)).has(r)?{kind:`shown`,zoomed:i.some(([e,,,,t])=>e===r&&t===`1`)}:{kind:`hidden`}:{kind:`gone`}}async function u9(e,t){let[n,r]=await Promise.all([YK(e,`bar-pane.tmux`,[`list-panes`,`-a`,`-f`,`#{||:#{==:#{pane_id},${t}},#{==:#{pane_id},${e.pane}}}`,`-F`,f3]),YK(e,`bar-pane.tmux`,[`list-clients`,`-F`,p3])]);return n.kind===`ok`?r.kind===`ok`?{kind:`ok`,placement:l9(n.stdout,r.stdout,t,e.pane)}:r:n}function d9(){let e=Date.now();return t=>{if(t.kind===`ok`)e=Date.now();else if(Date.now()-e>s9)throw Error(`tmux has not answered for ${s9/1e3} s: ${t.reason}`)}}function f9(e){let{positionals:t}=(()=>{try{return ce({args:[...e],allowPositionals:!0})}catch(e){throw Error(`${e.message}\n${c9}`)}})(),[n,...r]=t;if(n===void 0||r.length>0||!/^%\d+$/.test(n))throw Error(c9);return{pane:n}}async function p9(e){try{return await m9(e),0}catch(e){return t.stderr.write(`cc-candybar bar-pane: ${e.message}\n`),1}}async function m9(e){let{pane:n}=f9(e),r=vM(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 u9(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=d9(),f=async()=>{if(a.kind!==`shown`)return;let e=o9(l());e.rows!==t.stdout.rows&&!a.zoomed&&d(await YK(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:r9(St(),e,`pane`,{frame:e=>n(sW(mn(e)).output),off:e=>n(e.error),fault:n,exit:e=>o(Error(e))})}},_=d9();for(;a.kind!==`gone`;){if(a.kind===`hidden`)g(null);else{let e=await gn(r.socket,n);e.kind===`ok`?(g(e.value),c=e.value===null?`waiting for pane ${n}'s statusline to render on ${St()}`:`waiting for pane ${n}'s bar`):(e.kind===`transient`&&(_r(),u=``),c=un(e))}h(),await be(500);let e=await u9(r,n);_(e),e.kind===`ok`&&(a=e.placement)}g(null),t.stderr.write(`cc-candybar bar-pane: pane ${n} closed\n`)}const h9=i(import.meta.url),g9=e=>e.some(e=>t.argv.includes(e));function _9(){console.log(hM);let e=Oo(h9),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 ${Fv.statusline.label} yourself (a Bun-compiled Claude Code):\n ${He(e,{dir:void 0,env:[],program:`claude`,args:[]})}\n${t}`)}const v9={install:async e=>{await Wo(e,h9),t.exit(0)},"install-url-handler":async()=>{zo(h9),t.exit(0)},"url-handle":async e=>{await Vo(e[0])},daemon:async()=>{B8()},"daemon-stats":async e=>{await L0(e),t.exit(0)},frames:async()=>{await a9(t.argv,h9)},check:async e=>{await u7(e)},lint:async e=>{await u7(e)},plugin:async e=>{t.exit(S7(e))},schema:async()=>{Y5()},doctor:async e=>{await Q7(e)},"bar-pane":async e=>{t.exit(await p9(e))},...Object.fromEntries(e3.map(e=>[e,async n=>{await B5(e,n),t.exit(0)}]))};async function y9(){try{let e=t.argv[2],n=e!==void 0&&!e.startsWith(`-`)?e:null;if(n!==null&&!Object.hasOwn(v9,n)&&(console.error(`cc-candybar: unknown subcommand ${JSON.stringify(n)} — see --help`),t.exit(2)),g9($j.help)&&(_9(),t.exit(0)),g9($j.version)&&(console.log(`cc-candybar ${Ze}`),t.exit(0)),n!==null){await v9[n](t.argv.slice(3));return}t.stdin.isTTY===!0&&(console.error(`Error: This tool requires input from Claude Code
|
|
518
518
|
|
|
519
519
|
cc-candybar is designed to be used as a Claude Code statusLine command.
|
|
520
520
|
It reads hook data from stdin and outputs formatted statusline.
|
|
@@ -530,4 +530,4 @@ Add to ~/.claude/settings.json:
|
|
|
530
530
|
Run with --help for more options.
|
|
531
531
|
|
|
532
532
|
To test output manually:
|
|
533
|
-
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),
|
|
533
|
+
echo '{"session_id":"test-session","workspace":{"project_dir":"/path/to/project"},"model":{"id":"claude-sonnet-4-5","display_name":"Claude"}}' | cc-candybar`),t.exit(1)),E(`Working directory: ${t.cwd()}`),E(`Process args:`,t.argv);let r=await o(t.stdin);E(`Received hook data:`,JSON.stringify(r,null,2)),r||(console.error(`Error: No input data received from stdin`),_9(),t.exit(1));let i=sW(await hn(r,t.argv.slice(1),t.cwd(),{...T7(t.env,t.cwd(),t.stderr),client:zt(`node`,h9)}));i.debug!==null&&E(i.debug),i.kick&&_r(),t.stdout.write(i.output),t.exit(0)}catch(e){let n=e instanceof Error?e.message:String(e);console.error(`Error generating statusline:`,n),t.exit(1)}}y9();export{};
|