@promptctl/cc-candybar 1.178.1 → 1.179.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -154,7 +154,7 @@ Run the install once to stage the runtime, then point `~/.claude/settings.json`
154
154
 
155
155
  `just deploy` builds `dist/index.mjs` and stages the native binary at `bin/cc-candybar-native` — point your statusline command at that path. On a machine without cargo, `pnpm install && pnpm build` builds only the bundle — point your statusline at the committed `bin/cc-candybar` node entry instead. Either way the bar renders HEAD; the daemon watches the built bundle and respawns itself on rebuild.
156
156
 
157
- `pnpm bar:web` serves the bar at http://127.0.0.1:7317/ in a browser terminal you can click: an isolated daemon (`--config my.json5` starts it from a copy of your config, `--ssh` shows the host segment). `pnpm site:build` builds the GitHub Pages version into `site/dist`, the same page with the daemon running inside it against a simulated machine (`site/`).
157
+ `pnpm bar:web` serves the bar at http://127.0.0.1:7317/ in a browser terminal you can click: an isolated daemon (`--config my.json5` starts it from a copy of your config, `--ssh` shows the host segment). `pnpm site:build` builds the GitHub Pages version into `site/dist`, the same page with the daemon running inside it against a simulated machine (`site/`). `pnpm site:dev` serves that page at http://127.0.0.1:8931/ (`--port` picks another) and reloads it whenever the sources or the page change.
158
158
 
159
159
  ### Config file
160
160
 
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}from"node:url";import{json as a}from"node:stream/consumers";import o,{basename as s,dirname as c,isAbsolute as l,join as u,sep as d}from"node:path";import f,{closeSync as p,constants as m,existsSync as h,fstatSync as g,linkSync as _,openSync as v,readFileSync as y,readSync as b,rmSync as x,statSync as S,writeFileSync as C}from"node:fs";import ee,{createHash as w,createHmac as te,randomBytes as ne,randomUUID as T,timingSafeEqual as re}from"node:crypto";import E,{homedir as D}from"node:os";import ie from"node:net";import{spawn as O,spawnSync as ae}from"node:child_process";import{StringDecoder as oe}from"node:string_decoder";import{inspect as se,parseArgs as ce,types as le}from"node:util";import{clearInterval as ue,setImmediate as de,setInterval as fe}from"node:timers";import pe from"node:v8";import{open as me,readFile as he,readdir as ge,stat as _e}from"node:fs/promises";import{get as ve}from"node:https";import{setTimeout as ye}from"node:timers/promises";import{WriteStream as be}from"node:tty";import{createInterface as xe}from"node:readline";var Se=Object.create,Ce=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyNames,Ee=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Oe=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Te(t),a=0,o=i.length,s;a<o;a++)s=i[a],!De.call(e,s)&&s!==n&&Ce(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=we(t,s))||r.enumerable});return e},Ae=(e,t,n)=>(n=e==null?{}:Se(Ee(e)),ke(t||!e||!e.__esModule?Ce(n,`default`,{value:e,enumerable:!0}):n,e));const je=()=>!!process.env.CC_CANDYBAR_DEBUG;function Me(e){return je()?`[DEBUG] ${e()}\n`:``}function k(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}function Ne(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Pe=(e,t)=>k(t),Fe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ie(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Le(e){return Fe.test(e)?e:Ie(e)}function Re(e){return`${e.dir===void 0?``:`cd ${Le(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Le(t)} `).join(``)}${[e.program,...e.args].map(Le).join(` `)}`}const ze=`cc-extra`;function Be(e){return o.join(o.dirname(e),ze,`src`,`bun-attach.js`)}function Ve(e){return o.join(o.dirname(e),`bun-graph.js`)}const He=`attach-preload.cjs`;function Ue(e){return o.join(o.dirname(e),He)}function We(e,t){return Re({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ge=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ke(e,t){return t.isSymbolicLink()?Buffer.from(f.readlinkSync(e)):f.readFileSync(e)}function qe(e,t,n=Ge){return f.readdirSync(t).filter(n).sort().flatMap(n=>{let r=o.join(t,n),i=f.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?qe(e,r):[[o.relative(e,r).split(o.sep).join(`/`),Ke(r,i)]]})}function Je(e){let t=ee.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ye(e){return Je(qe(e,e))}const Xe=[`Cargo.toml`,`Cargo.lock`,`src`];function Ze(e){return Je(qe(e,e,e=>Xe.includes(e)))}const Qe=e=>e.slice(0,7),$e=`1.178.1`;function et(e){let t=o.dirname(o.dirname(e));return f.existsSync(o.join(t,`src`))?t:null}function tt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:$e,digest:e}}function nt(){return`eed316cdc1cceb874bc501a5e070f6108bf9d88226467632e1b357536cf6035a`}function rt(e){let t=JSON.parse(f.readFileSync(o.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${o.join(e,`package.json`)} has no version string`);return n}function it(e,t){try{let n=et(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ye(o.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:rt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function at(e,t,n){let r=ot(e);f.mkdirSync(o.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??f.statSync(r,{throwIfNoEntry:!1})?.mode;try{f.writeFileSync(i,t,a===void 0?{}:{mode:a}),f.renameSync(i,r)}catch(e){throw f.rmSync(i,{force:!0}),e}}function ot(e){return st(e).at(-1)}function st(e){let{hops:t,stopped:n}=ct(e);if(n!==null)throw n;return t}function ct(e){let t=[e];try{for(let e=0;e<ut;e++){let e=lt(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${ut} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function lt(e){try{return f.lstatSync(e).isSymbolicLink()?o.resolve(f.realpathSync(o.dirname(e)),f.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const ut=40;function dt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function ft(e=process.env){let t=dt(e,`XDG_STATE_HOME`)??o.join(E.homedir(),`.local`,`state`);return o.join(t,`cc-candybar`)}function pt(){let e=dt(process.env,`XDG_CACHE_HOME`)??o.join(E.homedir(),`.cache`);return o.join(e,`cc-candybar`)}function mt(){return ft()}function ht(){return process.env.CC_CANDYBAR_SOCKET||gt()}function gt(){let e=E.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function _t(e){f.mkdirSync(e,{recursive:!0,mode:448});let t=f.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=E.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 vt(e){_t(o.dirname(e));for(let t of[e,yt(e)])try{if(f.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function yt(e){return`${e}.lease`}function bt(){return yt(ht())}function xt(e=process.env){return o.join(ft(e),`session-state.json`)}function St(){return o.join(ft(),`settings-history.json`)}function Ct(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=E.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function wt(){return o.join(ft(),`spawn.lock`)}function Tt(){return o.join(ft(),`spawn.cooldown`)}function Et(){return o.join(ft(),`spawn.backoff`)}function Dt(){return o.join(ft(),`watch-probe`)}function Ot(e=process.env){return o.join(ft(e),`daemon.log`)}const kt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function At(e){return Object.fromEntries(kt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const jt=[`native`,`node`,`frames`];function Mt(e,t){return{kind:e,bundle:t,source:null}}const Nt=[`ansi`,`frame`],Pt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Ft(e){let t=Wt(e.termCols),n=Wt(e.termRows),r=A(e.ssh),i=Ht(e.tmux),a=Vt(e.configEnv),o=Vt(e.claudeConfigDir),s=Bt(e.terminalEnv),c=j(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 It(e,t){return Pt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Lt(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 Rt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function zt(e){let t=Object.keys(Rt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Rt[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}from"node:url";import{json as a}from"node:stream/consumers";import o,{basename as s,dirname as c,isAbsolute as l,join as u,sep as d}from"node:path";import f,{closeSync as p,constants as m,existsSync as h,fstatSync as g,linkSync as _,openSync as v,readFileSync as y,readSync as b,rmSync as x,statSync as S,writeFileSync as C}from"node:fs";import ee,{createHash as w,createHmac as te,randomBytes as ne,randomUUID as T,timingSafeEqual as re}from"node:crypto";import E,{homedir as D}from"node:os";import ie from"node:net";import{spawn as O,spawnSync as ae}from"node:child_process";import{StringDecoder as oe}from"node:string_decoder";import{inspect as se,parseArgs as ce,types as le}from"node:util";import{clearInterval as ue,setImmediate as de,setInterval as fe}from"node:timers";import pe from"node:v8";import{open as me,readFile as he,readdir as ge,stat as _e}from"node:fs/promises";import{get as ve}from"node:https";import{setTimeout as ye}from"node:timers/promises";import{WriteStream as be}from"node:tty";import{createInterface as xe}from"node:readline";var Se=Object.create,Ce=Object.defineProperty,we=Object.getOwnPropertyDescriptor,Te=Object.getOwnPropertyNames,Ee=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Oe=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),ke=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Te(t),a=0,o=i.length,s;a<o;a++)s=i[a],!De.call(e,s)&&s!==n&&Ce(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=we(t,s))||r.enumerable});return e},Ae=(e,t,n)=>(n=e==null?{}:Se(Ee(e)),ke(t||!e||!e.__esModule?Ce(n,`default`,{value:e,enumerable:!0}):n,e));const je=()=>!!process.env.CC_CANDYBAR_DEBUG;function Me(e){return je()?`[DEBUG] ${e()}\n`:``}function k(e,...t){je()&&console.error(`[DEBUG] ${e}`,...t)}function Ne(e){let t=null;return([n,r])=>{r!==t&&(t=r,e(n,r))}}const Pe=(e,t)=>k(t),Fe=/^[A-Za-z0-9_./,:@%+-][A-Za-z0-9_./,:@%+=-]*$/;function Ie(e){return`'${e.replaceAll(`'`,`'\\''`)}'`}function Le(e){return Fe.test(e)?e:Ie(e)}function Re(e){return`${e.dir===void 0?``:`cd ${Le(e.dir)} && `}${e.env.map(([e,t])=>`${e}=${Le(t)} `).join(``)}${[e.program,...e.args].map(Le).join(` `)}`}const ze=`cc-extra`;function Be(e){return o.join(o.dirname(e),ze,`src`,`bun-attach.js`)}function Ve(e){return o.join(o.dirname(e),`bun-graph.js`)}const He=`attach-preload.cjs`;function Ue(e){return o.join(o.dirname(e),He)}function We(e,t){return Re({...t,env:[...t.env,[`BUN_OPTIONS`,`--preload ${e.replace(/[\\\s]/g,`\\$&`)}`]]})}const Ge=e=>!e.startsWith(`.`)&&!e.endsWith(`~`);function Ke(e,t){return t.isSymbolicLink()?Buffer.from(f.readlinkSync(e)):f.readFileSync(e)}function qe(e,t,n=Ge){return f.readdirSync(t).filter(n).sort().flatMap(n=>{let r=o.join(t,n),i=f.lstatSync(r,{throwIfNoEntry:!1});return i===void 0?[]:i.isDirectory()?qe(e,r):[[o.relative(e,r).split(o.sep).join(`/`),Ke(r,i)]]})}function Je(e){let t=ee.createHash(`sha256`);for(let[n,r]of e)t.update(n).update(`\0`).update(r).update(`\0`);return t.digest(`hex`)}function Ye(e){return Je(qe(e,e))}const Xe=[`Cargo.toml`,`Cargo.lock`,`src`];function Ze(e){return Je(qe(e,e,e=>Xe.includes(e)))}const Qe=e=>e.slice(0,7),$e=`1.179.0`;function et(e){let t=o.dirname(o.dirname(e));return f.existsSync(o.join(t,`src`))?t:null}function tt(e){if(e===null)throw Error("this bundle carries no source digest (build via `pnpm build`, which stamps it)");return{version:$e,digest:e}}function nt(){return`901e9c7a3b6d41944ffeea1a781f8187e176a75c42bbf17bdcc79e9f537cb6cc`}function rt(e){let t=JSON.parse(f.readFileSync(o.join(e,`package.json`),`utf8`)),n=typeof t==`object`&&t?t.version:void 0;if(typeof n!=`string`)throw Error(`${o.join(e,`package.json`)} has no version string`);return n}function it(e,t){try{let n=et(i(e));if(n===null)return{kind:`not-source-checkout`};let r=t(),a=Ye(o.join(n,`src`));return a===r.digest?{kind:`current`,root:n,stamp:r}:{kind:`stale`,root:n,source:{version:rt(n),digest:a},running:r}}catch(e){return{kind:`unchecked`,reason:e.message}}}function at(e,t,n){let r=ot(e);f.mkdirSync(o.dirname(r),{recursive:!0});let i=`${r}.tmp`,a=n??f.statSync(r,{throwIfNoEntry:!1})?.mode;try{f.writeFileSync(i,t,a===void 0?{}:{mode:a}),f.renameSync(i,r)}catch(e){throw f.rmSync(i,{force:!0}),e}}function ot(e){return st(e).at(-1)}function st(e){let{hops:t,stopped:n}=ct(e);if(n!==null)throw n;return t}function ct(e){let t=[e];try{for(let e=0;e<ut;e++){let e=lt(t[t.length-1]);if(e===null)return{hops:t,stopped:null};t.push(e)}return{hops:t,stopped:Error(`${e}: more than ${ut} symbolic links`)}}catch(e){return{hops:t,stopped:e}}}function lt(e){try{return f.lstatSync(e).isSymbolicLink()?o.resolve(f.realpathSync(o.dirname(e)),f.readlinkSync(e)):null}catch(e){let{code:t}=e;if(t===`ENOENT`||t===`ENOTDIR`)return null;throw e}}const ut=40;function dt(e,t){let n=e[t];return n&&n.length>0?n:void 0}function ft(e=process.env){let t=dt(e,`XDG_STATE_HOME`)??o.join(E.homedir(),`.local`,`state`);return o.join(t,`cc-candybar`)}function pt(){let e=dt(process.env,`XDG_CACHE_HOME`)??o.join(E.homedir(),`.cache`);return o.join(e,`cc-candybar`)}function mt(){return ft()}function ht(){return process.env.CC_CANDYBAR_SOCKET||gt()}function gt(){let e=E.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${e}`,`socket`)}function _t(e){f.mkdirSync(e,{recursive:!0,mode:448});let t=f.lstatSync(e);if(t.isSymbolicLink())throw Error(`directory is a symlink: ${e}`);if(!t.isDirectory())throw Error(`not a directory: ${e}`);let n=E.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 vt(e){_t(o.dirname(e));for(let t of[e,yt(e)])try{if(f.lstatSync(t).isSymbolicLink())throw Error(`path is a symlink: ${t}`)}catch(e){if(e.code!==`ENOENT`)throw e}}function yt(e){return`${e}.lease`}function bt(){return yt(ht())}function xt(e=process.env){return o.join(ft(e),`session-state.json`)}function St(){return o.join(ft(),`settings-history.json`)}function Ct(){let e=process.env.CC_CANDYBAR_DAEMON_REGISTRY_DIR;if(e)return e;let t=E.userInfo().uid;return o.join(`/tmp`,`cc-candybar-${t}`,`daemons`)}function wt(){return o.join(ft(),`spawn.lock`)}function Tt(){return o.join(ft(),`spawn.cooldown`)}function Et(){return o.join(ft(),`spawn.backoff`)}function Dt(){return o.join(ft(),`watch-probe`)}function Ot(e=process.env){return o.join(ft(e),`daemon.log`)}const kt=[`TERM_PROGRAM`,`TERM_PROGRAM_VERSION`,`TERM`,`ITERM_PROFILE`,`XDG_CONFIG_HOME`];function At(e){return Object.fromEntries(kt.flatMap(t=>{let n=e[t]??``;return n===``?[]:[[t,n]]}))}const jt=[`native`,`node`,`frames`];function Mt(e,t){return{kind:e,bundle:t,source:null}}const Nt=[`ansi`,`frame`],Pt=Object.keys({termCols:!0,termRows:!0,ssh:!0,tmux:!0,configEnv:!0,claudeConfigDir:!0,terminalEnv:!0,client:!0});function Ft(e){let t=Wt(e.termCols),n=Wt(e.termRows),r=A(e.ssh),i=Ht(e.tmux),a=Vt(e.configEnv),o=Vt(e.claudeConfigDir),s=Bt(e.terminalEnv),c=j(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 It(e,t){return Pt.filter(n=>e[n]!==void 0&&t[n]===void 0).map(t=>({hint:t,sent:e[t]}))}function Lt(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 Rt={unknown:e=>`Unknown flags: ${e}`,"no-value":e=>`${e} names no file — the bar renders with no ${e}`,positional:e=>`Unexpected arguments: ${e}`};function zt(e){let t=Object.keys(Rt).flatMap(t=>{let n=e.filter(e=>e.why===t).map(e=>e.arg);return n.length===0?[]:[Rt[t](n.join(`, `))]});return t.length===0?null:t.join(`
3
3
  `)}function Bt(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e,n=kt.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 Vt(e){return typeof e==`string`&&o.isAbsolute(e)?e:void 0}function Ht(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 Ut=1e4;function Wt(e){if(typeof e!=`number`||!Number.isFinite(e))return;let t=Math.floor(e);if(!(t<=0))return t>Ut?Ut:t}function A(e){return typeof e==`boolean`?e:void 0}function Gt(e){return typeof e==`string`&&e!==``&&e.length<=64?e:null}var Kt=class extends Error{constructor(e){super(e),this.name=`ProtocolError`}};function qt(e){return Jt(JSON.stringify(e))}function Jt(e){let t=Buffer.from(e,`utf8`),n=Buffer.alloc(4);return n.writeUInt32BE(t.length,0),Buffer.concat([n,t])}function Yt(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 Kt(`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 Kt(e instanceof Error?e.message:String(e));e instanceof Error&&(n.cause=e),t(n);return}}}}function Xt(e,t,n){return new Promise((r,i)=>{let a=!1,o=t=>{if(!a){a=!0,clearTimeout(s),e.off(`data`,c),e.off(`error`,l),e.off(`close`,u);try{t()}catch{}}},s=setTimeout(()=>{o(()=>{e.destroy(),i(Error(`TIMEOUT`))})},n-Date.now()),c=Yt(e=>o(()=>r(e)),e=>o(()=>i(e))),l=e=>o(()=>i(e)),u=()=>o(()=>i(Error(`socket closed before response`)));e.on(`data`,c),e.on(`error`,l),e.on(`close`,u),e.write(qt(t))})}function j(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let{kind:t,bundle:n,source:r}=e,i=Vt(n);return jt.includes(t)&&i!==void 0&&(r===null||typeof r==`string`&&r!==``)?{kind:t,bundle:i,source:r}:void 0}async function Zt(e,t,n){let r=null;try{r=await nn(ht(),t.connectMs);let i=Date.now()+t.budgetMs,a=e(i),o=await Xt(r,{v:3,...a},i);return en(a.kind,o,n)}catch(e){return tn(e)}finally{r&&r.destroy()}}function Qt(e,t){return typeof e==`string`?e:t}function $t(e){return typeof e==`number`&&Number.isInteger(e)&&e>=0?e:0}function en(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=Qt(r.error,`(no error message)`);switch(r.code){case`VERSION_MISMATCH`:return{kind:`permanent`,cause:`version_mismatch`,clientV:3,daemonV:$t(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 tn(e){if(e instanceof Kt||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 nn(e,t){return new Promise((n,r)=>{let i=ie.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 rn(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 an={connectMs:50,budgetMs:150},on={connectMs:50,budgetMs:200};function sn(e){let t=e.output;return typeof t==`string`?t:void 0}function cn(e){return en(`render`,e,sn)}function ln(e,t,n,r){return Zt(i=>({kind:`render`,hookData:e,args:t,cwd:n,deadline:i,...r}),an,sn)}function un(e,t){return Zt(()=>({kind:`pane-session`,socket:e,pane:t}),on,e=>`paneSession`in e?e.paneSession:void 0)}function dn(e,t){return Zt(()=>({kind:`click`,verb:e,value:t,clientVersion:$e}),on,sn)}function fn(e,t){return le.isNativeError(e)?e.code===`ENOENT`&&t!==void 0&&!h(t)?`working directory does not exist: ${t}`:e.message:String(e)}const pn={"click.pbcopy":1e3,"click.open":1e3,"doctor.tmux":1e3,"doctor.font":1e3,"doctor.process":1e3,"claude-input.type":1e3};function mn(e,t){let n=pn[t];if(n===void 0)return{allowed:!0};let r=e.get(t);if(r===void 0)return{allowed:!0};let i=Date.now()-r;return i>=n?{allowed:!0}:{allowed:!1,minIntervalMs:n,sinceLastMs:i}}function hn(e){return e.env??process.env}const gn=({reason:e})=>({ok:!1,reason:`aborted`,stdout:``,stderr:``,exitCode:null,signal:null,error:e instanceof Error?e.message:String(e)});function _n(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`}}function vn(e,t){let n=t.finally(()=>e.ending.delete(n));return e.ending.add(n),n}function yn(e,t,n){let r=bn(e,t,n);return r===null?(e.lastStartAt.set(t,Date.now()),null):(e.scope.stats?.onRefused(t),r)}function bn(e,t,n){if(e.scope.signal.aborted)return gn(e.scope.signal);if(n?.aborted)return gn(n);let r=mn(e.lastStartAt,t);return r.allowed?null:_n(t,r.minIntervalMs,r.sinceLastMs)}const xn=`\$1 == "+" { live[\$2] = 1; next } \$1 == "-" { delete live[\$2]; next } END { for (g in live) groups = groups " -" g; if (groups != "") system("kill -TERM" groups " 2>/dev/null; sleep ${250/1e3}; kill -KILL" groups " 2>/dev/null") }`;function Sn(e,t){t!==e.fault&&(e.fault=t,e.scope.observeLifeline(t))}function Cn(e,t,n){e.lifeline?.process===t&&(e.lifeline=null,t.ref(),Sn(e,n))}function wn(e){return e.fault===null?[]:[{kind:`lifeline`,message:`programs launched now would outlive their launcher if it died: its launch lifeline ${e.fault}, and the next launch starts another`}]}function Tn(e){let{stats:t}=e.scope;t?.onStart(`lifeline`);let n=Date.now(),r;try{r=O(`awk`,[xn],{stdio:[`pipe`,`ignore`,`ignore`],detached:!0})}catch(r){return t?.onEnd(`lifeline`,Date.now()-n),Sn(e,`did not start: ${fn(r,void 0)}`),null}t?.onEnd(`lifeline`,Date.now()-n);let i=r.stdin;if(i==null)return r.once(`error`,t=>Sn(e,`did not start: ${t.message}`)),null;r.once(`spawn`,()=>{e.lifeline?.process===r&&Sn(e,null)}),r.once(`error`,t=>Cn(e,r,`failed: ${t.message}`)),r.once(`exit`,(t,n)=>Cn(e,r,`exited ${n??t}`)),i.on(`error`,t=>Cn(e,r,`pipe failed: ${t.message}`)),vn(e,new Promise(e=>r.once(`close`,e))),r.unref(),i.unref();for(let t of e.liveGroups)i.write(`+ ${t}\n`);return{process:r,pipe:i}}function En(e,t){e.liveGroups.add(t),e.lifeline??=Tn(e),e.lifeline?.pipe.write(`+ ${t}\n`)}function M(e,t){e.liveGroups.delete(t),e.lifeline?.pipe.write(`- ${t}\n`)}function Dn(e){let t=e.lifeline;e.lifeline=null,t?.process.ref(),t?.pipe.end()}function On(e,t){try{process.kill(-e,t)}catch(t){let n=t.code;if(n!==`ESRCH`&&!(n===`EPERM`&&!kn(e)))throw t}}function kn(e){try{return process.kill(e,0),!1}catch(e){return e.code===`EPERM`}}function An(e){let t=new oe(`utf8`),n=``,r=e=>{n+=t.write(e)};return e?.on(`data`,r),()=>{e?.off(`data`,r);let i=n+t.end();return n=``,i}}async function jn(e,t){let{stats:n}=e.scope,r=yn(e,t.category,t.signal);if(r!==null)return r;let i=Date.now();return n?.onStart(t.category),new Promise(r=>{let a;try{a=O(t.bin,t.args??[],{cwd:t.cwd,env:hn(t),stdio:[`pipe`,`pipe`,`pipe`],detached:!0})}catch(e){n?.onEnd(t.category,Date.now()-i),r({ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:fn(e,t.cwd)});return}let o=a.pid;o!==void 0&&En(e,o);let s=new Promise(e=>a.once(`exit`,e)),c=An(a.stdout),l=An(a.stderr),u=()=>({stdout:c(),stderr:l()}),d=!1,f=null,p=null,m=null,h=null,g=()=>S(`aborted`),_=()=>{t.signal?.removeEventListener(`abort`,g),e.inFlight.delete(g)},v=r=>{if(!d){d=!0,f&&clearTimeout(f),p&&clearTimeout(p),m&&clearTimeout(m),_(),o!==void 0&&M(e,o),n?.onEnd(t.category,Date.now()-i);for(let e of[a.stdout,a.stderr])e?.unref();r()}},y=e=>v(()=>r(e)),b=(n,r)=>{try{On(n,r)}catch(n){e.unreaped.set(a,t.category),s.then(()=>e.unreaped.delete(a)),y({ok:!1,reason:`signal-refused`,...u(),exitCode:null,signal:null,error:n instanceof Error?n.message:String(n)})}},x=()=>C(a.exitCode,a.signalCode);if(o!==void 0){let e=t=>{if(!d){if(Bn(o)){de(x);return}m=setTimeout(()=>e(Math.min(t*2,1e3)),t)}};s.then(()=>de(()=>e(25)))}let S=e=>{if((a.exitCode!==null||a.signalCode!==null)&&o!==void 0&&Bn(o)){h=e===`aborted`?e:null,de(x);return}h=e,f&&clearTimeout(f),_();let t=a.pid;t!==void 0&&(p=setTimeout(()=>{b(t,`SIGKILL`),s.then(()=>de(x))},250),b(t,`SIGTERM`))};a.on(`error`,e=>{y({ok:!1,reason:`spawn-error`,...u(),exitCode:null,signal:null,error:fn(e,t.cwd)})});let C=(e,t)=>{if(h!==null){y({ok:!1,reason:h,...u(),exitCode:e,signal:t});return}if(e===0){y({ok:!0,...u(),exitCode:e});return}y({ok:!1,reason:t?`signal`:`non-zero`,...u(),exitCode:e,signal:t})};a.on(`close`,C),t.timeoutMs&&t.timeoutMs>0&&(f=setTimeout(()=>S(`timeout`),t.timeoutMs)),t.signal?.addEventListener(`abort`,g,{once:!0}),e.inFlight.add(g),a.stdin?.on(`error`,()=>{}),a.stdin?.end(t.stdinInput)})}function Mn(e,t){let{stats:n}=e.scope,r=yn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=[`pipe`,`pipe`,`pipe`];try{let e=ae(t.bin,t.args??[],{cwd:t.cwd,env:hn(t),input:t.stdinInput,timeout:t.timeoutMs&&t.timeoutMs>0?t.timeoutMs:void 0,stdio:a,encoding:`utf8`});n?.onEnd(t.category,Date.now()-i);let r=typeof e.stdout==`string`?e.stdout:``,o=typeof e.stderr==`string`?e.stderr:``,s=e.error?.code;return e.error&&s!==`EPIPE`&&s!==`ECONNRESET`?{ok:!1,reason:s===`ETIMEDOUT`?`timeout`:`spawn-error`,stdout:r,stderr:o,exitCode:null,signal:e.signal??null,error:fn(e.error,t.cwd)}:e.status===0?{ok:!0,stdout:r,stderr:o,exitCode:e.status}:{ok:!1,reason:e.signal?`signal`:`non-zero`,stdout:r,stderr:o,exitCode:e.status,signal:e.signal??null}}catch(e){return n?.onEnd(t.category,Date.now()-i),{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:fn(e,t.cwd)}}}function Nn(e,t){let{stats:n}=e.scope,r=yn(e,t.category);if(r!==null)return r;let i=Date.now();n?.onStart(t.category);let a=Pn(t);return n?.onEnd(t.category,Date.now()-i),a}function Pn(e){let t;try{t=O(e.bin,e.args??[],{cwd:e.cwd,env:hn(e),detached:!0,stdio:`ignore`})}catch(t){return{ok:!1,reason:`spawn-error`,stdout:``,stderr:``,exitCode:null,signal:null,error:fn(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})}const Fn=e=>e.kind===`exit`?`exit ${e.code}`:`timeout`;function In(e,t,n){let{stats:r}=e.scope,i=yn(e,t.category);if(i!==null)return{ok:!1,error:i.error};let a=Date.now();r?.onStart(t.category);let o;try{o=O(`/bin/sh`,[`-c`,`out=$1 err=$2 status=$3; shift 3; read go || exit 0; "$@" >"$out" 2>"$err" </dev/null; echo "exit $?" >"$status.$$" && ln "$status.$$" "$status"; rm -f "$status.$$"`,`sh`,n.stdout,n.stderr,n.status,t.bin,...t.args??[]],{cwd:t.cwd,env:hn(t),detached:!0,stdio:[`pipe`,`ignore`,`ignore`]})}catch(e){return r?.onEnd(t.category,Date.now()-a),{ok:!1,error:fn(e,t.cwd)}}r?.onEnd(t.category,Date.now()-a),o.once(`error`,()=>{});let s=o.pid,c=o.stdin;return c.on(`error`,()=>{}),s===void 0?(c.destroy(),{ok:!1,error:`spawn(/bin/sh): no pid (shell not found or unexecutable)`}):(o.unref(),c.unref(),{ok:!0,pid:s,release:()=>c.end(`go
4
4
  `),withdraw:()=>c.end()})}function Ln(e){let t;try{t=y(e,`utf8`).trim()}catch(e){if(e.code===`ENOENT`)return null;throw e}let n=/^exit (\d+)$/.exec(t);if(n)return{kind:`exit`,code:Number(n[1])};if(t===`timeout`)return{kind:`timeout`};throw Error(`${e}: not a job verdict: ${JSON.stringify(t)}`)}function Rn(e,t){try{return process.kill(-e,t),!0}catch(e){let t=e.code;if(t===`ESRCH`||t===`EPERM`)return!1;throw e}}function zn(e){return Rn(e,0)}function Bn(e){try{return process.kill(-e,0),!1}catch(e){return e.code===`ESRCH`}}function Vn(e,t,n){let r=`${t}.${process.pid}`;try{C(r,`${Fn(n)}\n`)}catch(e){if(e.code===`ENOENT`)return{stands:!1,signalled:!1};throw e}let i=!0;try{_(r,t)}catch(e){if(e.code!==`EEXIST`)throw e;i=!1}finally{x(r,{force:!0})}let a=Rn(e,`SIGTERM`);return a&&setTimeout(()=>Rn(e,`SIGKILL`),250).unref(),{stands:i,signalled:a}}function Hn(e){let t={launch:e=>vn(n,jn(n,e)),launchSync:e=>Mn(n,e),launchDetachedSync:e=>Nn(n,e),launchJobSync:(e,t)=>In(n,e,t),lifelineWarnings:()=>wn(n),settled:async()=>(await Promise.all(n.ending),{unreaped:[...n.unreaped.values()]}),__lifelineForTest:()=>{let e=n.lifeline;return{pid:e?.process.pid,cut:()=>{e?.pipe.end(),e&&Cn(n,e.process,`cut by a test`)}}}},n={scope:{stats:null,observeLifeline:()=>t.lifelineWarnings().forEach(e=>process.emitWarning(e.message)),signal:new AbortController().signal,...e},lastStartAt:new Map,inFlight:new Set,liveGroups:new Set,lifeline:null,fault:null,ending:new Set,unreaped:new Map};return n.scope.signal.addEventListener(`abort`,()=>{n.inFlight.forEach(e=>e()),Dn(n)},{once:!0}),t}const Un=Hn({});let Wn=null;function Gn(){if(Wn!==null){try{f.closeSync(Wn.fd)}catch{}Wn=null}}async function Kn(e){let t=await f.promises.stat(e).catch(()=>null);if(Wn!==null&&Wn.path===e&&t!==null&&Wn.id===qn(t))return{held:Wn,size:t.size};Gn(),await f.promises.mkdir(o.dirname(e),{recursive:!0});let n=await new Promise((t,n)=>f.open(e,`a`,(e,r)=>e===null?t(r):n(e))),r=await new Promise((e,t)=>f.fstat(n,(n,r)=>n===null?e(r):t(n)));return Wn={path:e,fd:n,id:qn(r)},{held:Wn,size:r.size}}function qn(e){return`${e.dev}:${e.ino}`}function Jn(e,t){return new Promise((n,r)=>f.write(e,t,(e,t)=>e===null?n(t):r(e)))}async function Yn(e){for(let t=2;t>=1;t--)await f.promises.rename(`${e}.${t}`,`${e}.${t+1}`).catch(()=>{});await f.promises.rename(e,`${e}.1`).catch(()=>{})}let Xn=[],Zn=0,Qn=0,$n=0,er=null,tr=!1;const nr=[];let rr=!1,ir=!1;function ar(e,t){return`${new Date().toISOString()} [${e}] ${t}\n`}function or(e,t){let n=ar(e,t);if(ir||(ir=!0,process.on(`exit`,()=>{rr=!0,pr(!0,dr)})),Xn.push(n),Zn+=Buffer.byteLength(n),Zn>4194304){let e=0;for(;Zn>4194304/2&&e<Xn.length-1;){let t=Buffer.byteLength(Xn[e]);Zn-=t,$n+=t,e++}Xn.splice(0,e),Qn+=e}rr?pr(!0,dr):tr||cr()}function sr(){pr(!1,fr)}async function cr(){tr=!0;try{for(;Xn.length>0;){let e=lr();er={bytes:Buffer.from(e),state:{kind:`taken`}};try{await ur(Ot(),er)}catch(t){Gn(),er.state.kind!==`landed`&&hr(e,t)}finally{er=null}}}finally{tr=!1;for(let e of nr.splice(0))e()}}function lr(){let e=(Qn===0?``:ar(`warn`,`log: ${Qn} earlier line(s) dropped (${$n} bytes): more than 4194304 bytes were waiting for the disk`))+Xn.join(``);return Xn=[],Zn=0,Qn=0,$n=0,e}async function ur(e,t){let{held:n,size:r}=await Kn(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 Jn(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){Gn();let e=await f.promises.stat(n.path).catch(()=>null);e!==null&&qn(e)===n.id&&await Yn(n.path)}}const dr=1e3,fr=2e3;function pr(e,t){let n=er,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=mr(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`}),hr(n.bytes.toString(),t)}}if(r.length===0&&Xn.length===0)return;let a=Buffer.concat([r,Buffer.from(lr())]);try{let e=Ot();f.mkdirSync(o.dirname(e),{recursive:!0}),f.appendFileSync(e,a),i!==null&&n!==null&&qn(f.fstatSync(i.fd))===qn(f.statSync(e))&&(n.state={kind:`issued`,fd:i.fd,endsAt:i.endsAt+a.length})}catch(e){hr(a.toString(),e)}}function mr(e,t,n){let r=performance.now()+n,i=new Int32Array(new SharedArrayBuffer(4));for(;;){let{size:n}=f.fstatSync(e);if(n>=t||performance.now()>=r)return n;Atomics.wait(i,0,0,1)}}function hr(e,t){try{process.stderr.write(`${e}cc-candybar: daemon.log unwritable: ${t.message}\n`)}catch{}}const gr=5e3;async function _r(e){let t=[];for(let n of e){let e=await 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(`
5
5
  `)}const vr=`/usr/bin/footprint`;function yr(e,t,n){return t===`darwin`?[Cr(e,vr,[`-p`,String(n)]),Cr(e,`/usr/bin/vmmap`,[`--summary`,String(n)])]:t===`linux`?[wr(`/proc/self/smaps_rollup`),wr(`/proc/self/status`)]:[]}function br(e,t,n){return t===`darwin`?xr(n,t=>e.launch({bin:vr,args:t,timeoutMs:gr,category:`limits.charge`})):async e=>({kind:`charged`,measure:`rss`,bytes:e})}function xr(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}`}${Tr(r.stderr)}`};let i=Sr(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 Sr(e){let t=/^\s*phys_footprint:\s+(\d+) B\s*$/m.exec(e);return t===null?null:Number(t[1])}function Cr(e,t,n){return{name:`${t} ${n.join(` `)}`,read:async()=>{let r=await e.launch({bin:t,args:[...n],timeoutMs:gr,category:`limits.memory-report`});return r.ok?r.stdout.trim().length>0?{kind:`text`,text:r.stdout}:{kind:`unavailable`,reason:`exited 0 but printed nothing`}:{kind:`unavailable`,reason:`${r.reason}${r.error===void 0?``:`: ${r.error}`}${Tr(r.stderr)}`}}}}function wr(e){return{name:e,read:async()=>{try{let t=f.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 Tr(e){let t=e.split(`
@@ -481,7 +481,7 @@ function run(argv) {
481
481
  `),...e]));return o.overflow=`ignore`,o.end=``,o}function J2(e,t){return{themePreview:{fn:(...n)=>{let[r,...i]=n;if(NM(`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}=V0(e,`{{ themePreview }}`);return q2(r===void 0?a:V2(e,r,`themePreview`),o,{...T2(t,`{{ themePreview }}`).disclosure,depth:0},t.drawnAt(),O2(e))},argTypes:[`value`],arity:{kind:`variadic`},returnType:`T`}}}const Y2=e=>e.slice(e.lastIndexOf(`.`)+1),X2=(e,t)=>{let n=new G(Y2(e));return n.truncate(t,{marker:`…`}),n.plain};function Z2(e,t){let n=e.map(e=>e.map(({name:e})=>E2(Y2(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 Q2(e,t,n,r){let i=Z2(e,r),a=e.map(e=>{let a=[],o=0;for(let{name:s,address:c,palette:l}of e){let e=new G(` ${X2(s,i)} `,{style:o2(Zv(l,{kind:`bar`,decor:t,address:c},n))});if(o+=e.cellLength,o>r)break;a.push(e)}return a}),o=G.fromFragments(a.flatMap((e,t)=>t===0?e:[new G(`
482
482
  `),...e]));return o.overflow=`ignore`,o.end=``,o}const $2=`layoutPreview`;function e4(e,t){return{[$2]:{fn:()=>Q2(H0(e,`{{ layoutPreview }}`),V0(e,`{{ layoutPreview }}`).decor,t.drawnAt(),O2(e)),argTypes:[],arity:{kind:`exact`},returnType:`T`}}}function t4(e,t,n,r){let i=T2(r.activeSegment,`{{ menu }}`),a=r.action,o=qN(i.placementId,e,n.key),s=XN(o),c=KN(e),l=B0(a,`menu`).store,u=Y0(l,o)===c,d=Y0(l,`session.id`),f=u?di:c,p=Z0(hi(`{{ menu "${e}" }}`,t,2,+!!u),ba([{verb:Ri,args:[d,o,f,s,`0`]}]),!1);return i.drops.push(...u?(()=>{let t=r.activeSegment.drawnAt(),c=zv(i.palette,i.disclosure,t).plane,l=N2(a,e,`menu`);return P2(e,l,{key:s,stateVar:s},{kind:`own`,writes:[[o,di],[s,`0`]],onPick:n.closeOnPick},n.paged,a,p2(i,n.distribution,V0(a,`{{ menu }}`),l.paletteOf,t,c),s2(i.palette,c,t))})():[]),p}const n4=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function r4(e,t){let n=t[t.length-1],r=n4(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:eP(r??{})}}function i4(e){return{menu:{fn:(t,...n)=>{let{displays:r,options:i}=r4(t,n);return t4(t,r,i,e)},argTypes:[`string`,`value`],arity:{kind:`variadic`},returnType:`T`}}}function a4(e){let{value:t,max:n,width:r,filled:i,empty:a,colourAt:o}=e,s=o4(t,n,r),c=[];for(let e=0;e<r;e++){let t=e<s,l=t&&o!==void 0?o(e*n/r):void 0;c.push(new G(t?i:a,{style:l===void 0?void 0:new H({color:l})}))}let l=G.fromFragments(c);return l.end=``,l.overflow=`ignore`,l}function o4(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 s4(e){let t={fn:(()=>{let t=T2(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:(()=>T2(e,`{{ tint }}`).tint.hex),argTypes:[],arity:{kind:`exact`},returnType:`string`},r={fn:((t,n)=>{let{palette:r}=T2(e,`{{ roleTextOn }}`);return u4(r,t,zu(r,n)).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},i={fn:((t,n)=>{let{palette:r}=T2(e,`{{ keptOn }}`),i=zu(r,t),a=zu(r,n),o=kl($u(i,B.TRUECOLOR),$u(a,B.TRUECOLOR)),s=Math.min(Ov,Math.max(o,3));return(Qu(i,e.drawnAt(),(e,t)=>kl(e,t(a))>=s)??i).hex}),argTypes:[`string`,`string`],arity:{kind:`exact`},returnType:`string`},a=mM(()=>T2(e,`{{ color }} / {{ ramp }} / {{ gauge }}`).palette),o={fn:((e,t,n,r,i,o,...s)=>{let c=o===void 0?void 0:[o,...d4(s)];return a4({value:e,max:t,width:n,filled:r,empty:i,colourAt:c===void 0?void 0:e=>String(a.ramp.fn(e,...c))})}),argTypes:[`float`,`float`,`int`,`string`,`string`,`string`],arity:{kind:`variadic`},returnType:`T`};return{...a,bgOf:t,tint:n,roleTextOn:r,keptOn:i,gauge:o}}const c4={"#000000":[`darken-1`,`darken-2`,`darken-3`],"#ffffff":[`lighten-1`,`lighten-2`,`lighten-3`]},l4=Object.values(c4).flat();function u4(e,t,n){let r=$u(n,B.TRUECOLOR),i=t=>{let n=zu(e,t);return{colour:n,ratio:kl($u(n,B.TRUECOLOR),r)}},a=Xu(r).hex,o=c4[a];if(o===void 0)throw Error(`contrastFor named ${a} for ${n.hex}, which is neither pole`);let s=`text-${t}`,c=e=>`${t}-${e}`,l=new Map([s,t,...l4.map(c)].map(e=>[e,i(e)]));return([s,t,...o.map(c)].map(e=>l.get(e)).find(({ratio:e})=>e>=4.5)??[...l.values()].reduce((e,t)=>t.ratio>e.ratio?t:e)).colour}function d4(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 f4(e,t){if(e.kind!==`shell`&&e.kind!==`file`)return[];let n=`key`in e.cache&&[...t.calls(e.cache.key)].some(e=>tN.has(e));return[...t.ofVariable(e).flatMap(({reaches:e})=>e.length===0?[null]:e),...n?[null]:[]]}const p4={input:`view`,state:`view`,template:`view`,time:`view`,literal:`directory`,env:`directory`,dropped:`directory`,source:`view`},m4=new WeakMap;function h4(e){let t=m4.get(e);return t===void 0&&(t=g4(e),m4.set(e,t)),t}function g4(e){let t=new Map(uT(e)),n=wU(e),r=new Map([...t].map(([e,t])=>[e,t.kind===`shell`||t.kind===`file`?`directory`:p4[t.kind]])),i=new Map([...t].map(([e,t])=>[e,f4(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 _4(e){let t=[],n=[];for(let r of e){if(!r.contains(`
483
483
  `)){n.push(r);continue}let e=r.split(`
484
- `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function v4(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 y4=e=>e.kind===`failed`?x0:e;function b4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function x4(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 S4(e){return{...e,cells:e.cells.map(D0)}}function C4(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,...w4(e,r)]}function w4(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 T4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:C4(e.direction,e.children.map((t,i)=>n(t,[...r,E4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function E4(e,t){return e.steps[t]}function D4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=O4(e);return{width:k4(t),reach:A4(t)}}function O4(e){let t=e.children.map(D4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const k4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),A4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function j4(e,t){let n=O4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=zy[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),A4(n),k4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const M4={compile(e,t){let n=j4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Gy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),C4(e.direction,e.children.map((n,r)=>t.renderChild(n,y4(t.gate),E4(e,r))))}},N4={drop:e=>e.place,above:()=>`above`},P4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},F4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:By(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(vi(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ky(t.path),void 0),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,I4(e,t))};function I4(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=aN(t.scope,e.settings);if(t.gate.kind===`failed`)return H4(e,r,t,t.gate.message);try{let i=t.placement(e),a=b4(t.gate,i.gate());if(a.kind===`failed`)return H4(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 H4(e,r,t,s.message);let c=JC(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:oF(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`?L4(f.variable):R4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?z4(p.segment,u):B4(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:x0,h.disclosure).map(e=>({...e,place:N4[v.placement](e)})),b=(e,t,n)=>A0(L0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?P4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new G(` `.repeat(V4(E0(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap(E0)),[...ne,...te]}catch(n){return H4(e,r,t,n.message??String(n))}}const L4=e=>({kind:`waiting`,variable:e});function R4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=NT(e);if(t===void 0)throw e;return L4(t.variable)}}function z4(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:_4(L0(r,c)).map((e,t)=>({cells:A0(e,{...l,lead:t===0?L0(i,c):[],trail:t===0?L0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:A0(L0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function B4(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=L0(U4(e.lead,e,t,n),l),d=L0(U4(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 A0(L0([new G(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function V4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function H4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:A0([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:oF(n.palette)},lead:U4(e.lead,e,t,n),trail:U4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function U4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=NT(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const W4={container:M4,segment:F4};function G4(e){return W4[e]}var K4=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?q4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const q4={kind:`hidden`},J4={palette:`theme`,style:`style`,effect:`effect`},Y4=Kx.get(`colorCompatibility`),X4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function Z4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function Q4(e){if(e.ok)return e.value;throw e.error}const $4=e=>({read:()=>e}),e3=k_({basePalette:O_,palette:O_,decor:Wv});var t3=class{evaluated=0;memory=new K4;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&e3(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=Y.observable.box(r,{deep:!1}),this.scope=rN(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(Y4);return typeof e==`string`&&Oy(e)?e:`truecolor`});let i=(0,Y.observable)(X4,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 T4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=Pz(e);return i===void 0?[]:[{name:i,address:n,palette:JC(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>ky(this.colorCompatibility())})}bind(e){(0,Y.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,Y.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=HN(e);return t===void 0?BN(e)===void 0?kN(this.view.get().payload(),e):kN(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()[J4[e]];if(t.kind===`decided`)return i3(t.name,null,null);let r=o3(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=s3(this.source,e,i.name,r.where,e=>{t=e}),i3(n,t,null)}case`pending`:return i3(n??hy[e],null,i.variable);case`failed`:return n=hy[e],i3(n,gy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!a3(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)??hy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,Y.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return C0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>C2(this.source.activeSegment,()=>C0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new c3(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:U0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=NT(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:Z4(e)}),Q4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:Pz(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function n3(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new t3(t,n,e,r);return e.views.set(t,a),a}function r3(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 i3=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),a3=(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 o3(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 s3(e,t,n,r,i){switch(t){case`palette`:return $C(n,r,i).name;case`style`:return fy(n,e.styles).name;case`effect`:return Sy(n).name}}var c3=class{where=l3(k_({palette:O_,region:Hv}));ground=l3(k_({colours:d3,bodyOpen:O_}));opened=l3(k_({colours:d3,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=aN(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?$4(S0):e.derive(`${t.id} when`,e.readsInstant(a),()=>C2(r,()=>C0(a,i))),this.open=d===void 0?$4(x0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>C2(r,()=>C0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return m3(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 h3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?$4(_3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return g3(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}),y3(n,r,this.affixes.read())}};function l3(e){let t=Y.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,Y.runInAction)(()=>t.set(e)),get:()=>t.get()}}const u3=(e,t)=>e.hex===t.hex,d3=k_({palette:O_,drawnAt:O_,tint:u3,text:u3,bg:u3,disclosure:Gv});function f3(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const p3=e=>zv(e.palette,e.disclosure,e.drawnAt);function m3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Zv(n,r,i)};return S2(e,f3(t,c),e=>{let t=Ste(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function h3(e,t,n,r,i,a){return S2(e,f3(t,n),e=>(e.bg=i?p3(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function g3(e,t,n,r,i,a,o){return S2(e,f3(t,n),e=>(e.bg=r?p3(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const _3={lead:[],trail:[],drops:[]};function v3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return a2(t,p3(e).state,n)},get band(){return a2(t,p3(e).plane,n)},get close(){return c2(t,p3(e).state,n)},disclosure:r}}function y3(e,t,n){return{styles:v3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function b3(e,t,n,r,i,a,o){let s=m3(e,t,n,r,i,void 0,void 0,o);return y3(s,h3(e,t,s,a,!1,o),_3)}function x3(e,t,n,r,i){return v3(m3(e,t,n,r,i,void 0,void 0,{}))}function S3(e,t){return{payload:()=>e,selections:()=>t}}function C3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:vN(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 w3(e,t){switch(Yy(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 T3(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:C3(n.cache),parse:w3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:C3(n.cache),parse:w3(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 E3(e,t){let n=xE.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 D3(e,t,n){let{compiled:r,loadWarnings:i}=k3(e,t,n.cwd,O3(n.signer),N3);return{...r,loadWarnings:i}}const O3=e=>(t,n)=>P3(n,e);function k3(e,t,n,r,i=N3){let a=A3(e),o=j3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:M3(e,t,n,i)}}function A3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of qx)n in t&&r.set(e,n);for(let[t,n]of $y(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...OU(e)].sort(([e],[t])=>e<t?-1:1)}}function j3(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function M3(e,t,n,r){let i=h4(e),a=OU(e),o=[];for(let[s,c]of uT(e))if(r.has(i.get(s)))try{T3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const N3=new Set([`directory`,`view`]);function P3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>B0(i,`drawnAt`).registry.drawnAt(),o=b2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=bw(e.presets),u=Cz(e),d=[e=>U2(i,o,e.now)],f=nN({extraFuncs:{...r2(i),...H2(i),...F2(i,o),...R2(i),...J2(i,o),...e4(i,o),...i4(s),...s4(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=E3(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=W0(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})}},x=t=>{let n=rb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Nee(t,e,a,t=>String(B0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return G4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Cw(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(sy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of AU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:L3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w={reads:xU({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:$M(d)},te=NU(w),ne=[...C.values()].flatMap(I3(y)).some(e=>te(m.get(e))),T=ne?NU({...w,clock:new Set([...w.clock,$2])}):te;return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:new Set([...m].flatMap(([e,t])=>T(t)?[e]:[])),layoutReadsInstant:ne,styles:e.styles,runtime:i,views:new WeakMap}}function F3(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 I3=e=>t=>{let n=[];return T4(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 L3(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 R3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function z3(e,t,n,r,i){let a=B3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function B3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??hy[e];case`failed`:return r({kind:`rule`,slot:e,message:gy(t.where,e,`the rule failed — ${n.error}`)}),hy[e]}}function V3(e){return H3(e).filter(e=>!e.name.startsWith(ki)).map(e=>e.id)}function H3(e){return e.kind===`container`?e.children.flatMap(H3):[e,...e.opens===void 0?[]:H3(e.opens.body)]}function U3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return n3(e,t,n,S3(o,a)),o}function W3(e,t,n,r,i,a,o,s,c){try{var l=wo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new hS(``),h=m.clockAt(a,vy[c.animationSpeed]),g=l.u(UM(a,h.timeline)),_=r3(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:WS(v),padding:v.padding,seamCols:GS(v),preset:c.preset},i);let y=_.evaluated;l.u(U0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,x4),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.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&&te.add(n.waited),n.name;let r=s3(t,e,z3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:$C(re(`palette`),``,R3),ae=D.kind===`decided`?D:fy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Sy(re(`effect`)),se=O.value,ce=XC(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:x4,hold:S4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:b4(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${V3(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:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>b3(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Yv(a,n)),renderBody:(e,t,n)=>pe(e,t,Xv(n)),closeDisclosure:e=>i2(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>x3(t.activeSegment,e,n,a,r.drawnAt())};return G4(e.kind).render(e,c)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${vw}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=v4(pe(me,S0,Jv(S))).map(({line:e,row:t})=>{let n=F0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...ZS(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||H3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const G3={moving:1e3/30,still:1e3},K3=[`data`,`state`,`reload`,`visibility`];function q3(e){return Xb.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 J3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const Y3=(e,t)=>Yb[t].handsOff?e.resp:e.statusline,X3=e=>Math.round(1e3/e);var Z3=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 rx;let r=t-1,i=this.shown(n);return nx(e=>{let a=n.rates.get(e);if(a===void 0)return ex;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,drawMs:0,evaluated:0,cellBreaks: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}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}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,t){e.phase={kind:`drawing`};let n=this.deps.now(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${se(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,X3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}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=this.deps.now(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){e.phase.kind===`due`&&clearTimeout(e.phase.timer);let r=Math.max(0,(t-n)*1e3);e.phase={kind:`due`,at:this.deps.now()+r,timer:setTimeout(()=>this.draw(e,t),r)}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||Y3(a,t)!==Y3(i,t))&&J3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=Y3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}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:vP(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=pN.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} ceiling=${X3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${K3.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 Q3(e,t){return Xb.filter(n=>e[n]&&Yb[n].handsOff&&t.has(n))}function $3(e,t){return{severity:rC,lines:[[iC(`[⟲ claude]`,ba([{verb:Xi,args:[e,...t.map(e=>Yb[e].switch.setting)]}]))]]}}function e6(e,t){for(let n of Object.entries(t))e.push(n)}const t6={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function n6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,se(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function r6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...n6(n)];return{level:t6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${L(t)}`).join(``)}`}}const i6=()=>{},a6=e=>({ok:!1,error:e instanceof Error?e.message:se(e),code:`RENDER_FAILED`,daemonV:3}),o6={ansi:e=>({ok:!0,output:NS(e)}),frame:e=>({ok:!0,frame:e})};function s6(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.date().getTime(),s=[];try{try{var c=wo();let i=c.u(p6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=h6(e,i,{by:`feed`,fps:n}),p=o6.ansi(o.body),m=S6(t,o,Q3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:o6.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=r6(`render`,s,{kind:`threw`,error:e},i.date().getTime()-o),r=a6(e);return{bar:CS(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:i6,failure:{level:t,line:`frame ${n}`}}}}function c6(e,t,n){let{sessionState:r}=e;return yK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function l6(e,t){try{var n=wo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:gK(i.view.source.effective(),Nc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function u6(e,t,n){try{var r=wo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return gK(c6(e,n,o.state),s===null||Nc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function d6(e,t,n){e6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=It(e,r),a=Lt(i);return e6(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 f6(e,t,n,r){let{sessionState:i,renderCache:a}=e,s=t.hookData.workspace?.current_dir??t.cwd,c={...t,hookData:{...t.hookData,...s!==void 0&&o.isAbsolute(s)&&{location:jc(s)}}},l=c.sessionId,u=d6(c,n,r);e6(r,{encoding:c.encoding});let d=h1(c.requested,i,l);return m6(e,a.holdSession(d.projectDir,d.cwd,d.target.path,c),c,u,n,r)}function p6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{s=d6(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return m6(e,a,o,s,n,r)}function m6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function h6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.effective(),C=gK(S,Nc(b.facts().hints.tmux));e6(g,{lanes:Xb.filter(e=>C[e]).join(`,`)||`-`});let{hints:ee}=b.facts(),w=UX(ee);e6(g,{width:String(w)});let te=b.source.payload(),ne=aee(r,_,h,n.by),T=ne.kind===`held`||ne.kind===`owed`?ne.error:null,re=o.notice({sessionId:_,dismissed:r.get(_,sq),enabled:S.updateNotice}),E=Eq(v.repos,_,s),D=(e,t)=>({about:e,text:t,copy:t}),ie=e=>D(e??``,e),O=[ie(zt(m.refusedArgs)),ie(x),D(`load`,v.lastError),D(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(T?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:vT(`config watch`,v.watch,null),oe=[...Jc(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=aC(_,n.by,O,[...re,...E],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:hC(ce),drawing:n,feeds:i.feedsOf(_,h),today:aZ(u,b.lanes().today,b.facts().hookData,h)},ue=Co(te.metrics)?void 0:te.metrics;e6(g,eZ(b.lanes().sources)),e6(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:DX(te.git,zX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:q3(le.feeds)});let de=[],fe=wX(S,w),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=W3(y.config,y.compiled,b.store,b.registry,le,h,fe,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>de.push(e)},{...S,effects:pe,idleSince:me}),ye=sC(ce),be=new Map(ce.map((e,t)=>[ye[t],e.copy])),xe=()=>a.delivered(_,n.by,be);f.observe(_,h,he.rows.some(e=>e.kind===`menu`),S.menuTimeout);let Se=f.since(_,h);e6(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:w,rows:_C(ee.termRows,n.by===`feed`?Xb.flatMap(e=>{let t=Yb[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=gC(r.get(_,Fi),ce),Ee=Te===null?he:xS(he,vC(ce,Te,_,n.by,we)),De=u.gitProvider.getStats(),Oe=u.usageStore.getStats(),ke=pe.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`config-watch`:case`lifeline`:case`when`:return e.kind}},k=[...oe,...de].map(Me).join(`,`)||`-`;return e6(g,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:Ee.motion,evaluated:String(ge),cellBreaks:String(_e),pending:Ee.pending.join(`,`)||`-`,rules:[...ve].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:O.length>0?`Y`:`N`,clickError:ne.kind===`none`?`-`:ne.kind,upd:String(re.length),ask:String(E.length),warn:k,diag:String(ce.length),warnRecord:Ce?`new`:`kept`,viewer:Te===null?`-`:`${Te.index}/${ce.length}p${Te.page+1}`}),{drawn:{body:Ee,viewerOpen:Te!==null,diagnostics:ce,geometry:we},evaluated:ge,cellBreaks:_e,clickShown:T,delivered:xe,lanes:C}}function g6(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,G1,o);let s=g1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,m1,s)}async function _6(e,t,n,r,i){return g6(e,t),x6(e,t,n,r,i)}function v6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(y6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function y6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:h1(t.requested,n,r),transcript:t.hookData.transcript_path,answered:SF(t.hookData)}}function b6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:y6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function x6(e,t,n,r,i){try{var a=wo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(f6(e,t,n,i));v6(e,t,gK(l.view.source.effective(),Nc(t.hints.tmux)));let u=o.monotonic(),d=r-u;e6(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await bX(e=>Promise.all([oZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${se(e)}`),o.after),m=o.monotonic();e6(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:GX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=h6(e,l,Qb),y=t.sessionId,b=Q3(v,s.following(y)),x=wF(t.hints.client??null)===`statusline`,S=o6[t.encoding](x?S6(y,h,b):h.body);return e6(i,{handoff:(x?b:[]).join(`,`)||`-`,drew:`${Math.round(o.monotonic()-m)}ms`}),{resp:S,motion:h.body.motion,clickShown:g,delivered:_}}catch(e){a.e=e}finally{a.d()}}function S6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:xS(t.body,yC($3(e,[r,...i]),t.diagnostics,e,t.geometry))}const C6=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`]),w6=[[`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`]],T6=[[`workspace.added_dirs`,`string-list`]];function E6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of w6){let i=k6(n,e);if(i==null)t.missingRequired.push(e);else{let n=D6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of T6){let i=k6(n,e),a=i===void 0?r:O6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))C6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function D6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function O6(e){return Array.isArray(e)&&e.every(e=>D6(e)===`string`)?`string-list`:D6(e)}function k6(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 A6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function j6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-40-n.monoMs)}function M6(e,t){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:gF(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function N6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Nt.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Nt.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function P6(e,t,n){let{report:r}=E6(e.hookData),i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);let a=Y$(e.hookData?.session_id);a.ok||i.push(`field 'session_id' ${a.problem}`),(typeof e.cwd!=`string`||!l(e.cwd))&&i.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&i.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let o=N6(e.encoding);o.ok||i.push(o.problem);let s=A6(e.deadline);if(s.kind===`refused`)return{ok:!1,problems:[...i,s.problem]};if(i.length>0||!a.ok||!o.ok)return{ok:!1,problems:i};for(let e of r.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let c=Ft(e),{configFile:u,refusedArgs:d}=M6(e.args,e.cwd);return{ok:!0,req:{...e,deadline:s,encoding:o.encoding,sessionId:a.id,hints:c,rateLimits:Ote(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:yF(u,c.configEnv)},refusedArgs:d}}}function F6(e,t){switch(e){case`vars`:return{what:e,vars:I6(t)};case`segments`:return{what:e,segments:V6(t)};case`config`:return{what:e,config:G6(t)}}}function I6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=z6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=L6(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:R6(r.lastUpdatedMs())})}return o}function L6(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 R6(e){return e===null?null:Math.max(0,Date.now()-e)}function z6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,B6(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}`,B6(i));return t}function B6(e){return e.kind}function V6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=U6(n),o=H6(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:W6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function H6(e){let t=new Map;for(let n of bw(e.presets))for(let r of Wy(Cw(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=By(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function U6(e){let t=[],n=new Set;for(let r of Wy(cw(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 W6(e,t,n){let r=new Set([...rT(e,t).keys()].flatMap(e=>dT(e,n)));return Array.from(r).sort()}function G6(e){return e===null?null:e.config}const K6=[`vars`,`segments`,`config`];function q6(e){return typeof e==`string`&&K6.includes(e)}const J6=e=>({resp:e,exitAfterFlush:null,delivered:i6}),Y6=e=>({kind:`reply`,...e}),X6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},Z6=(e,t)=>Y6(J6({ok:!1,error:t,code:e,daemonV:3}));function Q6(e){let t=Y$(e.sessionId);if(!t.ok)return Z6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return Z6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Xb.join(`, `)}): it predates the lane toggles — update it`);let n=ix(e.lane);return n===null?Z6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Xb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function $6(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?Z6(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?Q6(t):typeof t.kind!=`string`||!Object.hasOwn(X6,t.kind)?Z6(`BAD_REQUEST`,`unknown kind`):Y6(await e8(e,t,n,r,i)):(t.v>3?e.log(`info`,`version mismatch: client=${t.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${t.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${t.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:t.v>3?0:null,delivered:i6})}async function e8(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,effectSessions:p,menuIdle:m,journalTurns:h,sessionState:g,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:i6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return J6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return J6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:t8(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:Mo(),renderCache:c.stats,effectCache:p.getStats(),menuIdle:m.getStats(),journalTurns:h.getStats(),sessionState:{sessions:g.size(),observers:g.observers(),revision:g.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(BM(o.date())),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:AQ(ee)})});if(t.kind===`render`){let c=o.date(),l=BM(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=P6(t,a,e.log),h=(e,t)=>x.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Uo(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:kte(e.hookData),frame:t},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await _6(e,m.req,l,u+j6(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u}),f).then(({resp:e,motion:t,clickShown:n,delivered:r})=>(h(m.req,t),{outcome:{kind:`ok`},resp:e,delivered:()=>{r(),n!==null&&gc(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:a6(e),delivered:i6})):u8(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,e6(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=r6(`render`,f,_.outcome,Math.round(o.monotonic()-u));return e.log(v,y),{resp:_.resp,exitAfterFlush:null,delivered:_.delivered}}if(t.kind===`click`){let a=o.monotonic(),s=[[`queued`,`${Math.round(a-r)}ms`]],c=await a8(e,t,s,()=>n()||i());e6(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=r6(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),J6(c8(c))}if(t.kind===`debug`){if(!q6(t.what))return J6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${K6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?i8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Lx(`colorCompatibility`)):r8};return J6({ok:!0,debug:F6(t.what,n)})}throw Error(`no reply for request ${se(t)}`)}function t8(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const n8={endcaps:Lx(`endcaps`),colorCompatibility:Lx(`colorCompatibility`),wrap:Lx(`autoWrap`),padding:Lx(`padding`),width:1/0},r8=new Map;function i8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,QS(i,{...n8,colorCompatibility:t}));return n}async function a8(e,t,n,r){let{verb:i,value:a}=t;if(typeof i!=`string`||typeof a!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof i} and ${typeof a}`]};try{return await s8(e,i,a,{via:`link`,handler:Gt(t.clientVersion)},n,r)}catch(e){return e instanceof J?{kind:`bad-request`,problems:[e.message]}:e instanceof UC?{kind:`closing`,error:e}:e instanceof WC?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const o8={link:`verb`,"tmux-status":`linkVerb`};async function s8(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return e6(i,{verb:t}),l8(e,n,i,a);let c=v0.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};e6(i,{[o8[r.via]]:t});let l=l0(t,n),u=l?.ok?l.id:null;l===null?e6(i,{sid:`-`}):u!==null&&(e6(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>e6(i,{placeWait:`${e}ms`}),gatherTook:e=>e6(i,{gather:`${e}ms`}),turnWaited:e=>e6(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function c8(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`:case`closing`:case`abandoned`:return a6(e.error)}}async function l8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(e6(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=GC(()=>ks(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):s8(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await $$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log),{kind:`ok`}}const u8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:i6});function d8(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function f8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function p8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o}=e,s=Ne(o),c=t.map(e=>({path:e,stamp:d8(e,r)})),l=c.filter(({stamp:e})=>e.kind!==`failed`),u=null,d=!1,f=()=>{d=!0,u&&clearInterval(u)},p=async()=>{if(!d)for(let{path:e,stamp:t}of l){let n=d8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!f8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(d)return;if(r){s([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),f(),a();return}}},m=()=>p().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of c)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);u=setInterval(()=>void m(),n),u.unref()},checkNow:m,close:f}}function m8(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var h8=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};const g8=`pass`,_8={okMs:5*6e4,failedMs:45e3};function v8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function y8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function b8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function x8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:o.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Rc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${zc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function S8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function C8(e){e.missed=!0,mX(e,`unread`)}function w8(e,t){return e.missed&&e.reading.get().kind===`pending`&&pX(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function T8(e,t){let n=_X(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:_X(t)})}function E8(e){return t=>I(`${e} threw: ${String(t)}`)}var D8=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,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new mN(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 wT({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 xX(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>T8(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new fN,watch:this.followWatch(e,null).watch,period:new h8(()=>{n.refresh.share(g8,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=x8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(g8,()=>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&&C8(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(g8,()=>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:dX(),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=b8(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(y8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(E8(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,pX(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of FY(n.value))c.add(e)});let l=S8(o),u=a===null||i.length===0?`-`:l===void 0?w8(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,v8(n),c.size===0?P(null):I([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new h8(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:dX(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(E8(`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?(C8(t),`owed`):(mX(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,pX(t,a.outcome),t.period.landed(m8(_8,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(E8(`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=${L(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||(pX(t,i),t.period.landed(m8(_8,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())hX(n,t);e.pr!==null&&hX(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},O8=class{static CACHE_DIR=pt();static USAGE_CACHE_DIR=o.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=o.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=o.join(this.LOCKS_DIR,e);if(!f.existsSync(t))return!1;try{let n=f.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${e}, removing stale lock`),f.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(k(`Removing stale lock file ${e} for dead process ${r}`),f.unlinkSync(t),!1):(k(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return k(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=o.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await f.promises.writeFile(n,i,{flag:`wx`}),k(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ye(50);else throw e}return k(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=o.join(this.LOCKS_DIR,e);try{await f.promises.unlink(t),k(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&k(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([f.promises.mkdir(this.CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return w(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=o.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){k(`Cache for ${e} is locked, waiting...`),await ye(75);continue}try{let r=await f.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(k(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(k(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return k(`No shared ${e} usage cache found`),null;k(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ye(75)}}return k(`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)){k(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=o.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await f.promises.writeFile(r,i,`utf-8`),k(`[CACHE-SET] ${e} disk cache stored`)}catch(t){k(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const k8={"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 A8=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 O8.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await O8.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ve({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){k(`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)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(k8).length} models`),this.executionCache=k8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(k8).length} models`),k8)}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 k(`[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),k(`[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`}},j8=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}},M8=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:()=>_X(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,mX(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:dX(),holders:0,flight:null,changed:!1,superseding:0,revisit:N8(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();F8(()=>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{pX(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(),hX(e,I(`${this.spec.name} entry dropped`))}};function N8(e,t){if(e===null)return new P8(t.holdReturned);let n=new h8(t.period);return{landed:t=>n.landed(m8(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var P8=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 F8(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function I8(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 L8={okMs:60*1e3,failedMs:10*1e3},R8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},z8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function B8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function V8(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function H8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const U8={entries:0,cost:0,breakdown:H8(),days:new Map};async function W8(e,t){let n=B8(new Date(V8())),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 A8.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=B8(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...R8};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 G8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function K8(e){let t=0,n=0,r=H8(),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)??{...R8};G8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:z8,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 q8(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function J8(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!q8(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...R8};G8(r,t),n.set(e,r)}return n}async function Y8(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 X8(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function Z8(e,t){(0,Y.runInAction)(()=>e.set(t))}var Q8=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new j8;scans;daySets=new Map;speedFlight=new j8;requestFlight=new j8;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Pe,this.ledger=e.ledger??new mN(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new M8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${L(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??L8,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=To(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(X8(t.kind===`ok`?t.value.sessionInfo:z8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await SX(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return So;let r=n.failure.get();return r===null?P(X8(n.record?.sessionInfo??z8,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=${L(e)}`,`request`,a,Date.now()-i),Z8(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=bZ(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=B8(VM(n)),o={...R8},s=e.sums.get(a);s!==void 0&&G8(o,s);let c=q8(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&G8(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 Z8(this.hold(e).speed,t),t;let r=I8(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 Z8(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??So: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,Y.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:Y.observable.box(null),speed:Y.observable.box(void 0,{deep:!1})};return(0,Y.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=>u(e,`projects`)+d),i={roots:r,sums:new IT(`today over ${e.join(`,`)}`,()=>J8(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await CZ(e,c(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of MZ(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 NZ(e,r,U8,W8);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 MZ(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...K8(i),mainStamp:a})}async scan(e){try{let t=V8(),n=await xZ(e),r=[];for(let e of n){let n=await SZ(ko(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=u(e,i),a=await SZ(Ao(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Eo(a)})}}let i=[],a={hits:0,misses:0};return await Y8(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=${L(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=B8(new Date(e)),n=0,r=0,i=0;return(0,Y.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,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},$8=class{values=Y.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,Y.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)}})}},e5=class{sessions;constructor(e,t,n,r=Pe,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new $8(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=To(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 NZ(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${L(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 MZ(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??So}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function t5(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 n5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(void 0,t5,(e.ledger??new mN(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 k(`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);k(`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,r5(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,r5(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),F):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function r5(e){return e.context_window?.context_window_size??2e5}const i5={messageCount:0,nonPrompts:0,recent:[]},a5=new Set([`turn`,`interrupt`,`claude-code`]);function o5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!a5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function s5(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 c5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(i5,o5,(e.ledger??new mN(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?l5(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:l5(e,n,r)}};function l5(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:s5(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 u5={command:null,todos:[],pending:[],done:[]};function d5(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 f5(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 p5(e,t){if(t.isSidechain)return e;let n=f5(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=d5(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 m5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>d5(e,t.name),[]),done:e.done}}var h5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(u5,p5,(e.ledger??new mN(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return g5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:g5(e,t)}};function g5(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(m5(t.value))}const _5=3e4;var v5=class{names;constructor(e){let t=e.logger??Pe;this.names=new M8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${L(e.pane)} socket=${L(e.socket)}`,read:t=>y5(e.launcher,t),every:{okMs:_5,failedMs:_5},maxEntries:64,logger:t,ledger:e.ledger??new mN(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function y5(e,t){let n=await oc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return I(n.reason);let r=n.stdout.trim();return r?P(r):F}const b5=6e4,x5={okMs:b5,failedMs:b5};function S5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function C5(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var w5=class{name;user;constructor(e={}){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:x5,maxEntries:1,logger:t,ledger:e.ledger??new mN(t)};this.name=new M8({...n,name:`host.name`,read:()=>C5(`name`,()=>S5(E.hostname()))}),this.user=new M8({...n,name:`host.user`,read:()=>C5(`user`,()=>E.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()}},T5=class{known=new $8(64);refreshes;constructor(e=Pe,t=new mN(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=E5(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=CL(e);return this.refreshes.recorded(`path=${L(e)} stamp=${L(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??So}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function E5(e){try{let t=f.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Eo(t)}catch(e){return`unread:${e.code??`error`}`}}const D5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function O5(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 k5=class{known=new $8(256);refreshes;constructor(e=Pe,t=new mN(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=To(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??So}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 A5(t);return this.refreshes.recorded(`sid=${L(e)} stamp=${L(n)}`,`request`,i,Date.now()-r),i}};async function A5(e){let t=await j5(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function j5(e){for(let t of[65536,1048576]){let n=await zo(e,t);if(n.kind!==`ok`)return n;let r=M5(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function M5(e,t){let n=e.toString(`utf8`).split(`
484
+ `);n.push(e[0]);for(let r=1;r<e.length;r++)t.push(n),n=[e[r]]}return t.push(n),t}function v4(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 y4=e=>e.kind===`failed`?x0:e;function b4(e,t){return t.kind===`shown`||t.kind===`failed`&&e.kind===`pending`?e:t}function x4(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 S4(e){return{...e,cells:e.cells.map(D0)}}function C4(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,...w4(e,r)]}function w4(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 T4(e,t){let n=(e,r)=>t(e)?e.kind===`segment`?[{cells:[{name:e.name,address:r,settings:e.settings}],band:`own`,place:`flow`}]:C4(e.direction,e.children.map((t,i)=>n(t,[...r,E4(e,i)]))):[];return n(e,[]).map(e=>[...e.cells])}function E4(e,t){return e.steps[t]}function D4(e){if(e.kind===`segment`||e.unit===!0)return{width:1,reach:1};let t=O4(e);return{width:k4(t),reach:A4(t)}}function O4(e){let t=e.children.map(D4),n=n=>e.direction===`vertical`&&t.slice(0,n).some(({width:e})=>e>0);if(e.direction===`vertical`||e.unit===!0)return t.map((e,t)=>({start:0,span:e,ownLine:n(t)}));let r=0;return t.map((e,t)=>{let i=r;return r+=e.width,{start:i,span:e,ownLine:n(t)}})}const k4=e=>e.reduce((e,{span:t,ownLine:n})=>e+(n?0:t.width),0),A4=e=>e.reduce((e,{start:t,span:n})=>Math.max(e,t+n.reach),0);function j4(e,t){let n=O4(e);if(t?.axis===`cell`)return n.map(({start:e,span:n,ownLine:r})=>{let i=t.index+e;return r?{...t,index:i,lineStart:i,lineEnd:i+n.width-1}:{...t,index:i}});let r=zy[e.direction],i=pv(e.distribution),[a,o,s]=r===`row`?[n.map((e,t)=>t),n.length,n.length-1]:[n.map(({start:e})=>e),A4(n),k4(n)-1];return a.map(e=>({index:e,count:o,distribution:i,axis:r,lineStart:0,lineEnd:s}))}const M4={compile(e,t){let n=j4(e,t.at);return{kind:`container`,direction:e.direction,when:t.when,steps:n,children:e.children.map((e,r)=>t.compileChild(e,Gy(t.path,r),n[r]))}},render(e,t){return t.gate.kind===`failed`&&t.gate.report(),C4(e.direction,e.children.map((n,r)=>t.renderChild(n,y4(t.gate),E4(e,r))))}},N4={drop:e=>e.place,above:()=>`above`},P4={drop:(e,t)=>({lead:t(),stays:e}),above:e=>({lead:e.slice(0,1).flatMap(e=>e.cells),stays:e.slice(1)})},F4={compile(e,t){return{kind:`segment`,when:t.when,name:e.name,id:By(e),settings:t.placementSettings(e),...e.opens!==void 0&&{opens:{open:t.parse(vi(e.opens.ref),`opens`),body:t.compileChild(e.opens.body,Ky(t.path),void 0),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,I4(e,t))};function I4(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=aN(t.scope,e.settings);if(t.gate.kind===`failed`)return H4(e,r,t,t.gate.message);try{let i=t.placement(e),a=b4(t.gate,i.gate());if(a.kind===`failed`)return H4(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 H4(e,r,t,s.message);let c=JC(e.settings.theme,t.palette),l={id:e.id,effect:e.settings.effect,ground:oF(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`?L4(f.variable):R4(()=>i.evaluate(c,t.region)),m=p.kind===`drawn`?z4(p.segment,u):B4(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:x0,h.disclosure).map(e=>({...e,place:N4[v.placement](e)})),b=(e,t,n)=>A0(L0([e],t),{...u(t),width:`auto`,padding:n}),x=y.findIndex(e=>e.band===`own`),{lead:S,stays:C}=v!==void 0&&x!==-1?P4[v.placement](g,()=>b(t.closeDisclosure(v.key),h.close,t.padding)):{lead:[],stays:g},ee=S.flatMap(e=>b(new G(` `.repeat(V4(E0(e)))),h.trigger,0)),w=(e,t)=>e.band===`own`?t===x?S:ee:[],te=y.map((e,t)=>({cells:[...w(e,t),...e.cells],band:`deeper`,place:e.place})),ne=[...C,..._];return t.perSegmentSink!==void 0&&t.perSegmentSink.set(e.id,[...ne.flatMap(e=>e.cells),...y.flatMap(w)].flatMap(E0)),[...ne,...te]}catch(n){return H4(e,r,t,n.message??String(n))}}const L4=e=>({kind:`waiting`,variable:e});function R4(e){try{return{kind:`drawn`,segment:e()}}catch(e){let t=NT(e);if(t===void 0)throw e;return L4(t.variable)}}function z4(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:_4(L0(r,c)).map((e,t)=>({cells:A0(e,{...l,lead:t===0?L0(i,c):[],trail:t===0?L0(a,c):[]}),band:`own`,place:`flow`})),drops:o.map(e=>({cells:A0(L0([e],n.band),{...l,baseStyle:n.band}),band:`deeper`,place:`flow`}))}}function B4(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=L0(U4(e.lead,e,t,n),l),d=L0(U4(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 A0(L0([new G(r?`…`:` `)],l),{...o(l),width:e,justify:`left`,truncate:`right`,lead:r?u:[],trail:r?d:[]})}),band:`own`,place:`flow`})),drops:[]}}function V4(e){return e.reduce((e,t)=>e+t.cellLength,0)}function H4(e,t,n,r){n.onSegmentError?.(e.id,r);let i=r.replace(/\s*\n\s*/g,` `);return[{cells:A0([new G(`⚠ ${e.id}: ${i}`,{end:``})],{width:`auto`,justify:`left`,truncate:`right`,padding:0,placement:{id:e.id,effect:`bar`,ground:oF(n.palette)},lead:U4(e.lead,e,t,n),trail:U4(e.trail,e,t,n)}),band:`own`,place:`flow`}]}function U4(e,t,n,r){if(e===void 0)return[];try{return r.evaluateOnce(t,n,r.palette,e).fragments}catch(e){let n=NT(e);return n===void 0?r.onSegmentError?.(t.id,e.message??String(e)):r.waited(n.variable),[]}}const W4={container:M4,segment:F4};function G4(e){return W4[e]}var K4=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?q4:{kind:`drew`,drawing:i}),r},rule:(e,t)=>r.set(e,t),commit:()=>{this.last={source:e,placements:n,rules:r}}}}};const q4={kind:`hidden`},J4={palette:`theme`,style:`style`,effect:`effect`},Y4=Kx.get(`colorCompatibility`),X4={width:0,chromeCols:0,padding:0,seamCols:0,preset:``};function Z4(e){try{return{ok:!0,value:e()}}catch(e){return{ok:!1,error:e}}}function Q4(e){if(e.ok)return e.value;throw e.error}const $4=e=>({read:()=>e}),e3=k_({basePalette:O_,palette:O_,decor:Wv});var t3=class{evaluated=0;memory=new K4;scope;binding;facts;look=Y.observable.box(void 0,{deep:!1,equals:(e,t)=>e!==void 0&&t!==void 0&&e3(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=Y.observable.box(r,{deep:!1}),this.scope=rN(e),this.depth=e.derive(`drawn depth`,`computed`,()=>{let e=this.inputAt(Y4);return typeof e==`string`&&Oy(e)?e:`truecolor`});let i=(0,Y.observable)(X4,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 T4(e,e=>this.shown(e)).map(e=>e.flatMap(({name:e,address:n,settings:r})=>{let i=Pz(e);return i===void 0?[]:[{name:i,address:n,palette:JC(r.theme,t)}]}))}),t.bindInputs({read:e=>this.inputAt(e),drawnAt:()=>ky(this.colorCompatibility())})}bind(e){(0,Y.runInAction)(()=>this.view.set(e))}selections(){return this.view.get().selections()}draw(e,t){this.draws++,this.projected=t,this.drawnSlots.clear(),(0,Y.runInAction)(()=>Object.assign(this.facts,e))}inputAt(e){let t=HN(e);return t===void 0?BN(e)===void 0?kN(this.view.get().payload(),e):kN(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()[J4[e]];if(t.kind===`decided`)return i3(t.name,null,null);let r=o3(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=s3(this.source,e,i.name,r.where,e=>{t=e}),i3(n,t,null)}case`pending`:return i3(n??hy[e],null,i.variable);case`failed`:return n=hy[e],i3(n,gy(r.where,e,`the rule failed — ${i.error}`),null)}},i;t=this.store.derive(`slot ${e}`,`computed`,()=>{let e=r();return(i===void 0||!a3(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)??hy[e]}drawnSlot(e,t){this.drawnSlots.set(e,t)}draws=0;publishLook(e){(0,Y.runInAction)(()=>this.look.set(e))}gate(e){let{when:t}=e;if(t===void 0)return C0(t,this.scope);let n=this.gates.get(e);return n===void 0&&(n=this.derive(`when`,this.readsInstant(t),()=>C2(this.source.activeSegment,()=>C0(t,this.scope))),this.gates.set(e,n)),n.read()}placement(e){let t=this.placements.get(e);return t===void 0&&(t=new c3(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:U0(this.source.runtime,this.binding);try{return{kind:`named`,name:e.evaluate(this.scope).map(e=>e.plain).join(``)}}catch(e){let t=NT(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:Z4(e)}),Q4(t.answer))}shown(e){let t=this.gate(e);return e.kind===`container`?t.kind===`shown`||t.kind===`pending`:Pz(e.name)===void 0||t.kind===`hidden`?!1:t.kind===`failed`?!0:this.placement(e).gate().kind!==`hidden`}};function n3(e,t,n,r){let i=e.views.get(t);if(i!==void 0)return i.bind(r),i;let a=new t3(t,n,e,r);return e.views.set(t,a),a}function r3(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 i3=(e,t,n)=>({kind:`settled`,name:e,warning:t,waited:n}),a3=(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 o3(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 s3(e,t,n,r,i){switch(t){case`palette`:return $C(n,r,i).name;case`style`:return fy(n,e.styles).name;case`effect`:return Sy(n).name}}var c3=class{where=l3(k_({palette:O_,region:Hv}));ground=l3(k_({colours:d3,bodyOpen:O_}));opened=l3(k_({colours:d3,open:O_}));ownGate;open;colours;body;affixes;constructor(e,t){let n=e.source.segments[t.name],r=e.source.activeSegment,i=aN(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?$4(S0):e.derive(`${t.id} when`,e.readsInstant(a),()=>C2(r,()=>C0(a,i))),this.open=d===void 0?$4(x0):e.derive(`${t.id} body gate`,e.readsInstant(d),()=>C2(r,()=>C0(d,e.scope))),this.colours=e.derive(`${t.id} colours`,e.readsInstant(o,s),()=>{let{palette:n,region:a}=this.where.get();return m3(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 h3(r,t,e,c,n,i)}),this.affixes=l===void 0&&u===void 0?$4(_3):e.derive(`${t.id} affixes`,e.readsInstant(l,u),()=>{let{colours:e,open:n}=this.opened.get();return g3(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}),y3(n,r,this.affixes.read())}};function l3(e){let t=Y.observable.box(void 0,{deep:!1,equals:(t,n)=>t!==void 0&&n!==void 0&&e(t,n)});return{set:e=>(0,Y.runInAction)(()=>t.set(e)),get:()=>t.get()}}const u3=(e,t)=>e.hex===t.hex,d3=k_({palette:O_,drawnAt:O_,tint:u3,text:u3,bg:u3,disclosure:Gv});function f3(e,t){return{segName:e.name,placementId:e.id,palette:t.palette,disclosure:t.disclosure,tint:t.tint,text:t.text}}const p3=e=>zv(e.palette,e.disclosure,e.drawnAt);function m3(e,t,n,r,i,a,o,s){let c={palette:n,drawnAt:i,...Zv(n,r,i)};return S2(e,f3(t,c),e=>{let t=Ste(e,i,a,o,s);return{...c,bg:e.bg,style:t}})}function h3(e,t,n,r,i,a){return S2(e,f3(t,n),e=>(e.bg=i?p3(n).state:n.bg,{fragments:r.evaluate(a),drops:e.drops,open:e.drops.length>0||i}))}function g3(e,t,n,r,i,a,o){return S2(e,f3(t,n),e=>(e.bg=r?p3(n).state:n.bg,{lead:i?.evaluate(o)??[],trail:a?.evaluate(o)??[],drops:e.drops}))}const _3={lead:[],trail:[],drops:[]};function v3(e){let{palette:t,drawnAt:n,disclosure:r}=e;return{closed:e.style,get trigger(){return a2(t,p3(e).state,n)},get band(){return a2(t,p3(e).plane,n)},get close(){return c2(t,p3(e).state,n)},disclosure:r}}function y3(e,t,n){return{styles:v3(e),fragments:t.fragments,lead:n.lead,trail:n.trail,drops:[...t.drops,...n.drops],open:t.open}}function b3(e,t,n,r,i,a,o){let s=m3(e,t,n,r,i,void 0,void 0,o);return y3(s,h3(e,t,s,a,!1,o),_3)}function x3(e,t,n,r,i){return v3(m3(e,t,n,r,i,void 0,void 0,{}))}function S3(e,t){return{payload:()=>e,selections:()=>t}}function C3(e){if(`ttl`in e)return{kind:`ttl`,durationMs:vN(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 w3(e,t){switch(Yy(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 T3(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:C3(n.cache),parse:w3(n.parse,n.default)});break;case`shell`:e.declareShell(t,n.command,{cwd:r,cache:C3(n.cache),parse:w3(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 E3(e,t){let n=xE.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 D3(e,t,n){let{compiled:r,loadWarnings:i}=k3(e,t,n.cwd,O3(n.signer),N3);return{...r,loadWarnings:i}}const O3=e=>(t,n)=>P3(n,e);function k3(e,t,n,r,i=N3){let a=A3(e),o=j3(a);return{compiled:r(o,a),compileKey:o,loadWarnings:M3(e,t,n,i)}}function A3(e){let{variables:t,...n}=e,r=new Map;for(let[e,n]of qx)n in t&&r.set(e,n);for(let[t,n]of $y(e))r.has(n.key)||r.set(n.key,t);return{config:n,stateReads:[...r].sort(([e],[t])=>e<t?-1:1),projections:[...OU(e)].sort(([e],[t])=>e<t?-1:1)}}function j3(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function M3(e,t,n,r){let i=h4(e),a=OU(e),o=[];for(let[s,c]of uT(e))if(r.has(i.get(s)))try{T3(t,s,c,n,a.has(s)?`projection`:`computed`)}catch(e){o.push(`Variable "${s}": ${e.message??String(e)}`)}return o}const N3=new Set([`directory`,`view`]);function P3({config:e,stateReads:t,projections:n},r){let i={bound:void 0,compiled:new Map,signer:r},a=()=>B0(i,`drawnAt`).registry.drawnAt(),o=b2(a),s={action:i,activeSegment:o},c=Object.keys(e.styles),l=bw(e.presets),u=Cz(e),d=[e=>U2(i,o,e.now)],f=nN({extraFuncs:{...r2(i),...H2(i),...F2(i,o),...R2(i),...J2(i,o),...e4(i,o),...i4(s),...s4(o),styles:{fn:()=>c,argTypes:[],arity:{kind:`exact`}},presets:{fn:()=>l,argTypes:[],arity:{kind:`exact`}}},clockFuncs:d,drawnAt:a}),p=E3(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=W0(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})}},x=t=>{let n=rb(e.segments[t.name]),r=Object.create(null);for(let[e,a]of Object.entries(n))Object.defineProperty(r,e,{enumerable:!0,get:()=>Nee(t,e,a,t=>String(B0(i,`setting ${e}`).store.read(t.variable)))});return Object.freeze(r)},S=(e,t,n)=>{let r={path:t,at:n,when:e.when===void 0?void 0:b(e.when,t,`when`),parse:(e,n)=>b(e,t,n),compileChild:S,placementSettings:x};return G4(e.kind).compile(e,r)},C=new Map;for(let t of l){let{node:n,path:r}=Cw(e,t);C.set(t,S(n,r,void 0))}let ee=new Map(sy.map(e=>[e,new Map]));for(let{at:t,slot:n,rule:r}of AU(e)){let e=t.join(`.`),i=ee.get(n),a=i.get(r);i.set(r,a===void 0?{where:e,template:L3(h,e,r)}:{where:`${a.where}, ${e}`,template:a.template})}let w={reads:xU({names:new Set(n.map(([e])=>e)),helpers:e.helpers,actions:e.actions}),projections:new Map(n),clock:$M(d)},te=NU(w),ne=[...C.values()].flatMap(I3(y)).some(e=>te(m.get(e))),T=ne?NU({...w,clock:new Set([...w.clock,$2])}):te;return{segments:y,roots:C,activeSegment:o,menuRuntime:s,globalExpressions:ee,instant:new Set([...m].flatMap(([e,t])=>T(t)?[e]:[])),layoutReadsInstant:ne,styles:e.styles,runtime:i,views:new WeakMap}}function F3(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 I3=e=>t=>{let n=[];return T4(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 L3(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 R3=e=>{throw Error(`a slot settled on a name its domain refuses: ${e}`)};function z3(e,t,n,r,i){let a=B3(e,t,n.rule(t.template),r,i);return i.settled(e,a),a}function B3(e,t,n,r,i){switch(n.kind){case`named`:return n.name;case`pending`:return i.waited(n.variable),i.held(e)??hy[e];case`failed`:return r({kind:`rule`,slot:e,message:gy(t.where,e,`the rule failed — ${n.error}`)}),hy[e]}}function V3(e){return H3(e).filter(e=>!e.name.startsWith(ki)).map(e=>e.id)}function H3(e){return e.kind===`container`?e.children.flatMap(H3):[e,...e.opens===void 0?[]:H3(e.opens.body)]}function U3(e,t,n,r,i,a){let o={...r,term:{cols:i.width},colorCompatibility:{effective:i.colorCompatibility}};return n3(e,t,n,S3(o,a)),o}function W3(e,t,n,r,i,a,o,s,c){try{var l=wo();let{perSegmentSink:u,onSegmentError:d,onRenderWarning:f}=s??{},p=e=>f?.(e),m=c.effects??new hS(``),h=m.clockAt(a,vy[c.animationSpeed]),g=l.u(UM(a,h.timeline)),_=r3(t,n),v={...o,colorCompatibility:_.colorCompatibility()};_.draw({width:v.width,chromeCols:WS(v),padding:v.padding,seamCols:GS(v),preset:c.preset},i);let y=_.evaluated;l.u(U0(t.menuRuntime.action,_.binding));let{preset:b,transitions:x}=c,S={variation:Z_[c.variation],shade:H_[c.shade]},C={config:e,preset:b,revision:r.stateRevision(),width:v.width},ee=_.memory.begin(C,x4),w=_.memory.from(C),te=new Set,ne={held:e=>w?.rules.get(e),waited:e=>te.add(e),settled:ee.rule},T=new Map,re=e=>{let n=_.slot(e);if(T.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&&te.add(n.waited),n.name;let r=s3(t,e,z3(e,n.rule,_,p,ne),n.rule.where,t=>p({kind:`rule`,slot:e,message:t}));return _.drawnSlot(e,r),r},{theme:E,style:D,effect:ie}=_.selections(),O=E.kind===`decided`?E:$C(re(`palette`),``,R3),ae=D.kind===`decided`?D:fy(re(`style`),e.styles),oe=ie.kind===`decided`?ie:Sy(re(`effect`)),se=O.value,ce=XC(se,ae.value);_.publishLook({basePalette:se,palette:ce,decor:S});let le=ce.get(`warning`),ue=c.idleSince===void 0?null:{idleSince:c.idleSince,timeoutS:c.menuTimeout,fill:le,text:kv(ce,le,r.drawnAt())},de=m.motion(oe.value,h,{transitions:x,source:C,last:w,returned:x4,hold:S4},ue);u?.clear();let fe=t=>e.segments[t],pe=(e,i,a)=>{let o=i.kind===`hidden`?i:b4(i,_.gate(e)),s=o.kind===`failed`?{...o,report:()=>{let t=`when over ${V3(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:ce,gate:s,padding:v.padding,region:a,perSegmentSink:u,onSegmentError:d,placement:e=>_.placement(e),evaluateOnce:(e,n,i,o)=>b3(t.activeSegment,e,i,a,r.drawnAt(),o,n),lookupSegment:fe,renderChild:(e,t,n)=>pe(e,t,Yv(a,n)),renderBody:(e,t,n)=>pe(e,t,Xv(n)),closeDisclosure:e=>i2(n,e),placed:(e,t)=>ee.placed(e,de.placed(e,t)),lastDrawn:e=>w?.placements.get(e),waited:e=>te.add(e),decorations:(e,n)=>x3(t.activeSegment,e,n,a,r.drawnAt())};return G4(e.kind).render(e,c)},me=t.roots.get(b);if(me===void 0)throw Error(`Preset "${b}" has no compiled layout — registerDslConfig compiles one per declared preset and effectivePresetName collapses unknown names to "${vw}"; a miss here is merge/policy drift (have: ${[...t.roots.keys()].join(`, `)})`);let he=v4(pe(me,S0,Jv(S))).map(({line:e,row:t})=>{let n=F0(e.cells,v),r=e.band===`deeper`?`menu`:`bar`;return{kind:r,cellBreaks:n.length-e.cells.length,...ZS(n.map(e=>e.owner),v,de.row(t,r,n))}});de.drawn(),ee.commit();let ge=()=>he.some(e=>e.kind===`menu`)||_.selections().effect.kind===`expression`||x||H3(me).some(({settings:e})=>e.effect!==`bar`&&e.effect!==`none`),_e=Math.min(g.heard(),...he.map(e=>e.nextChange)),ve=Number.isFinite(_e)?`moves`:ge()?`can-move`:`still`;for(let[e,t]of r.cachePolicyFaults())p({kind:`refresh`,variable:e,error:t.message,message:`variable "${e}" cannot refresh: ${t.message}`});return{frame:{depth:v.colorCompatibility,rows:he.flatMap(({kind:e,lines:t})=>t.map(t=>({kind:e,runs:t}))),nextChange:_e,motion:ve,pending:[...te].sort()},evaluated:_.evaluated-y,cellBreaks:he.reduce((e,t)=>e+t.cellBreaks,0),rules:T}}catch(e){l.e=e}finally{l.d()}}const G3={moving:1e3/30,still:1e3},K3=[`data`,`state`,`reload`,`visibility`];function q3(e){return Xb.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 J3(e,t){let n=e.filter(e=>e>t-1&&e<=t);e.splice(0,e.length,...n,t)}const Y3=(e,t)=>Yb[t].handsOff?e.resp:e.statusline,X3=e=>Math.round(1e3/e);var Z3=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 rx;let r=t-1,i=this.shown(n);return nx(e=>{let a=n.rates.get(e);if(a===void 0)return ex;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,drawMs:0,evaluated:0,cellBreaks: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}close(){for(let e of[...this.feeds.values()])for(let t of[...e.followers.keys()])this.unsubscribe(e,t)}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,t){e.phase={kind:`drawing`};let n=this.deps.now(),r=this.deps.instant(),i=Math.min(Math.max(t,r),r+.002),a=n+(i-r)*1e3;try{this.step(e,n,a,i)}catch(t){if(e.lastStart=a,this.deps.log(`error`,`feed sid=${JSON.stringify(e.sessionId)} threw: ${se(t)}`),this.feeds.get(e.sessionId)!==e)return;this.schedule(e,null,i)}}step(e,t,n,r){let i=this.deps.render(e.sessionId,X3(this.spacingOf(e)),r);if(i===null){e.noView++,e.phase={kind:`waiting`};return}e.lastStart=n;let a=this.deps.now();this.drawn++,e.drawn++,e.drawMs+=a-t,e.evaluated+=i.evaluated,e.cellBreaks+=i.cellBreaks,this.feeds.get(e.sessionId)===e&&(this.countFailure(e,i),this.push(e,i,r),this.feeds.get(e.sessionId)===e&&(a-e.summarizedAt>=6e4&&this.summarize(e,`running`),this.schedule(e,i,r)))}schedule(e,t,n){let{moving:r,still:i}=this.deps.periods,a=((t?.bar.nextChange??1/0)-n)*1e3,o=Math.min(Math.max(a,r),i),s=this.shown(e);o<i&&s&&e.moving++,o<i&&!s&&e.unseen++;let c=s?o:i;this.arm(e,n+c/1e3,this.deps.instant())}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=this.deps.now(),r=Math.max(n,e.lastStart+this.spacingOf(e));if(t.kind===`due`&&t.at<=r)return!1;let i=this.deps.instant();return this.arm(e,i+(r-n)/1e3,i),!0}arm(e,t,n){e.phase.kind===`due`&&clearTimeout(e.phase.timer);let r=Math.max(0,(t-n)*1e3);e.phase={kind:`due`,at:this.deps.now()+r,timer:setTimeout(()=>this.draw(e,t),r)}}shown(e){let t=this.requests.get(e.sessionId);return t===void 0||this.deps.shown(t.req)}countFailure(e,t){t.failure!==null&&e.failed++}push(e,t,n){let r=this.deps.lanes(e.sessionId);if(r!==null)for(let t of[...e.followers.keys()])r[t.lane]||(this.unsubscribe(e,t),this.refuse(e.sessionId,t));if(e.followers.size===0)return;t.delivered();let i={resp:JSON.stringify(t.resp),statusline:JSON.stringify(t.statusline)};if(e.last?.answers.resp===i.resp&&e.last.answers.statusline===i.statusline)return;let a=e.last?.answers??null;e.last={bar:t.bar,answers:i},this.pushed++,e.pushed++,t.failure!==null&&this.deps.log(t.failure.level,t.failure.line);for(let[t,r]of e.rates)(a===null||Y3(a,t)!==Y3(i,t))&&J3(r,n);for(let t of e.followers.keys())this.send(e,t)}send(e,t){if(e.last===null)return;let n=Y3(e.last.answers,t.lane);e.followers.get(t)!==n&&(t.frame(e.last.bar,n),e.followers.set(t,n))}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:vP(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=pN.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} ceiling=${X3(this.spacingOf(e))}fps achieved=${a} evaluated=${e.evaluated} cellBreaks=${e.cellBreaks} woke=${K3.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 Q3(e,t){return Xb.filter(n=>e[n]&&Yb[n].handsOff&&t.has(n))}function $3(e,t){return{severity:rC,lines:[[iC(`[⟲ claude]`,ba([{verb:Xi,args:[e,...t.map(e=>Yb[e].switch.setting)]}]))]]}}function e6(e,t){for(let n of Object.entries(t))e.push(n)}const t6={ok:`info`,"bad-request":`warn`,threw:`error`,closing:`info`,abandoned:`info`};function n6(e){switch(e.kind){case`ok`:return[];case`bad-request`:return[[`problems`,e.problems.join(`; `)]];case`threw`:return[[`error`,se(e.error)]];case`closing`:return[[`closing`,e.error.message]];case`abandoned`:return[[`abandoned`,`1`]]}}function r6(e,t,n,r){let i=[...t,[`took`,`${r}ms`],[`outcome`,n.kind],...n6(n)];return{level:t6[n.kind],line:`${e}${i.map(([e,t])=>` ${e}=${L(t)}`).join(``)}`}}const i6=()=>{},a6=e=>({ok:!1,error:e instanceof Error?e.message:se(e),code:`RENDER_FAILED`,daemonV:3}),o6={ansi:e=>({ok:!0,output:NS(e)}),frame:e=>({ok:!0,frame:e})};function s6(e,t,n,r){let{clock:i,frameFeeds:a}=e,o=i.date().getTime(),s=[];try{try{var c=wo();let i=c.u(p6(e,t,r,s));if(i===null)return null;let{drawn:o,evaluated:l,cellBreaks:u,delivered:d,lanes:f}=h6(e,i,{by:`feed`,fps:n}),p=o6.ansi(o.body),m=S6(t,o,Q3(f,a.following(t)));return{bar:o.body,resp:p,statusline:m===o.body?p:o6.ansi(m),evaluated:l,cellBreaks:u,delivered:d,failure:null}}catch(e){c.e=e}finally{c.d()}}catch(e){let{level:t,line:n}=r6(`render`,s,{kind:`threw`,error:e},i.date().getTime()-o),r=a6(e);return{bar:CS(r.error),resp:r,statusline:r,evaluated:0,cellBreaks:0,delivered:i6,failure:{level:t,line:`frame ${n}`}}}}function c6(e,t,n){let{sessionState:r}=e;return yK(n.config,e=>r.get(t,e),e=>n.authoredRoots.has(e))}function l6(e,t){try{var n=wo();let{renderCache:r}=e,i=n.u(r.holdView(t));return i===null?null:gK(i.view.source.effective(),Nc(i.view.facts().hints.tmux))}catch(e){n.e=e}finally{n.d()}}function u6(e,t,n){try{var r=wo();let{renderCache:i,frameFeeds:a}=e,o=r.u(i.hold(t.projectDir,t.cwd,t.target.path)),s=a.latest(n);return gK(c6(e,n,o.state),s===null||Nc(s.hints.tmux))}catch(e){r.e=e}finally{r.d()}}function d6(e,t,n){e6(n,{sid:e.sessionId,at:t.toFixed(3)});let r=e.hints,i=It(e,r),a=Lt(i);return e6(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 f6(e,t,n,r){let{sessionState:i,renderCache:a}=e,s=t.hookData.workspace?.current_dir??t.cwd,c={...t,hookData:{...t.hookData,...s!==void 0&&o.isAbsolute(s)&&{location:jc(s)}}},l=c.sessionId,u=d6(c,n,r);e6(r,{encoding:c.encoding});let d=h1(c.requested,i,l);return m6(e,a.holdSession(d.projectDir,d.cwd,d.target.path,c),c,u,n,r)}function p6(e,t,n,r){let{renderCache:i}=e,a=i.holdView(t);if(a===null){let e=i.openFailure(t);if(e!==null)throw e.error;return null}let o=a.view.facts(),s;try{s=d6(o,n,r)}catch(e){throw a[Symbol.dispose](),e}return m6(e,a,o,s,n,r)}function m6(e,t,n,r,i,a){let{payloadProviders:o}=e;try{let{entry:e,state:s,view:c}=t,{sessionId:l,hints:u}=n,d=c.source.effective();return{req:n,at:i,facts:a,sessionId:l,entry:e,state:s,view:c,hintsError:r,payloadInputs:{hookData:n.hookData,deps:{...o,lanes:c.lanes},cwd:n.cwd,neededInputPaths:s.neededInputPaths(d.preset),hints:u},[Symbol.dispose]:()=>t[Symbol.dispose]()}}catch(e){throw t[Symbol.dispose](),e}}function h6(e,t,n){let{sessionState:r,frameFeeds:i,renderCache:a,updateWatch:o,linkSigner:s,fileEvents:c,renderWarnings:l,payloadProviders:u,effectSessions:d,menuIdle:f,launcher:p}=e,{req:m,at:h,facts:g,sessionId:_,entry:v,state:y,view:b,hintsError:x}=t,S=b.source.effective(),C=gK(S,Nc(b.facts().hints.tmux));e6(g,{lanes:Xb.filter(e=>C[e]).join(`,`)||`-`});let{hints:ee}=b.facts(),w=UX(ee);e6(g,{width:String(w)});let te=b.source.payload(),ne=aee(r,_,h,n.by),T=ne.kind===`held`||ne.kind===`owed`?ne.error:null,re=o.notice({sessionId:_,dismissed:r.get(_,sq),enabled:S.updateNotice}),E=Eq(v.repos,_,s),D=(e,t)=>({about:e,text:t,copy:t}),ie=e=>D(e??``,e),O=[ie(zt(m.refusedArgs)),ie(x),D(`load`,v.lastError),D(`update-act`,o.error()),...y.dropped.map(e=>({about:`dropped\0${e.file}`,text:e.message,copy:e.prompt})),ie(T?.text)].flatMap(({about:e,text:t,copy:n})=>e&&t&&n?[{about:e,text:t,copy:n}]:[]),ae=v.watch===null?null:vT(`config watch`,v.watch,null),oe=[...Jc(c.delivery()),...p.lifelineWarnings(),...ae===null?[]:[{kind:`config-watch`,message:ae}],...v.lastWarning===null?[]:[{kind:`load`,message:v.lastWarning}]],se={config:y.config},ce=aC(_,n.by,O,[...re,...E],[...oe,...l.ofSession(_,n.by,se)].map(e=>({about:`${e.kind}\0${e.message}`,text:e.message,copy:e.message}))),le={diagnostics:hC(ce),drawing:n,feeds:i.feedsOf(_,h),today:aZ(u,b.lanes().today,b.facts().hookData,h)},ue=Co(te.metrics)?void 0:te.metrics;e6(g,eZ(b.lanes().sources)),e6(g,{prompts:String(ue?.messageCount??`-`),nonPrompts:String(ue?.nonPrompts??`-`),pr:DX(te.git,zX(t.payloadInputs.neededInputPaths).showPullRequest===!0),feeds:q3(le.feeds)});let de=[],fe=wX(S,w),pe=d.of(_),me=f.since(_,h),{frame:he,evaluated:ge,cellBreaks:_e,rules:ve}=W3(y.config,y.compiled,b.store,b.registry,le,h,fe,{perSegmentSink:b.lastRenderCellsBySegment,onRenderWarning:e=>de.push(e)},{...S,effects:pe,idleSince:me}),ye=sC(ce),be=new Map(ce.map((e,t)=>[ye[t],e.copy])),xe=()=>a.delivered(_,n.by,be);f.observe(_,h,he.rows.some(e=>e.kind===`menu`),S.menuTimeout);let Se=f.since(_,h);e6(g,{menuIdle:Se===void 0?`-`:`${(h-Se).toFixed(1)}s/${S.menuTimeout}s`});let Ce=l.drawn(_,n.by,se,de),we={width:w,rows:_C(ee.termRows,n.by===`feed`?Xb.flatMap(e=>{let t=Yb[e].rows;return C[e]&&t!==null?[t]:[]}):[]),colorCompatibility:he.depth},Te=gC(r.get(_,Fi),ce),Ee=Te===null?he:xS(he,vC(ce,Te,_,n.by,we)),De=u.gitProvider.getStats(),Oe=u.usageStore.getStats(),ke=pe.lastFrame(),Ae=ke.own.map(e=>`${e.placement}:${e.effect}@${e.t.toFixed(3)}`).join(`,`)||`-`,je=e=>e.map(e=>`${e.placement}@${e.t.toFixed(3)}`).join(`,`)||`-`,Me=e=>{switch(e.kind){case`rule`:return`rule:${e.slot}`;case`refresh`:return`refresh:${e.variable}`;case`file-events`:return`${e.kind}:${e.state}`;case`load`:case`config-watch`:case`lifeline`:case`when`:return e.kind}},k=[...oe,...de].map(Me).join(`,`)||`-`;return e6(g,{git:`${De.size}/${De.hits}h/${De.misses}m`,usage:`${Oe.size}/${Oe.hits}h/${Oe.misses}m`,effect:ke.effect,effectT:ke.t.toFixed(3),speed:`${ke.speed}x`,effectRows:`${ke.made}made/${ke.reused}reused`,effectOwn:Ae,fadeBasis:ke.basis,stateRev:String(ke.revision),fades:je(ke.fades),leaves:je(ke.leaves),motion:Ee.motion,evaluated:String(ge),cellBreaks:String(_e),pending:Ee.pending.join(`,`)||`-`,rules:[...ve].map(([e,t])=>`${e}:${t}`).join(`,`)||`-`,err:O.length>0?`Y`:`N`,clickError:ne.kind===`none`?`-`:ne.kind,upd:String(re.length),ask:String(E.length),warn:k,diag:String(ce.length),warnRecord:Ce?`new`:`kept`,viewer:Te===null?`-`:`${Te.index}/${ce.length}p${Te.page+1}`}),{drawn:{body:Ee,viewerOpen:Te!==null,diagnostics:ce,geometry:we},evaluated:ge,cellBreaks:_e,clickShown:T,delivered:xe,lanes:C}}function g6(e,t){let{sessionState:n}=e,r=t.sessionId,{client:i,...a}=t.hints,o=JSON.stringify(a);n.get(r,`client-hints`)!==o&&n.set(r,G1,o);let s=g1(t.requested);n.get(r,`render-origin`)!==s&&n.set(r,m1,s)}async function _6(e,t,n,r,i){return g6(e,t),x6(e,t,n,r,i)}function v6(e,t,n){let{laneSetups:r,tmuxStatusLines:i}=e;r.noted(y6(e,t),n),i.observe(t.hookData.session_id,t.hints.tmux,n.tmuxStatus)}function y6(e,t){let{sessionState:n}=e,r=t.hookData.session_id;return{sessionId:r,hints:t.hints,origin:h1(t.requested,n,r),transcript:t.hookData.transcript_path,answered:SF(t.hookData)}}function b6(e,t,n,r){let{frameFeeds:i,laneSetups:a,tmuxStatusLines:o}=e,s=i.latest(t);a.clicked(t,s===null?null:y6(e,s),n,r),s!==null&&n.tmuxStatus!==r.tmuxStatus&&o.observe(t,s.hints.tmux,r.tmuxStatus)}async function x6(e,t,n,r,i){try{var a=wo();let{clock:o,frameFeeds:s,log:c}=e,l=a.u(f6(e,t,n,i));v6(e,t,gK(l.view.source.effective(),Nc(t.hints.tmux)));let u=o.monotonic(),d=r-u;e6(i,{deadline:`${t.deadline.kind}:${Math.round(d)}ms`});let f=new Map,p=await bX(e=>Promise.all([oZ(l.payloadInputs,n,f),l.view.registry.inFlight(e)]),d,e=>c(`error`,`render wait failed after its deadline sid=${JSON.stringify(l.sessionId)}: ${se(e)}`),o.after),m=o.monotonic();e6(i,{waited:`${Math.round(m-u)}ms`,ended:p,refreshed:GX(f)});let{drawn:h,clickShown:g,delivered:_,lanes:v}=h6(e,l,Qb),y=t.sessionId,b=Q3(v,s.following(y)),x=wF(t.hints.client??null)===`statusline`,S=o6[t.encoding](x?S6(y,h,b):h.body);return e6(i,{handoff:(x?b:[]).join(`,`)||`-`,drew:`${Math.round(o.monotonic()-m)}ms`}),{resp:S,motion:h.body.motion,clickShown:g,delivered:_}}catch(e){a.e=e}finally{a.d()}}function S6(e,t,n){let[r,...i]=n;return r===void 0||t.viewerOpen?t.body:xS(t.body,yC($3(e,[r,...i]),t.diagnostics,e,t.geometry))}const C6=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`]),w6=[[`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`]],T6=[[`workspace.added_dirs`,`string-list`]];function E6(e){let t={missingRequired:[],typeMismatches:[],unknownTopLevelFields:[]},n=typeof e==`object`&&e&&!Array.isArray(e)?e:{};for(let[e,r]of w6){let i=k6(n,e);if(i==null)t.missingRequired.push(e);else{let n=D6(i);n!==r&&t.typeMismatches.push({path:e,expected:r,got:n})}}for(let[e,r]of T6){let i=k6(n,e),a=i===void 0?r:O6(i);a!==r&&t.typeMismatches.push({path:e,expected:r,got:a})}for(let e of Object.keys(n))C6.has(e)||t.unknownTopLevelFields.push(e);return{data:e,report:t}}function D6(e){return Array.isArray(e)?`array`:typeof e==`string`&&!e.isWellFormed()?`ill-formed string`:typeof e}function O6(e){return Array.isArray(e)&&e.every(e=>D6(e)===`string`)?`string-list`:D6(e)}function k6(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 A6(e){return e===void 0?{kind:`unstated`}:typeof e==`number`&&Number.isSafeInteger(e)&&e>0?{kind:`stated`,at:e}:{kind:`refused`,problem:`request 'deadline' is not epoch milliseconds: ${JSON.stringify(e)}`}}function j6(e,t,n){let r=e.kind===`stated`?n.monoMs+(e.at-n.epochMs):t+150-50,i=Math.min(r,t+200);return Math.round(i-60-n.monoMs)}function M6(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:gF(t,r?.value),refusedArgs:i.filter((e,t)=>i.findIndex(t=>t.arg===e.arg&&t.why===e.why)===t)}}function N6(e){if(e===void 0)return{ok:!0,encoding:`ansi`};let t=Nt.find(t=>t===e);return t===void 0?{ok:!1,problem:`request 'encoding' is not one of ${Nt.join(`, `)}: ${JSON.stringify(e)}`}:{ok:!0,encoding:t}}function P6(e,t,n){let{report:r}=E6(e.hookData),i=[];for(let e of r.missingRequired)i.push(`missing required field '${e}'`);for(let{path:e,expected:t,got:n}of r.typeMismatches)i.push(`field '${e}' expected ${t}, got ${n}`);let a=Y$(e.hookData?.session_id);a.ok||i.push(`field 'session_id' ${a.problem}`),(typeof e.cwd!=`string`||!l(e.cwd))&&i.push(`request 'cwd' is not an absolute path: ${JSON.stringify(e.cwd)}`),(!Array.isArray(e.args)||!e.args.every(e=>typeof e==`string`))&&i.push(`request 'args' is not a list of strings: ${JSON.stringify(e.args)}`);let o=N6(e.encoding);o.ok||i.push(o.problem);let s=A6(e.deadline);if(s.kind===`refused`)return{ok:!1,problems:[...i,s.problem]};if(i.length>0||!a.ok||!o.ok)return{ok:!1,problems:i};for(let e of r.unknownTopLevelFields)t.firstSightOfUnknownHookField(e)&&n(`info`,`schema: unknown field ${JSON.stringify(e)} — Anthropic may have added it`);let c=Ft(e),{configFile:u,refusedArgs:d}=M6(e.args,e.cwd);return{ok:!0,req:{...e,deadline:s,encoding:o.encoding,sessionId:a.id,hints:c,rateLimits:Ote(e.hookData),requested:{projectDir:e.hookData.workspace.project_dir,cwd:e.cwd,target:yF(u,c.configEnv)},refusedArgs:d}}}function F6(e,t){switch(e){case`vars`:return{what:e,vars:I6(t)};case`segments`:return{what:e,segments:V6(t)};case`config`:return{what:e,config:G6(t)}}}function I6(e){if(e===null)return[];let{store:t,registry:n,config:r}=e,i=z6(r),a=t.names().sort(),o=[];for(let e of a){let r=t.getNode(e),a=L6(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:R6(r.lastUpdatedMs())})}return o}function L6(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 R6(e){return e===null?null:Math.max(0,Date.now()-e)}function z6(e){let t=new Map;for(let[n,r]of Object.entries(e.variables))t.set(n,B6(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}`,B6(i));return t}function B6(e){return e.kind}function V6(e){if(e===null)return[];let{store:t,config:n,lastRenderBySegment:r}=e,i=new Set(t.names()),a=U6(n),o=H6(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:W6(t.template,n.helpers,i),placements:(o.get(e)??[]).map(e=>({id:e,lastRender:r.get(e)??null}))})}return s}function H6(e){let t=new Map;for(let n of bw(e.presets))for(let r of Wy(Cw(e,n).node)){if(r.kind!==`segment`)continue;let e=t.get(r.name)??[],n=By(r);e.includes(n)||t.set(r.name,[...e,n])}return t}function U6(e){let t=[],n=new Set;for(let r of Wy(cw(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 W6(e,t,n){let r=new Set([...rT(e,t).keys()].flatMap(e=>dT(e,n)));return Array.from(r).sort()}function G6(e){return e===null?null:e.config}const K6=[`vars`,`segments`,`config`];function q6(e){return typeof e==`string`&&K6.includes(e)}const J6=e=>({resp:e,exitAfterFlush:null,delivered:i6}),Y6=e=>({kind:`reply`,...e}),X6={render:!0,"pane-session":!0,shutdown:!0,stats:!0,click:!0,debug:!0},Z6=(e,t)=>Y6(J6({ok:!1,error:t,code:e,daemonV:3}));function Q6(e){let t=Y$(e.sessionId);if(!t.ok)return Z6(`BAD_REQUEST`,`subscribe's sessionId ${t.problem}`);if(e.lane===void 0)return Z6(`VERSION_MISMATCH`,`this client's subscribe names no lane (${Xb.join(`, `)}): it predates the lane toggles — update it`);let n=ix(e.lane);return n===null?Z6(`BAD_REQUEST`,`subscribe needs a lane, one of ${Xb.join(`, `)}: got ${JSON.stringify(e.lane)}`):{kind:`subscribe`,sessionId:t.id,lane:n}}async function $6(e,t,n,r,i){return!t||typeof t!=`object`||typeof t.v!=`number`?Z6(`BAD_REQUEST`,`malformed request`):t.v===3?t.kind===`subscribe`?Q6(t):typeof t.kind!=`string`||!Object.hasOwn(X6,t.kind)?Z6(`BAD_REQUEST`,`unknown kind`):Y6(await e8(e,t,n,r,i)):(t.v>3?e.log(`info`,`version mismatch: client=${t.v} > daemon=3; binary likely upgraded — exiting after the response flushes`):e.log(`info`,`version mismatch: client=${t.v} < daemon=3; client is stale — staying up`),{kind:`reply`,resp:{ok:!1,error:`protocol v${t.v} not supported (daemon at v3)`,code:`VERSION_MISMATCH`,daemonV:3},exitAfterFlush:t.v>3?0:null,delivered:i6})}async function e8(e,t,n,r,i){let{stats:a,clock:o,frameFeeds:s,renderCache:c,payloadProviders:{gitProvider:l,usageStore:u},fileEvents:d,runs:f,effectSessions:p,menuIdle:m,journalTurns:h,sessionState:g,tmuxStatusLines:_,watcherRegistry:v,limits:y,handlerProbes:b,renderSightings:x,bundle:S,sourceDigest:C,doctorStores:ee}=e;if(t.kind===`shutdown`)return{resp:{ok:!0,output:``},exitAfterFlush:0,delivered:i6};if(t.kind===`pane-session`){let{socket:e,pane:n}=t;return J6(typeof e!=`string`||typeof n!=`string`?{ok:!1,error:`pane-session needs a string socket and pane`,code:`BAD_REQUEST`,daemonV:3}:{ok:!0,paneSession:s.newestWhere(({hints:{tmux:t}})=>t!=null&&t.socket===e&&t.pane===n)})}if(t.kind===`stats`)return J6({ok:!0,stats:a.snapshot({gitCache:l.getStats(),usageCache:u.getStats(),sources:t8(e),fileEvents:d.stats(),runs:f.stats(),transcriptReads:Mo(),renderCache:c.stats,effectCache:p.getStats(),menuIdle:m.getStats(),journalTurns:h.getStats(),sessionState:{sessions:g.size(),observers:g.observers(),revision:g.latestRevision()},frameFeeds:s.getStats(),tmuxStatus:_.stats(),watchersActive:v.size(),dirWatchesActive:v.dirWatches(),nextRestartReason:y.describeNextRestart(),handlerProbes:b.list(),clients:x.list(BM(o.date())),bundle:S,sourceDigest:C,daemon:y.serving(),doctorStores:AQ(ee)})});if(t.kind===`render`){let c=o.date(),l=BM(c),u=o.monotonic(),d=Math.round(u-r),f=[],p=++a.requestsTotal,m=P6(t,a,e.log),h=(e,t)=>x.see(e.sessionId,{client:e.hints.client??null,termCols:e.hints.termCols??null,rateLimits:e.rateLimits,claudeConfigDir:Uo(e.hints.claudeConfigDir),projectDir:e.requested.projectDir,transcript:kte(e.hookData),frame:t},l,p);m.ok&&(h(m.req,`drawing`),s.note(m.req.sessionId,m.req,p));let _=m.ok?await _6(e,m.req,l,u+j6(m.req.deadline,r,{epochMs:c.getTime(),monoMs:u}),f).then(({resp:e,motion:t,clickShown:n,delivered:r})=>(h(m.req,t),{outcome:{kind:`ok`},resp:e,delivered:()=>{r(),n!==null&&gc(g,m.req.sessionId,n)}}),e=>(h(m.req,`failed`),{outcome:{kind:`threw`,error:e},resp:a6(e),delivered:i6})):u8(m.problems);_.outcome.kind!==`ok`&&a.requestsErrored++,e6(f,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`,queued:`${d}ms`});let{level:v,line:y}=r6(`render`,f,_.outcome,Math.round(o.monotonic()-u));return e.log(v,y),{resp:_.resp,exitAfterFlush:null,delivered:_.delivered}}if(t.kind===`click`){let a=o.monotonic(),s=[[`queued`,`${Math.round(a-r)}ms`]],c=await a8(e,t,s,()=>n()||i());e6(s,{timedOut:n()?`Y`:`N`,clientLeft:i()?`Y`:`N`});let{level:l,line:u}=r6(`click`,s,c,Math.round(o.monotonic()-a));return e.log(l,u),J6(c8(c))}if(t.kind===`debug`){if(!q6(t.what))return J6({ok:!1,error:`unknown debug 'what': ${String(t.what)} (have: ${K6.join(`, `)})`,code:`BAD_REQUEST`,daemonV:3});let e=c.latestView(),n=e===null?null:{store:e.store,registry:e.registry,config:e.state.config,compiled:e.state.compiled,lastRenderBySegment:t.what===`segments`?i8(e.lastRenderCellsBySegment,e.state.config.globals.colorCompatibility??Lx(`colorCompatibility`)):r8};return J6({ok:!0,debug:F6(t.what,n)})}throw Error(`no reply for request ${se(t)}`)}function t8(e){let{payloadProviders:{gitProvider:t,tmuxService:n,usageStore:r,managedStorage:i,hostService:a},renderCache:o,refreshLedger:s}=e,c=t.getStats(),l=n.getStats(),u=r.scanStats(),d=i.stats(),f=o.stats;return{records:s.snapshot(),homes:{daemon:1,configDir:u.entries,repo:c.size,directory:f.size,session:r.getStats().size,view:f.views,pane:l.entries},held:{git:c.held,tmux:l.held,host:a.held(),today:u.held,pluginStorage:d.held},pluginStorage:{folders:d.folders,faults:d.faults,lost:d.lost}}}const n8={endcaps:Lx(`endcaps`),colorCompatibility:Lx(`colorCompatibility`),wrap:Lx(`autoWrap`),padding:Lx(`padding`),width:1/0},r8=new Map;function i8(e,t){let n=new Map;for(let[r,i]of e)n.set(r,QS(i,{...n8,colorCompatibility:t}));return n}async function a8(e,t,n,r){let{verb:i,value:a}=t;if(typeof i!=`string`||typeof a!=`string`)return{kind:`bad-request`,problems:[`a click's verb and value are strings, got ${typeof i} and ${typeof a}`]};try{return await s8(e,i,a,{via:`link`,handler:Gt(t.clientVersion)},n,r)}catch(e){return e instanceof J?{kind:`bad-request`,problems:[e.message]}:e instanceof UC?{kind:`closing`,error:e}:e instanceof WC?{kind:`abandoned`,error:e}:{kind:`threw`,error:e}}}const o8={link:`verb`,"tmux-status":`linkVerb`};async function s8(e,t,n,r,i,a){let{menuIdle:o,verbCtx:s}=e;if(t===`tmux-status-click`)return e6(i,{verb:t}),l8(e,n,i,a);let c=v0.get(t);if(!c)return{kind:`bad-request`,problems:[`unknown click verb: ${t}`]};e6(i,{[o8[r.via]]:t});let l=l0(t,n),u=l?.ok?l.id:null;l===null?e6(i,{sid:`-`}):u!==null&&(e6(i,{sid:u}),o.clickArrived(u));try{await c(n,{...s,arrival:r,placeWaited:e=>e6(i,{placeWait:`${e}ms`}),gatherTook:e=>e6(i,{gather:`${e}ms`}),turnWaited:e=>e6(i,{turnWait:`${e}ms`}),clientGone:a})}finally{u!==null&&o.clickSettled(u)}return{kind:`ok`}}function c8(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`:case`closing`:case`abandoned`:return a6(e.error)}}async function l8(e,n,r,i){let{tmuxStatusLines:a}=e,o=e=>({kind:`bad-request`,problems:[e]}),s=a.linkAt(n);if(s.kind===`refused`)return o(s.reason);if(e6(r,{link:s.url}),s.url.startsWith(`cc-candybar://`)){let t=GC(()=>ks(s.url));return t.verb===`tmux-status-click`?o(`a status-line link names another status-line click`):s8(e,t.verb,t.value,{via:`tmux-status`},r,i)}return await $$(e.launcher,{bin:t.platform===`darwin`?`/usr/bin/open`:`xdg-open`,args:[s.url],category:`click.open`},`opening ${s.url}`,e.log),{kind:`ok`}}const u8=e=>({outcome:{kind:`bad-request`,problems:e},resp:{ok:!1,error:`malformed hookData: ${e.join(`; `)}`,code:`BAD_REQUEST`,daemonV:3},delivered:i6});function d8(e,t){try{return P(t(e).mtimeMs)}catch(e){let t=e.code;return t===`ENOENT`||t===`ENOTDIR`?F:I(e.message)}}function f8(e,t){return e.kind===`ok`&&t.kind===`ok`?e.value===t.value:e.kind===t.kind}function p8(e){let{targets:t,intervalMs:n,stat:r,held:i,exit:a,log:o}=e,s=Ne(o),c=t.map(e=>({path:e,stamp:d8(e,r)})),l=c.filter(({stamp:e})=>e.kind!==`failed`),u=null,d=!1,f=()=>{d=!0,u&&clearInterval(u)},p=async()=>{if(!d)for(let{path:e,stamp:t}of l){let n=d8(e,r);if(n.kind===`failed`){o(`warn`,`binary stat failed (${e}): ${n.reason}`);continue}if(!f8(t,n)){let t=`binary ${n.kind===`absent`?`gone`:`changed`} (${e})`,r=await i();if(d)return;if(r){s([`info`,`${t}; the restart waits for the running update`]);return}o(`info`,`${t}; shutting down`),f(),a();return}}},m=()=>p().catch(e=>{o(`error`,`binary check failed: ${e.message}`)});return{arm(){for(let{path:e,stamp:t}of c)t.kind===`failed`&&o(`warn`,`binary stat failed at boot (${e}): ${t.reason}; not watched`);u=setInterval(()=>void m(),n),u.unref()},checkNow:m,close:f}}function m8(e,t){return t.kind===`failed`?e.failedMs:e.okMs}var h8=class{timer=null;state=`released`;last=null;constructor(e,t=Date.now){this.tick=e,this.now=t}landed(e,t=this.now()){this.last={at:t,periodMs:e},this.schedule()}hold(e){if(this.state===`disposed`)return;let t=e?`held`:`released`;t!==this.state&&(this.state=t,this.schedule())}dispose(){this.state=`disposed`,this.cancel()}schedule(){if(this.cancel(),this.state!==`held`||this.last===null)return;let e=Math.max(0,this.last.at+this.last.periodMs-this.now());this.timer=setTimeout(()=>{this.timer=null,this.tick()},e),this.timer.unref?.()}cancel(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}};const g8=`pass`,_8={okMs:5*6e4,failedMs:45e3};function v8(e){return e.includes(`first`)||e.includes(`pr`)?`first`:e.length===0?`period`:`change`}function y8(e,t,n){return`git:${e}|${t}|${n?`pr`:`-`}`}function b8(e){let t=Object.keys(e).sort(),n={};for(let r of t)n[r]=e[r];return JSON.stringify(n)}function x8(e,t,n){let r=[{path:t,filenames:[`HEAD`,`index`]},{path:o.join(n,`refs`,`heads`),recursive:!0}],i=r.map(e=>Rc(e.path));return{key:`git:${e}:${r.map((e,t)=>`${e.path}@${zc(i[t])}`).join(`|`)}`,targets:{dirs:r},unbound:i.some(e=>typeof e==`string`||`unreadable`in e)}}function S8(e){return e.find(e=>e.kind===`ok`)?.value.branch}function C8(e){e.missed=!0,mX(e,`unread`)}function w8(e,t){return e.missed&&e.reading.get().kind===`pending`&&pX(e,t.size>0?I([...t].join(`; `)):F),`unkeyed`}function T8(e,t){let n=_X(e);return t===null||n.kind!==`ok`?n:P({...n.value,pullRequest:_X(t)})}function E8(e){return t=>I(`${e} threw: ${String(t)}`)}var D8=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,this.periodMs=e.periodMs??3e4,this.maxRepos=e.maxRepos??64,this.logger=e.logger??Pe;let t=e.ledger??new mN(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 wT({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 xX(i.outcome);let{value:a,pr:o}=i;return a.reading.get().kind===`pending`?this.misses++:this.hits++,{current:()=>T8(a,o)}}asked(e,t,n,r){let i=this.resolution(t,r);if(i.kind!==`ok`)return{kind:`not-a-repo`,outcome:i};let{showPullRequest:a,...o}=n;return{kind:`asked`,...this.ask(this.repo(i.value),e,o,a===!0)}}changed(e){let t=this.repos.get(e);if(t){if(this.changes++,t.holders===0){for(let e of t.values.values())e.missed=!0;return}this.changedPass(t,`watch`)}}touch(e){this.repos.get(e.root)===e&&(this.repos.delete(e.root),this.repos.set(e.root,e))}repo(e){let t=this.repos.get(e);if(t)return this.touch(t),t;let n={root:e,refresh:new fN,watch:this.followWatch(e,null).watch,period:new h8(()=>{n.refresh.share(g8,()=>this.refreshPass(n))}),values:new Map,holders:0,asked:new Set,pr:null};return this.repos.set(e,n),n}followWatch(e,t){let n=this.inner.resolveGitDir(e),r=x8(e,n,this.inner.resolveCommonGitDir(n)),i=this.watchers.follow(t,r,()=>this.changed(e));return i.move===`rebound`&&this.logger(`info`,`git watch bound root=${e} dirs=${r.targets.dirs.map(e=>e.path).join(`,`)} deaf=${i.watch.handle.deaf.length}`),i}changedPass(e,t){e.asked.add(t),e.refresh.run(g8,()=>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&&C8(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(g8,()=>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:dX(),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=b8(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(y8(e.root,a,r),()=>this.hold(e,o,s)),this.queue(e,i),{value:o,pr:s}}async pass(e){if(this.repos.get(e.root)!==e)return;let t=Date.now(),n=[...e.asked];e.asked.clear();let r=this.followWatch(e.root,e.watch);e.watch=r.watch;let i=[];for(let t of e.values.values())t.readers>0||t.reading.get().kind===`pending`?i.push(t):t.missed=!0;let a=e.pr,[o,s]=await Promise.all([Promise.all(i.map(t=>this.inner.getGitInfo(e.root,t.options).catch(E8(`git fetch`)))),a!==null&&a.holders>0?this.remoteOf(e):null]);if(this.repos.get(e.root)!==e)return;let c=new Set;i.forEach((e,t)=>{let n=o[t];if(e.missed=!1,pX(e,n),n.kind===`failed`&&c.add(n.reason),n.kind===`ok`)for(let e of FY(n.value))c.add(e)});let l=S8(o),u=a===null||i.length===0?`-`:l===void 0?w8(a,c):this.movePr(e,a,l,s??a.remote);this.held(e),this.gitRefreshes.recorded(`${e.root} asked=${n.join(`,`)||`-`} values=${i.length} pr=${u} watch=${r.move}`,v8(n),c.size===0?P(null):I([...c].join(`; `)),Date.now()-t)}prSource(e){let t={period:new h8(()=>{this.readPr(e,t,`period`)}),seen:new Map,holders:0,missed:!0,key:``,remote:F,reading:dX(),inFlight:null};return t}remoteOf(e){return this.inner.getRepoRemoteUrl(e.root).catch(E8(`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?(C8(t),`owed`):(mX(t,`unread`),t.missed=!1,this.readPr(e,t,`first`),`looked-up`):(t.seen.delete(i),t.seen.set(i,a),t.missed=!1,pX(t,a.outcome),t.period.landed(m8(_8,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(E8(`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=${L(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||(pX(t,i),t.period.landed(m8(_8,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())hX(n,t);e.pr!==null&&hX(e.pr,t),this.repos.delete(e.root),e.refresh.clear(),e.watch.handle.release(),e.period.dispose(),e.pr?.period.dispose()}evict(){for(let e of this.repos.values()){if(this.repos.size<=this.maxRepos)return;e.holders>0||(this.drop(e),this.logger(`info`,`gitCache evict ${e.root}`))}}close(){for(let e of this.repos.values())this.drop(e);this.repos.clear(),this.resolutions.clear(),this.ownsWatchers&&this.watchers.closeAll()}},O8=class{static CACHE_DIR=pt();static USAGE_CACHE_DIR=o.join(this.CACHE_DIR,`usage`);static LOCKS_DIR=o.join(this.CACHE_DIR,`locks`);static isLocked(e){let t=o.join(this.LOCKS_DIR,e);if(!f.existsSync(t))return!1;try{let n=f.readFileSync(t,`utf-8`),r=parseInt(n.trim(),10);if(isNaN(r))return k(`Invalid PID in lock file ${e}, removing stale lock`),f.unlinkSync(t),!1;try{return process.kill(r,0),!0}catch(n){return n.code===`ESRCH`?(k(`Removing stale lock file ${e} for dead process ${r}`),f.unlinkSync(t),!1):(k(`Error checking process ${r} for lock ${e}:`,n),!0)}}catch(t){return k(`Error reading lock file ${e}:`,t),!0}}static async acquireLock(e,t=5e3){await this.ensureCacheDirectories();let n=o.join(this.LOCKS_DIR,e),r=Date.now(),i=String(process.pid);for(;Date.now()-r<t;)try{return await f.promises.writeFile(n,i,{flag:`wx`}),k(`Lock acquired for ${e}`),!0}catch(e){if(e.code===`EEXIST`)await ye(50);else throw e}return k(`Failed to acquire lock for ${e} within ${t}ms`),!1}static async releaseLock(e){let t=o.join(this.LOCKS_DIR,e);try{await f.promises.unlink(t),k(`Lock released for ${e}`)}catch(t){t.code!==`ENOENT`&&k(`Error releasing lock for ${e}:`,t)}}static async ensureCacheDirectories(){try{await Promise.all([f.promises.mkdir(this.CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.USAGE_CACHE_DIR,{recursive:!0}),f.promises.mkdir(this.LOCKS_DIR,{recursive:!0})])}catch(e){k(`Failed to create cache directories:`,e)}}static createProjectHash(e){return w(`md5`).update(e).digest(`hex`).substring(0,8)}static async getUsageCache(e,t){await this.ensureCacheDirectories();let n=o.join(this.USAGE_CACHE_DIR,`${e}.json`),r=`${e}.usage.lock`;for(let i=0;i<3;i++){if(this.isLocked(r)){k(`Cache for ${e} is locked, waiting...`),await ye(75);continue}try{let r=await f.promises.readFile(n,`utf-8`),i=JSON.parse(r);return!t||i.timestamp>=t?(k(`[CACHE-HIT] ${e} disk cache: found`),this.deserializeDates(i.data)):(k(`${e} cache outdated: cache=${i.timestamp}, latest=${t}`),null)}catch(t){if(t.code===`ENOENT`)return k(`No shared ${e} usage cache found`),null;k(`Attempt ${i+1} failed to read ${e} cache: ${t.message}. Retrying...`),await ye(75)}}return k(`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)){k(`Could not acquire lock to set usage cache for ${e}`);return}try{await this.ensureCacheDirectories();let r=o.join(this.USAGE_CACHE_DIR,`${e}.json`),i=JSON.stringify({data:t,timestamp:n||Date.now()});await f.promises.writeFile(r,i,`utf-8`),k(`[CACHE-SET] ${e} disk cache stored`)}catch(t){k(`Failed to save ${e} usage cache:`,t)}finally{await this.releaseLock(r)}}};const k8={"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 A8=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 O8.getUsageCache(`pricing`,e)}static async saveDiskCache(e){await O8.setUsageCache(`pricing`,e)}static async fetchPricingData(){return new Promise(e=>{let t=new n(this.GITHUB_PRICING_URL),r=ve({hostname:t.hostname,path:t.pathname,headers:{"User-Agent":`cc-candybar`,"Cache-Control":`no-cache`},timeout:5e3},t=>{if(t.statusCode!==200){k(`HTTP ${t.statusCode}: ${t.statusMessage}`),e(null);return}let n=``,i=0;t.on(`data`,t=>{if(i+=t.length,i>1048576){k(`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)?(k(`Fetched fresh pricing from GitHub for ${Object.keys(i).length} models`),k(`Pricing last updated: ${r?.updated||`unknown`}`),e(i)):(k(`Invalid pricing data structure`),e(null))}catch(t){k(`Failed to parse JSON:`,t),e(null)}}),t.on(`error`,t=>{k(`Response error:`,t),e(null)})});r.on(`error`,t=>{k(`Request error:`,t),e(null)}),r.on(`timeout`,()=>{k(`Request timeout`),r.destroy(),e(null)}),r.end()})}static async getCurrentPricing(){if(this.executionCache!==null)return k(`[CACHE-HIT] Pricing execution cache: ${Object.keys(this.executionCache).length} models`),this.executionCache;let e=await this.loadDiskCache();if(e)return k(`[CACHE-HIT] Pricing disk cache: ${Object.keys(e).length} models`),this.executionCache=e,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(e).length} models`),e;let t=await this.fetchPricingData();return t?(await this.saveDiskCache(t),k(`[CACHE-SET] Pricing disk cache stored: ${Object.keys(t).length} models`),this.executionCache=t,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(t).length} models`),t):(k(`[CACHE-FALLBACK] Using offline pricing data: ${Object.keys(k8).length} models`),this.executionCache=k8,k(`[CACHE-SET] Pricing execution cache stored: ${Object.keys(k8).length} models`),k8)}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 k(`[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),k(`[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`}},j8=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}},M8=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:()=>_X(r)}}supersede(e){let t=this.spec.keyOf(e),n=this.touched(t)??this.created(t,e);n.superseding++,mX(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:dX(),holders:0,flight:null,changed:!1,superseding:0,revisit:N8(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();F8(()=>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{pX(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(),hX(e,I(`${this.spec.name} entry dropped`))}};function N8(e,t){if(e===null)return new P8(t.holdReturned);let n=new h8(t.period);return{landed:t=>n.landed(m8(e,t)),hold:e=>n.hold(e),dispose:()=>n.dispose()}}var P8=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 F8(e){let t=e=>I(`read threw: ${String(e)}`);try{return e().catch(t)}catch(e){return Promise.resolve(t(e))}}function I8(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 L8={okMs:60*1e3,failedMs:10*1e3},R8={cost:0,input:0,output:0,cacheCreation:0,cacheRead:0},z8={cost:null,calculatedCost:null,officialCost:null,tokens:null,tokenBreakdown:null};function B8(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function V8(){let e=new Date;return e.setHours(0,0,0,0),e.setDate(e.getDate()-1),e.getTime()}function H8(){return{input:0,output:0,cacheCreation:0,cacheRead:0}}const U8={entries:0,cost:0,breakdown:H8(),days:new Map};async function W8(e,t){let n=B8(new Date(V8())),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 A8.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=B8(new Date(e.timestamp));if(c<n)continue;let l=o.get(c)??{...R8};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 G8(e,t){e.cost+=t.cost,e.input+=t.input,e.output+=t.output,e.cacheCreation+=t.cacheCreation,e.cacheRead+=t.cacheRead}function K8(e){let t=0,n=0,r=H8(),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)??{...R8};G8(n,t),i.set(e,n)}}if(t===0)return{sessionInfo:z8,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 q8(e,t){return e!==void 0&&t.some(t=>e.startsWith(t))}function J8(e,t){let n=new Map;for(let{record:r}of e)if(!(r===void 0||!q8(r.transcriptPath,t)))for(let[e,t]of r.days){let r=n.get(e)??{...R8};G8(r,t),n.set(e,r)}return n}async function Y8(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 X8(e,t){let n=t?.cost?.total_cost_usd??null;return{session:{...e,cost:n??e.cost,officialCost:n}}}function Z8(e,t){(0,Y.runInAction)(()=>e.set(t))}var Q8=class{sessions=Y.observable.map(void 0,{deep:!1});flight=new j8;scans;daySets=new Map;speedFlight=new j8;requestFlight=new j8;staleAgeMs;log;renderTally={hits:0,misses:0};ledger;usage;sweeps=0;sweepTimer=null;constructor(e={}){this.log=e.logger??Pe,this.ledger=e.ledger??new mN(this.log),this.usage=this.ledger.declare({name:`usage`,scope:`session`,refresh:[`request`]}),this.staleAgeMs=e.staleAgeMs??864e5,this.scans=new M8({name:`today`,scope:`configDir`,keyOf:e=>e.join(`\0`),fields:e=>`dirs=${L(e.join(`,`))}`,read:e=>this.scan(e),every:e.rescan??L8,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=To(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(X8(t.kind===`ok`?t.value.sessionInfo:z8,e))},speed:t=>this.observed(e,r,t),today:async e=>{await SX(e),await r().record}}}usageOf(e,t){let n=this.sessions.get(e);if(n===void 0)return So;let r=n.failure.get();return r===null?P(X8(n.record?.sessionInfo??z8,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=${L(e)}`,`request`,a,Date.now()-i),Z8(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=bZ(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=B8(VM(n)),o={...R8},s=e.sums.get(a);s!==void 0&&G8(o,s);let c=q8(r?.record?.transcriptPath,e.roots)?void 0:r?.record?.days.get(a);return c!==void 0&&G8(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 Z8(this.hold(e).speed,t),t;let r=I8(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 Z8(this.hold(e).speed,s),s})}speedOf(e){return e?this.sessions.get(e)?.speed.get()??So: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,Y.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:Y.observable.box(null),speed:Y.observable.box(void 0,{deep:!1})};return(0,Y.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=>u(e,`projects`)+d),i={roots:r,sums:new IT(`today over ${e.join(`,`)}`,()=>J8(this.sessions.values(),r))};return this.daySets.set(t,i),i}async refold(e,t,n){let r=await CZ(e,c(t),n===void 0?void 0:new Set(n.files.keys()));for(let e of MZ(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 NZ(e,r,U8,W8);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 MZ(c))this.log(`info`,e);i.set(e,s),e===t&&(a=s.cursor.stamp)}return P({files:i,...K8(i),mainStamp:a})}async scan(e){try{let t=V8(),n=await xZ(e),r=[];for(let e of n){let n=await SZ(ko(e));for(let i of n??[]){if(!i.endsWith(`.jsonl`))continue;let n=u(e,i),a=await SZ(Ao(n));a===void 0||a.mtimeMs<t||r.push({sessionId:i.slice(0,-6),path:n,stamp:Eo(a)})}}let i=[],a={hits:0,misses:0};return await Y8(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=${L(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=B8(new Date(e)),n=0,r=0,i=0;return(0,Y.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,Y.runInAction)(()=>{for(let{sums:e}of this.daySets.values())e.release();this.sessions.clear()}),this.daySets.clear()}},$8=class{values=Y.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,Y.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)}})}},e5=class{sessions;constructor(e,t,n,r=Pe,i=256){this.empty=e,this.step=t,this.refreshes=n,this.log=r,this.sessions=new $8(i)}async read(e,t){let n=this.sessions.get(e),r=n?.folded,i=To(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 NZ(t,r,this.empty,(e,t)=>t.reduce(this.step,e));if(this.refreshes.recorded(`sid=${L(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 MZ(c))this.log(`info`,e);return this.store(e,s,{kind:`ok`,value:s.value})}answer(e){return this.sessions.get(e)?.answer??So}store(e,t,n){return this.sessions.set(e,{folded:t,answer:n}),n}};function t5(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 n5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(void 0,t5,(e.ledger??new mN(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 k(`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);k(`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,r5(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,r5(e))}contextFrom(e,t){if(e.kind===`failed`)return I(`context transcript: ${e.reason}`);let n=e.value;return n===void 0?(k(`No main chain entries with usage data found`),F):(k(`Most recent main chain context: ${n} tokens (limit: ${t})`),P({totalTokens:n,maxTokens:t,...this.ratioPercentages(n,t)}))}};function r5(e){return e.context_window?.context_window_size??2e5}const i5={messageCount:0,nonPrompts:0,recent:[]},a5=new Set([`turn`,`interrupt`,`claude-code`]);function o5(e,t){if(t.isSidechain)return e;let n=[...e.recent,t];return{messageCount:e.messageCount+ +(t.userEntry===`prompt`),nonPrompts:e.nonPrompts+ +!!a5.has(t.userEntry),recent:n.length>20?n.slice(-20):n}}function s5(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 c5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(i5,o5,(e.ledger??new mN(t)).declare({name:`metrics`,scope:`session`,refresh:[`request`]}),t)}async getMetricsInfo(e,t){k(`Getting metrics from hook data for session: ${e}`);let n=t.cost;return n?l5(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:l5(e,n,r)}};function l5(e,t,n){return n.kind===`failed`?I(`metrics (${e}): ${n.reason}`):P({responseTime:t.total_api_duration_ms/1e3,lastResponseTime:s5(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 u5={command:null,todos:[],pending:[],done:[]};function d5(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 f5(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 p5(e,t){if(t.isSidechain)return e;let n=f5(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=d5(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 m5(e){return{command:e.command,todos:e.todos,running:e.pending.reduce((e,t)=>d5(e,t.name),[]),done:e.done}}var h5=class{fold;constructor(e={}){let t=e.logger??Pe;this.fold=new e5(u5,p5,(e.ledger??new mN(t)).declare({name:`activity`,scope:`session`,refresh:[`request`]}),t)}async getActivityInfo(e,t){return g5(e,await this.fold.read(e,t.transcript_path))}activityOf(e){let t=this.fold.answer(e);return t.kind===`pending`?t:g5(e,t)}};function g5(e,t){return t.kind===`failed`?I(`activity (${e}): ${t.reason}`):P(m5(t.value))}const _5=3e4;var v5=class{names;constructor(e){let t=e.logger??Pe;this.names=new M8({name:`tmux`,scope:`pane`,keyOf:e=>`${e.socket}\n${e.pane}`,fields:e=>`pane=${L(e.pane)} socket=${L(e.socket)}`,read:t=>y5(e.launcher,t),every:{okMs:_5,failedMs:_5},maxEntries:64,logger:t,ledger:e.ledger??new mN(t)})}declare(e,t){return this.names.declare(e,t)}getStats(){return this.names.stats()}close(){this.names.close()}};async function y5(e,t){let n=await oc(e,t,`tmux`,[`display-message`,`-p`,`-t`,t.pane,`#S`]);if(n.kind!==`ok`)return I(n.reason);let r=n.stdout.trim();return r?P(r):F}const b5=6e4,x5={okMs:b5,failedMs:b5};function S5(e){let t=e.indexOf(`.`);return t<0?e:e.slice(0,t)}function C5(e,t){try{let e=t();return Promise.resolve(e===``?F:P(e))}catch(t){return Promise.resolve(I(`host.${e}: ${String(t)}`))}}var w5=class{name;user;constructor(e={}){let t=e.logger??Pe,n={scope:`daemon`,keyOf:()=>``,fields:()=>`-`,every:x5,maxEntries:1,logger:t,ledger:e.ledger??new mN(t)};this.name=new M8({...n,name:`host.name`,read:()=>C5(`name`,()=>S5(E.hostname()))}),this.user=new M8({...n,name:`host.user`,read:()=>C5(`user`,()=>E.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()}},T5=class{known=new $8(64);refreshes;constructor(e=Pe,t=new mN(e)){this.refreshes=t.declare({name:`autocompact`,scope:`configDir`,refresh:[`request`]})}window(e){let t=E5(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=CL(e);return this.refreshes.recorded(`path=${L(e)} stamp=${L(t)}`,`request`,i,Date.now()-r),this.known.set(e,{stamp:t,outcome:i}),i}stored(e){return this.known.get(e)?.outcome??So}getStats(){let{refreshes:e,failures:t,lastMs:n}=this.refreshes.record();return{entries:this.known.size,refreshes:e,failures:t,lastMs:n}}};function E5(e){try{let t=f.statSync(e,{throwIfNoEntry:!1});return t===void 0?`absent`:Eo(t)}catch(e){return`unread:${e.code??`error`}`}}const D5=/"(?:cache_read_input_tokens|cache_creation_input_tokens)":[1-9]/;function O5(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 k5=class{known=new $8(256);refreshes;constructor(e=Pe,t=new mN(e)){this.refreshes=t.declare({name:`cache`,scope:`session`,refresh:[`request`]})}async refresh(e,t){let n=To(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??So}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 A5(t);return this.refreshes.recorded(`sid=${L(e)} stamp=${L(n)}`,`request`,i,Date.now()-r),i}};async function A5(e){let t=await j5(e);return t.kind===`ok`?P(Math.floor((t.value+36e5)/1e3)):t}async function j5(e){for(let t of[65536,1048576]){let n=await zo(e,t);if(n.kind!==`ok`)return n;let r=M5(n.value.buf,n.value.fromStart);if(r!=null)return P(r);if(n.value.fromStart)return F}return F}function M5(e,t){let n=e.toString(`utf8`).split(`
485
485
  `),r=+!t;for(let e=n.length-1;e>=r;e--){let t=n[e];if(!t||!D5.test(t))continue;let r=O5(t);if(r!=null)return r}return null}var N5=class{bySession=Y.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,Y.runInAction)(()=>{i.size===0?this.bySession.delete(e):this.bySession.set(e,i)})}};const P5=e=>SW(e),F5=e=>o.join(e.storage.folder,P5(e.sessionId)),I5=e=>JSON.stringify([e.folder,e.generation]),L5=(e,t)=>e.folder===t.folder&&e.generation===t.generation;var R5=class{sessions;folders=new Map;watched=new Map;faultCounts={unusable:0,refused:0,error:0};lost=0;watchers;logger;identityOf;fileEvents;unsubscribe;constructor(e){this.watchers=e.watchers,this.logger=e.logger,this.identityOf=e.identityOf??Fc,this.fileEvents=e.fileEvents,this.unsubscribe=e.fileEvents.subscribe(e=>this.noticed(e)),this.sessions=new M8({name:`plugin storage`,scope:`session`,keyOf:e=>JSON.stringify([e.storage.folder,e.storage.generation,e.sessionId]),fields:e=>`file=${L(F5(e))} generation=${e.storage.generation}`,read:e=>this.read(e),every:null,maxEntries:256,logger:e.logger,ledger:e.ledger??new mN(e.logger)})}keyFor(e){let t=this.folders.get(e)??this.recorded(e),n=`gone`;t.unusable=null;try{f.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`||!Ic(n,t.identity)))&&(t.generation++,t.lost=!1,t.identity=n===`gone`?null:n,this.logger(`info`,`plugin storage generation folder=${L(e)} generation=${t.generation}`)),{folder:e,generation:t.generation}}watch(e){let t=this.watched.get(I5(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.unsubscribe(),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:${I5(e)}`,{dirs:[{path:e.folder}]},e=>this.invalidated(i,e)),sweep:setInterval(()=>void this.sweep(e),864e5),health:{kind:`watching`}};i.sweep.unref(),this.watched.set(I5(e),i),n!==null&&this.faulted(i,`unusable`,n);for(let e of i.handle.deaf)this.faulted(i,`refused`,e.reason);return this.sweep(e),i}closed(e){let t=I5(e.key);this.watched.delete(t),e.health={kind:`closed`},clearInterval(e.sweep),e.handle.release()}invalidated(e,t){let{key:n}=e,r=e=>L5(e.storage,n);switch(t.kind){case`unknown`:this.judged(e,()=>this.sessions.changed(r));return;case`changed`:{let{paths:i}=t;i.has(o.join(n.folder,o.basename(n.folder)))?this.judged(e,()=>this.sessions.changed(r)):this.sessions.changed(e=>r(e)&&i.has(F5(e)));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`&&Ic(a,o)){t();return}e.health={kind:`lost`},r.generation===i.generation&&(i.lost=!0,this.lost++,this.logger(`info`,`plugin storage lost folder=${L(r.folder)} generation=${r.generation} now=${a===`gone`?`gone`:`replaced`}`),this.sessions.changed(e=>L5(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=${L(r.folder)} generation=${r.generation} cause=${t} reason=${JSON.stringify(n)}`),this.sessions.changed(e=>L5(e.storage,r)))}noticed(e){switch(e.kind){case`period`:for(let e of[...this.watched.values()])this.judged(e,()=>{});return;case`moved`:case`caught-up`:this.sessions.changed(()=>!0);return}}standing(e){let t=this.watched.get(I5(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`:{let t=qc(this.fileEvents.delivery());return t===null?null:`cannot refresh: ${e.folder}: ${t}`}case`closed`:return null}}async read(e){let t=this.standing(e.storage);if(t!==null)return I(t);let n=F5(e),r;try{r=await f.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=dN(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=${L(e.folder)} scanned=${r} removed=${i} took=${Date.now()-t}ms`;try{let t=await f.promises.readdir(e.folder,{withFileTypes:!0});for(let a of t){if(!a.isFile()||!a.name.endsWith(`.json`))continue;r++;let t=o.join(e.folder,a.name);try{let{mtimeMs:r}=await f.promises.stat(t),o=this.sessions.isHeld(t=>t.storage.folder===e.folder&&P5(t.sessionId)===a.name);if(r>=n||o)continue;await f.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 z5(e){let{launcher:t,logger:n,ledger:r}=e;return{hostService:new w5({logger:n,ledger:r}),gitProvider:new D8({inner:new lX(t),watchers:e.watchers,logger:n,ledger:r}),usageStore:new Q8({logger:n,ledger:r}),contextProvider:new n5({logger:n,ledger:r}),metricsProvider:new c5({logger:n,ledger:r}),activityProvider:new h5({logger:n,ledger:r}),tmuxService:new v5({launcher:t,logger:n,ledger:r}),autoCompact:new T5(n,r),cacheExpiry:new k5(n,r),managedStorage:new R5({watchers:e.watchers,fileEvents:e.fileEvents,logger:n,ledger:r}),faults:new N5,log:e.logger}}function*B5(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*V5(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 bw(e.presets)){for(let n of Wy(Cw(e,t).node))n.when!==void 0&&(yield n.when);let n=Ew(e,t);for(let e of sy){let t=n[e];cy(t)&&(yield t)}}for(let[,t]of B5(e))for(let[,e]of Qy(t))yield e;for(let t of Object.values(e.actions))for(let[,e]of Lw(t))yield e}function H5(e,t,n){let r=wU(t),i=new Set,a=new Set,o=new Set;for(let e of V5(t)){for(let{reaches:t}of r.ofTemplate(e))for(let e of t)i.add(e);for(let{name:n}of oT(e,t.helpers))a.add(n);for(let n of ete(e,t.helpers))o.add(n)}for(let[,e]of B5(t))for(let{reaches:t}of r.ofVariable(e))for(let e of t)i.add(e);let s=new Set(a);for(let e of a){let n=t.actions[e];if(n!==void 0&&`do`in n)for(let e of n.do)s.add(e)}let c=new Set,l=new Set(n);for(let e of s){let n=t.actions[e];if(n!==void 0&&(`set`in n&&c.add(n.set),`insertSegment`in n&&l.add(n.insertSegment),`insertSegmentFrom`in n&&Array.isArray(n.insertSegmentFrom)))for(let e of n.insertSegmentFrom)l.add(e)}for(let e of bw(t.presets))for(let n of Wy(Cw(t,e).node))n.kind===`segment`&&l.add(n.name);let u=(e,t)=>i.has(e)||t.kind===`state`&&c.has(t.key),d=e=>[...e].filter(e=>!ji(e)),f=(e,t,n)=>d(t).filter(e=>!n(e)).map(t=>({kind:e,name:t})),p=new Map(B5(e));return[...f(`variable`,p.keys(),e=>u(e,p.get(e))),...f(`action`,Object.keys(e.actions??{}),e=>s.has(e)),...f(`helper`,Object.keys(e.helpers??{}),e=>o.has(e)),...f(`segment`,Object.keys(e.segments??{}),e=>l.has(e))]}function U5(e){return w(`sha256`).update(JSON.stringify(e)).digest(`hex`)}var W5=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 G5(e){return Math.floor(Math.max(e/4,e*Fr-67108864))}const K5={keyFor:e=>({folder:e,generation:0}),watch:()=>()=>{}};function q5(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=e.name===void 0?void 0:n.variables[xW(Vw(e))];return t?.kind===`file`?t.path:`none`},d=o.flatMap(e=>e.name===void 0?[]:[Vw(e)]).flatMap(e=>Object.entries(n.variables).filter(([t])=>Hw(e)(t)&&t!==xW(e))),f=d.filter(([,e])=>e.kind===`source`).length,p=d.length-f;return`config load ${xF(e,`<default>`)}: projections=${[...OU(n).keys()].join(`,`)||`-`} instantSegments=${F3(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.path} data=${u(e)}`).join(``)+s.map(e=>` -${e.path} (${e.reason})`).join(``)+c.map(e=>` ~${e.path} (${e.reason})`).join(``)}const J5=e=>{switch(e.kind){case`changed`:return[...e.paths].join(`,`);case`unknown`:return`unknown`;case`failed`:return`failed:${e.reason}`}},Y5=e=>{switch(e.kind){case`open`:case`write`:case`doctor`:return e.kind;case`config-watch`:case`answers-watch`:return`${e.kind}:${J5(e.heard)}`;case`events-resumed`:return`${e.kind}:${new Date(e.since).toISOString()}`}};function X5(e,t,n){let r=e=>L(e.join(`,`)||`-`);return`config loaded projectDir=${L(e.projectDir)} cwd=${L(e.cwd)} cause=${L(Y5(t))} state=${n} files=${L(xF(e.configLayers,`<bundled default>`))} awaiting=${r(e.repos.awaiting)} declined=${r(e.repos.declined)} unproven=${e.repos.unproven.length===0?`-`:JSON.stringify(e.repos.unproven)} error=${e.lastError===null?`none`:JSON.stringify(e.lastError)} warning=${e.lastWarning===null?`none`:JSON.stringify(e.lastWarning)}`}function Z5(e,t){return`config disposed reason=${e.reason} released=${t} held=${e.held}`}function Q5(e,t,n){return e+`\0`+t+`\0`+(n??``)}function $5(e,t){return new Set(bw(e.presets).filter(n=>Cw(e,n).path===`root`?t.root!==void 0:t.presets?.[n]?.root!==void 0))}function e7(e){let{loaded:t,dropped:n,unreached:r}=e.state.plugins,i=[...new Set([...e.state.plugins.roots,o.join(e.projectDir,tG)])];return _T({named:[..._G(e.projectDir,e.cwd,e.configFile),...i,...t.map(e=>e.path),...[...n,...r].map(e=>e.path),...new Set([...e.state.sources.values()].map(e=>e.folder))],whole:i})}function t7(e){return e.filter(Boolean).join(`
486
486
  `)||null}const n7=e=>e instanceof Error?e.message:String(e);function r7(e){return{loaded:e.loaded,dropped:e.dropped,reached:[...e.reached].sort(),rendering:[...e.rendering].sort(([e],[t])=>e.localeCompare(t))}}function i7(e){let{loaded:t,chain:n}=e;return U5({cwd:e.cwd,chain:{layers:n.layers,home:n.home,repo:n.repo},loaded:{layers:t.layers.map(e=>({path:e.path,raw:e.raw,config:e.config,plugins:r7(e.plugins),source:null,warnings:null})),base:t.base,installed:{...r7(t.installed),checkout:t.installed.checkout,roots:t.installed.roots,unreached:t.installed.unreached},config:t.config,dropped:t.dropped.map(e=>e.message),placed:null},sources:[...e.sources].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,t.folder,t.generation])})}function a7(e,t){let n=new Map,r=new Map;for(let[i,a]of Object.entries(e.variables)){if(a.kind!==`source`)continue;let e=n.get(a.storage)??t.keyFor(a.storage);n.set(a.storage,e),r.set(i,e)}return r}function o7(e,t,n){let r=[];try{let i=IG(t.layers,uK,{warned:e=>r.push(...e)},{repo:t.repo,cwd:e}),a={cwd:e,chain:t,loaded:i,sources:a7(i.config,n)};return{kind:`resolved`,...a,key:i7(a),warnings:r}}catch(e){return e instanceof ub&&r.push(...e.warnings),{kind:`failed`,cause:e,warnings:r}}}function s7(e,t){let{cwd:n,chain:r,loaded:i}=e,{layers:a,config:o,installed:s,dropped:c}=i,l=a.at(-1)?.config??uK,u=a.find(e=>e.path===r.home)?.raw??{},d=a.flatMap(e=>(e.raw.insert??[]).map(e=>e.seg)),f=[],p=new KT,m=new NN(t.launcher,p,o.globals.default_empty_value??``,t.sessionState,null,t.ledger,t.fileEvents,t.watchers),h;try{h=k3(o,m,n,t.compile??O3(t.signer),f7),f.push(...h.loadWarnings);let r=m.view();f.push(...M3(o,r,n,p7)),r.dispose(),tq(o),sB(o);for(let n of new Set(e.sources.values()))m.own(t.storage.watch(n))}catch(e){return m.dispose(),e instanceof ub&&f.push(...e.warnings),{kind:`failed`,cause:e,warnings:f}}return{kind:`built`,state:{config:o,dropped:c,compileKey:h.compileKey,loadKey:e.key,buildWarnings:f,store:p,registry:m,compiled:h.compiled,neededInputPaths:LX(o),authoredRoots:$5(l,u),fileHeldSettings:VK(u),configPath:r.layers.some(e=>e.path===r.home)?r.home:null,unused:[...new Map(a.flatMap(e=>H5(e.raw,i.placed,d)).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:e.sources}}}function c7(e,t,n,r){let i={layers:t.layers.map(e=>e.path),home:t.home,repos:e.repos,ms:Math.round(performance.now()-e.started)},a=t=>t7([...e.advisories,...n,...t]);switch(r.kind){case`built`:case`kept`:return{...i,kind:r.kind,warning:a(r.state.buildWarnings),state:r.state,error:null};case`failed`:return{...i,kind:`failed`,warning:a(r.warnings),state:null,error:n7(r.cause),cause:r.cause}}}function l7(e,t,n,r,i=null){let a=o7(t,n,r.storage);if(a.kind===`failed`)return c7(e,n,[],a);let o=i?.loadKey===a.key?{kind:`kept`,state:i}:s7(a,r);return c7(e,n,a.warnings,o)}function u7(e,t,n,r,i=null){let a=performance.now(),o=xG(Cq().read(),e,t,n),{repos:s}=o,c={layers:o.kind===`chain`?o.layers:[],home:o.home,repo:s.plugins};return l7({repos:s,advisories:[OG(e,t),EG(o),mG(s)],started:a},t,c,r,i)}function d7(e,t,n){let r=o7(e,{layers:[],home:``,repo:t},n.storage),i=r.kind===`failed`?r:s7(r,n);if(i.kind===`failed`)throw Error(`bundled default failed to load: ${n7(i.cause)}`,{cause:i.cause});return i.state}const f7=new Set([`directory`]),p7=new Set([`view`]);function m7(e,t,n,{sessionState:r,declare:i,source:a,changed:o,log:s}){let{sessionId:c}=n,l=e.registry.view(),u=new W5;M3(e.config,l,t,p7);let d=()=>vK(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)}`),JX(I(`view declaration threw: ${String(t)}`),[...e.sources.keys()])}},p=(e,t)=>({facts:e,preset:t,lanes:f(e,t)}),m=Y.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,Y.runInAction)(()=>m.set(r))},g=(0,Y.reaction)(d,e=>h(m.get().facts,e),{fireImmediately:!0}),_=a({sessionId:c,state:e,store:l.variableStore,declared:()=>m.get()});n3(e.compiled,l.variableStore,l,_);let v=(0,Y.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:Y.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 h7=class{entries=new Map;answersWatch;sweep=null;closed=!1;holds=new Map;views=new Map;copies=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??Pe,this.budgetBytes=t.budgetBytes,this.maxEntries=t.maxEntries??256,this.observers=t.observers??{},f.mkdirSync(xq(),{recursive:!0});let{dir:n,name:r}=mT(Sq());this.answersWatch=e.watchers.acquire(`repo-configs:${n}/${r}`,{dirs:[{path:n,filenames:[r]}]},e=>this.reloadEvery({kind:`answers-watch`,heard:e}))}compileOf(e,t){return this.compiles.get(e)??P3(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=Q5(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,null);a.state!==null&&this.log(`info`,q5(a.layers,a.state,a.ms));let o={projectDir:e,cwd:t,configFile:n,configLayers:[],configHome:``,repos:a.repos,lastError:a.error,lastWarning:a.warning,state:a.state??d7(t,a.repos.plugins,this.deps),watch:null};return this.serve(o.state),this.entries.set(r,o),this.fit(o),this.log(`info`,`render-cache entry projectDir=${e} cwd=${t} compile=${o.state.compileKey.slice(0,12)} entries=${this.entries.size} compiles=${this.compiles.size} accounted=${Ar(this.accountedBytes())}/${Ar(this.budgetBytes())}MB`),this.refreshWatcher(o,a),this.observers.onReload?.(o,[],{kind:`open`},a.kind),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=wo();let a=this.views.get(e),o=a?.facts()??this.openFailures.get(e)?.facts;if(o===void 0)return;let s=this.entries.get(Q5(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=m7(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),this.views.has(e.sessionId)||this.copies.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,r){if(this.closed)throw Error(`render cache used after close`);return u7(e,t,n,this.deps,r)}drop(e,t,n){t.watch?.held.handle.release(),this.entries.delete(e),this.retire(t.state,n,null)}get stats(){let e=0,t=0;for(let n of this.holds.values())n.holders>0&&e++,n.retired!==null&&t++;let n=0;for(let e of this.viewHolds.values())e.retired!==null&&n++;return{size:this.entries.size,held:e,retired:t,compiles:this.compiles.size,views:this.views.size,pinned:this.pins.size,retiredViews:n,accountedBytes:this.accountedBytes(),budgetBytes:this.budgetBytes()}}fit(e){let t=()=>this.entries.size<=this.maxEntries&&this.accountedBytes()<=this.budgetBytes(),n=new Set([...this.pins.keys()].flatMap(e=>{let t=this.views.get(e);return t===void 0?[]:[t.state]}));for(let[r,i]of this.entries){if(t())return;i===e||n.has(i.state)||this.drop(r,i,`evict`)}t()||this.log(`warn`,`render-cache over budget entries=${this.entries.size} views=${this.views.size} pinned=${n.size} accounted=${Ar(this.accountedBytes())}/${Ar(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`,Z5(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,r){this.reloadInto(this.getOrCreate(e,t,n),r)}reloadInto(e,t){let n=this.sessionsOn(e),r=e.state,i=this.load(e.projectDir,e.cwd,e.configFile,r);e.lastWarning=i.warning,e.lastError=i.error,i.state!==null&&this.log(`info`,q5(i.layers,i.state,i.ms)),i.kind===`built`&&(e.state=i.state,this.serve(i.state),this.retire(r,`reload`,{entry:e,state:i.state})),this.fit(e),this.refreshWatcher(e,i),this.observers.onReload?.(e,n,t,i.kind)}reloadEvery(e){for(let t of this.entries.values())this.reloadInto(t,e)}refreshWatcher(e,t){e.configLayers=t.layers,e.configHome=t.home,e.repos=t.repos;let n=e7(e),{targets:r,unresolved:i}=n,a=`config:${e.projectDir}:${e.cwd}:${e.configFile??``}:${n.key}`,{watch:o,move:s}=this.deps.watchers.follow(e.watch?.held??null,{...n,key:a},t=>this.reloadInto(e,{kind:`config-watch`,heard:t}));if(e.watch={derived:{...n,key:a},held:o},s!==`kept`){this.log(`info`,`config watch bound projectDir=${e.projectDir} cwd=${e.cwd} dirs=${r.dirs.map(e=>e.path).join(`,`)} deaf=${o.handle.deaf.length}`);for(let{path:t,reason:n}of i)this.log(`warn`,`config watch unresolved projectDir=${e.projectDir} path=${t} reason=${n}`)}}get size(){return this.entries.size}latestView(){return[...this.views.values()].at(-1)??null}delivered(e,t,n){if(!this.views.has(e))return;let r=this.copies.get(e)??new Map;this.copies.set(e,r.set(t,n))}drawnCopy(e,t,n){return this.copies.get(e)?.get(t)?.get(n)}stopDrawing(e,t){this.copies.get(e)?.delete(t)}};const g7=e=>!VJ(e)&&!dL(e)&&e!==`update.dismissed`&&e!==Fi;var _7=class{past=Y.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:IJ(e,g7,(e,n,r,i)=>{let a=t.get(e)??new Map,o=a.get(n);a.set(n,{key:n,before:o?o.before:r,after:i}),t.set(e,a)}),commit:()=>{for(let[e,n]of t){let t=[...n.values()].filter(e=>e.before!==e.after);t.length>0&&this.push(e,t)}t.clear()}}}back(e,t,n){let r=this.past.get(e)??[],i=this.restorable(e,t,n),a=i.at(-1),o=r.length-i.length;if(a===void 0)throw this.put(e,i),new J(`back: nothing to go back to${o>0?` (${o} step(s) over a view since gone, discarded)`:``}`);return(0,Y.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,Y.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)})}};function v7(e){return({sessionId:t,state:n,store:r,declared:i})=>{let a=n=>e.sessionState.get(t,n),o=r.derive(`session.effective`,`computed`,()=>yK(n.config,a,e=>n.authoredRoots.has(e))),s=r.derive(`session.payload`,`computed`,()=>{let{facts:r,lanes:s}=i(),c=o.read();return iZ({hookData:r.hookData,cwd:r.cwd,hints:r.hints,neededInputPaths:n.neededInputPaths(c.preset),deps:{...e.providers,lanes:()=>s}},{effective:c,configFacts:{...HK(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 y7=`#{pane_id} #{session_id} #{session_attached} #{window_active} #{window_zoomed_flag} #{pane_active}`,b7=`#{session_id} #{client_control_mode} #{pane_id}`;function x7(e){let t=new Set;for(let n of e.split(`
487
487
  `)){let[e,r]=n.trim().split(` `);e!==void 0&&r===`1`&&t.add(e)}return t}function S7(e,t){let n=new Set;for(let r of e.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptctl/cc-candybar",
3
- "version": "1.178.1",
3
+ "version": "1.179.0",
4
4
  "description": "Statusline renderer for Claude Code — a JSON5-configurable DSL with daemon-cached data sources, byte-clean palette-aware composition, and OSC8 click verbs.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.mjs",
@@ -30,6 +30,7 @@
30
30
  "bar": "node --require ./scripts/version-stamp.cjs --import tsx scripts/drive-bar.ts",
31
31
  "bar:web": "node --require ./scripts/version-stamp.cjs --import tsx scripts/bar-web.ts",
32
32
  "site:build": "node site/build.mjs",
33
+ "site:dev": "node site/build.mjs --serve",
33
34
  "bench": "node --require ./scripts/version-stamp.cjs --import tsx scripts/bench/index.ts",
34
35
  "load-gate": "node --require ./scripts/version-stamp.cjs --import tsx scripts/load-gate.ts",
35
36
  "check:protocol": "node scripts/check-protocol.mjs",
@@ -105,9 +106,9 @@
105
106
  "typescript": "^5.0.0"
106
107
  },
107
108
  "optionalDependencies": {
108
- "@promptctl/cc-candybar-darwin-arm64": "1.178.1",
109
- "@promptctl/cc-candybar-darwin-x64": "1.178.1",
110
- "@promptctl/cc-candybar-linux-arm64": "1.178.1",
111
- "@promptctl/cc-candybar-linux-x64": "1.178.1"
109
+ "@promptctl/cc-candybar-darwin-arm64": "1.179.0",
110
+ "@promptctl/cc-candybar-darwin-x64": "1.179.0",
111
+ "@promptctl/cc-candybar-linux-arm64": "1.179.0",
112
+ "@promptctl/cc-candybar-linux-x64": "1.179.0"
112
113
  }
113
114
  }